settings.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  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, 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, servConf[mdl.getVersionlessID()])).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 tSwitch = settingsModsContainer.querySelectorAll(`[formod='${m[0]}']`)
  486. if(typeof m[1] === 'boolean'){
  487. modConf[m[0]] = tSwitch[0].checked
  488. } else {
  489. if(m[1] != null){
  490. if(tSwitch.length > 0){
  491. modConf[m[0]].value = tSwitch[0].checked
  492. }
  493. modConf[m[0]].mods = _saveModConfiguration(modConf[m[0]].mods)
  494. }
  495. }
  496. }
  497. return modConf
  498. }
  499. function loadSelectedServerOnModsTab(){
  500. const serv = DistroManager.getDistribution().getServer(ConfigManager.getSelectedServer())
  501. document.getElementById('settingsSelServContent').innerHTML = `
  502. <img class="serverListingImg" src="${serv.getIcon()}"/>
  503. <div class="serverListingDetails">
  504. <span class="serverListingName">${serv.getName()}</span>
  505. <span class="serverListingDescription">${serv.getDescription()}</span>
  506. <div class="serverListingInfo">
  507. <div class="serverListingVersion">${serv.getMinecraftVersion()}</div>
  508. <div class="serverListingRevision">${serv.getVersion()}</div>
  509. ${serv.isMainServer() ? `<div class="serverListingStarWrapper">
  510. <svg id="Layer_1" viewBox="0 0 107.45 104.74" width="20px" height="20px">
  511. <defs>
  512. <style>.cls-1{fill:#fff;}.cls-2{fill:none;stroke:#fff;stroke-miterlimit:10;}</style>
  513. </defs>
  514. <path class="cls-1" d="M100.93,65.54C89,62,68.18,55.65,63.54,52.13c2.7-5.23,18.8-19.2,28-27.55C81.36,31.74,63.74,43.87,58.09,45.3c-2.41-5.37-3.61-26.52-4.37-39-.77,12.46-2,33.64-4.36,39-5.7-1.46-23.3-13.57-33.49-20.72,9.26,8.37,25.39,22.36,28,27.55C39.21,55.68,18.47,62,6.52,65.55c12.32-2,33.63-6.06,39.34-4.9-.16,5.87-8.41,26.16-13.11,37.69,6.1-10.89,16.52-30.16,21-33.9,4.5,3.79,14.93,23.09,21,34C70,86.84,61.73,66.48,61.59,60.65,67.36,59.49,88.64,63.52,100.93,65.54Z"/>
  515. <circle class="cls-2" cx="53.73" cy="53.9" r="38"/>
  516. </svg>
  517. <span class="serverListingStarTooltip">Main Server</span>
  518. </div>` : ''}
  519. </div>
  520. </div>
  521. `
  522. }
  523. document.getElementById("settingsSwitchServerButton").addEventListener('click', (e) => {
  524. e.target.blur()
  525. toggleServerSelection(true)
  526. })
  527. function animateModsTabRefresh(){
  528. $('#settingsTabMods').fadeOut(500, () => {
  529. prepareModsTab()
  530. $('#settingsTabMods').fadeIn(500)
  531. })
  532. }
  533. /**
  534. * Prepare the Mods tab for display.
  535. */
  536. function prepareModsTab(first){
  537. resolveModsForUI()
  538. bindModsToggleSwitch()
  539. loadSelectedServerOnModsTab()
  540. }
  541. /**
  542. * Java Tab
  543. */
  544. // DOM Cache
  545. const settingsMaxRAMRange = document.getElementById('settingsMaxRAMRange')
  546. const settingsMinRAMRange = document.getElementById('settingsMinRAMRange')
  547. const settingsMaxRAMLabel = document.getElementById('settingsMaxRAMLabel')
  548. const settingsMinRAMLabel = document.getElementById('settingsMinRAMLabel')
  549. const settingsMemoryTotal = document.getElementById('settingsMemoryTotal')
  550. const settingsMemoryAvail = document.getElementById('settingsMemoryAvail')
  551. const settingsJavaExecDetails = document.getElementById('settingsJavaExecDetails')
  552. const settingsJavaExecVal = document.getElementById('settingsJavaExecVal')
  553. const settingsJavaExecSel = document.getElementById('settingsJavaExecSel')
  554. // Store maximum memory values.
  555. const SETTINGS_MAX_MEMORY = ConfigManager.getAbsoluteMaxRAM()
  556. const SETTINGS_MIN_MEMORY = ConfigManager.getAbsoluteMinRAM()
  557. // Set the max and min values for the ranged sliders.
  558. settingsMaxRAMRange.setAttribute('max', SETTINGS_MAX_MEMORY)
  559. settingsMaxRAMRange.setAttribute('min', SETTINGS_MIN_MEMORY)
  560. settingsMinRAMRange.setAttribute('max', SETTINGS_MAX_MEMORY)
  561. settingsMinRAMRange.setAttribute('min', SETTINGS_MIN_MEMORY )
  562. // Bind on change event for min memory container.
  563. settingsMinRAMRange.onchange = (e) => {
  564. // Current range values
  565. const sMaxV = Number(settingsMaxRAMRange.getAttribute('value'))
  566. const sMinV = Number(settingsMinRAMRange.getAttribute('value'))
  567. // Get reference to range bar.
  568. const bar = e.target.getElementsByClassName('rangeSliderBar')[0]
  569. // Calculate effective total memory.
  570. const max = (os.totalmem()-1000000000)/1000000000
  571. // Change range bar color based on the selected value.
  572. if(sMinV >= max/2){
  573. bar.style.background = '#e86060'
  574. } else if(sMinV >= max/4) {
  575. bar.style.background = '#e8e18b'
  576. } else {
  577. bar.style.background = null
  578. }
  579. // Increase maximum memory if the minimum exceeds its value.
  580. if(sMaxV < sMinV){
  581. const sliderMeta = calculateRangeSliderMeta(settingsMaxRAMRange)
  582. updateRangedSlider(settingsMaxRAMRange, sMinV,
  583. ((sMinV-sliderMeta.min)/sliderMeta.step)*sliderMeta.inc)
  584. settingsMaxRAMLabel.innerHTML = sMinV.toFixed(1) + 'G'
  585. }
  586. // Update label
  587. settingsMinRAMLabel.innerHTML = sMinV.toFixed(1) + 'G'
  588. }
  589. // Bind on change event for max memory container.
  590. settingsMaxRAMRange.onchange = (e) => {
  591. // Current range values
  592. const sMaxV = Number(settingsMaxRAMRange.getAttribute('value'))
  593. const sMinV = Number(settingsMinRAMRange.getAttribute('value'))
  594. // Get reference to range bar.
  595. const bar = e.target.getElementsByClassName('rangeSliderBar')[0]
  596. // Calculate effective total memory.
  597. const max = (os.totalmem()-1000000000)/1000000000
  598. // Change range bar color based on the selected value.
  599. if(sMaxV >= max/2){
  600. bar.style.background = '#e86060'
  601. } else if(sMaxV >= max/4) {
  602. bar.style.background = '#e8e18b'
  603. } else {
  604. bar.style.background = null
  605. }
  606. // Decrease the minimum memory if the maximum value is less.
  607. if(sMaxV < sMinV){
  608. const sliderMeta = calculateRangeSliderMeta(settingsMaxRAMRange)
  609. updateRangedSlider(settingsMinRAMRange, sMaxV,
  610. ((sMaxV-sliderMeta.min)/sliderMeta.step)*sliderMeta.inc)
  611. settingsMinRAMLabel.innerHTML = sMaxV.toFixed(1) + 'G'
  612. }
  613. settingsMaxRAMLabel.innerHTML = sMaxV.toFixed(1) + 'G'
  614. }
  615. /**
  616. * Calculate common values for a ranged slider.
  617. *
  618. * @param {Element} v The range slider to calculate against.
  619. * @returns {Object} An object with meta values for the provided ranged slider.
  620. */
  621. function calculateRangeSliderMeta(v){
  622. const val = {
  623. max: Number(v.getAttribute('max')),
  624. min: Number(v.getAttribute('min')),
  625. step: Number(v.getAttribute('step')),
  626. }
  627. val.ticks = (val.max-val.min)/val.step
  628. val.inc = 100/val.ticks
  629. return val
  630. }
  631. /**
  632. * Binds functionality to the ranged sliders. They're more than
  633. * just divs now :').
  634. */
  635. function bindRangeSlider(){
  636. Array.from(document.getElementsByClassName('rangeSlider')).map((v) => {
  637. // Reference the track (thumb).
  638. const track = v.getElementsByClassName('rangeSliderTrack')[0]
  639. // Set the initial slider value.
  640. const value = v.getAttribute('value')
  641. const sliderMeta = calculateRangeSliderMeta(v)
  642. updateRangedSlider(v, value, ((value-sliderMeta.min)/sliderMeta.step)*sliderMeta.inc)
  643. // The magic happens when we click on the track.
  644. track.onmousedown = (e) => {
  645. // Stop moving the track on mouse up.
  646. document.onmouseup = (e) => {
  647. document.onmousemove = null
  648. document.onmouseup = null
  649. }
  650. // Move slider according to the mouse position.
  651. document.onmousemove = (e) => {
  652. // Distance from the beginning of the bar in pixels.
  653. const diff = e.pageX - v.offsetLeft - track.offsetWidth/2
  654. // Don't move the track off the bar.
  655. if(diff >= 0 && diff <= v.offsetWidth-track.offsetWidth/2){
  656. // Convert the difference to a percentage.
  657. const perc = (diff/v.offsetWidth)*100
  658. // Calculate the percentage of the closest notch.
  659. const notch = Number(perc/sliderMeta.inc).toFixed(0)*sliderMeta.inc
  660. // If we're close to that notch, stick to it.
  661. if(Math.abs(perc-notch) < sliderMeta.inc/2){
  662. updateRangedSlider(v, sliderMeta.min+(sliderMeta.step*(notch/sliderMeta.inc)), notch)
  663. }
  664. }
  665. }
  666. }
  667. })
  668. }
  669. /**
  670. * Update a ranged slider's value and position.
  671. *
  672. * @param {Element} element The ranged slider to update.
  673. * @param {string | number} value The new value for the ranged slider.
  674. * @param {number} notch The notch that the slider should now be at.
  675. */
  676. function updateRangedSlider(element, value, notch){
  677. const oldVal = element.getAttribute('value')
  678. const bar = element.getElementsByClassName('rangeSliderBar')[0]
  679. const track = element.getElementsByClassName('rangeSliderTrack')[0]
  680. element.setAttribute('value', value)
  681. if(notch < 0){
  682. notch = 0
  683. } else if(notch > 100) {
  684. notch = 100
  685. }
  686. const event = new MouseEvent('change', {
  687. target: element,
  688. type: 'change',
  689. bubbles: false,
  690. cancelable: true
  691. })
  692. let cancelled = !element.dispatchEvent(event)
  693. if(!cancelled){
  694. track.style.left = notch + '%'
  695. bar.style.width = notch + '%'
  696. } else {
  697. element.setAttribute('value', oldVal)
  698. }
  699. }
  700. /**
  701. * Display the total and available RAM.
  702. */
  703. function populateMemoryStatus(){
  704. settingsMemoryTotal.innerHTML = Number((os.totalmem()-1000000000)/1000000000).toFixed(1) + 'G'
  705. settingsMemoryAvail.innerHTML = Number(os.freemem()/1000000000).toFixed(1) + 'G'
  706. }
  707. // Bind the executable file input to the display text input.
  708. settingsJavaExecSel.onchange = (e) => {
  709. settingsJavaExecVal.value = settingsJavaExecSel.files[0].path
  710. populateJavaExecDetails(settingsJavaExecVal.value)
  711. }
  712. /**
  713. * Validate the provided executable path and display the data on
  714. * the UI.
  715. *
  716. * @param {string} execPath The executable path to populate against.
  717. */
  718. function populateJavaExecDetails(execPath){
  719. AssetGuard._validateJavaBinary(execPath).then(v => {
  720. if(v.valid){
  721. settingsJavaExecDetails.innerHTML = `Selected: Java ${v.version.major} Update ${v.version.update} (x${v.arch})`
  722. } else {
  723. settingsJavaExecDetails.innerHTML = 'Invalid Selection'
  724. }
  725. })
  726. }
  727. /**
  728. * Prepare the Java tab for display.
  729. */
  730. function prepareJavaTab(){
  731. bindRangeSlider()
  732. populateMemoryStatus()
  733. }
  734. /**
  735. * About Tab
  736. */
  737. const settingsAboutCurrentVersionCheck = document.getElementById('settingsAboutCurrentVersionCheck')
  738. const settingsAboutCurrentVersionTitle = document.getElementById('settingsAboutCurrentVersionTitle')
  739. const settingsAboutCurrentVersionValue = document.getElementById('settingsAboutCurrentVersionValue')
  740. const settingsChangelogTitle = document.getElementById('settingsChangelogTitle')
  741. const settingsChangelogText = document.getElementById('settingsChangelogText')
  742. const settingsChangelogButton = document.getElementById('settingsChangelogButton')
  743. // Bind the devtools toggle button.
  744. document.getElementById('settingsAboutDevToolsButton').onclick = (e) => {
  745. let window = remote.getCurrentWindow()
  746. window.toggleDevTools()
  747. }
  748. /**
  749. * Retrieve the version information and display it on the UI.
  750. */
  751. function populateVersionInformation(){
  752. const version = remote.app.getVersion()
  753. settingsAboutCurrentVersionValue.innerHTML = version
  754. const preRelComp = semver.prerelease(version)
  755. if(preRelComp != null && preRelComp.length > 0){
  756. settingsAboutCurrentVersionTitle.innerHTML = 'Pre-release'
  757. settingsAboutCurrentVersionTitle.style.color = '#ff886d'
  758. settingsAboutCurrentVersionCheck.style.background = '#ff886d'
  759. } else {
  760. settingsAboutCurrentVersionTitle.innerHTML = 'Stable Release'
  761. settingsAboutCurrentVersionTitle.style.color = null
  762. settingsAboutCurrentVersionCheck.style.background = null
  763. }
  764. }
  765. /**
  766. * Fetches the GitHub atom release feed and parses it for the release notes
  767. * of the current version. This value is displayed on the UI.
  768. */
  769. function populateReleaseNotes(){
  770. $.ajax({
  771. url: 'https://github.com/WesterosCraftCode/ElectronLauncher/releases.atom',
  772. success: (data) => {
  773. const version = 'v' + remote.app.getVersion()
  774. const entries = $(data).find('entry')
  775. for(let i=0; i<entries.length; i++){
  776. const entry = $(entries[i])
  777. let id = entry.find('id').text()
  778. id = id.substring(id.lastIndexOf('/')+1)
  779. if(id === version){
  780. settingsChangelogTitle.innerHTML = entry.find('title').text()
  781. settingsChangelogText.innerHTML = entry.find('content').text()
  782. settingsChangelogButton.href = entry.find('link').attr('href')
  783. }
  784. }
  785. },
  786. timeout: 2500
  787. }).catch(err => {
  788. settingsChangelogText.innerHTML = 'Failed to load release notes.'
  789. })
  790. }
  791. /**
  792. * Prepare account tab for display.
  793. */
  794. function prepareAboutTab(){
  795. populateVersionInformation()
  796. populateReleaseNotes()
  797. }
  798. /**
  799. * Settings preparation functions.
  800. */
  801. /**
  802. * Prepare the entire settings UI.
  803. *
  804. * @param {boolean} first Whether or not it is the first load.
  805. */
  806. function prepareSettings(first = false) {
  807. if(first){
  808. setupSettingsTabs()
  809. initSettingsValidators()
  810. } else {
  811. prepareModsTab()
  812. }
  813. initSettingsValues()
  814. prepareAccountsTab()
  815. prepareJavaTab()
  816. prepareAboutTab()
  817. }
  818. // Prepare the settings UI on startup.
  819. prepareSettings(true)