settings.js 54 KB

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