settings.js 47 KB

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