settings.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  1. // Requirements
  2. const os = require('os')
  3. const semver = require('semver')
  4. const { AssetGuard } = require('./assets/js/assetguard')
  5. const settingsState = {
  6. invalid: new Set()
  7. }
  8. /**
  9. * General Settings Functions
  10. */
  11. /**
  12. * Bind value validators to the settings UI elements. These will
  13. * validate against the criteria defined in the ConfigManager (if
  14. * and). If the value is invalid, the UI will reflect this and saving
  15. * will be disabled until the value is corrected. This is an automated
  16. * process. More complex UI may need to be bound separately.
  17. */
  18. function initSettingsValidators(){
  19. const sEls = document.getElementById('settingsContainer').querySelectorAll('[cValue]')
  20. Array.from(sEls).map((v, index, arr) => {
  21. const vFn = ConfigManager['validate' + v.getAttribute('cValue')]
  22. if(typeof vFn === 'function'){
  23. if(v.tagName === 'INPUT'){
  24. if(v.type === 'number' || v.type === 'text'){
  25. v.addEventListener('keyup', (e) => {
  26. const v = e.target
  27. if(!vFn(v.value)){
  28. settingsState.invalid.add(v.id)
  29. v.setAttribute('error', '')
  30. settingsSaveDisabled(true)
  31. } else {
  32. if(v.hasAttribute('error')){
  33. v.removeAttribute('error')
  34. settingsState.invalid.delete(v.id)
  35. if(settingsState.invalid.size === 0){
  36. settingsSaveDisabled(false)
  37. }
  38. }
  39. }
  40. })
  41. }
  42. }
  43. }
  44. })
  45. }
  46. /**
  47. * Load configuration values onto the UI. This is an automated process.
  48. */
  49. function initSettingsValues(){
  50. const sEls = document.getElementById('settingsContainer').querySelectorAll('[cValue]')
  51. Array.from(sEls).map((v, index, arr) => {
  52. const gFn = ConfigManager['get' + v.getAttribute('cValue')]
  53. if(typeof gFn === 'function'){
  54. if(v.tagName === 'INPUT'){
  55. if(v.type === 'number' || v.type === 'text'){
  56. // Special Conditions
  57. const cVal = v.getAttribute('cValue')
  58. if(cVal === 'JavaExecutable'){
  59. populateJavaExecDetails(v.value)
  60. v.value = gFn()
  61. } else if(cVal === 'JVMOptions'){
  62. v.value = gFn().join(' ')
  63. } else {
  64. v.value = gFn()
  65. }
  66. } else if(v.type === 'checkbox'){
  67. v.checked = gFn()
  68. }
  69. } else if(v.tagName === 'DIV'){
  70. if(v.classList.contains('rangeSlider')){
  71. // Special Conditions
  72. const cVal = v.getAttribute('cValue')
  73. if(cVal === 'MinRAM' || cVal === 'MaxRAM'){
  74. let val = gFn()
  75. if(val.endsWith('M')){
  76. val = Number(val.substring(0, val.length-1))/1000
  77. } else {
  78. val = Number.parseFloat(val)
  79. }
  80. v.setAttribute('value', val)
  81. } else {
  82. v.setAttribute('value', Number.parseFloat(gFn()))
  83. }
  84. }
  85. }
  86. }
  87. })
  88. }
  89. /**
  90. * Save the settings values.
  91. */
  92. function saveSettingsValues(){
  93. const sEls = document.getElementById('settingsContainer').querySelectorAll('[cValue]')
  94. Array.from(sEls).map((v, index, arr) => {
  95. const sFn = ConfigManager['set' + v.getAttribute('cValue')]
  96. if(typeof sFn === 'function'){
  97. if(v.tagName === 'INPUT'){
  98. if(v.type === 'number' || v.type === 'text'){
  99. // Special Conditions
  100. const cVal = v.getAttribute('cValue')
  101. if(cVal === 'JVMOptions'){
  102. sFn(v.value.split(' '))
  103. } else {
  104. sFn(v.value)
  105. }
  106. } else if(v.type === 'checkbox'){
  107. sFn(v.checked)
  108. // Special Conditions
  109. const cVal = v.getAttribute('cValue')
  110. if(cVal === 'AllowPrerelease'){
  111. changeAllowPrerelease(v.checked)
  112. }
  113. }
  114. } else if(v.tagName === 'DIV'){
  115. if(v.classList.contains('rangeSlider')){
  116. // Special Conditions
  117. const cVal = v.getAttribute('cValue')
  118. if(cVal === 'MinRAM' || cVal === 'MaxRAM'){
  119. let val = Number(v.getAttribute('value'))
  120. if(val%1 > 0){
  121. val = val*1000 + 'M'
  122. } else {
  123. val = val + 'G'
  124. }
  125. sFn(val)
  126. } else {
  127. sFn(v.getAttribute('value'))
  128. }
  129. }
  130. }
  131. }
  132. })
  133. }
  134. let selectedSettingsTab = 'settingsTabAccount'
  135. /**
  136. * Modify the settings container UI when the scroll threshold reaches
  137. * a certain poin.
  138. *
  139. * @param {UIEvent} e The scroll event.
  140. */
  141. function settingsTabScrollListener(e){
  142. if(e.target.scrollTop > Number.parseFloat(getComputedStyle(e.target.firstElementChild).marginTop)){
  143. document.getElementById('settingsContainer').setAttribute('scrolled', '')
  144. } else {
  145. document.getElementById('settingsContainer').removeAttribute('scrolled')
  146. }
  147. }
  148. /**
  149. * Bind functionality for the settings navigation items.
  150. */
  151. function setupSettingsTabs(){
  152. Array.from(document.getElementsByClassName('settingsNavItem')).map((val) => {
  153. if(val.hasAttribute('rSc')){
  154. val.onclick = () => {
  155. settingsNavItemListener(val)
  156. }
  157. }
  158. })
  159. }
  160. /**
  161. * Settings nav item onclick lisener. Function is exposed so that
  162. * other UI elements can quickly toggle to a certain tab from other views.
  163. *
  164. * @param {Element} ele The nav item which has been clicked.
  165. * @param {boolean} fade Optional. True to fade transition.
  166. */
  167. function settingsNavItemListener(ele, fade = true){
  168. if(ele.hasAttribute('selected')){
  169. return
  170. }
  171. const navItems = document.getElementsByClassName('settingsNavItem')
  172. for(let i=0; i<navItems.length; i++){
  173. if(navItems[i].hasAttribute('selected')){
  174. navItems[i].removeAttribute('selected')
  175. }
  176. }
  177. ele.setAttribute('selected', '')
  178. let prevTab = selectedSettingsTab
  179. selectedSettingsTab = ele.getAttribute('rSc')
  180. document.getElementById(prevTab).onscroll = null
  181. document.getElementById(selectedSettingsTab).onscroll = settingsTabScrollListener
  182. if(fade){
  183. $(`#${prevTab}`).fadeOut(250, () => {
  184. $(`#${selectedSettingsTab}`).fadeIn({
  185. duration: 250,
  186. start: () => {
  187. settingsTabScrollListener({
  188. target: document.getElementById(selectedSettingsTab)
  189. })
  190. }
  191. })
  192. })
  193. } else {
  194. $(`#${prevTab}`).hide(0, () => {
  195. $(`#${selectedSettingsTab}`).show({
  196. duration: 0,
  197. start: () => {
  198. settingsTabScrollListener({
  199. target: document.getElementById(selectedSettingsTab)
  200. })
  201. }
  202. })
  203. })
  204. }
  205. }
  206. const settingsNavDone = document.getElementById('settingsNavDone')
  207. /**
  208. * Set if the settings save (done) button is disabled.
  209. *
  210. * @param {boolean} v True to disable, false to enable.
  211. */
  212. function settingsSaveDisabled(v){
  213. settingsNavDone.disabled = v
  214. }
  215. /* Closes the settings view and saves all data. */
  216. settingsNavDone.onclick = () => {
  217. saveSettingsValues()
  218. ConfigManager.save()
  219. switchView(getCurrentView(), VIEWS.landing)
  220. }
  221. /**
  222. * Account Management Tab
  223. */
  224. // Bind the add account button.
  225. document.getElementById('settingsAddAccount').onclick = (e) => {
  226. switchView(getCurrentView(), VIEWS.login, 500, 500, () => {
  227. loginViewOnCancel = VIEWS.settings
  228. loginViewOnSuccess = VIEWS.settings
  229. loginCancelEnabled(true)
  230. })
  231. }
  232. /**
  233. * Bind functionality for the account selection buttons. If another account
  234. * is selected, the UI of the previously selected account will be updated.
  235. */
  236. function bindAuthAccountSelect(){
  237. Array.from(document.getElementsByClassName('settingsAuthAccountSelect')).map((val) => {
  238. val.onclick = (e) => {
  239. if(val.hasAttribute('selected')){
  240. return
  241. }
  242. const selectBtns = document.getElementsByClassName('settingsAuthAccountSelect')
  243. for(let i=0; i<selectBtns.length; i++){
  244. if(selectBtns[i].hasAttribute('selected')){
  245. selectBtns[i].removeAttribute('selected')
  246. selectBtns[i].innerHTML = 'Select Account'
  247. }
  248. }
  249. val.setAttribute('selected', '')
  250. val.innerHTML = 'Selected Account &#10004;'
  251. setSelectedAccount(val.closest('.settingsAuthAccount').getAttribute('uuid'))
  252. }
  253. })
  254. }
  255. /**
  256. * Bind functionality for the log out button. If the logged out account was
  257. * the selected account, another account will be selected and the UI will
  258. * be updated accordingly.
  259. */
  260. function bindAuthAccountLogOut(){
  261. Array.from(document.getElementsByClassName('settingsAuthAccountLogOut')).map((val) => {
  262. val.onclick = (e) => {
  263. let isLastAccount = false
  264. if(Object.keys(ConfigManager.getAuthAccounts()).length === 1){
  265. isLastAccount = true
  266. setOverlayContent(
  267. 'Warning<br>This is Your Last Account',
  268. 'In order to use the launcher you must be logged into at least one account. You will need to login again after.<br><br>Are you sure you want to log out?',
  269. 'I\'m Sure',
  270. 'Cancel'
  271. )
  272. setOverlayHandler(() => {
  273. processLogOut(val, isLastAccount)
  274. switchView(getCurrentView(), VIEWS.login)
  275. toggleOverlay(false)
  276. })
  277. setDismissHandler(() => {
  278. toggleOverlay(false)
  279. })
  280. toggleOverlay(true, true)
  281. } else {
  282. processLogOut(val, isLastAccount)
  283. }
  284. }
  285. })
  286. }
  287. /**
  288. * Process a log out.
  289. *
  290. * @param {Element} val The log out button element.
  291. * @param {boolean} isLastAccount If this logout is on the last added account.
  292. */
  293. function processLogOut(val, isLastAccount){
  294. const parent = val.closest('.settingsAuthAccount')
  295. const uuid = parent.getAttribute('uuid')
  296. const prevSelAcc = ConfigManager.getSelectedAccount()
  297. AuthManager.removeAccount(uuid).then(() => {
  298. if(!isLastAccount && uuid === prevSelAcc.uuid){
  299. const selAcc = ConfigManager.getSelectedAccount()
  300. refreshAuthAccountSelected(selAcc.uuid)
  301. updateSelectedAccount(selAcc)
  302. validateSelectedAccount()
  303. }
  304. })
  305. $(parent).fadeOut(250, () => {
  306. parent.remove()
  307. })
  308. }
  309. /**
  310. * Refreshes the status of the selected account on the auth account
  311. * elements.
  312. *
  313. * @param {string} uuid The UUID of the new selected account.
  314. */
  315. function refreshAuthAccountSelected(uuid){
  316. Array.from(document.getElementsByClassName('settingsAuthAccount')).map((val) => {
  317. const selBtn = val.getElementsByClassName('settingsAuthAccountSelect')[0]
  318. if(uuid === val.getAttribute('uuid')){
  319. selBtn.setAttribute('selected', '')
  320. selBtn.innerHTML = 'Selected Account &#10004;'
  321. } else {
  322. if(selBtn.hasAttribute('selected')){
  323. selBtn.removeAttribute('selected')
  324. }
  325. selBtn.innerHTML = 'Select Account'
  326. }
  327. })
  328. }
  329. const settingsCurrentAccounts = document.getElementById('settingsCurrentAccounts')
  330. /**
  331. * Add auth account elements for each one stored in the authentication database.
  332. */
  333. function populateAuthAccounts(){
  334. const authAccounts = ConfigManager.getAuthAccounts()
  335. const authKeys = Object.keys(authAccounts)
  336. const selectedUUID = ConfigManager.getSelectedAccount().uuid
  337. let authAccountStr = ``
  338. authKeys.map((val) => {
  339. const acc = authAccounts[val]
  340. authAccountStr += `<div class="settingsAuthAccount" uuid="${acc.uuid}">
  341. <div class="settingsAuthAccountLeft">
  342. <img class="settingsAuthAccountImage" alt="${acc.displayName}" src="https://crafatar.com/renders/body/${acc.uuid}?scale=3&default=MHF_Steve&overlay">
  343. </div>
  344. <div class="settingsAuthAccountRight">
  345. <div class="settingsAuthAccountDetails">
  346. <div class="settingsAuthAccountDetailPane">
  347. <div class="settingsAuthAccountDetailTitle">Username</div>
  348. <div class="settingsAuthAccountDetailValue">${acc.displayName}</div>
  349. </div>
  350. <div class="settingsAuthAccountDetailPane">
  351. <div class="settingsAuthAccountDetailTitle">UUID</div>
  352. <div class="settingsAuthAccountDetailValue">${acc.uuid}</div>
  353. </div>
  354. </div>
  355. <div class="settingsAuthAccountActions">
  356. <button class="settingsAuthAccountSelect" ${selectedUUID === acc.uuid ? 'selected>Selected Account &#10004;' : '>Select Account'}</button>
  357. <div class="settingsAuthAccountWrapper">
  358. <button class="settingsAuthAccountLogOut">Log Out</button>
  359. </div>
  360. </div>
  361. </div>
  362. </div>`
  363. })
  364. settingsCurrentAccounts.innerHTML = authAccountStr
  365. }
  366. /**
  367. * Prepare the accounts tab for display.
  368. */
  369. function prepareAccountsTab() {
  370. populateAuthAccounts()
  371. bindAuthAccountSelect()
  372. bindAuthAccountLogOut()
  373. }
  374. /**
  375. * Minecraft Tab
  376. */
  377. /**
  378. * Disable decimals, negative signs, and scientific notation.
  379. */
  380. document.getElementById('settingsGameWidth').addEventListener('keydown', (e) => {
  381. if(/[-\.eE]/.test(e.key)){
  382. e.preventDefault()
  383. }
  384. })
  385. document.getElementById('settingsGameHeight').addEventListener('keydown', (e) => {
  386. if(/[-\.eE]/.test(e.key)){
  387. e.preventDefault()
  388. }
  389. })
  390. /**
  391. * Java Tab
  392. */
  393. // DOM Cache
  394. const settingsMaxRAMRange = document.getElementById('settingsMaxRAMRange')
  395. const settingsMinRAMRange = document.getElementById('settingsMinRAMRange')
  396. const settingsMaxRAMLabel = document.getElementById('settingsMaxRAMLabel')
  397. const settingsMinRAMLabel = document.getElementById('settingsMinRAMLabel')
  398. const settingsMemoryTotal = document.getElementById('settingsMemoryTotal')
  399. const settingsMemoryAvail = document.getElementById('settingsMemoryAvail')
  400. const settingsJavaExecDetails = document.getElementById('settingsJavaExecDetails')
  401. const settingsJavaExecVal = document.getElementById('settingsJavaExecVal')
  402. const settingsJavaExecSel = document.getElementById('settingsJavaExecSel')
  403. // Store maximum memory values.
  404. const SETTINGS_MAX_MEMORY = ConfigManager.getAbsoluteMaxRAM()
  405. const SETTINGS_MIN_MEMORY = ConfigManager.getAbsoluteMinRAM()
  406. // Set the max and min values for the ranged sliders.
  407. settingsMaxRAMRange.setAttribute('max', SETTINGS_MAX_MEMORY)
  408. settingsMaxRAMRange.setAttribute('min', SETTINGS_MIN_MEMORY)
  409. settingsMinRAMRange.setAttribute('max', SETTINGS_MAX_MEMORY)
  410. settingsMinRAMRange.setAttribute('min', SETTINGS_MIN_MEMORY )
  411. // Bind on change event for min memory container.
  412. settingsMinRAMRange.onchange = (e) => {
  413. // Current range values
  414. const sMaxV = Number(settingsMaxRAMRange.getAttribute('value'))
  415. const sMinV = Number(settingsMinRAMRange.getAttribute('value'))
  416. // Get reference to range bar.
  417. const bar = e.target.getElementsByClassName('rangeSliderBar')[0]
  418. // Calculate effective total memory.
  419. const max = (os.totalmem()-1000000000)/1000000000
  420. // Change range bar color based on the selected value.
  421. if(sMinV >= max/2){
  422. bar.style.background = '#e86060'
  423. } else if(sMinV >= max/4) {
  424. bar.style.background = '#e8e18b'
  425. } else {
  426. bar.style.background = null
  427. }
  428. // Increase maximum memory if the minimum exceeds its value.
  429. if(sMaxV < sMinV){
  430. const sliderMeta = calculateRangeSliderMeta(settingsMaxRAMRange)
  431. updateRangedSlider(settingsMaxRAMRange, sMinV,
  432. ((sMinV-sliderMeta.min)/sliderMeta.step)*sliderMeta.inc)
  433. settingsMaxRAMLabel.innerHTML = sMinV.toFixed(1) + 'G'
  434. }
  435. // Update label
  436. settingsMinRAMLabel.innerHTML = sMinV.toFixed(1) + 'G'
  437. }
  438. // Bind on change event for max memory container.
  439. settingsMaxRAMRange.onchange = (e) => {
  440. // Current range values
  441. const sMaxV = Number(settingsMaxRAMRange.getAttribute('value'))
  442. const sMinV = Number(settingsMinRAMRange.getAttribute('value'))
  443. // Get reference to range bar.
  444. const bar = e.target.getElementsByClassName('rangeSliderBar')[0]
  445. // Calculate effective total memory.
  446. const max = (os.totalmem()-1000000000)/1000000000
  447. // Change range bar color based on the selected value.
  448. if(sMaxV >= max/2){
  449. bar.style.background = '#e86060'
  450. } else if(sMaxV >= max/4) {
  451. bar.style.background = '#e8e18b'
  452. } else {
  453. bar.style.background = null
  454. }
  455. // Decrease the minimum memory if the maximum value is less.
  456. if(sMaxV < sMinV){
  457. const sliderMeta = calculateRangeSliderMeta(settingsMaxRAMRange)
  458. updateRangedSlider(settingsMinRAMRange, sMaxV,
  459. ((sMaxV-sliderMeta.min)/sliderMeta.step)*sliderMeta.inc)
  460. settingsMinRAMLabel.innerHTML = sMaxV.toFixed(1) + 'G'
  461. }
  462. settingsMaxRAMLabel.innerHTML = sMaxV.toFixed(1) + 'G'
  463. }
  464. /**
  465. * Calculate common values for a ranged slider.
  466. *
  467. * @param {Element} v The range slider to calculate against.
  468. * @returns {Object} An object with meta values for the provided ranged slider.
  469. */
  470. function calculateRangeSliderMeta(v){
  471. const val = {
  472. max: Number(v.getAttribute('max')),
  473. min: Number(v.getAttribute('min')),
  474. step: Number(v.getAttribute('step')),
  475. }
  476. val.ticks = (val.max-val.min)/val.step
  477. val.inc = 100/val.ticks
  478. return val
  479. }
  480. /**
  481. * Binds functionality to the ranged sliders. They're more than
  482. * just divs now :').
  483. */
  484. function bindRangeSlider(){
  485. Array.from(document.getElementsByClassName('rangeSlider')).map((v) => {
  486. // Reference the track (thumb).
  487. const track = v.getElementsByClassName('rangeSliderTrack')[0]
  488. // Set the initial slider value.
  489. const value = v.getAttribute('value')
  490. const sliderMeta = calculateRangeSliderMeta(v)
  491. updateRangedSlider(v, value, ((value-sliderMeta.min)/sliderMeta.step)*sliderMeta.inc)
  492. // The magic happens when we click on the track.
  493. track.onmousedown = (e) => {
  494. // Stop moving the track on mouse up.
  495. document.onmouseup = (e) => {
  496. document.onmousemove = null
  497. document.onmouseup = null
  498. }
  499. // Move slider according to the mouse position.
  500. document.onmousemove = (e) => {
  501. // Distance from the beginning of the bar in pixels.
  502. const diff = e.pageX - v.offsetLeft - track.offsetWidth/2
  503. // Don't move the track off the bar.
  504. if(diff >= 0 && diff <= v.offsetWidth-track.offsetWidth/2){
  505. // Convert the difference to a percentage.
  506. const perc = (diff/v.offsetWidth)*100
  507. // Calculate the percentage of the closest notch.
  508. const notch = Number(perc/sliderMeta.inc).toFixed(0)*sliderMeta.inc
  509. // If we're close to that notch, stick to it.
  510. if(Math.abs(perc-notch) < sliderMeta.inc/2){
  511. updateRangedSlider(v, sliderMeta.min+(sliderMeta.step*(notch/sliderMeta.inc)), notch)
  512. }
  513. }
  514. }
  515. }
  516. })
  517. }
  518. /**
  519. * Update a ranged slider's value and position.
  520. *
  521. * @param {Element} element The ranged slider to update.
  522. * @param {string | number} value The new value for the ranged slider.
  523. * @param {number} notch The notch that the slider should now be at.
  524. */
  525. function updateRangedSlider(element, value, notch){
  526. const oldVal = element.getAttribute('value')
  527. const bar = element.getElementsByClassName('rangeSliderBar')[0]
  528. const track = element.getElementsByClassName('rangeSliderTrack')[0]
  529. element.setAttribute('value', value)
  530. if(notch < 0){
  531. notch = 0
  532. } else if(notch > 100) {
  533. notch = 100
  534. }
  535. const event = new MouseEvent('change', {
  536. target: element,
  537. type: 'change',
  538. bubbles: false,
  539. cancelable: true
  540. })
  541. let cancelled = !element.dispatchEvent(event)
  542. if(!cancelled){
  543. track.style.left = notch + '%'
  544. bar.style.width = notch + '%'
  545. } else {
  546. element.setAttribute('value', oldVal)
  547. }
  548. }
  549. /**
  550. * Display the total and available RAM.
  551. */
  552. function populateMemoryStatus(){
  553. settingsMemoryTotal.innerHTML = Number((os.totalmem()-1000000000)/1000000000).toFixed(1) + 'G'
  554. settingsMemoryAvail.innerHTML = Number(os.freemem()/1000000000).toFixed(1) + 'G'
  555. }
  556. // Bind the executable file input to the display text input.
  557. settingsJavaExecSel.onchange = (e) => {
  558. settingsJavaExecVal.value = settingsJavaExecSel.files[0].path
  559. populateJavaExecDetails(settingsJavaExecVal.value)
  560. }
  561. /**
  562. * Validate the provided executable path and display the data on
  563. * the UI.
  564. *
  565. * @param {string} execPath The executable path to populate against.
  566. */
  567. function populateJavaExecDetails(execPath){
  568. AssetGuard._validateJavaBinary(execPath).then(v => {
  569. if(v.valid){
  570. settingsJavaExecDetails.innerHTML = `Selected: Java ${v.version.major} Update ${v.version.update} (x${v.arch})`
  571. } else {
  572. settingsJavaExecDetails.innerHTML = 'Invalid Selection'
  573. }
  574. })
  575. }
  576. /**
  577. * Prepare the Java tab for display.
  578. */
  579. function prepareJavaTab(){
  580. bindRangeSlider()
  581. populateMemoryStatus()
  582. }
  583. /**
  584. * About Tab
  585. */
  586. const settingsAboutCurrentVersionCheck = document.getElementById('settingsAboutCurrentVersionCheck')
  587. const settingsAboutCurrentVersionTitle = document.getElementById('settingsAboutCurrentVersionTitle')
  588. const settingsAboutCurrentVersionValue = document.getElementById('settingsAboutCurrentVersionValue')
  589. const settingsChangelogTitle = document.getElementById('settingsChangelogTitle')
  590. const settingsChangelogText = document.getElementById('settingsChangelogText')
  591. const settingsChangelogButton = document.getElementById('settingsChangelogButton')
  592. // Bind the devtools toggle button.
  593. document.getElementById('settingsAboutDevToolsButton').onclick = (e) => {
  594. let window = remote.getCurrentWindow()
  595. window.toggleDevTools()
  596. }
  597. /**
  598. * Retrieve the version information and display it on the UI.
  599. */
  600. function populateVersionInformation(){
  601. const version = remote.app.getVersion()
  602. settingsAboutCurrentVersionValue.innerHTML = version
  603. const preRelComp = semver.prerelease(version)
  604. if(preRelComp != null && preRelComp.length > 0){
  605. settingsAboutCurrentVersionTitle.innerHTML = 'Pre-release'
  606. settingsAboutCurrentVersionTitle.style.color = '#ff886d'
  607. settingsAboutCurrentVersionCheck.style.background = '#ff886d'
  608. } else {
  609. settingsAboutCurrentVersionTitle.innerHTML = 'Stable Release'
  610. settingsAboutCurrentVersionTitle.style.color = null
  611. settingsAboutCurrentVersionCheck.style.background = null
  612. }
  613. }
  614. /**
  615. * Fetches the GitHub atom release feed and parses it for the release notes
  616. * of the current version. This value is displayed on the UI.
  617. */
  618. function populateReleaseNotes(){
  619. $.ajax({
  620. url: 'https://github.com/WesterosCraftCode/ElectronLauncher/releases.atom',
  621. success: (data) => {
  622. const version = 'v' + remote.app.getVersion()
  623. const entries = $(data).find('entry')
  624. for(let i=0; i<entries.length; i++){
  625. const entry = $(entries[i])
  626. let id = entry.find('id').text()
  627. id = id.substring(id.lastIndexOf('/')+1)
  628. if(id === version){
  629. settingsChangelogTitle.innerHTML = entry.find('title').text()
  630. settingsChangelogText.innerHTML = entry.find('content').text()
  631. settingsChangelogButton.href = entry.find('link').attr('href')
  632. }
  633. }
  634. },
  635. timeout: 2500
  636. }).catch(err => {
  637. settingsChangelogText.innerHTML = 'Failed to load release notes.'
  638. })
  639. }
  640. /**
  641. * Prepare account tab for display.
  642. */
  643. function prepareAboutTab(){
  644. populateVersionInformation()
  645. populateReleaseNotes()
  646. }
  647. /**
  648. * Settings preparation functions.
  649. */
  650. /**
  651. * Prepare the entire settings UI.
  652. *
  653. * @param {boolean} first Whether or not it is the first load.
  654. */
  655. function prepareSettings(first = false) {
  656. if(first){
  657. setupSettingsTabs()
  658. initSettingsValidators()
  659. }
  660. initSettingsValues()
  661. prepareAccountsTab()
  662. prepareJavaTab()
  663. prepareAboutTab()
  664. }
  665. // Prepare the settings UI on startup.
  666. prepareSettings(true)