settings.js 25 KB

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