settings.js 18 KB

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