settings.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  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 cVal = v.getAttribute('cValue')
  53. const gFn = ConfigManager['get' + cVal]
  54. if(typeof gFn === 'function'){
  55. if(v.tagName === 'INPUT'){
  56. if(v.type === 'number' || v.type === 'text'){
  57. // Special Conditions
  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. 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 cVal = v.getAttribute('cValue')
  95. const sFn = ConfigManager['set' + cVal]
  96. if(typeof sFn === 'function'){
  97. if(v.tagName === 'INPUT'){
  98. if(v.type === 'number' || v.type === 'text'){
  99. // Special Conditions
  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. if(cVal === 'AllowPrerelease'){
  109. changeAllowPrerelease(v.checked)
  110. }
  111. }
  112. } else if(v.tagName === 'DIV'){
  113. if(v.classList.contains('rangeSlider')){
  114. // Special Conditions
  115. if(cVal === 'MinRAM' || cVal === 'MaxRAM'){
  116. let val = Number(v.getAttribute('value'))
  117. if(val%1 > 0){
  118. val = val*1000 + 'M'
  119. } else {
  120. val = val + 'G'
  121. }
  122. sFn(val)
  123. } else {
  124. sFn(v.getAttribute('value'))
  125. }
  126. }
  127. }
  128. }
  129. })
  130. }
  131. let selectedSettingsTab = 'settingsTabAccount'
  132. /**
  133. * Modify the settings container UI when the scroll threshold reaches
  134. * a certain poin.
  135. *
  136. * @param {UIEvent} e The scroll event.
  137. */
  138. function settingsTabScrollListener(e){
  139. if(e.target.scrollTop > Number.parseFloat(getComputedStyle(e.target.firstElementChild).marginTop)){
  140. document.getElementById('settingsContainer').setAttribute('scrolled', '')
  141. } else {
  142. document.getElementById('settingsContainer').removeAttribute('scrolled')
  143. }
  144. }
  145. /**
  146. * Bind functionality for the settings navigation items.
  147. */
  148. function setupSettingsTabs(){
  149. Array.from(document.getElementsByClassName('settingsNavItem')).map((val) => {
  150. if(val.hasAttribute('rSc')){
  151. val.onclick = () => {
  152. settingsNavItemListener(val)
  153. }
  154. }
  155. })
  156. }
  157. /**
  158. * Settings nav item onclick lisener. Function is exposed so that
  159. * other UI elements can quickly toggle to a certain tab from other views.
  160. *
  161. * @param {Element} ele The nav item which has been clicked.
  162. * @param {boolean} fade Optional. True to fade transition.
  163. */
  164. function settingsNavItemListener(ele, fade = true){
  165. if(ele.hasAttribute('selected')){
  166. return
  167. }
  168. const navItems = document.getElementsByClassName('settingsNavItem')
  169. for(let i=0; i<navItems.length; i++){
  170. if(navItems[i].hasAttribute('selected')){
  171. navItems[i].removeAttribute('selected')
  172. }
  173. }
  174. ele.setAttribute('selected', '')
  175. let prevTab = selectedSettingsTab
  176. selectedSettingsTab = ele.getAttribute('rSc')
  177. document.getElementById(prevTab).onscroll = null
  178. document.getElementById(selectedSettingsTab).onscroll = settingsTabScrollListener
  179. if(fade){
  180. $(`#${prevTab}`).fadeOut(250, () => {
  181. $(`#${selectedSettingsTab}`).fadeIn({
  182. duration: 250,
  183. start: () => {
  184. settingsTabScrollListener({
  185. target: document.getElementById(selectedSettingsTab)
  186. })
  187. }
  188. })
  189. })
  190. } else {
  191. $(`#${prevTab}`).hide(0, () => {
  192. $(`#${selectedSettingsTab}`).show({
  193. duration: 0,
  194. start: () => {
  195. settingsTabScrollListener({
  196. target: document.getElementById(selectedSettingsTab)
  197. })
  198. }
  199. })
  200. })
  201. }
  202. }
  203. const settingsNavDone = document.getElementById('settingsNavDone')
  204. /**
  205. * Set if the settings save (done) button is disabled.
  206. *
  207. * @param {boolean} v True to disable, false to enable.
  208. */
  209. function settingsSaveDisabled(v){
  210. settingsNavDone.disabled = v
  211. }
  212. /* Closes the settings view and saves all data. */
  213. settingsNavDone.onclick = () => {
  214. saveSettingsValues()
  215. saveModConfiguration()
  216. ConfigManager.save()
  217. switchView(getCurrentView(), VIEWS.landing)
  218. }
  219. /**
  220. * Account Management Tab
  221. */
  222. // Bind the add account button.
  223. document.getElementById('settingsAddAccount').onclick = (e) => {
  224. switchView(getCurrentView(), VIEWS.login, 500, 500, () => {
  225. loginViewOnCancel = VIEWS.settings
  226. loginViewOnSuccess = VIEWS.settings
  227. loginCancelEnabled(true)
  228. })
  229. }
  230. /**
  231. * Bind functionality for the account selection buttons. If another account
  232. * is selected, the UI of the previously selected account will be updated.
  233. */
  234. function bindAuthAccountSelect(){
  235. Array.from(document.getElementsByClassName('settingsAuthAccountSelect')).map((val) => {
  236. val.onclick = (e) => {
  237. if(val.hasAttribute('selected')){
  238. return
  239. }
  240. const selectBtns = document.getElementsByClassName('settingsAuthAccountSelect')
  241. for(let i=0; i<selectBtns.length; i++){
  242. if(selectBtns[i].hasAttribute('selected')){
  243. selectBtns[i].removeAttribute('selected')
  244. selectBtns[i].innerHTML = 'Select Account'
  245. }
  246. }
  247. val.setAttribute('selected', '')
  248. val.innerHTML = 'Selected Account &#10004;'
  249. setSelectedAccount(val.closest('.settingsAuthAccount').getAttribute('uuid'))
  250. }
  251. })
  252. }
  253. /**
  254. * Bind functionality for the log out button. If the logged out account was
  255. * the selected account, another account will be selected and the UI will
  256. * be updated accordingly.
  257. */
  258. function bindAuthAccountLogOut(){
  259. Array.from(document.getElementsByClassName('settingsAuthAccountLogOut')).map((val) => {
  260. val.onclick = (e) => {
  261. let isLastAccount = false
  262. if(Object.keys(ConfigManager.getAuthAccounts()).length === 1){
  263. isLastAccount = true
  264. setOverlayContent(
  265. 'Warning<br>This is Your Last Account',
  266. '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?',
  267. 'I\'m Sure',
  268. 'Cancel'
  269. )
  270. setOverlayHandler(() => {
  271. processLogOut(val, isLastAccount)
  272. switchView(getCurrentView(), VIEWS.login)
  273. toggleOverlay(false)
  274. })
  275. setDismissHandler(() => {
  276. toggleOverlay(false)
  277. })
  278. toggleOverlay(true, true)
  279. } else {
  280. processLogOut(val, isLastAccount)
  281. }
  282. }
  283. })
  284. }
  285. /**
  286. * Process a log out.
  287. *
  288. * @param {Element} val The log out button element.
  289. * @param {boolean} isLastAccount If this logout is on the last added account.
  290. */
  291. function processLogOut(val, isLastAccount){
  292. const parent = val.closest('.settingsAuthAccount')
  293. const uuid = parent.getAttribute('uuid')
  294. const prevSelAcc = ConfigManager.getSelectedAccount()
  295. AuthManager.removeAccount(uuid).then(() => {
  296. if(!isLastAccount && uuid === prevSelAcc.uuid){
  297. const selAcc = ConfigManager.getSelectedAccount()
  298. refreshAuthAccountSelected(selAcc.uuid)
  299. updateSelectedAccount(selAcc)
  300. validateSelectedAccount()
  301. }
  302. })
  303. $(parent).fadeOut(250, () => {
  304. parent.remove()
  305. })
  306. }
  307. /**
  308. * Refreshes the status of the selected account on the auth account
  309. * elements.
  310. *
  311. * @param {string} uuid The UUID of the new selected account.
  312. */
  313. function refreshAuthAccountSelected(uuid){
  314. Array.from(document.getElementsByClassName('settingsAuthAccount')).map((val) => {
  315. const selBtn = val.getElementsByClassName('settingsAuthAccountSelect')[0]
  316. if(uuid === val.getAttribute('uuid')){
  317. selBtn.setAttribute('selected', '')
  318. selBtn.innerHTML = 'Selected Account &#10004;'
  319. } else {
  320. if(selBtn.hasAttribute('selected')){
  321. selBtn.removeAttribute('selected')
  322. }
  323. selBtn.innerHTML = 'Select Account'
  324. }
  325. })
  326. }
  327. const settingsCurrentAccounts = document.getElementById('settingsCurrentAccounts')
  328. /**
  329. * Add auth account elements for each one stored in the authentication database.
  330. */
  331. function populateAuthAccounts(){
  332. const authAccounts = ConfigManager.getAuthAccounts()
  333. const authKeys = Object.keys(authAccounts)
  334. const selectedUUID = ConfigManager.getSelectedAccount().uuid
  335. let authAccountStr = ''
  336. authKeys.map((val) => {
  337. const acc = authAccounts[val]
  338. authAccountStr += `<div class="settingsAuthAccount" uuid="${acc.uuid}">
  339. <div class="settingsAuthAccountLeft">
  340. <img class="settingsAuthAccountImage" alt="${acc.displayName}" src="https://crafatar.com/renders/body/${acc.uuid}?scale=3&default=MHF_Steve&overlay">
  341. </div>
  342. <div class="settingsAuthAccountRight">
  343. <div class="settingsAuthAccountDetails">
  344. <div class="settingsAuthAccountDetailPane">
  345. <div class="settingsAuthAccountDetailTitle">Username</div>
  346. <div class="settingsAuthAccountDetailValue">${acc.displayName}</div>
  347. </div>
  348. <div class="settingsAuthAccountDetailPane">
  349. <div class="settingsAuthAccountDetailTitle">UUID</div>
  350. <div class="settingsAuthAccountDetailValue">${acc.uuid}</div>
  351. </div>
  352. </div>
  353. <div class="settingsAuthAccountActions">
  354. <button class="settingsAuthAccountSelect" ${selectedUUID === acc.uuid ? 'selected>Selected Account &#10004;' : '>Select Account'}</button>
  355. <div class="settingsAuthAccountWrapper">
  356. <button class="settingsAuthAccountLogOut">Log Out</button>
  357. </div>
  358. </div>
  359. </div>
  360. </div>`
  361. })
  362. settingsCurrentAccounts.innerHTML = authAccountStr
  363. }
  364. /**
  365. * Prepare the accounts tab for display.
  366. */
  367. function prepareAccountsTab() {
  368. populateAuthAccounts()
  369. bindAuthAccountSelect()
  370. bindAuthAccountLogOut()
  371. }
  372. /**
  373. * Minecraft Tab
  374. */
  375. /**
  376. * Disable decimals, negative signs, and scientific notation.
  377. */
  378. document.getElementById('settingsGameWidth').addEventListener('keydown', (e) => {
  379. if(/^[-.eE]$/.test(e.key)){
  380. e.preventDefault()
  381. }
  382. })
  383. document.getElementById('settingsGameHeight').addEventListener('keydown', (e) => {
  384. if(/^[-.eE]$/.test(e.key)){
  385. e.preventDefault()
  386. }
  387. })
  388. /**
  389. * Mods Tab
  390. */
  391. const settingsModsContainer = document.getElementById('settingsModsContainer')
  392. function resolveModsForUI(){
  393. const serv = ConfigManager.getSelectedServer()
  394. const distro = DistroManager.getDistribution()
  395. const servConf = ConfigManager.getModConfiguration(serv)
  396. const modStr = parseModulesForUI(distro.getServer(serv).getModules(), false, servConf.mods)
  397. document.getElementById('settingsReqModsContent').innerHTML = modStr.reqMods
  398. document.getElementById('settingsOptModsContent').innerHTML = modStr.optMods
  399. }
  400. function parseModulesForUI(mdls, submodules = false, servConf){
  401. let reqMods = ''
  402. let optMods = ''
  403. for(const mdl of mdls){
  404. if(mdl.getType() === DistroManager.Types.ForgeMod || mdl.getType() === DistroManager.Types.LiteMod || mdl.getType() === DistroManager.Types.LiteLoader){
  405. if(mdl.getRequired().isRequired()){
  406. reqMods += `<div id="${mdl.getVersionlessID()}" class="settings${submodules ? 'Sub' : ''}Mod" enabled>
  407. <div class="settingsModContent">
  408. <div class="settingsModMainWrapper">
  409. <div class="settingsModStatus"></div>
  410. <div class="settingsModDetails">
  411. <span class="settingsModName">${mdl.getName()}</span>
  412. <span class="settingsModVersion">v${mdl.getVersion()}</span>
  413. </div>
  414. </div>
  415. <label class="toggleSwitch" reqmod>
  416. <input type="checkbox" checked>
  417. <span class="toggleSwitchSlider"></span>
  418. </label>
  419. </div>
  420. ${mdl.hasSubModules() ? `<div class="settingsSubModContainer">
  421. ${Object.values(parseModulesForUI(mdl.getSubModules(), true)).join('')}
  422. </div>` : ''}
  423. </div>`
  424. } else {
  425. const conf = servConf[mdl.getVersionlessID()]
  426. const val = typeof conf === 'object' ? conf.value : conf
  427. optMods += `<div id="${mdl.getVersionlessID()}" class="settings${submodules ? 'Sub' : ''}Mod" ${val ? 'enabled' : ''}>
  428. <div class="settingsModContent">
  429. <div class="settingsModMainWrapper">
  430. <div class="settingsModStatus"></div>
  431. <div class="settingsModDetails">
  432. <span class="settingsModName">${mdl.getName()}</span>
  433. <span class="settingsModVersion">v${mdl.getVersion()}</span>
  434. </div>
  435. </div>
  436. <label class="toggleSwitch">
  437. <input type="checkbox" formod="${mdl.getVersionlessID()}" ${val ? 'checked' : ''}>
  438. <span class="toggleSwitchSlider"></span>
  439. </label>
  440. </div>
  441. ${mdl.hasSubModules() ? `<div class="settingsSubModContainer">
  442. ${Object.values(parseModulesForUI(mdl.getSubModules(), true, conf.mods)).join('')}
  443. </div>` : ''}
  444. </div>`
  445. }
  446. }
  447. }
  448. return {
  449. reqMods,
  450. optMods
  451. }
  452. }
  453. /**
  454. * Bind functionality to mod config toggle switches. Switching the value
  455. * will also switch the status color on the left of the mod UI.
  456. */
  457. function bindModsToggleSwitch(){
  458. const sEls = settingsModsContainer.querySelectorAll('[formod]')
  459. Array.from(sEls).map((v, index, arr) => {
  460. v.onchange = () => {
  461. if(v.checked) {
  462. document.getElementById(v.getAttribute('formod')).setAttribute('enabled', '')
  463. } else {
  464. document.getElementById(v.getAttribute('formod')).removeAttribute('enabled')
  465. }
  466. }
  467. })
  468. }
  469. /**
  470. * Save the mod configuration based on the UI values.
  471. */
  472. function saveModConfiguration(){
  473. const serv = ConfigManager.getSelectedServer()
  474. const modConf = ConfigManager.getModConfiguration(serv)
  475. modConf.mods = _saveModConfiguration(modConf.mods)
  476. ConfigManager.setModConfiguration(serv, modConf)
  477. }
  478. /**
  479. * Recursively save mod config with submods.
  480. *
  481. * @param {Object} modConf Mod config object to save.
  482. */
  483. function _saveModConfiguration(modConf){
  484. for(m of Object.entries(modConf)){
  485. const val = settingsModsContainer.querySelectorAll(`[formod='${m[0]}']`)[0].checked
  486. if(typeof m[1] === 'boolean'){
  487. modConf[m[0]] = val
  488. } else {
  489. if(m[1] != null){
  490. modConf[m[0]].value = val
  491. modConf[m[0]].mods = _saveModConfiguration(modConf[m[0]].mods)
  492. }
  493. }
  494. }
  495. return modConf
  496. }
  497. /**
  498. * Prepare the Java tab for display.
  499. */
  500. function prepareModsTab(){
  501. resolveModsForUI()
  502. bindModsToggleSwitch()
  503. }
  504. /**
  505. * Java Tab
  506. */
  507. // DOM Cache
  508. const settingsMaxRAMRange = document.getElementById('settingsMaxRAMRange')
  509. const settingsMinRAMRange = document.getElementById('settingsMinRAMRange')
  510. const settingsMaxRAMLabel = document.getElementById('settingsMaxRAMLabel')
  511. const settingsMinRAMLabel = document.getElementById('settingsMinRAMLabel')
  512. const settingsMemoryTotal = document.getElementById('settingsMemoryTotal')
  513. const settingsMemoryAvail = document.getElementById('settingsMemoryAvail')
  514. const settingsJavaExecDetails = document.getElementById('settingsJavaExecDetails')
  515. const settingsJavaExecVal = document.getElementById('settingsJavaExecVal')
  516. const settingsJavaExecSel = document.getElementById('settingsJavaExecSel')
  517. // Store maximum memory values.
  518. const SETTINGS_MAX_MEMORY = ConfigManager.getAbsoluteMaxRAM()
  519. const SETTINGS_MIN_MEMORY = ConfigManager.getAbsoluteMinRAM()
  520. // Set the max and min values for the ranged sliders.
  521. settingsMaxRAMRange.setAttribute('max', SETTINGS_MAX_MEMORY)
  522. settingsMaxRAMRange.setAttribute('min', SETTINGS_MIN_MEMORY)
  523. settingsMinRAMRange.setAttribute('max', SETTINGS_MAX_MEMORY)
  524. settingsMinRAMRange.setAttribute('min', SETTINGS_MIN_MEMORY )
  525. // Bind on change event for min memory container.
  526. settingsMinRAMRange.onchange = (e) => {
  527. // Current range values
  528. const sMaxV = Number(settingsMaxRAMRange.getAttribute('value'))
  529. const sMinV = Number(settingsMinRAMRange.getAttribute('value'))
  530. // Get reference to range bar.
  531. const bar = e.target.getElementsByClassName('rangeSliderBar')[0]
  532. // Calculate effective total memory.
  533. const max = (os.totalmem()-1000000000)/1000000000
  534. // Change range bar color based on the selected value.
  535. if(sMinV >= max/2){
  536. bar.style.background = '#e86060'
  537. } else if(sMinV >= max/4) {
  538. bar.style.background = '#e8e18b'
  539. } else {
  540. bar.style.background = null
  541. }
  542. // Increase maximum memory if the minimum exceeds its value.
  543. if(sMaxV < sMinV){
  544. const sliderMeta = calculateRangeSliderMeta(settingsMaxRAMRange)
  545. updateRangedSlider(settingsMaxRAMRange, sMinV,
  546. ((sMinV-sliderMeta.min)/sliderMeta.step)*sliderMeta.inc)
  547. settingsMaxRAMLabel.innerHTML = sMinV.toFixed(1) + 'G'
  548. }
  549. // Update label
  550. settingsMinRAMLabel.innerHTML = sMinV.toFixed(1) + 'G'
  551. }
  552. // Bind on change event for max memory container.
  553. settingsMaxRAMRange.onchange = (e) => {
  554. // Current range values
  555. const sMaxV = Number(settingsMaxRAMRange.getAttribute('value'))
  556. const sMinV = Number(settingsMinRAMRange.getAttribute('value'))
  557. // Get reference to range bar.
  558. const bar = e.target.getElementsByClassName('rangeSliderBar')[0]
  559. // Calculate effective total memory.
  560. const max = (os.totalmem()-1000000000)/1000000000
  561. // Change range bar color based on the selected value.
  562. if(sMaxV >= max/2){
  563. bar.style.background = '#e86060'
  564. } else if(sMaxV >= max/4) {
  565. bar.style.background = '#e8e18b'
  566. } else {
  567. bar.style.background = null
  568. }
  569. // Decrease the minimum memory if the maximum value is less.
  570. if(sMaxV < sMinV){
  571. const sliderMeta = calculateRangeSliderMeta(settingsMaxRAMRange)
  572. updateRangedSlider(settingsMinRAMRange, sMaxV,
  573. ((sMaxV-sliderMeta.min)/sliderMeta.step)*sliderMeta.inc)
  574. settingsMinRAMLabel.innerHTML = sMaxV.toFixed(1) + 'G'
  575. }
  576. settingsMaxRAMLabel.innerHTML = sMaxV.toFixed(1) + 'G'
  577. }
  578. /**
  579. * Calculate common values for a ranged slider.
  580. *
  581. * @param {Element} v The range slider to calculate against.
  582. * @returns {Object} An object with meta values for the provided ranged slider.
  583. */
  584. function calculateRangeSliderMeta(v){
  585. const val = {
  586. max: Number(v.getAttribute('max')),
  587. min: Number(v.getAttribute('min')),
  588. step: Number(v.getAttribute('step')),
  589. }
  590. val.ticks = (val.max-val.min)/val.step
  591. val.inc = 100/val.ticks
  592. return val
  593. }
  594. /**
  595. * Binds functionality to the ranged sliders. They're more than
  596. * just divs now :').
  597. */
  598. function bindRangeSlider(){
  599. Array.from(document.getElementsByClassName('rangeSlider')).map((v) => {
  600. // Reference the track (thumb).
  601. const track = v.getElementsByClassName('rangeSliderTrack')[0]
  602. // Set the initial slider value.
  603. const value = v.getAttribute('value')
  604. const sliderMeta = calculateRangeSliderMeta(v)
  605. updateRangedSlider(v, value, ((value-sliderMeta.min)/sliderMeta.step)*sliderMeta.inc)
  606. // The magic happens when we click on the track.
  607. track.onmousedown = (e) => {
  608. // Stop moving the track on mouse up.
  609. document.onmouseup = (e) => {
  610. document.onmousemove = null
  611. document.onmouseup = null
  612. }
  613. // Move slider according to the mouse position.
  614. document.onmousemove = (e) => {
  615. // Distance from the beginning of the bar in pixels.
  616. const diff = e.pageX - v.offsetLeft - track.offsetWidth/2
  617. // Don't move the track off the bar.
  618. if(diff >= 0 && diff <= v.offsetWidth-track.offsetWidth/2){
  619. // Convert the difference to a percentage.
  620. const perc = (diff/v.offsetWidth)*100
  621. // Calculate the percentage of the closest notch.
  622. const notch = Number(perc/sliderMeta.inc).toFixed(0)*sliderMeta.inc
  623. // If we're close to that notch, stick to it.
  624. if(Math.abs(perc-notch) < sliderMeta.inc/2){
  625. updateRangedSlider(v, sliderMeta.min+(sliderMeta.step*(notch/sliderMeta.inc)), notch)
  626. }
  627. }
  628. }
  629. }
  630. })
  631. }
  632. /**
  633. * Update a ranged slider's value and position.
  634. *
  635. * @param {Element} element The ranged slider to update.
  636. * @param {string | number} value The new value for the ranged slider.
  637. * @param {number} notch The notch that the slider should now be at.
  638. */
  639. function updateRangedSlider(element, value, notch){
  640. const oldVal = element.getAttribute('value')
  641. const bar = element.getElementsByClassName('rangeSliderBar')[0]
  642. const track = element.getElementsByClassName('rangeSliderTrack')[0]
  643. element.setAttribute('value', value)
  644. if(notch < 0){
  645. notch = 0
  646. } else if(notch > 100) {
  647. notch = 100
  648. }
  649. const event = new MouseEvent('change', {
  650. target: element,
  651. type: 'change',
  652. bubbles: false,
  653. cancelable: true
  654. })
  655. let cancelled = !element.dispatchEvent(event)
  656. if(!cancelled){
  657. track.style.left = notch + '%'
  658. bar.style.width = notch + '%'
  659. } else {
  660. element.setAttribute('value', oldVal)
  661. }
  662. }
  663. /**
  664. * Display the total and available RAM.
  665. */
  666. function populateMemoryStatus(){
  667. settingsMemoryTotal.innerHTML = Number((os.totalmem()-1000000000)/1000000000).toFixed(1) + 'G'
  668. settingsMemoryAvail.innerHTML = Number(os.freemem()/1000000000).toFixed(1) + 'G'
  669. }
  670. // Bind the executable file input to the display text input.
  671. settingsJavaExecSel.onchange = (e) => {
  672. settingsJavaExecVal.value = settingsJavaExecSel.files[0].path
  673. populateJavaExecDetails(settingsJavaExecVal.value)
  674. }
  675. /**
  676. * Validate the provided executable path and display the data on
  677. * the UI.
  678. *
  679. * @param {string} execPath The executable path to populate against.
  680. */
  681. function populateJavaExecDetails(execPath){
  682. AssetGuard._validateJavaBinary(execPath).then(v => {
  683. if(v.valid){
  684. settingsJavaExecDetails.innerHTML = `Selected: Java ${v.version.major} Update ${v.version.update} (x${v.arch})`
  685. } else {
  686. settingsJavaExecDetails.innerHTML = 'Invalid Selection'
  687. }
  688. })
  689. }
  690. /**
  691. * Prepare the Java tab for display.
  692. */
  693. function prepareJavaTab(){
  694. bindRangeSlider()
  695. populateMemoryStatus()
  696. }
  697. /**
  698. * About Tab
  699. */
  700. const settingsAboutCurrentVersionCheck = document.getElementById('settingsAboutCurrentVersionCheck')
  701. const settingsAboutCurrentVersionTitle = document.getElementById('settingsAboutCurrentVersionTitle')
  702. const settingsAboutCurrentVersionValue = document.getElementById('settingsAboutCurrentVersionValue')
  703. const settingsChangelogTitle = document.getElementById('settingsChangelogTitle')
  704. const settingsChangelogText = document.getElementById('settingsChangelogText')
  705. const settingsChangelogButton = document.getElementById('settingsChangelogButton')
  706. // Bind the devtools toggle button.
  707. document.getElementById('settingsAboutDevToolsButton').onclick = (e) => {
  708. let window = remote.getCurrentWindow()
  709. window.toggleDevTools()
  710. }
  711. /**
  712. * Retrieve the version information and display it on the UI.
  713. */
  714. function populateVersionInformation(){
  715. const version = remote.app.getVersion()
  716. settingsAboutCurrentVersionValue.innerHTML = version
  717. const preRelComp = semver.prerelease(version)
  718. if(preRelComp != null && preRelComp.length > 0){
  719. settingsAboutCurrentVersionTitle.innerHTML = 'Pre-release'
  720. settingsAboutCurrentVersionTitle.style.color = '#ff886d'
  721. settingsAboutCurrentVersionCheck.style.background = '#ff886d'
  722. } else {
  723. settingsAboutCurrentVersionTitle.innerHTML = 'Stable Release'
  724. settingsAboutCurrentVersionTitle.style.color = null
  725. settingsAboutCurrentVersionCheck.style.background = null
  726. }
  727. }
  728. /**
  729. * Fetches the GitHub atom release feed and parses it for the release notes
  730. * of the current version. This value is displayed on the UI.
  731. */
  732. function populateReleaseNotes(){
  733. $.ajax({
  734. url: 'https://github.com/WesterosCraftCode/ElectronLauncher/releases.atom',
  735. success: (data) => {
  736. const version = 'v' + remote.app.getVersion()
  737. const entries = $(data).find('entry')
  738. for(let i=0; i<entries.length; i++){
  739. const entry = $(entries[i])
  740. let id = entry.find('id').text()
  741. id = id.substring(id.lastIndexOf('/')+1)
  742. if(id === version){
  743. settingsChangelogTitle.innerHTML = entry.find('title').text()
  744. settingsChangelogText.innerHTML = entry.find('content').text()
  745. settingsChangelogButton.href = entry.find('link').attr('href')
  746. }
  747. }
  748. },
  749. timeout: 2500
  750. }).catch(err => {
  751. settingsChangelogText.innerHTML = 'Failed to load release notes.'
  752. })
  753. }
  754. /**
  755. * Prepare account tab for display.
  756. */
  757. function prepareAboutTab(){
  758. populateVersionInformation()
  759. populateReleaseNotes()
  760. }
  761. /**
  762. * Settings preparation functions.
  763. */
  764. /**
  765. * Prepare the entire settings UI.
  766. *
  767. * @param {boolean} first Whether or not it is the first load.
  768. */
  769. function prepareSettings(first = false) {
  770. if(first){
  771. setupSettingsTabs()
  772. initSettingsValidators()
  773. } else {
  774. prepareModsTab()
  775. }
  776. initSettingsValues()
  777. prepareAccountsTab()
  778. prepareJavaTab()
  779. prepareAboutTab()
  780. }
  781. // Prepare the settings UI on startup.
  782. prepareSettings(true)