settings.js 19 KB

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