settings.js 45 KB

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