settings.js 21 KB

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