settings.js 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349
  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://crafatar.com/renders/body/${acc.uuid}?scale=3&default=MHF_Steve&overlay">
  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 = () => {
  613. const fullName = v.getAttribute('remmod')
  614. const res = 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. if(v.version.major < 9) {
  1009. settingsJavaExecDetails.innerHTML = `Selected: Java ${v.version.major} Update ${v.version.update} (x${v.arch})`
  1010. } else {
  1011. settingsJavaExecDetails.innerHTML = `Selected: Java ${v.version.major}.${v.version.minor}.${v.version.revision} (x${v.arch})`
  1012. }
  1013. } else {
  1014. settingsJavaExecDetails.innerHTML = 'Invalid Selection'
  1015. }
  1016. })
  1017. }
  1018. /**
  1019. * Prepare the Java tab for display.
  1020. */
  1021. function prepareJavaTab(){
  1022. bindRangeSlider()
  1023. populateMemoryStatus()
  1024. }
  1025. /**
  1026. * About Tab
  1027. */
  1028. const settingsTabAbout = document.getElementById('settingsTabAbout')
  1029. const settingsAboutChangelogTitle = settingsTabAbout.getElementsByClassName('settingsChangelogTitle')[0]
  1030. const settingsAboutChangelogText = settingsTabAbout.getElementsByClassName('settingsChangelogText')[0]
  1031. const settingsAboutChangelogButton = settingsTabAbout.getElementsByClassName('settingsChangelogButton')[0]
  1032. // Bind the devtools toggle button.
  1033. document.getElementById('settingsAboutDevToolsButton').onclick = (e) => {
  1034. let window = remote.getCurrentWindow()
  1035. window.toggleDevTools()
  1036. }
  1037. /**
  1038. * Return whether or not the provided version is a prerelease.
  1039. *
  1040. * @param {string} version The semver version to test.
  1041. * @returns {boolean} True if the version is a prerelease, otherwise false.
  1042. */
  1043. function isPrerelease(version){
  1044. const preRelComp = semver.prerelease(version)
  1045. return preRelComp != null && preRelComp.length > 0
  1046. }
  1047. /**
  1048. * Utility method to display version information on the
  1049. * About and Update settings tabs.
  1050. *
  1051. * @param {string} version The semver version to display.
  1052. * @param {Element} valueElement The value element.
  1053. * @param {Element} titleElement The title element.
  1054. * @param {Element} checkElement The check mark element.
  1055. */
  1056. function populateVersionInformation(version, valueElement, titleElement, checkElement){
  1057. valueElement.innerHTML = version
  1058. if(isPrerelease(version)){
  1059. titleElement.innerHTML = 'Pre-release'
  1060. titleElement.style.color = '#ff886d'
  1061. checkElement.style.background = '#ff886d'
  1062. } else {
  1063. titleElement.innerHTML = 'Stable Release'
  1064. titleElement.style.color = null
  1065. checkElement.style.background = null
  1066. }
  1067. }
  1068. /**
  1069. * Retrieve the version information and display it on the UI.
  1070. */
  1071. function populateAboutVersionInformation(){
  1072. populateVersionInformation(remote.app.getVersion(), document.getElementById('settingsAboutCurrentVersionValue'), document.getElementById('settingsAboutCurrentVersionTitle'), document.getElementById('settingsAboutCurrentVersionCheck'))
  1073. }
  1074. /**
  1075. * Fetches the GitHub atom release feed and parses it for the release notes
  1076. * of the current version. This value is displayed on the UI.
  1077. */
  1078. function populateReleaseNotes(){
  1079. $.ajax({
  1080. url: 'https://github.com/dscalzi/HeliosLauncher/releases.atom',
  1081. success: (data) => {
  1082. const version = 'v' + remote.app.getVersion()
  1083. const entries = $(data).find('entry')
  1084. for(let i=0; i<entries.length; i++){
  1085. const entry = $(entries[i])
  1086. let id = entry.find('id').text()
  1087. id = id.substring(id.lastIndexOf('/')+1)
  1088. if(id === version){
  1089. settingsAboutChangelogTitle.innerHTML = entry.find('title').text()
  1090. settingsAboutChangelogText.innerHTML = entry.find('content').text()
  1091. settingsAboutChangelogButton.href = entry.find('link').attr('href')
  1092. }
  1093. }
  1094. },
  1095. timeout: 2500
  1096. }).catch(err => {
  1097. settingsAboutChangelogText.innerHTML = 'Failed to load release notes.'
  1098. })
  1099. }
  1100. /**
  1101. * Prepare account tab for display.
  1102. */
  1103. function prepareAboutTab(){
  1104. populateAboutVersionInformation()
  1105. populateReleaseNotes()
  1106. }
  1107. /**
  1108. * Update Tab
  1109. */
  1110. const settingsTabUpdate = document.getElementById('settingsTabUpdate')
  1111. const settingsUpdateTitle = document.getElementById('settingsUpdateTitle')
  1112. const settingsUpdateVersionCheck = document.getElementById('settingsUpdateVersionCheck')
  1113. const settingsUpdateVersionTitle = document.getElementById('settingsUpdateVersionTitle')
  1114. const settingsUpdateVersionValue = document.getElementById('settingsUpdateVersionValue')
  1115. const settingsUpdateChangelogTitle = settingsTabUpdate.getElementsByClassName('settingsChangelogTitle')[0]
  1116. const settingsUpdateChangelogText = settingsTabUpdate.getElementsByClassName('settingsChangelogText')[0]
  1117. const settingsUpdateChangelogCont = settingsTabUpdate.getElementsByClassName('settingsChangelogContainer')[0]
  1118. const settingsUpdateActionButton = document.getElementById('settingsUpdateActionButton')
  1119. /**
  1120. * Update the properties of the update action button.
  1121. *
  1122. * @param {string} text The new button text.
  1123. * @param {boolean} disabled Optional. Disable or enable the button
  1124. * @param {function} handler Optional. New button event handler.
  1125. */
  1126. function settingsUpdateButtonStatus(text, disabled = false, handler = null){
  1127. settingsUpdateActionButton.innerHTML = text
  1128. settingsUpdateActionButton.disabled = disabled
  1129. if(handler != null){
  1130. settingsUpdateActionButton.onclick = handler
  1131. }
  1132. }
  1133. /**
  1134. * Populate the update tab with relevant information.
  1135. *
  1136. * @param {Object} data The update data.
  1137. */
  1138. function populateSettingsUpdateInformation(data){
  1139. if(data != null){
  1140. settingsUpdateTitle.innerHTML = `New ${isPrerelease(data.version) ? 'Pre-release' : 'Release'} Available`
  1141. settingsUpdateChangelogCont.style.display = null
  1142. settingsUpdateChangelogTitle.innerHTML = data.releaseName
  1143. settingsUpdateChangelogText.innerHTML = data.releaseNotes
  1144. populateVersionInformation(data.version, settingsUpdateVersionValue, settingsUpdateVersionTitle, settingsUpdateVersionCheck)
  1145. if(process.platform === 'darwin'){
  1146. 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, () => {
  1147. shell.openExternal(data.darwindownload)
  1148. })
  1149. } else {
  1150. settingsUpdateButtonStatus('Downloading..', true)
  1151. }
  1152. } else {
  1153. settingsUpdateTitle.innerHTML = 'You Are Running the Latest Version'
  1154. settingsUpdateChangelogCont.style.display = 'none'
  1155. populateVersionInformation(remote.app.getVersion(), settingsUpdateVersionValue, settingsUpdateVersionTitle, settingsUpdateVersionCheck)
  1156. settingsUpdateButtonStatus('Check for Updates', false, () => {
  1157. if(!isDev){
  1158. ipcRenderer.send('autoUpdateAction', 'checkForUpdate')
  1159. settingsUpdateButtonStatus('Checking for Updates..', true)
  1160. }
  1161. })
  1162. }
  1163. }
  1164. /**
  1165. * Prepare update tab for display.
  1166. *
  1167. * @param {Object} data The update data.
  1168. */
  1169. function prepareUpdateTab(data = null){
  1170. populateSettingsUpdateInformation(data)
  1171. }
  1172. /**
  1173. * Settings preparation functions.
  1174. */
  1175. /**
  1176. * Prepare the entire settings UI.
  1177. *
  1178. * @param {boolean} first Whether or not it is the first load.
  1179. */
  1180. function prepareSettings(first = false) {
  1181. if(first){
  1182. setupSettingsTabs()
  1183. initSettingsValidators()
  1184. prepareUpdateTab()
  1185. } else {
  1186. prepareModsTab()
  1187. }
  1188. initSettingsValues()
  1189. prepareAccountsTab()
  1190. prepareJavaTab()
  1191. prepareAboutTab()
  1192. }
  1193. // Prepare the settings UI on startup.
  1194. //prepareSettings(true)