settings.js 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537
  1. // Requirements
  2. const os = require('os')
  3. const semver = require('semver')
  4. const { JavaGuard } = require('./assets/js/assetguard')
  5. const DropinModUtil = require('./assets/js/dropinmodutil')
  6. const { MSFT_OPCODE, MSFT_REPLY_TYPE, MSFT_ERROR } = require('./assets/js/ipcconstants')
  7. const settingsState = {
  8. invalid: new Set()
  9. }
  10. function bindSettingsSelect(){
  11. for(let ele of document.getElementsByClassName('settingsSelectContainer')) {
  12. const selectedDiv = ele.getElementsByClassName('settingsSelectSelected')[0]
  13. selectedDiv.onclick = (e) => {
  14. e.stopPropagation()
  15. closeSettingsSelect(e.target)
  16. e.target.nextElementSibling.toggleAttribute('hidden')
  17. e.target.classList.toggle('select-arrow-active')
  18. }
  19. }
  20. }
  21. function closeSettingsSelect(el){
  22. for(let ele of document.getElementsByClassName('settingsSelectContainer')) {
  23. const selectedDiv = ele.getElementsByClassName('settingsSelectSelected')[0]
  24. const optionsDiv = ele.getElementsByClassName('settingsSelectOptions')[0]
  25. if(!(selectedDiv === el)) {
  26. selectedDiv.classList.remove('select-arrow-active')
  27. optionsDiv.setAttribute('hidden', '')
  28. }
  29. }
  30. }
  31. /* If the user clicks anywhere outside the select box,
  32. then close all select boxes: */
  33. document.addEventListener('click', closeSettingsSelect)
  34. bindSettingsSelect()
  35. function bindFileSelectors(){
  36. for(let ele of document.getElementsByClassName('settingsFileSelButton')){
  37. ele.onclick = async e => {
  38. const isJavaExecSel = ele.id === 'settingsJavaExecSel'
  39. const directoryDialog = ele.hasAttribute('dialogDirectory') && ele.getAttribute('dialogDirectory') == 'true'
  40. const properties = directoryDialog ? ['openDirectory', 'createDirectory'] : ['openFile']
  41. const options = {
  42. properties
  43. }
  44. if(ele.hasAttribute('dialogTitle')) {
  45. options.title = ele.getAttribute('dialogTitle')
  46. }
  47. if(isJavaExecSel && process.platform === 'win32') {
  48. options.filters = [
  49. { name: 'Executables', extensions: ['exe'] },
  50. { name: 'All Files', extensions: ['*'] }
  51. ]
  52. }
  53. const res = await remote.dialog.showOpenDialog(remote.getCurrentWindow(), options)
  54. if(!res.canceled) {
  55. ele.previousElementSibling.value = res.filePaths[0]
  56. if(isJavaExecSel) {
  57. populateJavaExecDetails(ele.previousElementSibling.value)
  58. }
  59. }
  60. }
  61. }
  62. }
  63. bindFileSelectors()
  64. /**
  65. * General Settings Functions
  66. */
  67. /**
  68. * Bind value validators to the settings UI elements. These will
  69. * validate against the criteria defined in the ConfigManager (if
  70. * any). If the value is invalid, the UI will reflect this and saving
  71. * will be disabled until the value is corrected. This is an automated
  72. * process. More complex UI may need to be bound separately.
  73. */
  74. function initSettingsValidators(){
  75. const sEls = document.getElementById('settingsContainer').querySelectorAll('[cValue]')
  76. Array.from(sEls).map((v, index, arr) => {
  77. const vFn = ConfigManager['validate' + v.getAttribute('cValue')]
  78. if(typeof vFn === 'function'){
  79. if(v.tagName === 'INPUT'){
  80. if(v.type === 'number' || v.type === 'text'){
  81. v.addEventListener('keyup', (e) => {
  82. const v = e.target
  83. if(!vFn(v.value)){
  84. settingsState.invalid.add(v.id)
  85. v.setAttribute('error', '')
  86. settingsSaveDisabled(true)
  87. } else {
  88. if(v.hasAttribute('error')){
  89. v.removeAttribute('error')
  90. settingsState.invalid.delete(v.id)
  91. if(settingsState.invalid.size === 0){
  92. settingsSaveDisabled(false)
  93. }
  94. }
  95. }
  96. })
  97. }
  98. }
  99. }
  100. })
  101. }
  102. /**
  103. * Load configuration values onto the UI. This is an automated process.
  104. */
  105. function initSettingsValues(){
  106. const sEls = document.getElementById('settingsContainer').querySelectorAll('[cValue]')
  107. Array.from(sEls).map((v, index, arr) => {
  108. const cVal = v.getAttribute('cValue')
  109. const gFn = ConfigManager['get' + cVal]
  110. if(typeof gFn === 'function'){
  111. if(v.tagName === 'INPUT'){
  112. if(v.type === 'number' || v.type === 'text'){
  113. // Special Conditions
  114. if(cVal === 'JavaExecutable'){
  115. populateJavaExecDetails(v.value)
  116. v.value = gFn()
  117. } else if (cVal === 'DataDirectory'){
  118. v.value = gFn()
  119. } else if(cVal === 'JVMOptions'){
  120. v.value = gFn().join(' ')
  121. } else {
  122. v.value = gFn()
  123. }
  124. } else if(v.type === 'checkbox'){
  125. v.checked = gFn()
  126. }
  127. } else if(v.tagName === 'DIV'){
  128. if(v.classList.contains('rangeSlider')){
  129. // Special Conditions
  130. if(cVal === 'MinRAM' || cVal === 'MaxRAM'){
  131. let val = gFn()
  132. if(val.endsWith('M')){
  133. val = Number(val.substring(0, val.length-1))/1000
  134. } else {
  135. val = Number.parseFloat(val)
  136. }
  137. v.setAttribute('value', val)
  138. } else {
  139. v.setAttribute('value', Number.parseFloat(gFn()))
  140. }
  141. }
  142. }
  143. }
  144. })
  145. }
  146. /**
  147. * Save the settings values.
  148. */
  149. function saveSettingsValues(){
  150. const sEls = document.getElementById('settingsContainer').querySelectorAll('[cValue]')
  151. Array.from(sEls).map((v, index, arr) => {
  152. const cVal = v.getAttribute('cValue')
  153. const sFn = ConfigManager['set' + cVal]
  154. if(typeof sFn === 'function'){
  155. if(v.tagName === 'INPUT'){
  156. if(v.type === 'number' || v.type === 'text'){
  157. // Special Conditions
  158. if(cVal === 'JVMOptions'){
  159. if(!v.value.trim()) {
  160. sFn([])
  161. } else {
  162. sFn(v.value.trim().split(/\s+/))
  163. }
  164. } else {
  165. sFn(v.value)
  166. }
  167. } else if(v.type === 'checkbox'){
  168. sFn(v.checked)
  169. // Special Conditions
  170. if(cVal === 'AllowPrerelease'){
  171. changeAllowPrerelease(v.checked)
  172. }
  173. }
  174. } else if(v.tagName === 'DIV'){
  175. if(v.classList.contains('rangeSlider')){
  176. // Special Conditions
  177. if(cVal === 'MinRAM' || cVal === 'MaxRAM'){
  178. let val = Number(v.getAttribute('value'))
  179. if(val%1 > 0){
  180. val = val*1000 + 'M'
  181. } else {
  182. val = val + 'G'
  183. }
  184. sFn(val)
  185. } else {
  186. sFn(v.getAttribute('value'))
  187. }
  188. }
  189. }
  190. }
  191. })
  192. }
  193. let selectedSettingsTab = 'settingsTabAccount'
  194. /**
  195. * Modify the settings container UI when the scroll threshold reaches
  196. * a certain poin.
  197. *
  198. * @param {UIEvent} e The scroll event.
  199. */
  200. function settingsTabScrollListener(e){
  201. if(e.target.scrollTop > Number.parseFloat(getComputedStyle(e.target.firstElementChild).marginTop)){
  202. document.getElementById('settingsContainer').setAttribute('scrolled', '')
  203. } else {
  204. document.getElementById('settingsContainer').removeAttribute('scrolled')
  205. }
  206. }
  207. /**
  208. * Bind functionality for the settings navigation items.
  209. */
  210. function setupSettingsTabs(){
  211. Array.from(document.getElementsByClassName('settingsNavItem')).map((val) => {
  212. if(val.hasAttribute('rSc')){
  213. val.onclick = () => {
  214. settingsNavItemListener(val)
  215. }
  216. }
  217. })
  218. }
  219. /**
  220. * Settings nav item onclick lisener. Function is exposed so that
  221. * other UI elements can quickly toggle to a certain tab from other views.
  222. *
  223. * @param {Element} ele The nav item which has been clicked.
  224. * @param {boolean} fade Optional. True to fade transition.
  225. */
  226. function settingsNavItemListener(ele, fade = true){
  227. if(ele.hasAttribute('selected')){
  228. return
  229. }
  230. const navItems = document.getElementsByClassName('settingsNavItem')
  231. for(let i=0; i<navItems.length; i++){
  232. if(navItems[i].hasAttribute('selected')){
  233. navItems[i].removeAttribute('selected')
  234. }
  235. }
  236. ele.setAttribute('selected', '')
  237. let prevTab = selectedSettingsTab
  238. selectedSettingsTab = ele.getAttribute('rSc')
  239. document.getElementById(prevTab).onscroll = null
  240. document.getElementById(selectedSettingsTab).onscroll = settingsTabScrollListener
  241. if(fade){
  242. $(`#${prevTab}`).fadeOut(250, () => {
  243. $(`#${selectedSettingsTab}`).fadeIn({
  244. duration: 250,
  245. start: () => {
  246. settingsTabScrollListener({
  247. target: document.getElementById(selectedSettingsTab)
  248. })
  249. }
  250. })
  251. })
  252. } else {
  253. $(`#${prevTab}`).hide(0, () => {
  254. $(`#${selectedSettingsTab}`).show({
  255. duration: 0,
  256. start: () => {
  257. settingsTabScrollListener({
  258. target: document.getElementById(selectedSettingsTab)
  259. })
  260. }
  261. })
  262. })
  263. }
  264. }
  265. const settingsNavDone = document.getElementById('settingsNavDone')
  266. /**
  267. * Set if the settings save (done) button is disabled.
  268. *
  269. * @param {boolean} v True to disable, false to enable.
  270. */
  271. function settingsSaveDisabled(v){
  272. settingsNavDone.disabled = v
  273. }
  274. /* Closes the settings view and saves all data. */
  275. settingsNavDone.onclick = () => {
  276. saveSettingsValues()
  277. saveModConfiguration()
  278. ConfigManager.save()
  279. saveDropinModConfiguration()
  280. saveShaderpackSettings()
  281. switchView(getCurrentView(), VIEWS.landing)
  282. }
  283. /**
  284. * Account Management Tab
  285. */
  286. const msftLoginLogger = LoggerUtil.getLogger('Microsoft Login')
  287. const msftLogoutLogger = LoggerUtil.getLogger('Microsoft Logout')
  288. // Bind the add mojang account button.
  289. document.getElementById('settingsAddMojangAccount').onclick = (e) => {
  290. switchView(getCurrentView(), VIEWS.login, 500, 500, () => {
  291. loginViewOnCancel = VIEWS.settings
  292. loginViewOnSuccess = VIEWS.settings
  293. loginCancelEnabled(true)
  294. })
  295. }
  296. // Bind the add microsoft account button.
  297. document.getElementById('settingsAddMicrosoftAccount').onclick = (e) => {
  298. switchView(getCurrentView(), VIEWS.waiting, 500, 500, () => {
  299. ipcRenderer.send(MSFT_OPCODE.OPEN_LOGIN, VIEWS.settings, VIEWS.settings)
  300. })
  301. }
  302. // Bind reply for Microsoft Login.
  303. ipcRenderer.on(MSFT_OPCODE.REPLY_LOGIN, (_, ...arguments_) => {
  304. if (arguments_[0] === MSFT_REPLY_TYPE.ERROR) {
  305. const viewOnClose = arguments_[2]
  306. console.log(arguments_)
  307. switchView(getCurrentView(), viewOnClose, 500, 500, () => {
  308. if(arguments_[1] === MSFT_ERROR.NOT_FINISHED) {
  309. // User cancelled.
  310. msftLoginLogger.info('Login cancelled by user.')
  311. return
  312. }
  313. // Unexpected error.
  314. setOverlayContent(
  315. 'Something Went Wrong',
  316. 'Microsoft authentication failed. Please try again.',
  317. 'OK'
  318. )
  319. setOverlayHandler(() => {
  320. toggleOverlay(false)
  321. })
  322. toggleOverlay(true)
  323. })
  324. } else if(arguments_[0] === MSFT_REPLY_TYPE.SUCCESS) {
  325. const queryMap = arguments_[1]
  326. const viewOnClose = arguments_[2]
  327. // Error from request to Microsoft.
  328. if (Object.prototype.hasOwnProperty.call(queryMap, 'error')) {
  329. switchView(getCurrentView(), viewOnClose, 500, 500, () => {
  330. // TODO Dont know what these errors are. Just show them I guess.
  331. // This is probably if you messed up the app registration with Azure.
  332. console.log('Error getting authCode, is Azure application registered correctly?')
  333. console.log(error)
  334. console.log(error_description)
  335. console.log('Full query map', queryMap)
  336. let error = queryMap.error // Error might be 'access_denied' ?
  337. let errorDesc = queryMap.error_description
  338. setOverlayContent(
  339. error,
  340. errorDesc,
  341. 'OK'
  342. )
  343. setOverlayHandler(() => {
  344. toggleOverlay(false)
  345. })
  346. toggleOverlay(true)
  347. })
  348. } else {
  349. msftLoginLogger.info('Acquired authCode, proceeding with authentication.')
  350. const authCode = queryMap.code
  351. AuthManager.addMicrosoftAccount(authCode).then(value => {
  352. updateSelectedAccount(value)
  353. switchView(getCurrentView(), viewOnClose, 500, 500, () => {
  354. prepareSettings()
  355. })
  356. })
  357. .catch((displayableError) => {
  358. let actualDisplayableError
  359. if(isDisplayableError(displayableError)) {
  360. msftLoginLogger.error('Error while logging in.', displayableError)
  361. actualDisplayableError = displayableError
  362. } else {
  363. // Uh oh.
  364. msftLoginLogger.error('Unhandled error during login.', displayableError)
  365. actualDisplayableError = {
  366. title: 'Unknown Error During Login',
  367. desc: 'An unknown error has occurred. Please see the console for details.'
  368. }
  369. }
  370. switchView(getCurrentView(), viewOnClose, 500, 500, () => {
  371. setOverlayContent(actualDisplayableError.title, actualDisplayableError.desc, Lang.queryJS('login.tryAgain'))
  372. setOverlayHandler(() => {
  373. toggleOverlay(false)
  374. })
  375. toggleOverlay(true)
  376. })
  377. })
  378. }
  379. }
  380. })
  381. /**
  382. * Bind functionality for the account selection buttons. If another account
  383. * is selected, the UI of the previously selected account will be updated.
  384. */
  385. function bindAuthAccountSelect(){
  386. Array.from(document.getElementsByClassName('settingsAuthAccountSelect')).map((val) => {
  387. val.onclick = (e) => {
  388. if(val.hasAttribute('selected')){
  389. return
  390. }
  391. const selectBtns = document.getElementsByClassName('settingsAuthAccountSelect')
  392. for(let i=0; i<selectBtns.length; i++){
  393. if(selectBtns[i].hasAttribute('selected')){
  394. selectBtns[i].removeAttribute('selected')
  395. selectBtns[i].innerHTML = 'Select Account'
  396. }
  397. }
  398. val.setAttribute('selected', '')
  399. val.innerHTML = 'Selected Account &#10004;'
  400. setSelectedAccount(val.closest('.settingsAuthAccount').getAttribute('uuid'))
  401. }
  402. })
  403. }
  404. /**
  405. * Bind functionality for the log out button. If the logged out account was
  406. * the selected account, another account will be selected and the UI will
  407. * be updated accordingly.
  408. */
  409. function bindAuthAccountLogOut(){
  410. Array.from(document.getElementsByClassName('settingsAuthAccountLogOut')).map((val) => {
  411. val.onclick = (e) => {
  412. let isLastAccount = false
  413. if(Object.keys(ConfigManager.getAuthAccounts()).length === 1){
  414. isLastAccount = true
  415. setOverlayContent(
  416. 'Warning<br>This is Your Last Account',
  417. '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?',
  418. 'I\'m Sure',
  419. 'Cancel'
  420. )
  421. setOverlayHandler(() => {
  422. processLogOut(val, isLastAccount)
  423. toggleOverlay(false)
  424. })
  425. setDismissHandler(() => {
  426. toggleOverlay(false)
  427. })
  428. toggleOverlay(true, true)
  429. } else {
  430. processLogOut(val, isLastAccount)
  431. }
  432. }
  433. })
  434. }
  435. let msAccDomElementCache
  436. /**
  437. * Process a log out.
  438. *
  439. * @param {Element} val The log out button element.
  440. * @param {boolean} isLastAccount If this logout is on the last added account.
  441. */
  442. function processLogOut(val, isLastAccount){
  443. const parent = val.closest('.settingsAuthAccount')
  444. const uuid = parent.getAttribute('uuid')
  445. const prevSelAcc = ConfigManager.getSelectedAccount()
  446. const targetAcc = ConfigManager.getAuthAccount(uuid)
  447. if(targetAcc.type === 'microsoft') {
  448. msAccDomElementCache = parent
  449. switchView(getCurrentView(), VIEWS.waiting, 500, 500, () => {
  450. ipcRenderer.send(MSFT_OPCODE.OPEN_LOGOUT, uuid, isLastAccount)
  451. })
  452. } else {
  453. AuthManager.removeMojangAccount(uuid).then(() => {
  454. if(!isLastAccount && uuid === prevSelAcc.uuid){
  455. const selAcc = ConfigManager.getSelectedAccount()
  456. refreshAuthAccountSelected(selAcc.uuid)
  457. updateSelectedAccount(selAcc)
  458. validateSelectedAccount()
  459. }
  460. if(isLastAccount) {
  461. loginOptionsCancelEnabled(false)
  462. loginOptionsViewOnLoginSuccess = VIEWS.settings
  463. loginOptionsViewOnLoginCancel = VIEWS.loginOptions
  464. switchView(getCurrentView(), VIEWS.loginOptions)
  465. }
  466. })
  467. $(parent).fadeOut(250, () => {
  468. parent.remove()
  469. })
  470. }
  471. }
  472. // Bind reply for Microsoft Logout.
  473. ipcRenderer.on(MSFT_OPCODE.REPLY_LOGOUT, (_, ...arguments_) => {
  474. if (arguments_[0] === MSFT_REPLY_TYPE.ERROR) {
  475. switchView(getCurrentView(), VIEWS.settings, 500, 500, () => {
  476. if(arguments_.length > 1 && arguments_[1] === MSFT_ERROR.NOT_FINISHED) {
  477. // User cancelled.
  478. msftLogoutLogger.info('Logout cancelled by user.')
  479. return
  480. }
  481. // Unexpected error.
  482. setOverlayContent(
  483. 'Something Went Wrong',
  484. 'Microsoft logout failed. Please try again.',
  485. 'OK'
  486. )
  487. setOverlayHandler(() => {
  488. toggleOverlay(false)
  489. })
  490. toggleOverlay(true)
  491. })
  492. } else if(arguments_[0] === MSFT_REPLY_TYPE.SUCCESS) {
  493. const uuid = arguments_[1]
  494. const isLastAccount = arguments_[2]
  495. const prevSelAcc = ConfigManager.getSelectedAccount()
  496. msftLogoutLogger.info('Logout Successful. uuid:', uuid)
  497. AuthManager.removeMicrosoftAccount(uuid)
  498. .then(() => {
  499. if(!isLastAccount && uuid === prevSelAcc.uuid){
  500. const selAcc = ConfigManager.getSelectedAccount()
  501. refreshAuthAccountSelected(selAcc.uuid)
  502. updateSelectedAccount(selAcc)
  503. validateSelectedAccount()
  504. }
  505. if(isLastAccount) {
  506. loginOptionsCancelEnabled(false)
  507. loginOptionsViewOnLoginSuccess = VIEWS.settings
  508. loginOptionsViewOnLoginCancel = VIEWS.loginOptions
  509. switchView(getCurrentView(), VIEWS.loginOptions)
  510. }
  511. if(msAccDomElementCache) {
  512. msAccDomElementCache.remove()
  513. msAccDomElementCache = null
  514. }
  515. })
  516. .finally(() => {
  517. if(!isLastAccount) {
  518. switchView(getCurrentView(), VIEWS.settings, 500, 500)
  519. }
  520. })
  521. }
  522. })
  523. /**
  524. * Refreshes the status of the selected account on the auth account
  525. * elements.
  526. *
  527. * @param {string} uuid The UUID of the new selected account.
  528. */
  529. function refreshAuthAccountSelected(uuid){
  530. Array.from(document.getElementsByClassName('settingsAuthAccount')).map((val) => {
  531. const selBtn = val.getElementsByClassName('settingsAuthAccountSelect')[0]
  532. if(uuid === val.getAttribute('uuid')){
  533. selBtn.setAttribute('selected', '')
  534. selBtn.innerHTML = 'Selected Account &#10004;'
  535. } else {
  536. if(selBtn.hasAttribute('selected')){
  537. selBtn.removeAttribute('selected')
  538. }
  539. selBtn.innerHTML = 'Select Account'
  540. }
  541. })
  542. }
  543. const settingsCurrentMicrosoftAccounts = document.getElementById('settingsCurrentMicrosoftAccounts')
  544. const settingsCurrentMojangAccounts = document.getElementById('settingsCurrentMojangAccounts')
  545. /**
  546. * Add auth account elements for each one stored in the authentication database.
  547. */
  548. function populateAuthAccounts(){
  549. const authAccounts = ConfigManager.getAuthAccounts()
  550. const authKeys = Object.keys(authAccounts)
  551. if(authKeys.length === 0){
  552. return
  553. }
  554. const selectedUUID = ConfigManager.getSelectedAccount().uuid
  555. let microsoftAuthAccountStr = ''
  556. let mojangAuthAccountStr = ''
  557. authKeys.forEach((val) => {
  558. const acc = authAccounts[val]
  559. const accHtml = `<div class="settingsAuthAccount" uuid="${acc.uuid}">
  560. <div class="settingsAuthAccountLeft">
  561. <img class="settingsAuthAccountImage" alt="${acc.displayName}" src="https://mc-heads.net/body/${acc.uuid}/60">
  562. </div>
  563. <div class="settingsAuthAccountRight">
  564. <div class="settingsAuthAccountDetails">
  565. <div class="settingsAuthAccountDetailPane">
  566. <div class="settingsAuthAccountDetailTitle">Username</div>
  567. <div class="settingsAuthAccountDetailValue">${acc.displayName}</div>
  568. </div>
  569. <div class="settingsAuthAccountDetailPane">
  570. <div class="settingsAuthAccountDetailTitle">UUID</div>
  571. <div class="settingsAuthAccountDetailValue">${acc.uuid}</div>
  572. </div>
  573. </div>
  574. <div class="settingsAuthAccountActions">
  575. <button class="settingsAuthAccountSelect" ${selectedUUID === acc.uuid ? 'selected>Selected Account &#10004;' : '>Select Account'}</button>
  576. <div class="settingsAuthAccountWrapper">
  577. <button class="settingsAuthAccountLogOut">Log Out</button>
  578. </div>
  579. </div>
  580. </div>
  581. </div>`
  582. if(acc.type === 'microsoft') {
  583. microsoftAuthAccountStr += accHtml
  584. } else {
  585. mojangAuthAccountStr += accHtml
  586. }
  587. })
  588. settingsCurrentMicrosoftAccounts.innerHTML = microsoftAuthAccountStr
  589. settingsCurrentMojangAccounts.innerHTML = mojangAuthAccountStr
  590. }
  591. /**
  592. * Prepare the accounts tab for display.
  593. */
  594. function prepareAccountsTab() {
  595. populateAuthAccounts()
  596. bindAuthAccountSelect()
  597. bindAuthAccountLogOut()
  598. }
  599. /**
  600. * Minecraft Tab
  601. */
  602. /**
  603. * Disable decimals, negative signs, and scientific notation.
  604. */
  605. document.getElementById('settingsGameWidth').addEventListener('keydown', (e) => {
  606. if(/^[-.eE]$/.test(e.key)){
  607. e.preventDefault()
  608. }
  609. })
  610. document.getElementById('settingsGameHeight').addEventListener('keydown', (e) => {
  611. if(/^[-.eE]$/.test(e.key)){
  612. e.preventDefault()
  613. }
  614. })
  615. /**
  616. * Mods Tab
  617. */
  618. const settingsModsContainer = document.getElementById('settingsModsContainer')
  619. /**
  620. * Resolve and update the mods on the UI.
  621. */
  622. function resolveModsForUI(){
  623. const serv = ConfigManager.getSelectedServer()
  624. const distro = DistroManager.getDistribution()
  625. const servConf = ConfigManager.getModConfiguration(serv)
  626. const modStr = parseModulesForUI(distro.getServer(serv).getModules(), false, servConf.mods)
  627. document.getElementById('settingsReqModsContent').innerHTML = modStr.reqMods
  628. document.getElementById('settingsOptModsContent').innerHTML = modStr.optMods
  629. }
  630. /**
  631. * Recursively build the mod UI elements.
  632. *
  633. * @param {Object[]} mdls An array of modules to parse.
  634. * @param {boolean} submodules Whether or not we are parsing submodules.
  635. * @param {Object} servConf The server configuration object for this module level.
  636. */
  637. function parseModulesForUI(mdls, submodules, servConf){
  638. let reqMods = ''
  639. let optMods = ''
  640. for(const mdl of mdls){
  641. if(mdl.getType() === DistroManager.Types.ForgeMod || mdl.getType() === DistroManager.Types.LiteMod || mdl.getType() === DistroManager.Types.LiteLoader){
  642. if(mdl.getRequired().isRequired()){
  643. reqMods += `<div id="${mdl.getVersionlessID()}" class="settingsBaseMod settings${submodules ? 'Sub' : ''}Mod" enabled>
  644. <div class="settingsModContent">
  645. <div class="settingsModMainWrapper">
  646. <div class="settingsModStatus"></div>
  647. <div class="settingsModDetails">
  648. <span class="settingsModName">${mdl.getName()}</span>
  649. <span class="settingsModVersion">v${mdl.getVersion()}</span>
  650. </div>
  651. </div>
  652. <label class="toggleSwitch" reqmod>
  653. <input type="checkbox" checked>
  654. <span class="toggleSwitchSlider"></span>
  655. </label>
  656. </div>
  657. ${mdl.hasSubModules() ? `<div class="settingsSubModContainer">
  658. ${Object.values(parseModulesForUI(mdl.getSubModules(), true, servConf[mdl.getVersionlessID()])).join('')}
  659. </div>` : ''}
  660. </div>`
  661. } else {
  662. const conf = servConf[mdl.getVersionlessID()]
  663. const val = typeof conf === 'object' ? conf.value : conf
  664. optMods += `<div id="${mdl.getVersionlessID()}" class="settingsBaseMod settings${submodules ? 'Sub' : ''}Mod" ${val ? 'enabled' : ''}>
  665. <div class="settingsModContent">
  666. <div class="settingsModMainWrapper">
  667. <div class="settingsModStatus"></div>
  668. <div class="settingsModDetails">
  669. <span class="settingsModName">${mdl.getName()}</span>
  670. <span class="settingsModVersion">v${mdl.getVersion()}</span>
  671. </div>
  672. </div>
  673. <label class="toggleSwitch">
  674. <input type="checkbox" formod="${mdl.getVersionlessID()}" ${val ? 'checked' : ''}>
  675. <span class="toggleSwitchSlider"></span>
  676. </label>
  677. </div>
  678. ${mdl.hasSubModules() ? `<div class="settingsSubModContainer">
  679. ${Object.values(parseModulesForUI(mdl.getSubModules(), true, conf.mods)).join('')}
  680. </div>` : ''}
  681. </div>`
  682. }
  683. }
  684. }
  685. return {
  686. reqMods,
  687. optMods
  688. }
  689. }
  690. /**
  691. * Bind functionality to mod config toggle switches. Switching the value
  692. * will also switch the status color on the left of the mod UI.
  693. */
  694. function bindModsToggleSwitch(){
  695. const sEls = settingsModsContainer.querySelectorAll('[formod]')
  696. Array.from(sEls).map((v, index, arr) => {
  697. v.onchange = () => {
  698. if(v.checked) {
  699. document.getElementById(v.getAttribute('formod')).setAttribute('enabled', '')
  700. } else {
  701. document.getElementById(v.getAttribute('formod')).removeAttribute('enabled')
  702. }
  703. }
  704. })
  705. }
  706. /**
  707. * Save the mod configuration based on the UI values.
  708. */
  709. function saveModConfiguration(){
  710. const serv = ConfigManager.getSelectedServer()
  711. const modConf = ConfigManager.getModConfiguration(serv)
  712. modConf.mods = _saveModConfiguration(modConf.mods)
  713. ConfigManager.setModConfiguration(serv, modConf)
  714. }
  715. /**
  716. * Recursively save mod config with submods.
  717. *
  718. * @param {Object} modConf Mod config object to save.
  719. */
  720. function _saveModConfiguration(modConf){
  721. for(let m of Object.entries(modConf)){
  722. const tSwitch = settingsModsContainer.querySelectorAll(`[formod='${m[0]}']`)
  723. if(!tSwitch[0].hasAttribute('dropin')){
  724. if(typeof m[1] === 'boolean'){
  725. modConf[m[0]] = tSwitch[0].checked
  726. } else {
  727. if(m[1] != null){
  728. if(tSwitch.length > 0){
  729. modConf[m[0]].value = tSwitch[0].checked
  730. }
  731. modConf[m[0]].mods = _saveModConfiguration(modConf[m[0]].mods)
  732. }
  733. }
  734. }
  735. }
  736. return modConf
  737. }
  738. // Drop-in mod elements.
  739. let CACHE_SETTINGS_MODS_DIR
  740. let CACHE_DROPIN_MODS
  741. /**
  742. * Resolve any located drop-in mods for this server and
  743. * populate the results onto the UI.
  744. */
  745. function resolveDropinModsForUI(){
  746. const serv = DistroManager.getDistribution().getServer(ConfigManager.getSelectedServer())
  747. CACHE_SETTINGS_MODS_DIR = path.join(ConfigManager.getInstanceDirectory(), serv.getID(), 'mods')
  748. CACHE_DROPIN_MODS = DropinModUtil.scanForDropinMods(CACHE_SETTINGS_MODS_DIR, serv.getMinecraftVersion())
  749. let dropinMods = ''
  750. for(dropin of CACHE_DROPIN_MODS){
  751. dropinMods += `<div id="${dropin.fullName}" class="settingsBaseMod settingsDropinMod" ${!dropin.disabled ? 'enabled' : ''}>
  752. <div class="settingsModContent">
  753. <div class="settingsModMainWrapper">
  754. <div class="settingsModStatus"></div>
  755. <div class="settingsModDetails">
  756. <span class="settingsModName">${dropin.name}</span>
  757. <div class="settingsDropinRemoveWrapper">
  758. <button class="settingsDropinRemoveButton" remmod="${dropin.fullName}">Remove</button>
  759. </div>
  760. </div>
  761. </div>
  762. <label class="toggleSwitch">
  763. <input type="checkbox" formod="${dropin.fullName}" dropin ${!dropin.disabled ? 'checked' : ''}>
  764. <span class="toggleSwitchSlider"></span>
  765. </label>
  766. </div>
  767. </div>`
  768. }
  769. document.getElementById('settingsDropinModsContent').innerHTML = dropinMods
  770. }
  771. /**
  772. * Bind the remove button for each loaded drop-in mod.
  773. */
  774. function bindDropinModsRemoveButton(){
  775. const sEls = settingsModsContainer.querySelectorAll('[remmod]')
  776. Array.from(sEls).map((v, index, arr) => {
  777. v.onclick = async () => {
  778. const fullName = v.getAttribute('remmod')
  779. const res = await DropinModUtil.deleteDropinMod(CACHE_SETTINGS_MODS_DIR, fullName)
  780. if(res){
  781. document.getElementById(fullName).remove()
  782. } else {
  783. setOverlayContent(
  784. `Failed to Delete<br>Drop-in Mod ${fullName}`,
  785. 'Make sure the file is not in use and try again.',
  786. 'Okay'
  787. )
  788. setOverlayHandler(null)
  789. toggleOverlay(true)
  790. }
  791. }
  792. })
  793. }
  794. /**
  795. * Bind functionality to the file system button for the selected
  796. * server configuration.
  797. */
  798. function bindDropinModFileSystemButton(){
  799. const fsBtn = document.getElementById('settingsDropinFileSystemButton')
  800. fsBtn.onclick = () => {
  801. DropinModUtil.validateDir(CACHE_SETTINGS_MODS_DIR)
  802. shell.openPath(CACHE_SETTINGS_MODS_DIR)
  803. }
  804. fsBtn.ondragenter = e => {
  805. e.dataTransfer.dropEffect = 'move'
  806. fsBtn.setAttribute('drag', '')
  807. e.preventDefault()
  808. }
  809. fsBtn.ondragover = e => {
  810. e.preventDefault()
  811. }
  812. fsBtn.ondragleave = e => {
  813. fsBtn.removeAttribute('drag')
  814. }
  815. fsBtn.ondrop = e => {
  816. fsBtn.removeAttribute('drag')
  817. e.preventDefault()
  818. DropinModUtil.addDropinMods(e.dataTransfer.files, CACHE_SETTINGS_MODS_DIR)
  819. reloadDropinMods()
  820. }
  821. }
  822. /**
  823. * Save drop-in mod states. Enabling and disabling is just a matter
  824. * of adding/removing the .disabled extension.
  825. */
  826. function saveDropinModConfiguration(){
  827. for(dropin of CACHE_DROPIN_MODS){
  828. const dropinUI = document.getElementById(dropin.fullName)
  829. if(dropinUI != null){
  830. const dropinUIEnabled = dropinUI.hasAttribute('enabled')
  831. if(DropinModUtil.isDropinModEnabled(dropin.fullName) != dropinUIEnabled){
  832. DropinModUtil.toggleDropinMod(CACHE_SETTINGS_MODS_DIR, dropin.fullName, dropinUIEnabled).catch(err => {
  833. if(!isOverlayVisible()){
  834. setOverlayContent(
  835. 'Failed to Toggle<br>One or More Drop-in Mods',
  836. err.message,
  837. 'Okay'
  838. )
  839. setOverlayHandler(null)
  840. toggleOverlay(true)
  841. }
  842. })
  843. }
  844. }
  845. }
  846. }
  847. // Refresh the drop-in mods when F5 is pressed.
  848. // Only active on the mods tab.
  849. document.addEventListener('keydown', (e) => {
  850. if(getCurrentView() === VIEWS.settings && selectedSettingsTab === 'settingsTabMods'){
  851. if(e.key === 'F5'){
  852. reloadDropinMods()
  853. saveShaderpackSettings()
  854. resolveShaderpacksForUI()
  855. }
  856. }
  857. })
  858. function reloadDropinMods(){
  859. resolveDropinModsForUI()
  860. bindDropinModsRemoveButton()
  861. bindDropinModFileSystemButton()
  862. bindModsToggleSwitch()
  863. }
  864. // Shaderpack
  865. let CACHE_SETTINGS_INSTANCE_DIR
  866. let CACHE_SHADERPACKS
  867. let CACHE_SELECTED_SHADERPACK
  868. /**
  869. * Load shaderpack information.
  870. */
  871. function resolveShaderpacksForUI(){
  872. const serv = DistroManager.getDistribution().getServer(ConfigManager.getSelectedServer())
  873. CACHE_SETTINGS_INSTANCE_DIR = path.join(ConfigManager.getInstanceDirectory(), serv.getID())
  874. CACHE_SHADERPACKS = DropinModUtil.scanForShaderpacks(CACHE_SETTINGS_INSTANCE_DIR)
  875. CACHE_SELECTED_SHADERPACK = DropinModUtil.getEnabledShaderpack(CACHE_SETTINGS_INSTANCE_DIR)
  876. setShadersOptions(CACHE_SHADERPACKS, CACHE_SELECTED_SHADERPACK)
  877. }
  878. function setShadersOptions(arr, selected){
  879. const cont = document.getElementById('settingsShadersOptions')
  880. cont.innerHTML = ''
  881. for(let opt of arr) {
  882. const d = document.createElement('DIV')
  883. d.innerHTML = opt.name
  884. d.setAttribute('value', opt.fullName)
  885. if(opt.fullName === selected) {
  886. d.setAttribute('selected', '')
  887. document.getElementById('settingsShadersSelected').innerHTML = opt.name
  888. }
  889. d.addEventListener('click', function(e) {
  890. this.parentNode.previousElementSibling.innerHTML = this.innerHTML
  891. for(let sib of this.parentNode.children){
  892. sib.removeAttribute('selected')
  893. }
  894. this.setAttribute('selected', '')
  895. closeSettingsSelect()
  896. })
  897. cont.appendChild(d)
  898. }
  899. }
  900. function saveShaderpackSettings(){
  901. let sel = 'OFF'
  902. for(let opt of document.getElementById('settingsShadersOptions').childNodes){
  903. if(opt.hasAttribute('selected')){
  904. sel = opt.getAttribute('value')
  905. }
  906. }
  907. DropinModUtil.setEnabledShaderpack(CACHE_SETTINGS_INSTANCE_DIR, sel)
  908. }
  909. function bindShaderpackButton() {
  910. const spBtn = document.getElementById('settingsShaderpackButton')
  911. spBtn.onclick = () => {
  912. const p = path.join(CACHE_SETTINGS_INSTANCE_DIR, 'shaderpacks')
  913. DropinModUtil.validateDir(p)
  914. shell.openPath(p)
  915. }
  916. spBtn.ondragenter = e => {
  917. e.dataTransfer.dropEffect = 'move'
  918. spBtn.setAttribute('drag', '')
  919. e.preventDefault()
  920. }
  921. spBtn.ondragover = e => {
  922. e.preventDefault()
  923. }
  924. spBtn.ondragleave = e => {
  925. spBtn.removeAttribute('drag')
  926. }
  927. spBtn.ondrop = e => {
  928. spBtn.removeAttribute('drag')
  929. e.preventDefault()
  930. DropinModUtil.addShaderpacks(e.dataTransfer.files, CACHE_SETTINGS_INSTANCE_DIR)
  931. saveShaderpackSettings()
  932. resolveShaderpacksForUI()
  933. }
  934. }
  935. // Server status bar functions.
  936. /**
  937. * Load the currently selected server information onto the mods tab.
  938. */
  939. function loadSelectedServerOnModsTab(){
  940. const serv = DistroManager.getDistribution().getServer(ConfigManager.getSelectedServer())
  941. document.getElementById('settingsSelServContent').innerHTML = `
  942. <img class="serverListingImg" src="${serv.getIcon()}"/>
  943. <div class="serverListingDetails">
  944. <span class="serverListingName">${serv.getName()}</span>
  945. <span class="serverListingDescription">${serv.getDescription()}</span>
  946. <div class="serverListingInfo">
  947. <div class="serverListingVersion">${serv.getMinecraftVersion()}</div>
  948. <div class="serverListingRevision">${serv.getVersion()}</div>
  949. ${serv.isMainServer() ? `<div class="serverListingStarWrapper">
  950. <svg id="Layer_1" viewBox="0 0 107.45 104.74" width="20px" height="20px">
  951. <defs>
  952. <style>.cls-1{fill:#fff;}.cls-2{fill:none;stroke:#fff;stroke-miterlimit:10;}</style>
  953. </defs>
  954. <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"/>
  955. <circle class="cls-2" cx="53.73" cy="53.9" r="38"/>
  956. </svg>
  957. <span class="serverListingStarTooltip">Main Server</span>
  958. </div>` : ''}
  959. </div>
  960. </div>
  961. `
  962. }
  963. // Bind functionality to the server switch button.
  964. document.getElementById('settingsSwitchServerButton').addEventListener('click', (e) => {
  965. e.target.blur()
  966. toggleServerSelection(true)
  967. })
  968. /**
  969. * Save mod configuration for the current selected server.
  970. */
  971. function saveAllModConfigurations(){
  972. saveModConfiguration()
  973. ConfigManager.save()
  974. saveDropinModConfiguration()
  975. }
  976. /**
  977. * Function to refresh the mods tab whenever the selected
  978. * server is changed.
  979. */
  980. function animateModsTabRefresh(){
  981. $('#settingsTabMods').fadeOut(500, () => {
  982. prepareModsTab()
  983. $('#settingsTabMods').fadeIn(500)
  984. })
  985. }
  986. /**
  987. * Prepare the Mods tab for display.
  988. */
  989. function prepareModsTab(first){
  990. resolveModsForUI()
  991. resolveDropinModsForUI()
  992. resolveShaderpacksForUI()
  993. bindDropinModsRemoveButton()
  994. bindDropinModFileSystemButton()
  995. bindShaderpackButton()
  996. bindModsToggleSwitch()
  997. loadSelectedServerOnModsTab()
  998. }
  999. /**
  1000. * Java Tab
  1001. */
  1002. // DOM Cache
  1003. const settingsMaxRAMRange = document.getElementById('settingsMaxRAMRange')
  1004. const settingsMinRAMRange = document.getElementById('settingsMinRAMRange')
  1005. const settingsMaxRAMLabel = document.getElementById('settingsMaxRAMLabel')
  1006. const settingsMinRAMLabel = document.getElementById('settingsMinRAMLabel')
  1007. const settingsMemoryTotal = document.getElementById('settingsMemoryTotal')
  1008. const settingsMemoryAvail = document.getElementById('settingsMemoryAvail')
  1009. const settingsJavaExecDetails = document.getElementById('settingsJavaExecDetails')
  1010. // Store maximum memory values.
  1011. const SETTINGS_MAX_MEMORY = ConfigManager.getAbsoluteMaxRAM()
  1012. const SETTINGS_MIN_MEMORY = ConfigManager.getAbsoluteMinRAM()
  1013. // Set the max and min values for the ranged sliders.
  1014. settingsMaxRAMRange.setAttribute('max', SETTINGS_MAX_MEMORY)
  1015. settingsMaxRAMRange.setAttribute('min', SETTINGS_MIN_MEMORY)
  1016. settingsMinRAMRange.setAttribute('max', SETTINGS_MAX_MEMORY)
  1017. settingsMinRAMRange.setAttribute('min', SETTINGS_MIN_MEMORY )
  1018. // Bind on change event for min memory container.
  1019. settingsMinRAMRange.onchange = (e) => {
  1020. // Current range values
  1021. const sMaxV = Number(settingsMaxRAMRange.getAttribute('value'))
  1022. const sMinV = Number(settingsMinRAMRange.getAttribute('value'))
  1023. // Get reference to range bar.
  1024. const bar = e.target.getElementsByClassName('rangeSliderBar')[0]
  1025. // Calculate effective total memory.
  1026. const max = (os.totalmem()-1000000000)/1000000000
  1027. // Change range bar color based on the selected value.
  1028. if(sMinV >= max/2){
  1029. bar.style.background = '#e86060'
  1030. } else if(sMinV >= max/4) {
  1031. bar.style.background = '#e8e18b'
  1032. } else {
  1033. bar.style.background = null
  1034. }
  1035. // Increase maximum memory if the minimum exceeds its value.
  1036. if(sMaxV < sMinV){
  1037. const sliderMeta = calculateRangeSliderMeta(settingsMaxRAMRange)
  1038. updateRangedSlider(settingsMaxRAMRange, sMinV,
  1039. ((sMinV-sliderMeta.min)/sliderMeta.step)*sliderMeta.inc)
  1040. settingsMaxRAMLabel.innerHTML = sMinV.toFixed(1) + 'G'
  1041. }
  1042. // Update label
  1043. settingsMinRAMLabel.innerHTML = sMinV.toFixed(1) + 'G'
  1044. }
  1045. // Bind on change event for max memory container.
  1046. settingsMaxRAMRange.onchange = (e) => {
  1047. // Current range values
  1048. const sMaxV = Number(settingsMaxRAMRange.getAttribute('value'))
  1049. const sMinV = Number(settingsMinRAMRange.getAttribute('value'))
  1050. // Get reference to range bar.
  1051. const bar = e.target.getElementsByClassName('rangeSliderBar')[0]
  1052. // Calculate effective total memory.
  1053. const max = (os.totalmem()-1000000000)/1000000000
  1054. // Change range bar color based on the selected value.
  1055. if(sMaxV >= max/2){
  1056. bar.style.background = '#e86060'
  1057. } else if(sMaxV >= max/4) {
  1058. bar.style.background = '#e8e18b'
  1059. } else {
  1060. bar.style.background = null
  1061. }
  1062. // Decrease the minimum memory if the maximum value is less.
  1063. if(sMaxV < sMinV){
  1064. const sliderMeta = calculateRangeSliderMeta(settingsMaxRAMRange)
  1065. updateRangedSlider(settingsMinRAMRange, sMaxV,
  1066. ((sMaxV-sliderMeta.min)/sliderMeta.step)*sliderMeta.inc)
  1067. settingsMinRAMLabel.innerHTML = sMaxV.toFixed(1) + 'G'
  1068. }
  1069. settingsMaxRAMLabel.innerHTML = sMaxV.toFixed(1) + 'G'
  1070. }
  1071. /**
  1072. * Calculate common values for a ranged slider.
  1073. *
  1074. * @param {Element} v The range slider to calculate against.
  1075. * @returns {Object} An object with meta values for the provided ranged slider.
  1076. */
  1077. function calculateRangeSliderMeta(v){
  1078. const val = {
  1079. max: Number(v.getAttribute('max')),
  1080. min: Number(v.getAttribute('min')),
  1081. step: Number(v.getAttribute('step')),
  1082. }
  1083. val.ticks = (val.max-val.min)/val.step
  1084. val.inc = 100/val.ticks
  1085. return val
  1086. }
  1087. /**
  1088. * Binds functionality to the ranged sliders. They're more than
  1089. * just divs now :').
  1090. */
  1091. function bindRangeSlider(){
  1092. Array.from(document.getElementsByClassName('rangeSlider')).map((v) => {
  1093. // Reference the track (thumb).
  1094. const track = v.getElementsByClassName('rangeSliderTrack')[0]
  1095. // Set the initial slider value.
  1096. const value = v.getAttribute('value')
  1097. const sliderMeta = calculateRangeSliderMeta(v)
  1098. updateRangedSlider(v, value, ((value-sliderMeta.min)/sliderMeta.step)*sliderMeta.inc)
  1099. // The magic happens when we click on the track.
  1100. track.onmousedown = (e) => {
  1101. // Stop moving the track on mouse up.
  1102. document.onmouseup = (e) => {
  1103. document.onmousemove = null
  1104. document.onmouseup = null
  1105. }
  1106. // Move slider according to the mouse position.
  1107. document.onmousemove = (e) => {
  1108. // Distance from the beginning of the bar in pixels.
  1109. const diff = e.pageX - v.offsetLeft - track.offsetWidth/2
  1110. // Don't move the track off the bar.
  1111. if(diff >= 0 && diff <= v.offsetWidth-track.offsetWidth/2){
  1112. // Convert the difference to a percentage.
  1113. const perc = (diff/v.offsetWidth)*100
  1114. // Calculate the percentage of the closest notch.
  1115. const notch = Number(perc/sliderMeta.inc).toFixed(0)*sliderMeta.inc
  1116. // If we're close to that notch, stick to it.
  1117. if(Math.abs(perc-notch) < sliderMeta.inc/2){
  1118. updateRangedSlider(v, sliderMeta.min+(sliderMeta.step*(notch/sliderMeta.inc)), notch)
  1119. }
  1120. }
  1121. }
  1122. }
  1123. })
  1124. }
  1125. /**
  1126. * Update a ranged slider's value and position.
  1127. *
  1128. * @param {Element} element The ranged slider to update.
  1129. * @param {string | number} value The new value for the ranged slider.
  1130. * @param {number} notch The notch that the slider should now be at.
  1131. */
  1132. function updateRangedSlider(element, value, notch){
  1133. const oldVal = element.getAttribute('value')
  1134. const bar = element.getElementsByClassName('rangeSliderBar')[0]
  1135. const track = element.getElementsByClassName('rangeSliderTrack')[0]
  1136. element.setAttribute('value', value)
  1137. if(notch < 0){
  1138. notch = 0
  1139. } else if(notch > 100) {
  1140. notch = 100
  1141. }
  1142. const event = new MouseEvent('change', {
  1143. target: element,
  1144. type: 'change',
  1145. bubbles: false,
  1146. cancelable: true
  1147. })
  1148. let cancelled = !element.dispatchEvent(event)
  1149. if(!cancelled){
  1150. track.style.left = notch + '%'
  1151. bar.style.width = notch + '%'
  1152. } else {
  1153. element.setAttribute('value', oldVal)
  1154. }
  1155. }
  1156. /**
  1157. * Display the total and available RAM.
  1158. */
  1159. function populateMemoryStatus(){
  1160. settingsMemoryTotal.innerHTML = Number((os.totalmem()-1000000000)/1000000000).toFixed(1) + 'G'
  1161. settingsMemoryAvail.innerHTML = Number(os.freemem()/1000000000).toFixed(1) + 'G'
  1162. }
  1163. /**
  1164. * Validate the provided executable path and display the data on
  1165. * the UI.
  1166. *
  1167. * @param {string} execPath The executable path to populate against.
  1168. */
  1169. function populateJavaExecDetails(execPath){
  1170. const jg = new JavaGuard(DistroManager.getDistribution().getServer(ConfigManager.getSelectedServer()).getMinecraftVersion())
  1171. jg._validateJavaBinary(execPath).then(v => {
  1172. if(v.valid){
  1173. const vendor = v.vendor != null ? ` (${v.vendor})` : ''
  1174. if(v.version.major < 9) {
  1175. settingsJavaExecDetails.innerHTML = `Selected: Java ${v.version.major} Update ${v.version.update} (x${v.arch})${vendor}`
  1176. } else {
  1177. settingsJavaExecDetails.innerHTML = `Selected: Java ${v.version.major}.${v.version.minor}.${v.version.revision} (x${v.arch})${vendor}`
  1178. }
  1179. } else {
  1180. settingsJavaExecDetails.innerHTML = 'Invalid Selection'
  1181. }
  1182. })
  1183. }
  1184. /**
  1185. * Prepare the Java tab for display.
  1186. */
  1187. function prepareJavaTab(){
  1188. bindRangeSlider()
  1189. populateMemoryStatus()
  1190. }
  1191. /**
  1192. * About Tab
  1193. */
  1194. const settingsTabAbout = document.getElementById('settingsTabAbout')
  1195. const settingsAboutChangelogTitle = settingsTabAbout.getElementsByClassName('settingsChangelogTitle')[0]
  1196. const settingsAboutChangelogText = settingsTabAbout.getElementsByClassName('settingsChangelogText')[0]
  1197. const settingsAboutChangelogButton = settingsTabAbout.getElementsByClassName('settingsChangelogButton')[0]
  1198. // Bind the devtools toggle button.
  1199. document.getElementById('settingsAboutDevToolsButton').onclick = (e) => {
  1200. let window = remote.getCurrentWindow()
  1201. window.toggleDevTools()
  1202. }
  1203. /**
  1204. * Return whether or not the provided version is a prerelease.
  1205. *
  1206. * @param {string} version The semver version to test.
  1207. * @returns {boolean} True if the version is a prerelease, otherwise false.
  1208. */
  1209. function isPrerelease(version){
  1210. const preRelComp = semver.prerelease(version)
  1211. return preRelComp != null && preRelComp.length > 0
  1212. }
  1213. /**
  1214. * Utility method to display version information on the
  1215. * About and Update settings tabs.
  1216. *
  1217. * @param {string} version The semver version to display.
  1218. * @param {Element} valueElement The value element.
  1219. * @param {Element} titleElement The title element.
  1220. * @param {Element} checkElement The check mark element.
  1221. */
  1222. function populateVersionInformation(version, valueElement, titleElement, checkElement){
  1223. valueElement.innerHTML = version
  1224. if(isPrerelease(version)){
  1225. titleElement.innerHTML = 'Pre-release'
  1226. titleElement.style.color = '#ff886d'
  1227. checkElement.style.background = '#ff886d'
  1228. } else {
  1229. titleElement.innerHTML = 'Stable Release'
  1230. titleElement.style.color = null
  1231. checkElement.style.background = null
  1232. }
  1233. }
  1234. /**
  1235. * Retrieve the version information and display it on the UI.
  1236. */
  1237. function populateAboutVersionInformation(){
  1238. populateVersionInformation(remote.app.getVersion(), document.getElementById('settingsAboutCurrentVersionValue'), document.getElementById('settingsAboutCurrentVersionTitle'), document.getElementById('settingsAboutCurrentVersionCheck'))
  1239. }
  1240. /**
  1241. * Fetches the GitHub atom release feed and parses it for the release notes
  1242. * of the current version. This value is displayed on the UI.
  1243. */
  1244. function populateReleaseNotes(){
  1245. $.ajax({
  1246. url: 'https://github.com/dscalzi/HeliosLauncher/releases.atom',
  1247. success: (data) => {
  1248. const version = 'v' + remote.app.getVersion()
  1249. const entries = $(data).find('entry')
  1250. for(let i=0; i<entries.length; i++){
  1251. const entry = $(entries[i])
  1252. let id = entry.find('id').text()
  1253. id = id.substring(id.lastIndexOf('/')+1)
  1254. if(id === version){
  1255. settingsAboutChangelogTitle.innerHTML = entry.find('title').text()
  1256. settingsAboutChangelogText.innerHTML = entry.find('content').text()
  1257. settingsAboutChangelogButton.href = entry.find('link').attr('href')
  1258. }
  1259. }
  1260. },
  1261. timeout: 2500
  1262. }).catch(err => {
  1263. settingsAboutChangelogText.innerHTML = 'Failed to load release notes.'
  1264. })
  1265. }
  1266. /**
  1267. * Prepare account tab for display.
  1268. */
  1269. function prepareAboutTab(){
  1270. populateAboutVersionInformation()
  1271. populateReleaseNotes()
  1272. }
  1273. /**
  1274. * Update Tab
  1275. */
  1276. const settingsTabUpdate = document.getElementById('settingsTabUpdate')
  1277. const settingsUpdateTitle = document.getElementById('settingsUpdateTitle')
  1278. const settingsUpdateVersionCheck = document.getElementById('settingsUpdateVersionCheck')
  1279. const settingsUpdateVersionTitle = document.getElementById('settingsUpdateVersionTitle')
  1280. const settingsUpdateVersionValue = document.getElementById('settingsUpdateVersionValue')
  1281. const settingsUpdateChangelogTitle = settingsTabUpdate.getElementsByClassName('settingsChangelogTitle')[0]
  1282. const settingsUpdateChangelogText = settingsTabUpdate.getElementsByClassName('settingsChangelogText')[0]
  1283. const settingsUpdateChangelogCont = settingsTabUpdate.getElementsByClassName('settingsChangelogContainer')[0]
  1284. const settingsUpdateActionButton = document.getElementById('settingsUpdateActionButton')
  1285. /**
  1286. * Update the properties of the update action button.
  1287. *
  1288. * @param {string} text The new button text.
  1289. * @param {boolean} disabled Optional. Disable or enable the button
  1290. * @param {function} handler Optional. New button event handler.
  1291. */
  1292. function settingsUpdateButtonStatus(text, disabled = false, handler = null){
  1293. settingsUpdateActionButton.innerHTML = text
  1294. settingsUpdateActionButton.disabled = disabled
  1295. if(handler != null){
  1296. settingsUpdateActionButton.onclick = handler
  1297. }
  1298. }
  1299. /**
  1300. * Populate the update tab with relevant information.
  1301. *
  1302. * @param {Object} data The update data.
  1303. */
  1304. function populateSettingsUpdateInformation(data){
  1305. if(data != null){
  1306. settingsUpdateTitle.innerHTML = `New ${isPrerelease(data.version) ? 'Pre-release' : 'Release'} Available`
  1307. settingsUpdateChangelogCont.style.display = null
  1308. settingsUpdateChangelogTitle.innerHTML = data.releaseName
  1309. settingsUpdateChangelogText.innerHTML = data.releaseNotes
  1310. populateVersionInformation(data.version, settingsUpdateVersionValue, settingsUpdateVersionTitle, settingsUpdateVersionCheck)
  1311. if(process.platform === 'darwin'){
  1312. settingsUpdateButtonStatus('Download from GitHub<span style="font-size: 10px;color: gray;text-shadow: none !important;">Close the launcher and run the dmg to update.</span>', false, () => {
  1313. shell.openExternal(data.darwindownload)
  1314. })
  1315. } else {
  1316. settingsUpdateButtonStatus('Downloading..', true)
  1317. }
  1318. } else {
  1319. settingsUpdateTitle.innerHTML = 'You Are Running the Latest Version'
  1320. settingsUpdateChangelogCont.style.display = 'none'
  1321. populateVersionInformation(remote.app.getVersion(), settingsUpdateVersionValue, settingsUpdateVersionTitle, settingsUpdateVersionCheck)
  1322. settingsUpdateButtonStatus('Check for Updates', false, () => {
  1323. if(!isDev){
  1324. ipcRenderer.send('autoUpdateAction', 'checkForUpdate')
  1325. settingsUpdateButtonStatus('Checking for Updates..', true)
  1326. }
  1327. })
  1328. }
  1329. }
  1330. /**
  1331. * Prepare update tab for display.
  1332. *
  1333. * @param {Object} data The update data.
  1334. */
  1335. function prepareUpdateTab(data = null){
  1336. populateSettingsUpdateInformation(data)
  1337. }
  1338. /**
  1339. * Settings preparation functions.
  1340. */
  1341. /**
  1342. * Prepare the entire settings UI.
  1343. *
  1344. * @param {boolean} first Whether or not it is the first load.
  1345. */
  1346. function prepareSettings(first = false) {
  1347. if(first){
  1348. setupSettingsTabs()
  1349. initSettingsValidators()
  1350. prepareUpdateTab()
  1351. } else {
  1352. prepareModsTab()
  1353. }
  1354. initSettingsValues()
  1355. prepareAccountsTab()
  1356. prepareJavaTab()
  1357. prepareAboutTab()
  1358. }
  1359. // Prepare the settings UI on startup.
  1360. //prepareSettings(true)