settings.js 46 KB

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