settings.js 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317
  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. saveShaderpackSettings()
  736. resolveShaderpacksForUI()
  737. }
  738. }
  739. // Server status bar functions.
  740. /**
  741. * Load the currently selected server information onto the mods tab.
  742. */
  743. function loadSelectedServerOnModsTab(){
  744. const serv = DistroManager.getDistribution().getServer(ConfigManager.getSelectedServer())
  745. document.getElementById('settingsSelServContent').innerHTML = `
  746. <img class="serverListingImg" src="${serv.getIcon()}"/>
  747. <div class="serverListingDetails">
  748. <span class="serverListingName">${serv.getName()}</span>
  749. <span class="serverListingDescription">${serv.getDescription()}</span>
  750. <div class="serverListingInfo">
  751. <div class="serverListingVersion">${serv.getMinecraftVersion()}</div>
  752. <div class="serverListingRevision">${serv.getVersion()}</div>
  753. ${serv.isMainServer() ? `<div class="serverListingStarWrapper">
  754. <svg id="Layer_1" viewBox="0 0 107.45 104.74" width="20px" height="20px">
  755. <defs>
  756. <style>.cls-1{fill:#fff;}.cls-2{fill:none;stroke:#fff;stroke-miterlimit:10;}</style>
  757. </defs>
  758. <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"/>
  759. <circle class="cls-2" cx="53.73" cy="53.9" r="38"/>
  760. </svg>
  761. <span class="serverListingStarTooltip">Main Server</span>
  762. </div>` : ''}
  763. </div>
  764. </div>
  765. `
  766. }
  767. // Bind functionality to the server switch button.
  768. document.getElementById('settingsSwitchServerButton').addEventListener('click', (e) => {
  769. e.target.blur()
  770. toggleServerSelection(true)
  771. })
  772. /**
  773. * Save mod configuration for the current selected server.
  774. */
  775. function saveAllModConfigurations(){
  776. saveModConfiguration()
  777. ConfigManager.save()
  778. saveDropinModConfiguration()
  779. }
  780. /**
  781. * Function to refresh the mods tab whenever the selected
  782. * server is changed.
  783. */
  784. function animateModsTabRefresh(){
  785. $('#settingsTabMods').fadeOut(500, () => {
  786. prepareModsTab()
  787. $('#settingsTabMods').fadeIn(500)
  788. })
  789. }
  790. /**
  791. * Prepare the Mods tab for display.
  792. */
  793. function prepareModsTab(first){
  794. resolveModsForUI()
  795. resolveDropinModsForUI()
  796. resolveShaderpacksForUI()
  797. bindDropinModsRemoveButton()
  798. bindDropinModFileSystemButton()
  799. bindShaderpackButton()
  800. bindModsToggleSwitch()
  801. loadSelectedServerOnModsTab()
  802. }
  803. /**
  804. * Java Tab
  805. */
  806. // DOM Cache
  807. const settingsMaxRAMRange = document.getElementById('settingsMaxRAMRange')
  808. const settingsMinRAMRange = document.getElementById('settingsMinRAMRange')
  809. const settingsMaxRAMLabel = document.getElementById('settingsMaxRAMLabel')
  810. const settingsMinRAMLabel = document.getElementById('settingsMinRAMLabel')
  811. const settingsMemoryTotal = document.getElementById('settingsMemoryTotal')
  812. const settingsMemoryAvail = document.getElementById('settingsMemoryAvail')
  813. const settingsJavaExecDetails = document.getElementById('settingsJavaExecDetails')
  814. const settingsJavaExecVal = document.getElementById('settingsJavaExecVal')
  815. const settingsJavaExecSel = document.getElementById('settingsJavaExecSel')
  816. // Store maximum memory values.
  817. const SETTINGS_MAX_MEMORY = ConfigManager.getAbsoluteMaxRAM()
  818. const SETTINGS_MIN_MEMORY = ConfigManager.getAbsoluteMinRAM()
  819. // Set the max and min values for the ranged sliders.
  820. settingsMaxRAMRange.setAttribute('max', SETTINGS_MAX_MEMORY)
  821. settingsMaxRAMRange.setAttribute('min', SETTINGS_MIN_MEMORY)
  822. settingsMinRAMRange.setAttribute('max', SETTINGS_MAX_MEMORY)
  823. settingsMinRAMRange.setAttribute('min', SETTINGS_MIN_MEMORY )
  824. // Bind on change event for min memory container.
  825. settingsMinRAMRange.onchange = (e) => {
  826. // Current range values
  827. const sMaxV = Number(settingsMaxRAMRange.getAttribute('value'))
  828. const sMinV = Number(settingsMinRAMRange.getAttribute('value'))
  829. // Get reference to range bar.
  830. const bar = e.target.getElementsByClassName('rangeSliderBar')[0]
  831. // Calculate effective total memory.
  832. const max = (os.totalmem()-1000000000)/1000000000
  833. // Change range bar color based on the selected value.
  834. if(sMinV >= max/2){
  835. bar.style.background = '#e86060'
  836. } else if(sMinV >= max/4) {
  837. bar.style.background = '#e8e18b'
  838. } else {
  839. bar.style.background = null
  840. }
  841. // Increase maximum memory if the minimum exceeds its value.
  842. if(sMaxV < sMinV){
  843. const sliderMeta = calculateRangeSliderMeta(settingsMaxRAMRange)
  844. updateRangedSlider(settingsMaxRAMRange, sMinV,
  845. ((sMinV-sliderMeta.min)/sliderMeta.step)*sliderMeta.inc)
  846. settingsMaxRAMLabel.innerHTML = sMinV.toFixed(1) + 'G'
  847. }
  848. // Update label
  849. settingsMinRAMLabel.innerHTML = sMinV.toFixed(1) + 'G'
  850. }
  851. // Bind on change event for max memory container.
  852. settingsMaxRAMRange.onchange = (e) => {
  853. // Current range values
  854. const sMaxV = Number(settingsMaxRAMRange.getAttribute('value'))
  855. const sMinV = Number(settingsMinRAMRange.getAttribute('value'))
  856. // Get reference to range bar.
  857. const bar = e.target.getElementsByClassName('rangeSliderBar')[0]
  858. // Calculate effective total memory.
  859. const max = (os.totalmem()-1000000000)/1000000000
  860. // Change range bar color based on the selected value.
  861. if(sMaxV >= max/2){
  862. bar.style.background = '#e86060'
  863. } else if(sMaxV >= max/4) {
  864. bar.style.background = '#e8e18b'
  865. } else {
  866. bar.style.background = null
  867. }
  868. // Decrease the minimum memory if the maximum value is less.
  869. if(sMaxV < sMinV){
  870. const sliderMeta = calculateRangeSliderMeta(settingsMaxRAMRange)
  871. updateRangedSlider(settingsMinRAMRange, sMaxV,
  872. ((sMaxV-sliderMeta.min)/sliderMeta.step)*sliderMeta.inc)
  873. settingsMinRAMLabel.innerHTML = sMaxV.toFixed(1) + 'G'
  874. }
  875. settingsMaxRAMLabel.innerHTML = sMaxV.toFixed(1) + 'G'
  876. }
  877. /**
  878. * Calculate common values for a ranged slider.
  879. *
  880. * @param {Element} v The range slider to calculate against.
  881. * @returns {Object} An object with meta values for the provided ranged slider.
  882. */
  883. function calculateRangeSliderMeta(v){
  884. const val = {
  885. max: Number(v.getAttribute('max')),
  886. min: Number(v.getAttribute('min')),
  887. step: Number(v.getAttribute('step')),
  888. }
  889. val.ticks = (val.max-val.min)/val.step
  890. val.inc = 100/val.ticks
  891. return val
  892. }
  893. /**
  894. * Binds functionality to the ranged sliders. They're more than
  895. * just divs now :').
  896. */
  897. function bindRangeSlider(){
  898. Array.from(document.getElementsByClassName('rangeSlider')).map((v) => {
  899. // Reference the track (thumb).
  900. const track = v.getElementsByClassName('rangeSliderTrack')[0]
  901. // Set the initial slider value.
  902. const value = v.getAttribute('value')
  903. const sliderMeta = calculateRangeSliderMeta(v)
  904. updateRangedSlider(v, value, ((value-sliderMeta.min)/sliderMeta.step)*sliderMeta.inc)
  905. // The magic happens when we click on the track.
  906. track.onmousedown = (e) => {
  907. // Stop moving the track on mouse up.
  908. document.onmouseup = (e) => {
  909. document.onmousemove = null
  910. document.onmouseup = null
  911. }
  912. // Move slider according to the mouse position.
  913. document.onmousemove = (e) => {
  914. // Distance from the beginning of the bar in pixels.
  915. const diff = e.pageX - v.offsetLeft - track.offsetWidth/2
  916. // Don't move the track off the bar.
  917. if(diff >= 0 && diff <= v.offsetWidth-track.offsetWidth/2){
  918. // Convert the difference to a percentage.
  919. const perc = (diff/v.offsetWidth)*100
  920. // Calculate the percentage of the closest notch.
  921. const notch = Number(perc/sliderMeta.inc).toFixed(0)*sliderMeta.inc
  922. // If we're close to that notch, stick to it.
  923. if(Math.abs(perc-notch) < sliderMeta.inc/2){
  924. updateRangedSlider(v, sliderMeta.min+(sliderMeta.step*(notch/sliderMeta.inc)), notch)
  925. }
  926. }
  927. }
  928. }
  929. })
  930. }
  931. /**
  932. * Update a ranged slider's value and position.
  933. *
  934. * @param {Element} element The ranged slider to update.
  935. * @param {string | number} value The new value for the ranged slider.
  936. * @param {number} notch The notch that the slider should now be at.
  937. */
  938. function updateRangedSlider(element, value, notch){
  939. const oldVal = element.getAttribute('value')
  940. const bar = element.getElementsByClassName('rangeSliderBar')[0]
  941. const track = element.getElementsByClassName('rangeSliderTrack')[0]
  942. element.setAttribute('value', value)
  943. if(notch < 0){
  944. notch = 0
  945. } else if(notch > 100) {
  946. notch = 100
  947. }
  948. const event = new MouseEvent('change', {
  949. target: element,
  950. type: 'change',
  951. bubbles: false,
  952. cancelable: true
  953. })
  954. let cancelled = !element.dispatchEvent(event)
  955. if(!cancelled){
  956. track.style.left = notch + '%'
  957. bar.style.width = notch + '%'
  958. } else {
  959. element.setAttribute('value', oldVal)
  960. }
  961. }
  962. /**
  963. * Display the total and available RAM.
  964. */
  965. function populateMemoryStatus(){
  966. settingsMemoryTotal.innerHTML = Number((os.totalmem()-1000000000)/1000000000).toFixed(1) + 'G'
  967. settingsMemoryAvail.innerHTML = Number(os.freemem()/1000000000).toFixed(1) + 'G'
  968. }
  969. // Bind the executable file input to the display text input.
  970. settingsJavaExecSel.onchange = (e) => {
  971. settingsJavaExecVal.value = settingsJavaExecSel.files[0].path
  972. populateJavaExecDetails(settingsJavaExecVal.value)
  973. }
  974. /**
  975. * Validate the provided executable path and display the data on
  976. * the UI.
  977. *
  978. * @param {string} execPath The executable path to populate against.
  979. */
  980. function populateJavaExecDetails(execPath){
  981. AssetGuard._validateJavaBinary(execPath).then(v => {
  982. if(v.valid){
  983. if(v.version.major < 9) {
  984. settingsJavaExecDetails.innerHTML = `Selected: Java ${v.version.major} Update ${v.version.update} (x${v.arch})`
  985. } else {
  986. settingsJavaExecDetails.innerHTML = `Selected: Java ${v.version.major}.${v.version.minor}.${v.version.revision} (x${v.arch})`
  987. }
  988. } else {
  989. settingsJavaExecDetails.innerHTML = 'Invalid Selection'
  990. }
  991. })
  992. }
  993. /**
  994. * Prepare the Java tab for display.
  995. */
  996. function prepareJavaTab(){
  997. bindRangeSlider()
  998. populateMemoryStatus()
  999. }
  1000. /**
  1001. * About Tab
  1002. */
  1003. const settingsTabAbout = document.getElementById('settingsTabAbout')
  1004. const settingsAboutChangelogTitle = settingsTabAbout.getElementsByClassName('settingsChangelogTitle')[0]
  1005. const settingsAboutChangelogText = settingsTabAbout.getElementsByClassName('settingsChangelogText')[0]
  1006. const settingsAboutChangelogButton = settingsTabAbout.getElementsByClassName('settingsChangelogButton')[0]
  1007. // Bind the devtools toggle button.
  1008. document.getElementById('settingsAboutDevToolsButton').onclick = (e) => {
  1009. let window = remote.getCurrentWindow()
  1010. window.toggleDevTools()
  1011. }
  1012. /**
  1013. * Return whether or not the provided version is a prerelease.
  1014. *
  1015. * @param {string} version The semver version to test.
  1016. * @returns {boolean} True if the version is a prerelease, otherwise false.
  1017. */
  1018. function isPrerelease(version){
  1019. const preRelComp = semver.prerelease(version)
  1020. return preRelComp != null && preRelComp.length > 0
  1021. }
  1022. /**
  1023. * Utility method to display version information on the
  1024. * About and Update settings tabs.
  1025. *
  1026. * @param {string} version The semver version to display.
  1027. * @param {Element} valueElement The value element.
  1028. * @param {Element} titleElement The title element.
  1029. * @param {Element} checkElement The check mark element.
  1030. */
  1031. function populateVersionInformation(version, valueElement, titleElement, checkElement){
  1032. valueElement.innerHTML = version
  1033. if(isPrerelease(version)){
  1034. titleElement.innerHTML = 'Pre-release'
  1035. titleElement.style.color = '#ff886d'
  1036. checkElement.style.background = '#ff886d'
  1037. } else {
  1038. titleElement.innerHTML = 'Stable Release'
  1039. titleElement.style.color = null
  1040. checkElement.style.background = null
  1041. }
  1042. }
  1043. /**
  1044. * Retrieve the version information and display it on the UI.
  1045. */
  1046. function populateAboutVersionInformation(){
  1047. populateVersionInformation(remote.app.getVersion(), document.getElementById('settingsAboutCurrentVersionValue'), document.getElementById('settingsAboutCurrentVersionTitle'), document.getElementById('settingsAboutCurrentVersionCheck'))
  1048. }
  1049. /**
  1050. * Fetches the GitHub atom release feed and parses it for the release notes
  1051. * of the current version. This value is displayed on the UI.
  1052. */
  1053. function populateReleaseNotes(){
  1054. $.ajax({
  1055. url: 'https://github.com/WesterosCraftCode/ElectronLauncher/releases.atom',
  1056. success: (data) => {
  1057. const version = 'v' + remote.app.getVersion()
  1058. const entries = $(data).find('entry')
  1059. for(let i=0; i<entries.length; i++){
  1060. const entry = $(entries[i])
  1061. let id = entry.find('id').text()
  1062. id = id.substring(id.lastIndexOf('/')+1)
  1063. if(id === version){
  1064. settingsAboutChangelogTitle.innerHTML = entry.find('title').text()
  1065. settingsAboutChangelogText.innerHTML = entry.find('content').text()
  1066. settingsAboutChangelogButton.href = entry.find('link').attr('href')
  1067. }
  1068. }
  1069. },
  1070. timeout: 2500
  1071. }).catch(err => {
  1072. settingsAboutChangelogText.innerHTML = 'Failed to load release notes.'
  1073. })
  1074. }
  1075. /**
  1076. * Prepare account tab for display.
  1077. */
  1078. function prepareAboutTab(){
  1079. populateAboutVersionInformation()
  1080. populateReleaseNotes()
  1081. }
  1082. /**
  1083. * Update Tab
  1084. */
  1085. const settingsTabUpdate = document.getElementById('settingsTabUpdate')
  1086. const settingsUpdateTitle = document.getElementById('settingsUpdateTitle')
  1087. const settingsUpdateVersionCheck = document.getElementById('settingsUpdateVersionCheck')
  1088. const settingsUpdateVersionTitle = document.getElementById('settingsUpdateVersionTitle')
  1089. const settingsUpdateVersionValue = document.getElementById('settingsUpdateVersionValue')
  1090. const settingsUpdateChangelogTitle = settingsTabUpdate.getElementsByClassName('settingsChangelogTitle')[0]
  1091. const settingsUpdateChangelogText = settingsTabUpdate.getElementsByClassName('settingsChangelogText')[0]
  1092. const settingsUpdateChangelogCont = settingsTabUpdate.getElementsByClassName('settingsChangelogContainer')[0]
  1093. const settingsUpdateActionButton = document.getElementById('settingsUpdateActionButton')
  1094. /**
  1095. * Update the properties of the update action button.
  1096. *
  1097. * @param {string} text The new button text.
  1098. * @param {boolean} disabled Optional. Disable or enable the button
  1099. * @param {function} handler Optional. New button event handler.
  1100. */
  1101. function settingsUpdateButtonStatus(text, disabled = false, handler = null){
  1102. settingsUpdateActionButton.innerHTML = text
  1103. settingsUpdateActionButton.disabled = disabled
  1104. if(handler != null){
  1105. settingsUpdateActionButton.onclick = handler
  1106. }
  1107. }
  1108. /**
  1109. * Populate the update tab with relevant information.
  1110. *
  1111. * @param {Object} data The update data.
  1112. */
  1113. function populateSettingsUpdateInformation(data){
  1114. if(data != null){
  1115. settingsUpdateTitle.innerHTML = `New ${isPrerelease(data.version) ? 'Pre-release' : 'Release'} Available`
  1116. settingsUpdateChangelogCont.style.display = null
  1117. settingsUpdateChangelogTitle.innerHTML = data.releaseName
  1118. settingsUpdateChangelogText.innerHTML = data.releaseNotes
  1119. populateVersionInformation(data.version, settingsUpdateVersionValue, settingsUpdateVersionTitle, settingsUpdateVersionCheck)
  1120. if(process.platform === 'darwin'){
  1121. 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, () => {
  1122. shell.openExternal(data.darwindownload)
  1123. })
  1124. } else {
  1125. settingsUpdateButtonStatus('Downloading..', true)
  1126. }
  1127. } else {
  1128. settingsUpdateTitle.innerHTML = 'You Are Running the Latest Version'
  1129. settingsUpdateChangelogCont.style.display = 'none'
  1130. populateVersionInformation(remote.app.getVersion(), settingsUpdateVersionValue, settingsUpdateVersionTitle, settingsUpdateVersionCheck)
  1131. settingsUpdateButtonStatus('Check for Updates', false, () => {
  1132. if(!isDev){
  1133. ipcRenderer.send('autoUpdateAction', 'checkForUpdate')
  1134. settingsUpdateButtonStatus('Checking for Updates..', true)
  1135. }
  1136. })
  1137. }
  1138. }
  1139. /**
  1140. * Prepare update tab for display.
  1141. *
  1142. * @param {Object} data The update data.
  1143. */
  1144. function prepareUpdateTab(data = null){
  1145. populateSettingsUpdateInformation(data)
  1146. }
  1147. /**
  1148. * Settings preparation functions.
  1149. */
  1150. /**
  1151. * Prepare the entire settings UI.
  1152. *
  1153. * @param {boolean} first Whether or not it is the first load.
  1154. */
  1155. function prepareSettings(first = false) {
  1156. if(first){
  1157. setupSettingsTabs()
  1158. initSettingsValidators()
  1159. prepareUpdateTab()
  1160. } else {
  1161. prepareModsTab()
  1162. }
  1163. initSettingsValues()
  1164. prepareAccountsTab()
  1165. prepareJavaTab()
  1166. prepareAboutTab()
  1167. }
  1168. // Prepare the settings UI on startup.
  1169. prepareSettings(true)