settings.js 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313
  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. settingsJavaExecDetails.innerHTML = `Selected: Java ${v.version.major} Update ${v.version.update} (x${v.arch})`
  984. } else {
  985. settingsJavaExecDetails.innerHTML = 'Invalid Selection'
  986. }
  987. })
  988. }
  989. /**
  990. * Prepare the Java tab for display.
  991. */
  992. function prepareJavaTab(){
  993. bindRangeSlider()
  994. populateMemoryStatus()
  995. }
  996. /**
  997. * About Tab
  998. */
  999. const settingsTabAbout = document.getElementById('settingsTabAbout')
  1000. const settingsAboutChangelogTitle = settingsTabAbout.getElementsByClassName('settingsChangelogTitle')[0]
  1001. const settingsAboutChangelogText = settingsTabAbout.getElementsByClassName('settingsChangelogText')[0]
  1002. const settingsAboutChangelogButton = settingsTabAbout.getElementsByClassName('settingsChangelogButton')[0]
  1003. // Bind the devtools toggle button.
  1004. document.getElementById('settingsAboutDevToolsButton').onclick = (e) => {
  1005. let window = remote.getCurrentWindow()
  1006. window.toggleDevTools()
  1007. }
  1008. /**
  1009. * Return whether or not the provided version is a prerelease.
  1010. *
  1011. * @param {string} version The semver version to test.
  1012. * @returns {boolean} True if the version is a prerelease, otherwise false.
  1013. */
  1014. function isPrerelease(version){
  1015. const preRelComp = semver.prerelease(version)
  1016. return preRelComp != null && preRelComp.length > 0
  1017. }
  1018. /**
  1019. * Utility method to display version information on the
  1020. * About and Update settings tabs.
  1021. *
  1022. * @param {string} version The semver version to display.
  1023. * @param {Element} valueElement The value element.
  1024. * @param {Element} titleElement The title element.
  1025. * @param {Element} checkElement The check mark element.
  1026. */
  1027. function populateVersionInformation(version, valueElement, titleElement, checkElement){
  1028. valueElement.innerHTML = version
  1029. if(isPrerelease(version)){
  1030. titleElement.innerHTML = 'Pre-release'
  1031. titleElement.style.color = '#ff886d'
  1032. checkElement.style.background = '#ff886d'
  1033. } else {
  1034. titleElement.innerHTML = 'Stable Release'
  1035. titleElement.style.color = null
  1036. checkElement.style.background = null
  1037. }
  1038. }
  1039. /**
  1040. * Retrieve the version information and display it on the UI.
  1041. */
  1042. function populateAboutVersionInformation(){
  1043. populateVersionInformation(remote.app.getVersion(), document.getElementById('settingsAboutCurrentVersionValue'), document.getElementById('settingsAboutCurrentVersionTitle'), document.getElementById('settingsAboutCurrentVersionCheck'))
  1044. }
  1045. /**
  1046. * Fetches the GitHub atom release feed and parses it for the release notes
  1047. * of the current version. This value is displayed on the UI.
  1048. */
  1049. function populateReleaseNotes(){
  1050. $.ajax({
  1051. url: 'https://github.com/WesterosCraftCode/ElectronLauncher/releases.atom',
  1052. success: (data) => {
  1053. const version = 'v' + remote.app.getVersion()
  1054. const entries = $(data).find('entry')
  1055. for(let i=0; i<entries.length; i++){
  1056. const entry = $(entries[i])
  1057. let id = entry.find('id').text()
  1058. id = id.substring(id.lastIndexOf('/')+1)
  1059. if(id === version){
  1060. settingsAboutChangelogTitle.innerHTML = entry.find('title').text()
  1061. settingsAboutChangelogText.innerHTML = entry.find('content').text()
  1062. settingsAboutChangelogButton.href = entry.find('link').attr('href')
  1063. }
  1064. }
  1065. },
  1066. timeout: 2500
  1067. }).catch(err => {
  1068. settingsAboutChangelogText.innerHTML = 'Failed to load release notes.'
  1069. })
  1070. }
  1071. /**
  1072. * Prepare account tab for display.
  1073. */
  1074. function prepareAboutTab(){
  1075. populateAboutVersionInformation()
  1076. populateReleaseNotes()
  1077. }
  1078. /**
  1079. * Update Tab
  1080. */
  1081. const settingsTabUpdate = document.getElementById('settingsTabUpdate')
  1082. const settingsUpdateTitle = document.getElementById('settingsUpdateTitle')
  1083. const settingsUpdateVersionCheck = document.getElementById('settingsUpdateVersionCheck')
  1084. const settingsUpdateVersionTitle = document.getElementById('settingsUpdateVersionTitle')
  1085. const settingsUpdateVersionValue = document.getElementById('settingsUpdateVersionValue')
  1086. const settingsUpdateChangelogTitle = settingsTabUpdate.getElementsByClassName('settingsChangelogTitle')[0]
  1087. const settingsUpdateChangelogText = settingsTabUpdate.getElementsByClassName('settingsChangelogText')[0]
  1088. const settingsUpdateChangelogCont = settingsTabUpdate.getElementsByClassName('settingsChangelogContainer')[0]
  1089. const settingsUpdateActionButton = document.getElementById('settingsUpdateActionButton')
  1090. /**
  1091. * Update the properties of the update action button.
  1092. *
  1093. * @param {string} text The new button text.
  1094. * @param {boolean} disabled Optional. Disable or enable the button
  1095. * @param {function} handler Optional. New button event handler.
  1096. */
  1097. function settingsUpdateButtonStatus(text, disabled = false, handler = null){
  1098. settingsUpdateActionButton.innerHTML = text
  1099. settingsUpdateActionButton.disabled = disabled
  1100. if(handler != null){
  1101. settingsUpdateActionButton.onclick = handler
  1102. }
  1103. }
  1104. /**
  1105. * Populate the update tab with relevant information.
  1106. *
  1107. * @param {Object} data The update data.
  1108. */
  1109. function populateSettingsUpdateInformation(data){
  1110. if(data != null){
  1111. settingsUpdateTitle.innerHTML = `New ${isPrerelease(data.version) ? 'Pre-release' : 'Release'} Available`
  1112. settingsUpdateChangelogCont.style.display = null
  1113. settingsUpdateChangelogTitle.innerHTML = data.releaseName
  1114. settingsUpdateChangelogText.innerHTML = data.releaseNotes
  1115. populateVersionInformation(data.version, settingsUpdateVersionValue, settingsUpdateVersionTitle, settingsUpdateVersionCheck)
  1116. if(process.platform === 'darwin'){
  1117. 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, () => {
  1118. shell.openExternal(data.darwindownload)
  1119. })
  1120. } else {
  1121. settingsUpdateButtonStatus('Downloading..', true)
  1122. }
  1123. } else {
  1124. settingsUpdateTitle.innerHTML = 'You Are Running the Latest Version'
  1125. settingsUpdateChangelogCont.style.display = 'none'
  1126. populateVersionInformation(remote.app.getVersion(), settingsUpdateVersionValue, settingsUpdateVersionTitle, settingsUpdateVersionCheck)
  1127. settingsUpdateButtonStatus('Check for Updates', false, () => {
  1128. if(!isDev){
  1129. ipcRenderer.send('autoUpdateAction', 'checkForUpdate')
  1130. settingsUpdateButtonStatus('Checking for Updates..', true)
  1131. }
  1132. })
  1133. }
  1134. }
  1135. /**
  1136. * Prepare update tab for display.
  1137. *
  1138. * @param {Object} data The update data.
  1139. */
  1140. function prepareUpdateTab(data = null){
  1141. populateSettingsUpdateInformation(data)
  1142. }
  1143. /**
  1144. * Settings preparation functions.
  1145. */
  1146. /**
  1147. * Prepare the entire settings UI.
  1148. *
  1149. * @param {boolean} first Whether or not it is the first load.
  1150. */
  1151. function prepareSettings(first = false) {
  1152. if(first){
  1153. setupSettingsTabs()
  1154. initSettingsValidators()
  1155. prepareUpdateTab()
  1156. } else {
  1157. prepareModsTab()
  1158. }
  1159. initSettingsValues()
  1160. prepareAccountsTab()
  1161. prepareJavaTab()
  1162. prepareAboutTab()
  1163. }
  1164. // Prepare the settings UI on startup.
  1165. prepareSettings(true)