settings.js 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159
  1. // Requirements
  2. const os = require('os')
  3. const semver = require('semver')
  4. const { AssetGuard } = require('./assets/js/assetguard')
  5. const DropinModUtil = require('./assets/js/dropinmodutil')
  6. const settingsState = {
  7. invalid: new Set()
  8. }
  9. /**
  10. * General Settings Functions
  11. */
  12. /**
  13. * Bind value validators to the settings UI elements. These will
  14. * validate against the criteria defined in the ConfigManager (if
  15. * and). If the value is invalid, the UI will reflect this and saving
  16. * will be disabled until the value is corrected. This is an automated
  17. * process. More complex UI may need to be bound separately.
  18. */
  19. function initSettingsValidators(){
  20. const sEls = document.getElementById('settingsContainer').querySelectorAll('[cValue]')
  21. Array.from(sEls).map((v, index, arr) => {
  22. const vFn = ConfigManager['validate' + v.getAttribute('cValue')]
  23. if(typeof vFn === 'function'){
  24. if(v.tagName === 'INPUT'){
  25. if(v.type === 'number' || v.type === 'text'){
  26. v.addEventListener('keyup', (e) => {
  27. const v = e.target
  28. if(!vFn(v.value)){
  29. settingsState.invalid.add(v.id)
  30. v.setAttribute('error', '')
  31. settingsSaveDisabled(true)
  32. } else {
  33. if(v.hasAttribute('error')){
  34. v.removeAttribute('error')
  35. settingsState.invalid.delete(v.id)
  36. if(settingsState.invalid.size === 0){
  37. settingsSaveDisabled(false)
  38. }
  39. }
  40. }
  41. })
  42. }
  43. }
  44. }
  45. })
  46. }
  47. /**
  48. * Load configuration values onto the UI. This is an automated process.
  49. */
  50. function initSettingsValues(){
  51. const sEls = document.getElementById('settingsContainer').querySelectorAll('[cValue]')
  52. Array.from(sEls).map((v, index, arr) => {
  53. const cVal = v.getAttribute('cValue')
  54. const gFn = ConfigManager['get' + cVal]
  55. if(typeof gFn === 'function'){
  56. if(v.tagName === 'INPUT'){
  57. if(v.type === 'number' || v.type === 'text'){
  58. // Special Conditions
  59. if(cVal === 'JavaExecutable'){
  60. populateJavaExecDetails(v.value)
  61. v.value = gFn()
  62. } else if(cVal === 'JVMOptions'){
  63. v.value = gFn().join(' ')
  64. } else {
  65. v.value = gFn()
  66. }
  67. } else if(v.type === 'checkbox'){
  68. v.checked = gFn()
  69. }
  70. } else if(v.tagName === 'DIV'){
  71. if(v.classList.contains('rangeSlider')){
  72. // Special Conditions
  73. if(cVal === 'MinRAM' || cVal === 'MaxRAM'){
  74. let val = gFn()
  75. if(val.endsWith('M')){
  76. val = Number(val.substring(0, val.length-1))/1000
  77. } else {
  78. val = Number.parseFloat(val)
  79. }
  80. v.setAttribute('value', val)
  81. } else {
  82. v.setAttribute('value', Number.parseFloat(gFn()))
  83. }
  84. }
  85. }
  86. }
  87. })
  88. }
  89. /**
  90. * Save the settings values.
  91. */
  92. function saveSettingsValues(){
  93. const sEls = document.getElementById('settingsContainer').querySelectorAll('[cValue]')
  94. Array.from(sEls).map((v, index, arr) => {
  95. const cVal = v.getAttribute('cValue')
  96. const sFn = ConfigManager['set' + cVal]
  97. if(typeof sFn === 'function'){
  98. if(v.tagName === 'INPUT'){
  99. if(v.type === 'number' || v.type === 'text'){
  100. // Special Conditions
  101. if(cVal === 'JVMOptions'){
  102. sFn(v.value.split(' '))
  103. } else {
  104. sFn(v.value)
  105. }
  106. } else if(v.type === 'checkbox'){
  107. sFn(v.checked)
  108. // Special Conditions
  109. if(cVal === 'AllowPrerelease'){
  110. changeAllowPrerelease(v.checked)
  111. }
  112. }
  113. } else if(v.tagName === 'DIV'){
  114. if(v.classList.contains('rangeSlider')){
  115. // Special Conditions
  116. if(cVal === 'MinRAM' || cVal === 'MaxRAM'){
  117. let val = Number(v.getAttribute('value'))
  118. if(val%1 > 0){
  119. val = val*1000 + 'M'
  120. } else {
  121. val = val + 'G'
  122. }
  123. sFn(val)
  124. } else {
  125. sFn(v.getAttribute('value'))
  126. }
  127. }
  128. }
  129. }
  130. })
  131. }
  132. let selectedSettingsTab = 'settingsTabAccount'
  133. /**
  134. * Modify the settings container UI when the scroll threshold reaches
  135. * a certain poin.
  136. *
  137. * @param {UIEvent} e The scroll event.
  138. */
  139. function settingsTabScrollListener(e){
  140. if(e.target.scrollTop > Number.parseFloat(getComputedStyle(e.target.firstElementChild).marginTop)){
  141. document.getElementById('settingsContainer').setAttribute('scrolled', '')
  142. } else {
  143. document.getElementById('settingsContainer').removeAttribute('scrolled')
  144. }
  145. }
  146. /**
  147. * Bind functionality for the settings navigation items.
  148. */
  149. function setupSettingsTabs(){
  150. Array.from(document.getElementsByClassName('settingsNavItem')).map((val) => {
  151. if(val.hasAttribute('rSc')){
  152. val.onclick = () => {
  153. settingsNavItemListener(val)
  154. }
  155. }
  156. })
  157. }
  158. /**
  159. * Settings nav item onclick lisener. Function is exposed so that
  160. * other UI elements can quickly toggle to a certain tab from other views.
  161. *
  162. * @param {Element} ele The nav item which has been clicked.
  163. * @param {boolean} fade Optional. True to fade transition.
  164. */
  165. function settingsNavItemListener(ele, fade = true){
  166. if(ele.hasAttribute('selected')){
  167. return
  168. }
  169. const navItems = document.getElementsByClassName('settingsNavItem')
  170. for(let i=0; i<navItems.length; i++){
  171. if(navItems[i].hasAttribute('selected')){
  172. navItems[i].removeAttribute('selected')
  173. }
  174. }
  175. ele.setAttribute('selected', '')
  176. let prevTab = selectedSettingsTab
  177. selectedSettingsTab = ele.getAttribute('rSc')
  178. document.getElementById(prevTab).onscroll = null
  179. document.getElementById(selectedSettingsTab).onscroll = settingsTabScrollListener
  180. if(fade){
  181. $(`#${prevTab}`).fadeOut(250, () => {
  182. $(`#${selectedSettingsTab}`).fadeIn({
  183. duration: 250,
  184. start: () => {
  185. settingsTabScrollListener({
  186. target: document.getElementById(selectedSettingsTab)
  187. })
  188. }
  189. })
  190. })
  191. } else {
  192. $(`#${prevTab}`).hide(0, () => {
  193. $(`#${selectedSettingsTab}`).show({
  194. duration: 0,
  195. start: () => {
  196. settingsTabScrollListener({
  197. target: document.getElementById(selectedSettingsTab)
  198. })
  199. }
  200. })
  201. })
  202. }
  203. }
  204. const settingsNavDone = document.getElementById('settingsNavDone')
  205. /**
  206. * Set if the settings save (done) button is disabled.
  207. *
  208. * @param {boolean} v True to disable, false to enable.
  209. */
  210. function settingsSaveDisabled(v){
  211. settingsNavDone.disabled = v
  212. }
  213. /* Closes the settings view and saves all data. */
  214. settingsNavDone.onclick = () => {
  215. saveSettingsValues()
  216. saveModConfiguration()
  217. ConfigManager.save()
  218. saveDropinModConfiguration()
  219. switchView(getCurrentView(), VIEWS.landing)
  220. }
  221. /**
  222. * Account Management Tab
  223. */
  224. // Bind the add account button.
  225. document.getElementById('settingsAddAccount').onclick = (e) => {
  226. switchView(getCurrentView(), VIEWS.login, 500, 500, () => {
  227. loginViewOnCancel = VIEWS.settings
  228. loginViewOnSuccess = VIEWS.settings
  229. loginCancelEnabled(true)
  230. })
  231. }
  232. /**
  233. * Bind functionality for the account selection buttons. If another account
  234. * is selected, the UI of the previously selected account will be updated.
  235. */
  236. function bindAuthAccountSelect(){
  237. Array.from(document.getElementsByClassName('settingsAuthAccountSelect')).map((val) => {
  238. val.onclick = (e) => {
  239. if(val.hasAttribute('selected')){
  240. return
  241. }
  242. const selectBtns = document.getElementsByClassName('settingsAuthAccountSelect')
  243. for(let i=0; i<selectBtns.length; i++){
  244. if(selectBtns[i].hasAttribute('selected')){
  245. selectBtns[i].removeAttribute('selected')
  246. selectBtns[i].innerHTML = 'Select Account'
  247. }
  248. }
  249. val.setAttribute('selected', '')
  250. val.innerHTML = 'Selected Account &#10004;'
  251. setSelectedAccount(val.closest('.settingsAuthAccount').getAttribute('uuid'))
  252. }
  253. })
  254. }
  255. /**
  256. * Bind functionality for the log out button. If the logged out account was
  257. * the selected account, another account will be selected and the UI will
  258. * be updated accordingly.
  259. */
  260. function bindAuthAccountLogOut(){
  261. Array.from(document.getElementsByClassName('settingsAuthAccountLogOut')).map((val) => {
  262. val.onclick = (e) => {
  263. let isLastAccount = false
  264. if(Object.keys(ConfigManager.getAuthAccounts()).length === 1){
  265. isLastAccount = true
  266. setOverlayContent(
  267. 'Warning<br>This is Your Last Account',
  268. 'In order to use the launcher you must be logged into at least one account. You will need to login again after.<br><br>Are you sure you want to log out?',
  269. 'I\'m Sure',
  270. 'Cancel'
  271. )
  272. setOverlayHandler(() => {
  273. processLogOut(val, isLastAccount)
  274. toggleOverlay(false)
  275. switchView(getCurrentView(), VIEWS.login)
  276. })
  277. setDismissHandler(() => {
  278. toggleOverlay(false)
  279. })
  280. toggleOverlay(true, true)
  281. } else {
  282. processLogOut(val, isLastAccount)
  283. }
  284. }
  285. })
  286. }
  287. /**
  288. * Process a log out.
  289. *
  290. * @param {Element} val The log out button element.
  291. * @param {boolean} isLastAccount If this logout is on the last added account.
  292. */
  293. function processLogOut(val, isLastAccount){
  294. const parent = val.closest('.settingsAuthAccount')
  295. const uuid = parent.getAttribute('uuid')
  296. const prevSelAcc = ConfigManager.getSelectedAccount()
  297. AuthManager.removeAccount(uuid).then(() => {
  298. if(!isLastAccount && uuid === prevSelAcc.uuid){
  299. const selAcc = ConfigManager.getSelectedAccount()
  300. refreshAuthAccountSelected(selAcc.uuid)
  301. updateSelectedAccount(selAcc)
  302. validateSelectedAccount()
  303. }
  304. })
  305. $(parent).fadeOut(250, () => {
  306. parent.remove()
  307. })
  308. }
  309. /**
  310. * Refreshes the status of the selected account on the auth account
  311. * elements.
  312. *
  313. * @param {string} uuid The UUID of the new selected account.
  314. */
  315. function refreshAuthAccountSelected(uuid){
  316. Array.from(document.getElementsByClassName('settingsAuthAccount')).map((val) => {
  317. const selBtn = val.getElementsByClassName('settingsAuthAccountSelect')[0]
  318. if(uuid === val.getAttribute('uuid')){
  319. selBtn.setAttribute('selected', '')
  320. selBtn.innerHTML = 'Selected Account &#10004;'
  321. } else {
  322. if(selBtn.hasAttribute('selected')){
  323. selBtn.removeAttribute('selected')
  324. }
  325. selBtn.innerHTML = 'Select Account'
  326. }
  327. })
  328. }
  329. const settingsCurrentAccounts = document.getElementById('settingsCurrentAccounts')
  330. /**
  331. * Add auth account elements for each one stored in the authentication database.
  332. */
  333. function populateAuthAccounts(){
  334. const authAccounts = ConfigManager.getAuthAccounts()
  335. const authKeys = Object.keys(authAccounts)
  336. if(authKeys.length === 0){
  337. return
  338. }
  339. const selectedUUID = ConfigManager.getSelectedAccount().uuid
  340. let authAccountStr = ''
  341. authKeys.map((val) => {
  342. const acc = authAccounts[val]
  343. authAccountStr += `<div class="settingsAuthAccount" uuid="${acc.uuid}">
  344. <div class="settingsAuthAccountLeft">
  345. <img class="settingsAuthAccountImage" alt="${acc.displayName}" src="https://crafatar.com/renders/body/${acc.uuid}?scale=3&default=MHF_Steve&overlay">
  346. </div>
  347. <div class="settingsAuthAccountRight">
  348. <div class="settingsAuthAccountDetails">
  349. <div class="settingsAuthAccountDetailPane">
  350. <div class="settingsAuthAccountDetailTitle">Username</div>
  351. <div class="settingsAuthAccountDetailValue">${acc.displayName}</div>
  352. </div>
  353. <div class="settingsAuthAccountDetailPane">
  354. <div class="settingsAuthAccountDetailTitle">UUID</div>
  355. <div class="settingsAuthAccountDetailValue">${acc.uuid}</div>
  356. </div>
  357. </div>
  358. <div class="settingsAuthAccountActions">
  359. <button class="settingsAuthAccountSelect" ${selectedUUID === acc.uuid ? 'selected>Selected Account &#10004;' : '>Select Account'}</button>
  360. <div class="settingsAuthAccountWrapper">
  361. <button class="settingsAuthAccountLogOut">Log Out</button>
  362. </div>
  363. </div>
  364. </div>
  365. </div>`
  366. })
  367. settingsCurrentAccounts.innerHTML = authAccountStr
  368. }
  369. /**
  370. * Prepare the accounts tab for display.
  371. */
  372. function prepareAccountsTab() {
  373. populateAuthAccounts()
  374. bindAuthAccountSelect()
  375. bindAuthAccountLogOut()
  376. }
  377. /**
  378. * Minecraft Tab
  379. */
  380. /**
  381. * Disable decimals, negative signs, and scientific notation.
  382. */
  383. document.getElementById('settingsGameWidth').addEventListener('keydown', (e) => {
  384. if(/^[-.eE]$/.test(e.key)){
  385. e.preventDefault()
  386. }
  387. })
  388. document.getElementById('settingsGameHeight').addEventListener('keydown', (e) => {
  389. if(/^[-.eE]$/.test(e.key)){
  390. e.preventDefault()
  391. }
  392. })
  393. /**
  394. * Mods Tab
  395. */
  396. const settingsModsContainer = document.getElementById('settingsModsContainer')
  397. /**
  398. * Resolve and update the mods on the UI.
  399. */
  400. function resolveModsForUI(){
  401. const serv = ConfigManager.getSelectedServer()
  402. const distro = DistroManager.getDistribution()
  403. const servConf = ConfigManager.getModConfiguration(serv)
  404. const modStr = parseModulesForUI(distro.getServer(serv).getModules(), false, servConf.mods)
  405. document.getElementById('settingsReqModsContent').innerHTML = modStr.reqMods
  406. document.getElementById('settingsOptModsContent').innerHTML = modStr.optMods
  407. }
  408. /**
  409. * Recursively build the mod UI elements.
  410. *
  411. * @param {Object[]} mdls An array of modules to parse.
  412. * @param {boolean} submodules Whether or not we are parsing submodules.
  413. * @param {Object} servConf The server configuration object for this module level.
  414. */
  415. function parseModulesForUI(mdls, submodules, servConf){
  416. let reqMods = ''
  417. let optMods = ''
  418. for(const mdl of mdls){
  419. if(mdl.getType() === DistroManager.Types.ForgeMod || mdl.getType() === DistroManager.Types.LiteMod || mdl.getType() === DistroManager.Types.LiteLoader){
  420. if(mdl.getRequired().isRequired()){
  421. reqMods += `<div id="${mdl.getVersionlessID()}" class="settingsBaseMod settings${submodules ? 'Sub' : ''}Mod" enabled>
  422. <div class="settingsModContent">
  423. <div class="settingsModMainWrapper">
  424. <div class="settingsModStatus"></div>
  425. <div class="settingsModDetails">
  426. <span class="settingsModName">${mdl.getName()}</span>
  427. <span class="settingsModVersion">v${mdl.getVersion()}</span>
  428. </div>
  429. </div>
  430. <label class="toggleSwitch" reqmod>
  431. <input type="checkbox" checked>
  432. <span class="toggleSwitchSlider"></span>
  433. </label>
  434. </div>
  435. ${mdl.hasSubModules() ? `<div class="settingsSubModContainer">
  436. ${Object.values(parseModulesForUI(mdl.getSubModules(), true, servConf[mdl.getVersionlessID()])).join('')}
  437. </div>` : ''}
  438. </div>`
  439. } else {
  440. const conf = servConf[mdl.getVersionlessID()]
  441. const val = typeof conf === 'object' ? conf.value : conf
  442. optMods += `<div id="${mdl.getVersionlessID()}" class="settingsBaseMod settings${submodules ? 'Sub' : ''}Mod" ${val ? 'enabled' : ''}>
  443. <div class="settingsModContent">
  444. <div class="settingsModMainWrapper">
  445. <div class="settingsModStatus"></div>
  446. <div class="settingsModDetails">
  447. <span class="settingsModName">${mdl.getName()}</span>
  448. <span class="settingsModVersion">v${mdl.getVersion()}</span>
  449. </div>
  450. </div>
  451. <label class="toggleSwitch">
  452. <input type="checkbox" formod="${mdl.getVersionlessID()}" ${val ? 'checked' : ''}>
  453. <span class="toggleSwitchSlider"></span>
  454. </label>
  455. </div>
  456. ${mdl.hasSubModules() ? `<div class="settingsSubModContainer">
  457. ${Object.values(parseModulesForUI(mdl.getSubModules(), true, conf.mods)).join('')}
  458. </div>` : ''}
  459. </div>`
  460. }
  461. }
  462. }
  463. return {
  464. reqMods,
  465. optMods
  466. }
  467. }
  468. /**
  469. * Bind functionality to mod config toggle switches. Switching the value
  470. * will also switch the status color on the left of the mod UI.
  471. */
  472. function bindModsToggleSwitch(){
  473. const sEls = settingsModsContainer.querySelectorAll('[formod]')
  474. Array.from(sEls).map((v, index, arr) => {
  475. v.onchange = () => {
  476. if(v.checked) {
  477. document.getElementById(v.getAttribute('formod')).setAttribute('enabled', '')
  478. } else {
  479. document.getElementById(v.getAttribute('formod')).removeAttribute('enabled')
  480. }
  481. }
  482. })
  483. }
  484. /**
  485. * Save the mod configuration based on the UI values.
  486. */
  487. function saveModConfiguration(){
  488. const serv = ConfigManager.getSelectedServer()
  489. const modConf = ConfigManager.getModConfiguration(serv)
  490. modConf.mods = _saveModConfiguration(modConf.mods)
  491. ConfigManager.setModConfiguration(serv, modConf)
  492. }
  493. /**
  494. * Recursively save mod config with submods.
  495. *
  496. * @param {Object} modConf Mod config object to save.
  497. */
  498. function _saveModConfiguration(modConf){
  499. for(m of Object.entries(modConf)){
  500. const tSwitch = settingsModsContainer.querySelectorAll(`[formod='${m[0]}']`)
  501. if(!tSwitch[0].hasAttribute('dropin')){
  502. if(typeof m[1] === 'boolean'){
  503. modConf[m[0]] = tSwitch[0].checked
  504. } else {
  505. if(m[1] != null){
  506. if(tSwitch.length > 0){
  507. modConf[m[0]].value = tSwitch[0].checked
  508. }
  509. modConf[m[0]].mods = _saveModConfiguration(modConf[m[0]].mods)
  510. }
  511. }
  512. }
  513. }
  514. return modConf
  515. }
  516. // Drop-in mod elements.
  517. let CACHE_SETTINGS_MODS_DIR
  518. let CACHE_DROPIN_MODS
  519. /**
  520. * Resolve any located drop-in mods for this server and
  521. * populate the results onto the UI.
  522. */
  523. function resolveDropinModsForUI(){
  524. const serv = DistroManager.getDistribution().getServer(ConfigManager.getSelectedServer())
  525. CACHE_SETTINGS_MODS_DIR = path.join(ConfigManager.getInstanceDirectory(), serv.getID(), 'mods')
  526. CACHE_DROPIN_MODS = DropinModUtil.scanForDropinMods(CACHE_SETTINGS_MODS_DIR, serv.getMinecraftVersion())
  527. let dropinMods = ''
  528. for(dropin of CACHE_DROPIN_MODS){
  529. dropinMods += `<div id="${dropin.fullName}" class="settingsBaseMod settingsDropinMod" ${!dropin.disabled ? 'enabled' : ''}>
  530. <div class="settingsModContent">
  531. <div class="settingsModMainWrapper">
  532. <div class="settingsModStatus"></div>
  533. <div class="settingsModDetails">
  534. <span class="settingsModName">${dropin.name}</span>
  535. <div class="settingsDropinRemoveWrapper">
  536. <button class="settingsDropinRemoveButton" remmod="${dropin.fullName}">Remove</button>
  537. </div>
  538. </div>
  539. </div>
  540. <label class="toggleSwitch">
  541. <input type="checkbox" formod="${dropin.fullName}" dropin ${!dropin.disabled ? 'checked' : ''}>
  542. <span class="toggleSwitchSlider"></span>
  543. </label>
  544. </div>
  545. </div>`
  546. }
  547. document.getElementById('settingsDropinModsContent').innerHTML = dropinMods
  548. }
  549. /**
  550. * Bind the remove button for each loaded drop-in mod.
  551. */
  552. function bindDropinModsRemoveButton(){
  553. const sEls = settingsModsContainer.querySelectorAll('[remmod]')
  554. Array.from(sEls).map((v, index, arr) => {
  555. v.onclick = () => {
  556. const fullName = v.getAttribute('remmod')
  557. const res = DropinModUtil.deleteDropinMod(CACHE_SETTINGS_MODS_DIR, fullName)
  558. if(res){
  559. document.getElementById(fullName).remove()
  560. } else {
  561. setOverlayContent(
  562. `Failed to Delete<br>Drop-in Mod ${fullName}`,
  563. 'Make sure the file is not in use and try again.',
  564. 'Okay'
  565. )
  566. setOverlayHandler(null)
  567. toggleOverlay(true)
  568. }
  569. }
  570. })
  571. }
  572. /**
  573. * Bind functionality to the file system button for the selected
  574. * server configuration.
  575. */
  576. function bindDropinModFileSystemButton(){
  577. const fsBtn = document.getElementById('settingsDropinFileSystemButton')
  578. fsBtn.onclick = () => {
  579. shell.openItem(CACHE_SETTINGS_MODS_DIR)
  580. }
  581. }
  582. /**
  583. * Save drop-in mod states. Enabling and disabling is just a matter
  584. * of adding/removing the .disabled extension.
  585. */
  586. function saveDropinModConfiguration(){
  587. for(dropin of CACHE_DROPIN_MODS){
  588. const dropinUI = document.getElementById(dropin.fullName)
  589. if(dropinUI != null){
  590. const dropinUIEnabled = dropinUI.hasAttribute('enabled')
  591. if(DropinModUtil.isDropinModEnabled(dropin.fullName) != dropinUIEnabled){
  592. DropinModUtil.toggleDropinMod(CACHE_SETTINGS_MODS_DIR, dropin.fullName, dropinUIEnabled).catch(err => {
  593. if(!isOverlayVisible()){
  594. setOverlayContent(
  595. 'Failed to Toggle<br>One or More Drop-in Mods',
  596. err.message,
  597. 'Okay'
  598. )
  599. setOverlayHandler(null)
  600. toggleOverlay(true)
  601. }
  602. })
  603. }
  604. }
  605. }
  606. }
  607. // Refresh the drop-in mods when F5 is pressed.
  608. // Only active on the mods tab.
  609. document.addEventListener('keydown', (e) => {
  610. if(getCurrentView() === VIEWS.settings && selectedSettingsTab === 'settingsTabMods'){
  611. if(e.key === 'F5'){
  612. resolveDropinModsForUI()
  613. bindDropinModsRemoveButton()
  614. bindDropinModFileSystemButton()
  615. bindModsToggleSwitch()
  616. }
  617. }
  618. })
  619. // Server status bar functions.
  620. /**
  621. * Load the currently selected server information onto the mods tab.
  622. */
  623. function loadSelectedServerOnModsTab(){
  624. const serv = DistroManager.getDistribution().getServer(ConfigManager.getSelectedServer())
  625. document.getElementById('settingsSelServContent').innerHTML = `
  626. <img class="serverListingImg" src="${serv.getIcon()}"/>
  627. <div class="serverListingDetails">
  628. <span class="serverListingName">${serv.getName()}</span>
  629. <span class="serverListingDescription">${serv.getDescription()}</span>
  630. <div class="serverListingInfo">
  631. <div class="serverListingVersion">${serv.getMinecraftVersion()}</div>
  632. <div class="serverListingRevision">${serv.getVersion()}</div>
  633. ${serv.isMainServer() ? `<div class="serverListingStarWrapper">
  634. <svg id="Layer_1" viewBox="0 0 107.45 104.74" width="20px" height="20px">
  635. <defs>
  636. <style>.cls-1{fill:#fff;}.cls-2{fill:none;stroke:#fff;stroke-miterlimit:10;}</style>
  637. </defs>
  638. <path class="cls-1" d="M100.93,65.54C89,62,68.18,55.65,63.54,52.13c2.7-5.23,18.8-19.2,28-27.55C81.36,31.74,63.74,43.87,58.09,45.3c-2.41-5.37-3.61-26.52-4.37-39-.77,12.46-2,33.64-4.36,39-5.7-1.46-23.3-13.57-33.49-20.72,9.26,8.37,25.39,22.36,28,27.55C39.21,55.68,18.47,62,6.52,65.55c12.32-2,33.63-6.06,39.34-4.9-.16,5.87-8.41,26.16-13.11,37.69,6.1-10.89,16.52-30.16,21-33.9,4.5,3.79,14.93,23.09,21,34C70,86.84,61.73,66.48,61.59,60.65,67.36,59.49,88.64,63.52,100.93,65.54Z"/>
  639. <circle class="cls-2" cx="53.73" cy="53.9" r="38"/>
  640. </svg>
  641. <span class="serverListingStarTooltip">Main Server</span>
  642. </div>` : ''}
  643. </div>
  644. </div>
  645. `
  646. }
  647. // Bind functionality to the server switch button.
  648. document.getElementById('settingsSwitchServerButton').addEventListener('click', (e) => {
  649. e.target.blur()
  650. toggleServerSelection(true)
  651. })
  652. /**
  653. * Function to refresh the mods tab whenever the selected
  654. * server is changed.
  655. */
  656. function animateModsTabRefresh(){
  657. $('#settingsTabMods').fadeOut(500, () => {
  658. saveModConfiguration()
  659. ConfigManager.save()
  660. saveDropinModConfiguration()
  661. prepareModsTab()
  662. $('#settingsTabMods').fadeIn(500)
  663. })
  664. }
  665. /**
  666. * Prepare the Mods tab for display.
  667. */
  668. function prepareModsTab(first){
  669. resolveModsForUI()
  670. resolveDropinModsForUI()
  671. bindDropinModsRemoveButton()
  672. bindDropinModFileSystemButton()
  673. bindModsToggleSwitch()
  674. loadSelectedServerOnModsTab()
  675. }
  676. /**
  677. * Java Tab
  678. */
  679. // DOM Cache
  680. const settingsMaxRAMRange = document.getElementById('settingsMaxRAMRange')
  681. const settingsMinRAMRange = document.getElementById('settingsMinRAMRange')
  682. const settingsMaxRAMLabel = document.getElementById('settingsMaxRAMLabel')
  683. const settingsMinRAMLabel = document.getElementById('settingsMinRAMLabel')
  684. const settingsMemoryTotal = document.getElementById('settingsMemoryTotal')
  685. const settingsMemoryAvail = document.getElementById('settingsMemoryAvail')
  686. const settingsJavaExecDetails = document.getElementById('settingsJavaExecDetails')
  687. const settingsJavaExecVal = document.getElementById('settingsJavaExecVal')
  688. const settingsJavaExecSel = document.getElementById('settingsJavaExecSel')
  689. // Store maximum memory values.
  690. const SETTINGS_MAX_MEMORY = ConfigManager.getAbsoluteMaxRAM()
  691. const SETTINGS_MIN_MEMORY = ConfigManager.getAbsoluteMinRAM()
  692. // Set the max and min values for the ranged sliders.
  693. settingsMaxRAMRange.setAttribute('max', SETTINGS_MAX_MEMORY)
  694. settingsMaxRAMRange.setAttribute('min', SETTINGS_MIN_MEMORY)
  695. settingsMinRAMRange.setAttribute('max', SETTINGS_MAX_MEMORY)
  696. settingsMinRAMRange.setAttribute('min', SETTINGS_MIN_MEMORY )
  697. // Bind on change event for min memory container.
  698. settingsMinRAMRange.onchange = (e) => {
  699. // Current range values
  700. const sMaxV = Number(settingsMaxRAMRange.getAttribute('value'))
  701. const sMinV = Number(settingsMinRAMRange.getAttribute('value'))
  702. // Get reference to range bar.
  703. const bar = e.target.getElementsByClassName('rangeSliderBar')[0]
  704. // Calculate effective total memory.
  705. const max = (os.totalmem()-1000000000)/1000000000
  706. // Change range bar color based on the selected value.
  707. if(sMinV >= max/2){
  708. bar.style.background = '#e86060'
  709. } else if(sMinV >= max/4) {
  710. bar.style.background = '#e8e18b'
  711. } else {
  712. bar.style.background = null
  713. }
  714. // Increase maximum memory if the minimum exceeds its value.
  715. if(sMaxV < sMinV){
  716. const sliderMeta = calculateRangeSliderMeta(settingsMaxRAMRange)
  717. updateRangedSlider(settingsMaxRAMRange, sMinV,
  718. ((sMinV-sliderMeta.min)/sliderMeta.step)*sliderMeta.inc)
  719. settingsMaxRAMLabel.innerHTML = sMinV.toFixed(1) + 'G'
  720. }
  721. // Update label
  722. settingsMinRAMLabel.innerHTML = sMinV.toFixed(1) + 'G'
  723. }
  724. // Bind on change event for max memory container.
  725. settingsMaxRAMRange.onchange = (e) => {
  726. // Current range values
  727. const sMaxV = Number(settingsMaxRAMRange.getAttribute('value'))
  728. const sMinV = Number(settingsMinRAMRange.getAttribute('value'))
  729. // Get reference to range bar.
  730. const bar = e.target.getElementsByClassName('rangeSliderBar')[0]
  731. // Calculate effective total memory.
  732. const max = (os.totalmem()-1000000000)/1000000000
  733. // Change range bar color based on the selected value.
  734. if(sMaxV >= max/2){
  735. bar.style.background = '#e86060'
  736. } else if(sMaxV >= max/4) {
  737. bar.style.background = '#e8e18b'
  738. } else {
  739. bar.style.background = null
  740. }
  741. // Decrease the minimum memory if the maximum value is less.
  742. if(sMaxV < sMinV){
  743. const sliderMeta = calculateRangeSliderMeta(settingsMaxRAMRange)
  744. updateRangedSlider(settingsMinRAMRange, sMaxV,
  745. ((sMaxV-sliderMeta.min)/sliderMeta.step)*sliderMeta.inc)
  746. settingsMinRAMLabel.innerHTML = sMaxV.toFixed(1) + 'G'
  747. }
  748. settingsMaxRAMLabel.innerHTML = sMaxV.toFixed(1) + 'G'
  749. }
  750. /**
  751. * Calculate common values for a ranged slider.
  752. *
  753. * @param {Element} v The range slider to calculate against.
  754. * @returns {Object} An object with meta values for the provided ranged slider.
  755. */
  756. function calculateRangeSliderMeta(v){
  757. const val = {
  758. max: Number(v.getAttribute('max')),
  759. min: Number(v.getAttribute('min')),
  760. step: Number(v.getAttribute('step')),
  761. }
  762. val.ticks = (val.max-val.min)/val.step
  763. val.inc = 100/val.ticks
  764. return val
  765. }
  766. /**
  767. * Binds functionality to the ranged sliders. They're more than
  768. * just divs now :').
  769. */
  770. function bindRangeSlider(){
  771. Array.from(document.getElementsByClassName('rangeSlider')).map((v) => {
  772. // Reference the track (thumb).
  773. const track = v.getElementsByClassName('rangeSliderTrack')[0]
  774. // Set the initial slider value.
  775. const value = v.getAttribute('value')
  776. const sliderMeta = calculateRangeSliderMeta(v)
  777. updateRangedSlider(v, value, ((value-sliderMeta.min)/sliderMeta.step)*sliderMeta.inc)
  778. // The magic happens when we click on the track.
  779. track.onmousedown = (e) => {
  780. // Stop moving the track on mouse up.
  781. document.onmouseup = (e) => {
  782. document.onmousemove = null
  783. document.onmouseup = null
  784. }
  785. // Move slider according to the mouse position.
  786. document.onmousemove = (e) => {
  787. // Distance from the beginning of the bar in pixels.
  788. const diff = e.pageX - v.offsetLeft - track.offsetWidth/2
  789. // Don't move the track off the bar.
  790. if(diff >= 0 && diff <= v.offsetWidth-track.offsetWidth/2){
  791. // Convert the difference to a percentage.
  792. const perc = (diff/v.offsetWidth)*100
  793. // Calculate the percentage of the closest notch.
  794. const notch = Number(perc/sliderMeta.inc).toFixed(0)*sliderMeta.inc
  795. // If we're close to that notch, stick to it.
  796. if(Math.abs(perc-notch) < sliderMeta.inc/2){
  797. updateRangedSlider(v, sliderMeta.min+(sliderMeta.step*(notch/sliderMeta.inc)), notch)
  798. }
  799. }
  800. }
  801. }
  802. })
  803. }
  804. /**
  805. * Update a ranged slider's value and position.
  806. *
  807. * @param {Element} element The ranged slider to update.
  808. * @param {string | number} value The new value for the ranged slider.
  809. * @param {number} notch The notch that the slider should now be at.
  810. */
  811. function updateRangedSlider(element, value, notch){
  812. const oldVal = element.getAttribute('value')
  813. const bar = element.getElementsByClassName('rangeSliderBar')[0]
  814. const track = element.getElementsByClassName('rangeSliderTrack')[0]
  815. element.setAttribute('value', value)
  816. if(notch < 0){
  817. notch = 0
  818. } else if(notch > 100) {
  819. notch = 100
  820. }
  821. const event = new MouseEvent('change', {
  822. target: element,
  823. type: 'change',
  824. bubbles: false,
  825. cancelable: true
  826. })
  827. let cancelled = !element.dispatchEvent(event)
  828. if(!cancelled){
  829. track.style.left = notch + '%'
  830. bar.style.width = notch + '%'
  831. } else {
  832. element.setAttribute('value', oldVal)
  833. }
  834. }
  835. /**
  836. * Display the total and available RAM.
  837. */
  838. function populateMemoryStatus(){
  839. settingsMemoryTotal.innerHTML = Number((os.totalmem()-1000000000)/1000000000).toFixed(1) + 'G'
  840. settingsMemoryAvail.innerHTML = Number(os.freemem()/1000000000).toFixed(1) + 'G'
  841. }
  842. // Bind the executable file input to the display text input.
  843. settingsJavaExecSel.onchange = (e) => {
  844. settingsJavaExecVal.value = settingsJavaExecSel.files[0].path
  845. populateJavaExecDetails(settingsJavaExecVal.value)
  846. }
  847. /**
  848. * Validate the provided executable path and display the data on
  849. * the UI.
  850. *
  851. * @param {string} execPath The executable path to populate against.
  852. */
  853. function populateJavaExecDetails(execPath){
  854. AssetGuard._validateJavaBinary(execPath).then(v => {
  855. if(v.valid){
  856. settingsJavaExecDetails.innerHTML = `Selected: Java ${v.version.major} Update ${v.version.update} (x${v.arch})`
  857. } else {
  858. settingsJavaExecDetails.innerHTML = 'Invalid Selection'
  859. }
  860. })
  861. }
  862. /**
  863. * Prepare the Java tab for display.
  864. */
  865. function prepareJavaTab(){
  866. bindRangeSlider()
  867. populateMemoryStatus()
  868. }
  869. /**
  870. * About Tab
  871. */
  872. const settingsTabAbout = document.getElementById('settingsTabAbout')
  873. const settingsAboutChangelogTitle = settingsTabAbout.getElementsByClassName('settingsChangelogTitle')[0]
  874. const settingsAboutChangelogText = settingsTabAbout.getElementsByClassName('settingsChangelogText')[0]
  875. const settingsAboutChangelogButton = settingsTabAbout.getElementsByClassName('settingsChangelogButton')[0]
  876. // Bind the devtools toggle button.
  877. document.getElementById('settingsAboutDevToolsButton').onclick = (e) => {
  878. let window = remote.getCurrentWindow()
  879. window.toggleDevTools()
  880. }
  881. /**
  882. * Return whether or not the provided version is a prerelease.
  883. *
  884. * @param {string} version The semver version to test.
  885. * @returns {boolean} True if the version is a prerelease, otherwise false.
  886. */
  887. function isPrerelease(version){
  888. const preRelComp = semver.prerelease(version)
  889. return preRelComp != null && preRelComp.length > 0
  890. }
  891. /**
  892. * Utility method to display version information on the
  893. * About and Update settings tabs.
  894. *
  895. * @param {string} version The semver version to display.
  896. * @param {Element} valueElement The value element.
  897. * @param {Element} titleElement The title element.
  898. * @param {Element} checkElement The check mark element.
  899. */
  900. function populateVersionInformation(version, valueElement, titleElement, checkElement){
  901. valueElement.innerHTML = version
  902. if(isPrerelease(version)){
  903. titleElement.innerHTML = 'Pre-release'
  904. titleElement.style.color = '#ff886d'
  905. checkElement.style.background = '#ff886d'
  906. } else {
  907. titleElement.innerHTML = 'Stable Release'
  908. titleElement.style.color = null
  909. checkElement.style.background = null
  910. }
  911. }
  912. /**
  913. * Retrieve the version information and display it on the UI.
  914. */
  915. function populateAboutVersionInformation(){
  916. populateVersionInformation(remote.app.getVersion(), document.getElementById('settingsAboutCurrentVersionValue'), document.getElementById('settingsAboutCurrentVersionTitle'), document.getElementById('settingsAboutCurrentVersionCheck'))
  917. }
  918. /**
  919. * Fetches the GitHub atom release feed and parses it for the release notes
  920. * of the current version. This value is displayed on the UI.
  921. */
  922. function populateReleaseNotes(){
  923. $.ajax({
  924. url: 'https://github.com/WesterosCraftCode/ElectronLauncher/releases.atom',
  925. success: (data) => {
  926. const version = 'v' + remote.app.getVersion()
  927. const entries = $(data).find('entry')
  928. for(let i=0; i<entries.length; i++){
  929. const entry = $(entries[i])
  930. let id = entry.find('id').text()
  931. id = id.substring(id.lastIndexOf('/')+1)
  932. if(id === version){
  933. settingsAboutChangelogTitle.innerHTML = entry.find('title').text()
  934. settingsAboutChangelogText.innerHTML = entry.find('content').text()
  935. settingsAboutChangelogButton.href = entry.find('link').attr('href')
  936. }
  937. }
  938. },
  939. timeout: 2500
  940. }).catch(err => {
  941. settingsAboutChangelogText.innerHTML = 'Failed to load release notes.'
  942. })
  943. }
  944. /**
  945. * Prepare account tab for display.
  946. */
  947. function prepareAboutTab(){
  948. populateAboutVersionInformation()
  949. populateReleaseNotes()
  950. }
  951. /**
  952. * Update Tab
  953. */
  954. const settingsTabUpdate = document.getElementById('settingsTabUpdate')
  955. const settingsUpdateTitle = document.getElementById('settingsUpdateTitle')
  956. const settingsUpdateVersionCheck = document.getElementById('settingsUpdateVersionCheck')
  957. const settingsUpdateVersionTitle = document.getElementById('settingsUpdateVersionTitle')
  958. const settingsUpdateVersionValue = document.getElementById('settingsUpdateVersionValue')
  959. const settingsUpdateChangelogTitle = settingsTabUpdate.getElementsByClassName('settingsChangelogTitle')[0]
  960. const settingsUpdateChangelogText = settingsTabUpdate.getElementsByClassName('settingsChangelogText')[0]
  961. const settingsUpdateChangelogCont = settingsTabUpdate.getElementsByClassName('settingsChangelogContainer')[0]
  962. const settingsUpdateActionButton = document.getElementById('settingsUpdateActionButton')
  963. /**
  964. * Update the properties of the update action button.
  965. *
  966. * @param {string} text The new button text.
  967. * @param {boolean} disabled Optional. Disable or enable the button
  968. * @param {function} handler Optional. New button event handler.
  969. */
  970. function settingsUpdateButtonStatus(text, disabled = false, handler = null){
  971. settingsUpdateActionButton.innerHTML = text
  972. settingsUpdateActionButton.disabled = disabled
  973. if(handler != null){
  974. settingsUpdateActionButton.onclick = handler
  975. }
  976. }
  977. /**
  978. * Populate the update tab with relevant information.
  979. *
  980. * @param {Object} data The update data.
  981. */
  982. function populateSettingsUpdateInformation(data){
  983. if(data != null){
  984. settingsUpdateTitle.innerHTML = `New ${isPrerelease(data.version) ? 'Pre-release' : 'Release'} Available`
  985. settingsUpdateChangelogCont.style.display = null
  986. settingsUpdateChangelogTitle.innerHTML = data.releaseName
  987. settingsUpdateChangelogText.innerHTML = data.releaseNotes
  988. populateVersionInformation(data.version, settingsUpdateVersionValue, settingsUpdateVersionTitle, settingsUpdateVersionCheck)
  989. settingsUpdateButtonStatus('Downloading..', true)
  990. } else {
  991. settingsUpdateTitle.innerHTML = 'You Are Running the Latest Version'
  992. settingsUpdateChangelogCont.style.display = 'none'
  993. populateVersionInformation(remote.app.getVersion(), settingsUpdateVersionValue, settingsUpdateVersionTitle, settingsUpdateVersionCheck)
  994. settingsUpdateButtonStatus('Check for Updates', false, () => {
  995. if(!isDev){
  996. ipcRenderer.send('autoUpdateAction', 'checkForUpdate')
  997. settingsUpdateButtonStatus('Checking for Updates..', true)
  998. }
  999. })
  1000. }
  1001. }
  1002. /**
  1003. * Prepare update tab for display.
  1004. *
  1005. * @param {Object} data The update data.
  1006. */
  1007. function prepareUpdateTab(data = null){
  1008. populateSettingsUpdateInformation(data)
  1009. }
  1010. /**
  1011. * Settings preparation functions.
  1012. */
  1013. /**
  1014. * Prepare the entire settings UI.
  1015. *
  1016. * @param {boolean} first Whether or not it is the first load.
  1017. */
  1018. function prepareSettings(first = false) {
  1019. if(first){
  1020. setupSettingsTabs()
  1021. initSettingsValidators()
  1022. prepareUpdateTab()
  1023. } else {
  1024. prepareModsTab()
  1025. }
  1026. initSettingsValues()
  1027. prepareAccountsTab()
  1028. prepareJavaTab()
  1029. prepareAboutTab()
  1030. }
  1031. // Prepare the settings UI on startup.
  1032. prepareSettings(true)