settings.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843
  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. * Mods Tab
  392. */
  393. function resolveModsForUI(){
  394. const serv = ConfigManager.getSelectedServer()
  395. const distro = DistroManager.getDistribution()
  396. const servConf = ConfigManager.getModConfiguration(serv)
  397. const modStr = parseModulesForUI(distro.getServer(serv).getModules(), false, servConf.mods)
  398. document.getElementById('settingsReqModsContent').innerHTML = modStr.reqMods
  399. document.getElementById('settingsOptModsContent').innerHTML = modStr.optMods
  400. }
  401. function parseModulesForUI(mdls, submodules = false, servConf){
  402. let reqMods = ''
  403. let optMods = ''
  404. for(const mdl of mdls){
  405. if(mdl.getType() === DistroManager.Types.ForgeMod || mdl.getType() === DistroManager.Types.LiteMod || mdl.getType() === DistroManager.Types.LiteLoader){
  406. if(mdl.getRequired().isRequired()){
  407. reqMods += `<div id="${mdl.getVersionlessID()}" class="settings${submodules ? 'Sub' : ''}Mod" enabled>
  408. <div class="settingsModContent">
  409. <div class="settingsModMainWrapper">
  410. <div class="settingsModStatus"></div>
  411. <div class="settingsModDetails">
  412. <span class="settingsModName">${mdl.getName()}</span>
  413. <span class="settingsModVersion">v${mdl.getVersion()}</span>
  414. </div>
  415. </div>
  416. <label class="toggleSwitch" reqmod>
  417. <input type="checkbox" checked>
  418. <span class="toggleSwitchSlider"></span>
  419. </label>
  420. </div>
  421. ${mdl.hasSubModules() ? `<div class="settingsSubModContainer">
  422. ${Object.values(parseModulesForUI(mdl.getSubModules(), true)).join('')}
  423. </div>` : ''}
  424. </div>`
  425. } else {
  426. const conf = servConf[mdl.getVersionlessID()]
  427. const val = typeof conf === 'object' ? conf.value : conf
  428. optMods += `<div id="${mdl.getVersionlessID()}" class="settings${submodules ? 'Sub' : ''}Mod" ${val ? 'enabled' : ''}>
  429. <div class="settingsModContent">
  430. <div class="settingsModMainWrapper">
  431. <div class="settingsModStatus"></div>
  432. <div class="settingsModDetails">
  433. <span class="settingsModName">${mdl.getName()}</span>
  434. <span class="settingsModVersion">v${mdl.getVersion()}</span>
  435. </div>
  436. </div>
  437. <label class="toggleSwitch">
  438. <input type="checkbox" ${val ? 'checked' : ''}>
  439. <span class="toggleSwitchSlider"></span>
  440. </label>
  441. </div>
  442. ${mdl.hasSubModules() ? `<div class="settingsSubModContainer">
  443. ${mdl.hasSubModules() ? Object.values(parseModulesForUI(mdl.getSubModules(), true, conf.mods)).join('') : ''}
  444. </div>` : ''}
  445. </div>`
  446. }
  447. }
  448. }
  449. return {
  450. reqMods,
  451. optMods
  452. }
  453. }
  454. /**
  455. * Prepare the Java tab for display.
  456. */
  457. function prepareModsTab(){
  458. resolveModsForUI()
  459. }
  460. /**
  461. * Java Tab
  462. */
  463. // DOM Cache
  464. const settingsMaxRAMRange = document.getElementById('settingsMaxRAMRange')
  465. const settingsMinRAMRange = document.getElementById('settingsMinRAMRange')
  466. const settingsMaxRAMLabel = document.getElementById('settingsMaxRAMLabel')
  467. const settingsMinRAMLabel = document.getElementById('settingsMinRAMLabel')
  468. const settingsMemoryTotal = document.getElementById('settingsMemoryTotal')
  469. const settingsMemoryAvail = document.getElementById('settingsMemoryAvail')
  470. const settingsJavaExecDetails = document.getElementById('settingsJavaExecDetails')
  471. const settingsJavaExecVal = document.getElementById('settingsJavaExecVal')
  472. const settingsJavaExecSel = document.getElementById('settingsJavaExecSel')
  473. // Store maximum memory values.
  474. const SETTINGS_MAX_MEMORY = ConfigManager.getAbsoluteMaxRAM()
  475. const SETTINGS_MIN_MEMORY = ConfigManager.getAbsoluteMinRAM()
  476. // Set the max and min values for the ranged sliders.
  477. settingsMaxRAMRange.setAttribute('max', SETTINGS_MAX_MEMORY)
  478. settingsMaxRAMRange.setAttribute('min', SETTINGS_MIN_MEMORY)
  479. settingsMinRAMRange.setAttribute('max', SETTINGS_MAX_MEMORY)
  480. settingsMinRAMRange.setAttribute('min', SETTINGS_MIN_MEMORY )
  481. // Bind on change event for min memory container.
  482. settingsMinRAMRange.onchange = (e) => {
  483. // Current range values
  484. const sMaxV = Number(settingsMaxRAMRange.getAttribute('value'))
  485. const sMinV = Number(settingsMinRAMRange.getAttribute('value'))
  486. // Get reference to range bar.
  487. const bar = e.target.getElementsByClassName('rangeSliderBar')[0]
  488. // Calculate effective total memory.
  489. const max = (os.totalmem()-1000000000)/1000000000
  490. // Change range bar color based on the selected value.
  491. if(sMinV >= max/2){
  492. bar.style.background = '#e86060'
  493. } else if(sMinV >= max/4) {
  494. bar.style.background = '#e8e18b'
  495. } else {
  496. bar.style.background = null
  497. }
  498. // Increase maximum memory if the minimum exceeds its value.
  499. if(sMaxV < sMinV){
  500. const sliderMeta = calculateRangeSliderMeta(settingsMaxRAMRange)
  501. updateRangedSlider(settingsMaxRAMRange, sMinV,
  502. ((sMinV-sliderMeta.min)/sliderMeta.step)*sliderMeta.inc)
  503. settingsMaxRAMLabel.innerHTML = sMinV.toFixed(1) + 'G'
  504. }
  505. // Update label
  506. settingsMinRAMLabel.innerHTML = sMinV.toFixed(1) + 'G'
  507. }
  508. // Bind on change event for max memory container.
  509. settingsMaxRAMRange.onchange = (e) => {
  510. // Current range values
  511. const sMaxV = Number(settingsMaxRAMRange.getAttribute('value'))
  512. const sMinV = Number(settingsMinRAMRange.getAttribute('value'))
  513. // Get reference to range bar.
  514. const bar = e.target.getElementsByClassName('rangeSliderBar')[0]
  515. // Calculate effective total memory.
  516. const max = (os.totalmem()-1000000000)/1000000000
  517. // Change range bar color based on the selected value.
  518. if(sMaxV >= max/2){
  519. bar.style.background = '#e86060'
  520. } else if(sMaxV >= max/4) {
  521. bar.style.background = '#e8e18b'
  522. } else {
  523. bar.style.background = null
  524. }
  525. // Decrease the minimum memory if the maximum value is less.
  526. if(sMaxV < sMinV){
  527. const sliderMeta = calculateRangeSliderMeta(settingsMaxRAMRange)
  528. updateRangedSlider(settingsMinRAMRange, sMaxV,
  529. ((sMaxV-sliderMeta.min)/sliderMeta.step)*sliderMeta.inc)
  530. settingsMinRAMLabel.innerHTML = sMaxV.toFixed(1) + 'G'
  531. }
  532. settingsMaxRAMLabel.innerHTML = sMaxV.toFixed(1) + 'G'
  533. }
  534. /**
  535. * Calculate common values for a ranged slider.
  536. *
  537. * @param {Element} v The range slider to calculate against.
  538. * @returns {Object} An object with meta values for the provided ranged slider.
  539. */
  540. function calculateRangeSliderMeta(v){
  541. const val = {
  542. max: Number(v.getAttribute('max')),
  543. min: Number(v.getAttribute('min')),
  544. step: Number(v.getAttribute('step')),
  545. }
  546. val.ticks = (val.max-val.min)/val.step
  547. val.inc = 100/val.ticks
  548. return val
  549. }
  550. /**
  551. * Binds functionality to the ranged sliders. They're more than
  552. * just divs now :').
  553. */
  554. function bindRangeSlider(){
  555. Array.from(document.getElementsByClassName('rangeSlider')).map((v) => {
  556. // Reference the track (thumb).
  557. const track = v.getElementsByClassName('rangeSliderTrack')[0]
  558. // Set the initial slider value.
  559. const value = v.getAttribute('value')
  560. const sliderMeta = calculateRangeSliderMeta(v)
  561. updateRangedSlider(v, value, ((value-sliderMeta.min)/sliderMeta.step)*sliderMeta.inc)
  562. // The magic happens when we click on the track.
  563. track.onmousedown = (e) => {
  564. // Stop moving the track on mouse up.
  565. document.onmouseup = (e) => {
  566. document.onmousemove = null
  567. document.onmouseup = null
  568. }
  569. // Move slider according to the mouse position.
  570. document.onmousemove = (e) => {
  571. // Distance from the beginning of the bar in pixels.
  572. const diff = e.pageX - v.offsetLeft - track.offsetWidth/2
  573. // Don't move the track off the bar.
  574. if(diff >= 0 && diff <= v.offsetWidth-track.offsetWidth/2){
  575. // Convert the difference to a percentage.
  576. const perc = (diff/v.offsetWidth)*100
  577. // Calculate the percentage of the closest notch.
  578. const notch = Number(perc/sliderMeta.inc).toFixed(0)*sliderMeta.inc
  579. // If we're close to that notch, stick to it.
  580. if(Math.abs(perc-notch) < sliderMeta.inc/2){
  581. updateRangedSlider(v, sliderMeta.min+(sliderMeta.step*(notch/sliderMeta.inc)), notch)
  582. }
  583. }
  584. }
  585. }
  586. })
  587. }
  588. /**
  589. * Update a ranged slider's value and position.
  590. *
  591. * @param {Element} element The ranged slider to update.
  592. * @param {string | number} value The new value for the ranged slider.
  593. * @param {number} notch The notch that the slider should now be at.
  594. */
  595. function updateRangedSlider(element, value, notch){
  596. const oldVal = element.getAttribute('value')
  597. const bar = element.getElementsByClassName('rangeSliderBar')[0]
  598. const track = element.getElementsByClassName('rangeSliderTrack')[0]
  599. element.setAttribute('value', value)
  600. if(notch < 0){
  601. notch = 0
  602. } else if(notch > 100) {
  603. notch = 100
  604. }
  605. const event = new MouseEvent('change', {
  606. target: element,
  607. type: 'change',
  608. bubbles: false,
  609. cancelable: true
  610. })
  611. let cancelled = !element.dispatchEvent(event)
  612. if(!cancelled){
  613. track.style.left = notch + '%'
  614. bar.style.width = notch + '%'
  615. } else {
  616. element.setAttribute('value', oldVal)
  617. }
  618. }
  619. /**
  620. * Display the total and available RAM.
  621. */
  622. function populateMemoryStatus(){
  623. settingsMemoryTotal.innerHTML = Number((os.totalmem()-1000000000)/1000000000).toFixed(1) + 'G'
  624. settingsMemoryAvail.innerHTML = Number(os.freemem()/1000000000).toFixed(1) + 'G'
  625. }
  626. // Bind the executable file input to the display text input.
  627. settingsJavaExecSel.onchange = (e) => {
  628. settingsJavaExecVal.value = settingsJavaExecSel.files[0].path
  629. populateJavaExecDetails(settingsJavaExecVal.value)
  630. }
  631. /**
  632. * Validate the provided executable path and display the data on
  633. * the UI.
  634. *
  635. * @param {string} execPath The executable path to populate against.
  636. */
  637. function populateJavaExecDetails(execPath){
  638. AssetGuard._validateJavaBinary(execPath).then(v => {
  639. if(v.valid){
  640. settingsJavaExecDetails.innerHTML = `Selected: Java ${v.version.major} Update ${v.version.update} (x${v.arch})`
  641. } else {
  642. settingsJavaExecDetails.innerHTML = 'Invalid Selection'
  643. }
  644. })
  645. }
  646. /**
  647. * Prepare the Java tab for display.
  648. */
  649. function prepareJavaTab(){
  650. bindRangeSlider()
  651. populateMemoryStatus()
  652. }
  653. /**
  654. * About Tab
  655. */
  656. const settingsAboutCurrentVersionCheck = document.getElementById('settingsAboutCurrentVersionCheck')
  657. const settingsAboutCurrentVersionTitle = document.getElementById('settingsAboutCurrentVersionTitle')
  658. const settingsAboutCurrentVersionValue = document.getElementById('settingsAboutCurrentVersionValue')
  659. const settingsChangelogTitle = document.getElementById('settingsChangelogTitle')
  660. const settingsChangelogText = document.getElementById('settingsChangelogText')
  661. const settingsChangelogButton = document.getElementById('settingsChangelogButton')
  662. // Bind the devtools toggle button.
  663. document.getElementById('settingsAboutDevToolsButton').onclick = (e) => {
  664. let window = remote.getCurrentWindow()
  665. window.toggleDevTools()
  666. }
  667. /**
  668. * Retrieve the version information and display it on the UI.
  669. */
  670. function populateVersionInformation(){
  671. const version = remote.app.getVersion()
  672. settingsAboutCurrentVersionValue.innerHTML = version
  673. const preRelComp = semver.prerelease(version)
  674. if(preRelComp != null && preRelComp.length > 0){
  675. settingsAboutCurrentVersionTitle.innerHTML = 'Pre-release'
  676. settingsAboutCurrentVersionTitle.style.color = '#ff886d'
  677. settingsAboutCurrentVersionCheck.style.background = '#ff886d'
  678. } else {
  679. settingsAboutCurrentVersionTitle.innerHTML = 'Stable Release'
  680. settingsAboutCurrentVersionTitle.style.color = null
  681. settingsAboutCurrentVersionCheck.style.background = null
  682. }
  683. }
  684. /**
  685. * Fetches the GitHub atom release feed and parses it for the release notes
  686. * of the current version. This value is displayed on the UI.
  687. */
  688. function populateReleaseNotes(){
  689. $.ajax({
  690. url: 'https://github.com/WesterosCraftCode/ElectronLauncher/releases.atom',
  691. success: (data) => {
  692. const version = 'v' + remote.app.getVersion()
  693. const entries = $(data).find('entry')
  694. for(let i=0; i<entries.length; i++){
  695. const entry = $(entries[i])
  696. let id = entry.find('id').text()
  697. id = id.substring(id.lastIndexOf('/')+1)
  698. if(id === version){
  699. settingsChangelogTitle.innerHTML = entry.find('title').text()
  700. settingsChangelogText.innerHTML = entry.find('content').text()
  701. settingsChangelogButton.href = entry.find('link').attr('href')
  702. }
  703. }
  704. },
  705. timeout: 2500
  706. }).catch(err => {
  707. settingsChangelogText.innerHTML = 'Failed to load release notes.'
  708. })
  709. }
  710. /**
  711. * Prepare account tab for display.
  712. */
  713. function prepareAboutTab(){
  714. populateVersionInformation()
  715. populateReleaseNotes()
  716. }
  717. /**
  718. * Settings preparation functions.
  719. */
  720. /**
  721. * Prepare the entire settings UI.
  722. *
  723. * @param {boolean} first Whether or not it is the first load.
  724. */
  725. function prepareSettings(first = false) {
  726. if(first){
  727. setupSettingsTabs()
  728. initSettingsValidators()
  729. } else {
  730. prepareModsTab()
  731. }
  732. initSettingsValues()
  733. prepareAccountsTab()
  734. prepareJavaTab()
  735. prepareAboutTab()
  736. }
  737. // Prepare the settings UI on startup.
  738. prepareSettings(true)