settings.js 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  1. // Requirements
  2. const os = require('os')
  3. const semver = require('semver')
  4. const { AssetGuard } = require('./assets/js/assetguard')
  5. const DropinModUtil = require('./assets/js/dropinmodutil')
  6. const settingsState = {
  7. invalid: new Set()
  8. }
  9. /**
  10. * General Settings Functions
  11. */
  12. /**
  13. * Bind value validators to the settings UI elements. These will
  14. * validate against the criteria defined in the ConfigManager (if
  15. * and). If the value is invalid, the UI will reflect this and saving
  16. * will be disabled until the value is corrected. This is an automated
  17. * process. More complex UI may need to be bound separately.
  18. */
  19. function initSettingsValidators(){
  20. const sEls = document.getElementById('settingsContainer').querySelectorAll('[cValue]')
  21. Array.from(sEls).map((v, index, arr) => {
  22. const vFn = ConfigManager['validate' + v.getAttribute('cValue')]
  23. if(typeof vFn === 'function'){
  24. if(v.tagName === 'INPUT'){
  25. if(v.type === 'number' || v.type === 'text'){
  26. v.addEventListener('keyup', (e) => {
  27. const v = e.target
  28. if(!vFn(v.value)){
  29. settingsState.invalid.add(v.id)
  30. v.setAttribute('error', '')
  31. settingsSaveDisabled(true)
  32. } else {
  33. if(v.hasAttribute('error')){
  34. v.removeAttribute('error')
  35. settingsState.invalid.delete(v.id)
  36. if(settingsState.invalid.size === 0){
  37. settingsSaveDisabled(false)
  38. }
  39. }
  40. }
  41. })
  42. }
  43. }
  44. }
  45. })
  46. }
  47. /**
  48. * Load configuration values onto the UI. This is an automated process.
  49. */
  50. function initSettingsValues(){
  51. const sEls = document.getElementById('settingsContainer').querySelectorAll('[cValue]')
  52. Array.from(sEls).map((v, index, arr) => {
  53. const cVal = v.getAttribute('cValue')
  54. const gFn = ConfigManager['get' + cVal]
  55. if(typeof gFn === 'function'){
  56. if(v.tagName === 'INPUT'){
  57. if(v.type === 'number' || v.type === 'text'){
  58. // Special Conditions
  59. if(cVal === 'JavaExecutable'){
  60. populateJavaExecDetails(v.value)
  61. v.value = gFn()
  62. } else if(cVal === 'JVMOptions'){
  63. v.value = gFn().join(' ')
  64. } else {
  65. v.value = gFn()
  66. }
  67. } else if(v.type === 'checkbox'){
  68. v.checked = gFn()
  69. }
  70. } else if(v.tagName === 'DIV'){
  71. if(v.classList.contains('rangeSlider')){
  72. // Special Conditions
  73. if(cVal === 'MinRAM' || cVal === 'MaxRAM'){
  74. let val = gFn()
  75. if(val.endsWith('M')){
  76. val = Number(val.substring(0, val.length-1))/1000
  77. } else {
  78. val = Number.parseFloat(val)
  79. }
  80. v.setAttribute('value', val)
  81. } else {
  82. v.setAttribute('value', Number.parseFloat(gFn()))
  83. }
  84. }
  85. }
  86. }
  87. })
  88. }
  89. /**
  90. * Save the settings values.
  91. */
  92. function saveSettingsValues(){
  93. const sEls = document.getElementById('settingsContainer').querySelectorAll('[cValue]')
  94. Array.from(sEls).map((v, index, arr) => {
  95. const cVal = v.getAttribute('cValue')
  96. const sFn = ConfigManager['set' + cVal]
  97. if(typeof sFn === 'function'){
  98. if(v.tagName === 'INPUT'){
  99. if(v.type === 'number' || v.type === 'text'){
  100. // Special Conditions
  101. if(cVal === 'JVMOptions'){
  102. sFn(v.value.split(' '))
  103. } else {
  104. sFn(v.value)
  105. }
  106. } else if(v.type === 'checkbox'){
  107. sFn(v.checked)
  108. // Special Conditions
  109. if(cVal === 'AllowPrerelease'){
  110. changeAllowPrerelease(v.checked)
  111. }
  112. }
  113. } else if(v.tagName === 'DIV'){
  114. if(v.classList.contains('rangeSlider')){
  115. // Special Conditions
  116. if(cVal === 'MinRAM' || cVal === 'MaxRAM'){
  117. let val = Number(v.getAttribute('value'))
  118. if(val%1 > 0){
  119. val = val*1000 + 'M'
  120. } else {
  121. val = val + 'G'
  122. }
  123. sFn(val)
  124. } else {
  125. sFn(v.getAttribute('value'))
  126. }
  127. }
  128. }
  129. }
  130. })
  131. }
  132. let selectedSettingsTab = 'settingsTabAccount'
  133. /**
  134. * Modify the settings container UI when the scroll threshold reaches
  135. * a certain poin.
  136. *
  137. * @param {UIEvent} e The scroll event.
  138. */
  139. function settingsTabScrollListener(e){
  140. if(e.target.scrollTop > Number.parseFloat(getComputedStyle(e.target.firstElementChild).marginTop)){
  141. document.getElementById('settingsContainer').setAttribute('scrolled', '')
  142. } else {
  143. document.getElementById('settingsContainer').removeAttribute('scrolled')
  144. }
  145. }
  146. /**
  147. * Bind functionality for the settings navigation items.
  148. */
  149. function setupSettingsTabs(){
  150. Array.from(document.getElementsByClassName('settingsNavItem')).map((val) => {
  151. if(val.hasAttribute('rSc')){
  152. val.onclick = () => {
  153. settingsNavItemListener(val)
  154. }
  155. }
  156. })
  157. }
  158. /**
  159. * Settings nav item onclick lisener. Function is exposed so that
  160. * other UI elements can quickly toggle to a certain tab from other views.
  161. *
  162. * @param {Element} ele The nav item which has been clicked.
  163. * @param {boolean} fade Optional. True to fade transition.
  164. */
  165. function settingsNavItemListener(ele, fade = true){
  166. if(ele.hasAttribute('selected')){
  167. return
  168. }
  169. const navItems = document.getElementsByClassName('settingsNavItem')
  170. for(let i=0; i<navItems.length; i++){
  171. if(navItems[i].hasAttribute('selected')){
  172. navItems[i].removeAttribute('selected')
  173. }
  174. }
  175. ele.setAttribute('selected', '')
  176. let prevTab = selectedSettingsTab
  177. selectedSettingsTab = ele.getAttribute('rSc')
  178. document.getElementById(prevTab).onscroll = null
  179. document.getElementById(selectedSettingsTab).onscroll = settingsTabScrollListener
  180. if(fade){
  181. $(`#${prevTab}`).fadeOut(250, () => {
  182. $(`#${selectedSettingsTab}`).fadeIn({
  183. duration: 250,
  184. start: () => {
  185. settingsTabScrollListener({
  186. target: document.getElementById(selectedSettingsTab)
  187. })
  188. }
  189. })
  190. })
  191. } else {
  192. $(`#${prevTab}`).hide(0, () => {
  193. $(`#${selectedSettingsTab}`).show({
  194. duration: 0,
  195. start: () => {
  196. settingsTabScrollListener({
  197. target: document.getElementById(selectedSettingsTab)
  198. })
  199. }
  200. })
  201. })
  202. }
  203. }
  204. const settingsNavDone = document.getElementById('settingsNavDone')
  205. /**
  206. * Set if the settings save (done) button is disabled.
  207. *
  208. * @param {boolean} v True to disable, false to enable.
  209. */
  210. function settingsSaveDisabled(v){
  211. settingsNavDone.disabled = v
  212. }
  213. /* Closes the settings view and saves all data. */
  214. settingsNavDone.onclick = () => {
  215. saveSettingsValues()
  216. saveModConfiguration()
  217. ConfigManager.save()
  218. saveDropinModConfiguration()
  219. switchView(getCurrentView(), VIEWS.landing)
  220. }
  221. /**
  222. * Account Management Tab
  223. */
  224. // Bind the add account button.
  225. document.getElementById('settingsAddAccount').onclick = (e) => {
  226. switchView(getCurrentView(), VIEWS.login, 500, 500, () => {
  227. loginViewOnCancel = VIEWS.settings
  228. loginViewOnSuccess = VIEWS.settings
  229. loginCancelEnabled(true)
  230. })
  231. }
  232. /**
  233. * Bind functionality for the account selection buttons. If another account
  234. * is selected, the UI of the previously selected account will be updated.
  235. */
  236. function bindAuthAccountSelect(){
  237. Array.from(document.getElementsByClassName('settingsAuthAccountSelect')).map((val) => {
  238. val.onclick = (e) => {
  239. if(val.hasAttribute('selected')){
  240. return
  241. }
  242. const selectBtns = document.getElementsByClassName('settingsAuthAccountSelect')
  243. for(let i=0; i<selectBtns.length; i++){
  244. if(selectBtns[i].hasAttribute('selected')){
  245. selectBtns[i].removeAttribute('selected')
  246. selectBtns[i].innerHTML = 'Select Account'
  247. }
  248. }
  249. val.setAttribute('selected', '')
  250. val.innerHTML = 'Selected Account &#10004;'
  251. setSelectedAccount(val.closest('.settingsAuthAccount').getAttribute('uuid'))
  252. }
  253. })
  254. }
  255. /**
  256. * Bind functionality for the log out button. If the logged out account was
  257. * the selected account, another account will be selected and the UI will
  258. * be updated accordingly.
  259. */
  260. function bindAuthAccountLogOut(){
  261. Array.from(document.getElementsByClassName('settingsAuthAccountLogOut')).map((val) => {
  262. val.onclick = (e) => {
  263. let isLastAccount = false
  264. if(Object.keys(ConfigManager.getAuthAccounts()).length === 1){
  265. isLastAccount = true
  266. setOverlayContent(
  267. 'Warning<br>This is Your Last Account',
  268. '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?',
  269. 'I\'m Sure',
  270. 'Cancel'
  271. )
  272. setOverlayHandler(() => {
  273. processLogOut(val, isLastAccount)
  274. switchView(getCurrentView(), VIEWS.login)
  275. toggleOverlay(false)
  276. })
  277. setDismissHandler(() => {
  278. toggleOverlay(false)
  279. })
  280. toggleOverlay(true, true)
  281. } else {
  282. processLogOut(val, isLastAccount)
  283. }
  284. }
  285. })
  286. }
  287. /**
  288. * Process a log out.
  289. *
  290. * @param {Element} val The log out button element.
  291. * @param {boolean} isLastAccount If this logout is on the last added account.
  292. */
  293. function processLogOut(val, isLastAccount){
  294. const parent = val.closest('.settingsAuthAccount')
  295. const uuid = parent.getAttribute('uuid')
  296. const prevSelAcc = ConfigManager.getSelectedAccount()
  297. AuthManager.removeAccount(uuid).then(() => {
  298. if(!isLastAccount && uuid === prevSelAcc.uuid){
  299. const selAcc = ConfigManager.getSelectedAccount()
  300. refreshAuthAccountSelected(selAcc.uuid)
  301. updateSelectedAccount(selAcc)
  302. validateSelectedAccount()
  303. }
  304. })
  305. $(parent).fadeOut(250, () => {
  306. parent.remove()
  307. })
  308. }
  309. /**
  310. * Refreshes the status of the selected account on the auth account
  311. * elements.
  312. *
  313. * @param {string} uuid The UUID of the new selected account.
  314. */
  315. function refreshAuthAccountSelected(uuid){
  316. Array.from(document.getElementsByClassName('settingsAuthAccount')).map((val) => {
  317. const selBtn = val.getElementsByClassName('settingsAuthAccountSelect')[0]
  318. if(uuid === val.getAttribute('uuid')){
  319. selBtn.setAttribute('selected', '')
  320. selBtn.innerHTML = 'Selected Account &#10004;'
  321. } else {
  322. if(selBtn.hasAttribute('selected')){
  323. selBtn.removeAttribute('selected')
  324. }
  325. selBtn.innerHTML = 'Select Account'
  326. }
  327. })
  328. }
  329. const settingsCurrentAccounts = document.getElementById('settingsCurrentAccounts')
  330. /**
  331. * Add auth account elements for each one stored in the authentication database.
  332. */
  333. function populateAuthAccounts(){
  334. const authAccounts = ConfigManager.getAuthAccounts()
  335. const authKeys = Object.keys(authAccounts)
  336. const selectedUUID = ConfigManager.getSelectedAccount().uuid
  337. let authAccountStr = ''
  338. authKeys.map((val) => {
  339. const acc = authAccounts[val]
  340. authAccountStr += `<div class="settingsAuthAccount" uuid="${acc.uuid}">
  341. <div class="settingsAuthAccountLeft">
  342. <img class="settingsAuthAccountImage" alt="${acc.displayName}" src="https://crafatar.com/renders/body/${acc.uuid}?scale=3&default=MHF_Steve&overlay">
  343. </div>
  344. <div class="settingsAuthAccountRight">
  345. <div class="settingsAuthAccountDetails">
  346. <div class="settingsAuthAccountDetailPane">
  347. <div class="settingsAuthAccountDetailTitle">Username</div>
  348. <div class="settingsAuthAccountDetailValue">${acc.displayName}</div>
  349. </div>
  350. <div class="settingsAuthAccountDetailPane">
  351. <div class="settingsAuthAccountDetailTitle">UUID</div>
  352. <div class="settingsAuthAccountDetailValue">${acc.uuid}</div>
  353. </div>
  354. </div>
  355. <div class="settingsAuthAccountActions">
  356. <button class="settingsAuthAccountSelect" ${selectedUUID === acc.uuid ? 'selected>Selected Account &#10004;' : '>Select Account'}</button>
  357. <div class="settingsAuthAccountWrapper">
  358. <button class="settingsAuthAccountLogOut">Log Out</button>
  359. </div>
  360. </div>
  361. </div>
  362. </div>`
  363. })
  364. settingsCurrentAccounts.innerHTML = authAccountStr
  365. }
  366. /**
  367. * Prepare the accounts tab for display.
  368. */
  369. function prepareAccountsTab() {
  370. populateAuthAccounts()
  371. bindAuthAccountSelect()
  372. bindAuthAccountLogOut()
  373. }
  374. /**
  375. * Minecraft Tab
  376. */
  377. /**
  378. * Disable decimals, negative signs, and scientific notation.
  379. */
  380. document.getElementById('settingsGameWidth').addEventListener('keydown', (e) => {
  381. if(/^[-.eE]$/.test(e.key)){
  382. e.preventDefault()
  383. }
  384. })
  385. document.getElementById('settingsGameHeight').addEventListener('keydown', (e) => {
  386. if(/^[-.eE]$/.test(e.key)){
  387. e.preventDefault()
  388. }
  389. })
  390. /**
  391. * Mods Tab
  392. */
  393. const settingsModsContainer = document.getElementById('settingsModsContainer')
  394. function resolveModsForUI(){
  395. const serv = ConfigManager.getSelectedServer()
  396. const distro = DistroManager.getDistribution()
  397. const servConf = ConfigManager.getModConfiguration(serv)
  398. const modStr = parseModulesForUI(distro.getServer(serv).getModules(), false, servConf.mods)
  399. document.getElementById('settingsReqModsContent').innerHTML = modStr.reqMods
  400. document.getElementById('settingsOptModsContent').innerHTML = modStr.optMods
  401. }
  402. function parseModulesForUI(mdls, submodules, servConf){
  403. let reqMods = ''
  404. let optMods = ''
  405. for(const mdl of mdls){
  406. if(mdl.getType() === DistroManager.Types.ForgeMod || mdl.getType() === DistroManager.Types.LiteMod || mdl.getType() === DistroManager.Types.LiteLoader){
  407. if(mdl.getRequired().isRequired()){
  408. reqMods += `<div id="${mdl.getVersionlessID()}" class="settingsBaseMod settings${submodules ? 'Sub' : ''}Mod" enabled>
  409. <div class="settingsModContent">
  410. <div class="settingsModMainWrapper">
  411. <div class="settingsModStatus"></div>
  412. <div class="settingsModDetails">
  413. <span class="settingsModName">${mdl.getName()}</span>
  414. <span class="settingsModVersion">v${mdl.getVersion()}</span>
  415. </div>
  416. </div>
  417. <label class="toggleSwitch" reqmod>
  418. <input type="checkbox" checked>
  419. <span class="toggleSwitchSlider"></span>
  420. </label>
  421. </div>
  422. ${mdl.hasSubModules() ? `<div class="settingsSubModContainer">
  423. ${Object.values(parseModulesForUI(mdl.getSubModules(), true, servConf[mdl.getVersionlessID()])).join('')}
  424. </div>` : ''}
  425. </div>`
  426. } else {
  427. const conf = servConf[mdl.getVersionlessID()]
  428. const val = typeof conf === 'object' ? conf.value : conf
  429. optMods += `<div id="${mdl.getVersionlessID()}" class="settingsBaseMod settings${submodules ? 'Sub' : ''}Mod" ${val ? 'enabled' : ''}>
  430. <div class="settingsModContent">
  431. <div class="settingsModMainWrapper">
  432. <div class="settingsModStatus"></div>
  433. <div class="settingsModDetails">
  434. <span class="settingsModName">${mdl.getName()}</span>
  435. <span class="settingsModVersion">v${mdl.getVersion()}</span>
  436. </div>
  437. </div>
  438. <label class="toggleSwitch">
  439. <input type="checkbox" formod="${mdl.getVersionlessID()}" ${val ? 'checked' : ''}>
  440. <span class="toggleSwitchSlider"></span>
  441. </label>
  442. </div>
  443. ${mdl.hasSubModules() ? `<div class="settingsSubModContainer">
  444. ${Object.values(parseModulesForUI(mdl.getSubModules(), true, conf.mods)).join('')}
  445. </div>` : ''}
  446. </div>`
  447. }
  448. }
  449. }
  450. return {
  451. reqMods,
  452. optMods
  453. }
  454. }
  455. /**
  456. * Bind functionality to mod config toggle switches. Switching the value
  457. * will also switch the status color on the left of the mod UI.
  458. */
  459. function bindModsToggleSwitch(){
  460. const sEls = settingsModsContainer.querySelectorAll('[formod]')
  461. Array.from(sEls).map((v, index, arr) => {
  462. v.onchange = () => {
  463. if(v.checked) {
  464. document.getElementById(v.getAttribute('formod')).setAttribute('enabled', '')
  465. } else {
  466. document.getElementById(v.getAttribute('formod')).removeAttribute('enabled')
  467. }
  468. }
  469. })
  470. }
  471. /**
  472. * Save the mod configuration based on the UI values.
  473. */
  474. function saveModConfiguration(){
  475. const serv = ConfigManager.getSelectedServer()
  476. const modConf = ConfigManager.getModConfiguration(serv)
  477. modConf.mods = _saveModConfiguration(modConf.mods)
  478. ConfigManager.setModConfiguration(serv, modConf)
  479. }
  480. /**
  481. * Recursively save mod config with submods.
  482. *
  483. * @param {Object} modConf Mod config object to save.
  484. */
  485. function _saveModConfiguration(modConf){
  486. for(m of Object.entries(modConf)){
  487. const tSwitch = settingsModsContainer.querySelectorAll(`[formod='${m[0]}']`)
  488. if(!tSwitch[0].hasAttribute('dropin')){
  489. if(typeof m[1] === 'boolean'){
  490. modConf[m[0]] = tSwitch[0].checked
  491. } else {
  492. if(m[1] != null){
  493. if(tSwitch.length > 0){
  494. modConf[m[0]].value = tSwitch[0].checked
  495. }
  496. modConf[m[0]].mods = _saveModConfiguration(modConf[m[0]].mods)
  497. }
  498. }
  499. }
  500. }
  501. return modConf
  502. }
  503. function loadSelectedServerOnModsTab(){
  504. const serv = DistroManager.getDistribution().getServer(ConfigManager.getSelectedServer())
  505. document.getElementById('settingsSelServContent').innerHTML = `
  506. <img class="serverListingImg" src="${serv.getIcon()}"/>
  507. <div class="serverListingDetails">
  508. <span class="serverListingName">${serv.getName()}</span>
  509. <span class="serverListingDescription">${serv.getDescription()}</span>
  510. <div class="serverListingInfo">
  511. <div class="serverListingVersion">${serv.getMinecraftVersion()}</div>
  512. <div class="serverListingRevision">${serv.getVersion()}</div>
  513. ${serv.isMainServer() ? `<div class="serverListingStarWrapper">
  514. <svg id="Layer_1" viewBox="0 0 107.45 104.74" width="20px" height="20px">
  515. <defs>
  516. <style>.cls-1{fill:#fff;}.cls-2{fill:none;stroke:#fff;stroke-miterlimit:10;}</style>
  517. </defs>
  518. <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"/>
  519. <circle class="cls-2" cx="53.73" cy="53.9" r="38"/>
  520. </svg>
  521. <span class="serverListingStarTooltip">Main Server</span>
  522. </div>` : ''}
  523. </div>
  524. </div>
  525. `
  526. }
  527. let CACHE_SETTINGS_MODS_DIR
  528. let CACHE_DROPIN_MODS
  529. function resolveDropinModsForUI(){
  530. const serv = DistroManager.getDistribution().getServer(ConfigManager.getSelectedServer())
  531. CACHE_SETTINGS_MODS_DIR = path.join(ConfigManager.getInstanceDirectory(), serv.getID(), 'mods')
  532. CACHE_DROPIN_MODS = DropinModUtil.scanForDropinMods(CACHE_SETTINGS_MODS_DIR, serv.getMinecraftVersion())
  533. let dropinMods = ''
  534. for(dropin of CACHE_DROPIN_MODS){
  535. dropinMods += `<div id="${dropin.fullName}" class="settingsBaseMod settingsDropinMod" ${!dropin.disabled ? 'enabled' : ''}>
  536. <div class="settingsModContent">
  537. <div class="settingsModMainWrapper">
  538. <div class="settingsModStatus"></div>
  539. <div class="settingsModDetails">
  540. <span class="settingsModName">${dropin.name}</span>
  541. <div class="settingsDropinRemoveWrapper">
  542. <button class="settingsDropinRemoveButton" remmod="${dropin.fullName}">Remove</button>
  543. </div>
  544. </div>
  545. </div>
  546. <label class="toggleSwitch">
  547. <input type="checkbox" formod="${dropin.fullName}" dropin ${!dropin.disabled ? 'checked' : ''}>
  548. <span class="toggleSwitchSlider"></span>
  549. </label>
  550. </div>
  551. </div>`
  552. }
  553. document.getElementById('settingsDropinModsContent').innerHTML = dropinMods
  554. }
  555. function bindDropinModsRemoveButton(){
  556. const sEls = settingsModsContainer.querySelectorAll('[remmod]')
  557. Array.from(sEls).map((v, index, arr) => {
  558. v.onclick = () => {
  559. const fullName = v.getAttribute('remmod')
  560. const res = DropinModUtil.deleteDropinMod(CACHE_SETTINGS_MODS_DIR, fullName)
  561. if(res){
  562. document.getElementById(fullName).remove()
  563. } else {
  564. setOverlayContent(
  565. `Failed to Delete<br>Drop-in Mod ${fullName}`,
  566. 'Make sure the file is not in use and try again.',
  567. 'Okay'
  568. )
  569. setOverlayHandler(null)
  570. toggleOverlay(true)
  571. }
  572. }
  573. })
  574. }
  575. function bindDropinModFileSystemButton(){
  576. const fsBtn = document.getElementById('settingsDropinFileSystemButton')
  577. fsBtn.onclick = () => {
  578. shell.openItem(CACHE_SETTINGS_MODS_DIR)
  579. }
  580. }
  581. function saveDropinModConfiguration(){
  582. for(dropin of CACHE_DROPIN_MODS){
  583. const dropinUI = document.getElementById(dropin.fullName)
  584. if(dropinUI != null){
  585. const dropinUIEnabled = dropinUI.hasAttribute('enabled')
  586. if(DropinModUtil.isDropinModEnabled(dropin.fullName) != dropinUIEnabled){
  587. DropinModUtil.toggleDropinMod(CACHE_SETTINGS_MODS_DIR, dropin.fullName, dropinUIEnabled).catch(err => {
  588. if(!isOverlayVisible()){
  589. setOverlayContent(
  590. 'Failed to Toggle<br>One or More Drop-in Mods',
  591. err.message,
  592. 'Okay'
  593. )
  594. setOverlayHandler(null)
  595. toggleOverlay(true)
  596. }
  597. })
  598. }
  599. }
  600. }
  601. }
  602. document.getElementById('settingsSwitchServerButton').addEventListener('click', (e) => {
  603. e.target.blur()
  604. toggleServerSelection(true)
  605. })
  606. document.addEventListener('keydown', (e) => {
  607. if(getCurrentView() === VIEWS.settings && selectedSettingsTab === 'settingsTabMods'){
  608. if(e.key === 'F5'){
  609. resolveDropinModsForUI()
  610. bindDropinModsRemoveButton()
  611. bindDropinModFileSystemButton()
  612. bindModsToggleSwitch()
  613. }
  614. }
  615. })
  616. function animateModsTabRefresh(){
  617. $('#settingsTabMods').fadeOut(500, () => {
  618. saveModConfiguration()
  619. ConfigManager.save()
  620. saveDropinModConfiguration()
  621. prepareModsTab()
  622. $('#settingsTabMods').fadeIn(500)
  623. })
  624. }
  625. /**
  626. * Prepare the Mods tab for display.
  627. */
  628. function prepareModsTab(first){
  629. resolveModsForUI()
  630. resolveDropinModsForUI()
  631. bindDropinModsRemoveButton()
  632. bindDropinModFileSystemButton()
  633. bindModsToggleSwitch()
  634. loadSelectedServerOnModsTab()
  635. }
  636. /**
  637. * Java Tab
  638. */
  639. // DOM Cache
  640. const settingsMaxRAMRange = document.getElementById('settingsMaxRAMRange')
  641. const settingsMinRAMRange = document.getElementById('settingsMinRAMRange')
  642. const settingsMaxRAMLabel = document.getElementById('settingsMaxRAMLabel')
  643. const settingsMinRAMLabel = document.getElementById('settingsMinRAMLabel')
  644. const settingsMemoryTotal = document.getElementById('settingsMemoryTotal')
  645. const settingsMemoryAvail = document.getElementById('settingsMemoryAvail')
  646. const settingsJavaExecDetails = document.getElementById('settingsJavaExecDetails')
  647. const settingsJavaExecVal = document.getElementById('settingsJavaExecVal')
  648. const settingsJavaExecSel = document.getElementById('settingsJavaExecSel')
  649. // Store maximum memory values.
  650. const SETTINGS_MAX_MEMORY = ConfigManager.getAbsoluteMaxRAM()
  651. const SETTINGS_MIN_MEMORY = ConfigManager.getAbsoluteMinRAM()
  652. // Set the max and min values for the ranged sliders.
  653. settingsMaxRAMRange.setAttribute('max', SETTINGS_MAX_MEMORY)
  654. settingsMaxRAMRange.setAttribute('min', SETTINGS_MIN_MEMORY)
  655. settingsMinRAMRange.setAttribute('max', SETTINGS_MAX_MEMORY)
  656. settingsMinRAMRange.setAttribute('min', SETTINGS_MIN_MEMORY )
  657. // Bind on change event for min memory container.
  658. settingsMinRAMRange.onchange = (e) => {
  659. // Current range values
  660. const sMaxV = Number(settingsMaxRAMRange.getAttribute('value'))
  661. const sMinV = Number(settingsMinRAMRange.getAttribute('value'))
  662. // Get reference to range bar.
  663. const bar = e.target.getElementsByClassName('rangeSliderBar')[0]
  664. // Calculate effective total memory.
  665. const max = (os.totalmem()-1000000000)/1000000000
  666. // Change range bar color based on the selected value.
  667. if(sMinV >= max/2){
  668. bar.style.background = '#e86060'
  669. } else if(sMinV >= max/4) {
  670. bar.style.background = '#e8e18b'
  671. } else {
  672. bar.style.background = null
  673. }
  674. // Increase maximum memory if the minimum exceeds its value.
  675. if(sMaxV < sMinV){
  676. const sliderMeta = calculateRangeSliderMeta(settingsMaxRAMRange)
  677. updateRangedSlider(settingsMaxRAMRange, sMinV,
  678. ((sMinV-sliderMeta.min)/sliderMeta.step)*sliderMeta.inc)
  679. settingsMaxRAMLabel.innerHTML = sMinV.toFixed(1) + 'G'
  680. }
  681. // Update label
  682. settingsMinRAMLabel.innerHTML = sMinV.toFixed(1) + 'G'
  683. }
  684. // Bind on change event for max memory container.
  685. settingsMaxRAMRange.onchange = (e) => {
  686. // Current range values
  687. const sMaxV = Number(settingsMaxRAMRange.getAttribute('value'))
  688. const sMinV = Number(settingsMinRAMRange.getAttribute('value'))
  689. // Get reference to range bar.
  690. const bar = e.target.getElementsByClassName('rangeSliderBar')[0]
  691. // Calculate effective total memory.
  692. const max = (os.totalmem()-1000000000)/1000000000
  693. // Change range bar color based on the selected value.
  694. if(sMaxV >= max/2){
  695. bar.style.background = '#e86060'
  696. } else if(sMaxV >= max/4) {
  697. bar.style.background = '#e8e18b'
  698. } else {
  699. bar.style.background = null
  700. }
  701. // Decrease the minimum memory if the maximum value is less.
  702. if(sMaxV < sMinV){
  703. const sliderMeta = calculateRangeSliderMeta(settingsMaxRAMRange)
  704. updateRangedSlider(settingsMinRAMRange, sMaxV,
  705. ((sMaxV-sliderMeta.min)/sliderMeta.step)*sliderMeta.inc)
  706. settingsMinRAMLabel.innerHTML = sMaxV.toFixed(1) + 'G'
  707. }
  708. settingsMaxRAMLabel.innerHTML = sMaxV.toFixed(1) + 'G'
  709. }
  710. /**
  711. * Calculate common values for a ranged slider.
  712. *
  713. * @param {Element} v The range slider to calculate against.
  714. * @returns {Object} An object with meta values for the provided ranged slider.
  715. */
  716. function calculateRangeSliderMeta(v){
  717. const val = {
  718. max: Number(v.getAttribute('max')),
  719. min: Number(v.getAttribute('min')),
  720. step: Number(v.getAttribute('step')),
  721. }
  722. val.ticks = (val.max-val.min)/val.step
  723. val.inc = 100/val.ticks
  724. return val
  725. }
  726. /**
  727. * Binds functionality to the ranged sliders. They're more than
  728. * just divs now :').
  729. */
  730. function bindRangeSlider(){
  731. Array.from(document.getElementsByClassName('rangeSlider')).map((v) => {
  732. // Reference the track (thumb).
  733. const track = v.getElementsByClassName('rangeSliderTrack')[0]
  734. // Set the initial slider value.
  735. const value = v.getAttribute('value')
  736. const sliderMeta = calculateRangeSliderMeta(v)
  737. updateRangedSlider(v, value, ((value-sliderMeta.min)/sliderMeta.step)*sliderMeta.inc)
  738. // The magic happens when we click on the track.
  739. track.onmousedown = (e) => {
  740. // Stop moving the track on mouse up.
  741. document.onmouseup = (e) => {
  742. document.onmousemove = null
  743. document.onmouseup = null
  744. }
  745. // Move slider according to the mouse position.
  746. document.onmousemove = (e) => {
  747. // Distance from the beginning of the bar in pixels.
  748. const diff = e.pageX - v.offsetLeft - track.offsetWidth/2
  749. // Don't move the track off the bar.
  750. if(diff >= 0 && diff <= v.offsetWidth-track.offsetWidth/2){
  751. // Convert the difference to a percentage.
  752. const perc = (diff/v.offsetWidth)*100
  753. // Calculate the percentage of the closest notch.
  754. const notch = Number(perc/sliderMeta.inc).toFixed(0)*sliderMeta.inc
  755. // If we're close to that notch, stick to it.
  756. if(Math.abs(perc-notch) < sliderMeta.inc/2){
  757. updateRangedSlider(v, sliderMeta.min+(sliderMeta.step*(notch/sliderMeta.inc)), notch)
  758. }
  759. }
  760. }
  761. }
  762. })
  763. }
  764. /**
  765. * Update a ranged slider's value and position.
  766. *
  767. * @param {Element} element The ranged slider to update.
  768. * @param {string | number} value The new value for the ranged slider.
  769. * @param {number} notch The notch that the slider should now be at.
  770. */
  771. function updateRangedSlider(element, value, notch){
  772. const oldVal = element.getAttribute('value')
  773. const bar = element.getElementsByClassName('rangeSliderBar')[0]
  774. const track = element.getElementsByClassName('rangeSliderTrack')[0]
  775. element.setAttribute('value', value)
  776. if(notch < 0){
  777. notch = 0
  778. } else if(notch > 100) {
  779. notch = 100
  780. }
  781. const event = new MouseEvent('change', {
  782. target: element,
  783. type: 'change',
  784. bubbles: false,
  785. cancelable: true
  786. })
  787. let cancelled = !element.dispatchEvent(event)
  788. if(!cancelled){
  789. track.style.left = notch + '%'
  790. bar.style.width = notch + '%'
  791. } else {
  792. element.setAttribute('value', oldVal)
  793. }
  794. }
  795. /**
  796. * Display the total and available RAM.
  797. */
  798. function populateMemoryStatus(){
  799. settingsMemoryTotal.innerHTML = Number((os.totalmem()-1000000000)/1000000000).toFixed(1) + 'G'
  800. settingsMemoryAvail.innerHTML = Number(os.freemem()/1000000000).toFixed(1) + 'G'
  801. }
  802. // Bind the executable file input to the display text input.
  803. settingsJavaExecSel.onchange = (e) => {
  804. settingsJavaExecVal.value = settingsJavaExecSel.files[0].path
  805. populateJavaExecDetails(settingsJavaExecVal.value)
  806. }
  807. /**
  808. * Validate the provided executable path and display the data on
  809. * the UI.
  810. *
  811. * @param {string} execPath The executable path to populate against.
  812. */
  813. function populateJavaExecDetails(execPath){
  814. AssetGuard._validateJavaBinary(execPath).then(v => {
  815. if(v.valid){
  816. settingsJavaExecDetails.innerHTML = `Selected: Java ${v.version.major} Update ${v.version.update} (x${v.arch})`
  817. } else {
  818. settingsJavaExecDetails.innerHTML = 'Invalid Selection'
  819. }
  820. })
  821. }
  822. /**
  823. * Prepare the Java tab for display.
  824. */
  825. function prepareJavaTab(){
  826. bindRangeSlider()
  827. populateMemoryStatus()
  828. }
  829. /**
  830. * About Tab
  831. */
  832. const settingsAboutCurrentVersionCheck = document.getElementById('settingsAboutCurrentVersionCheck')
  833. const settingsAboutCurrentVersionTitle = document.getElementById('settingsAboutCurrentVersionTitle')
  834. const settingsAboutCurrentVersionValue = document.getElementById('settingsAboutCurrentVersionValue')
  835. const settingsChangelogTitle = document.getElementById('settingsChangelogTitle')
  836. const settingsChangelogText = document.getElementById('settingsChangelogText')
  837. const settingsChangelogButton = document.getElementById('settingsChangelogButton')
  838. // Bind the devtools toggle button.
  839. document.getElementById('settingsAboutDevToolsButton').onclick = (e) => {
  840. let window = remote.getCurrentWindow()
  841. window.toggleDevTools()
  842. }
  843. /**
  844. * Retrieve the version information and display it on the UI.
  845. */
  846. function populateVersionInformation(){
  847. const version = remote.app.getVersion()
  848. settingsAboutCurrentVersionValue.innerHTML = version
  849. const preRelComp = semver.prerelease(version)
  850. if(preRelComp != null && preRelComp.length > 0){
  851. settingsAboutCurrentVersionTitle.innerHTML = 'Pre-release'
  852. settingsAboutCurrentVersionTitle.style.color = '#ff886d'
  853. settingsAboutCurrentVersionCheck.style.background = '#ff886d'
  854. } else {
  855. settingsAboutCurrentVersionTitle.innerHTML = 'Stable Release'
  856. settingsAboutCurrentVersionTitle.style.color = null
  857. settingsAboutCurrentVersionCheck.style.background = null
  858. }
  859. }
  860. /**
  861. * Fetches the GitHub atom release feed and parses it for the release notes
  862. * of the current version. This value is displayed on the UI.
  863. */
  864. function populateReleaseNotes(){
  865. $.ajax({
  866. url: 'https://github.com/WesterosCraftCode/ElectronLauncher/releases.atom',
  867. success: (data) => {
  868. const version = 'v' + remote.app.getVersion()
  869. const entries = $(data).find('entry')
  870. for(let i=0; i<entries.length; i++){
  871. const entry = $(entries[i])
  872. let id = entry.find('id').text()
  873. id = id.substring(id.lastIndexOf('/')+1)
  874. if(id === version){
  875. settingsChangelogTitle.innerHTML = entry.find('title').text()
  876. settingsChangelogText.innerHTML = entry.find('content').text()
  877. settingsChangelogButton.href = entry.find('link').attr('href')
  878. }
  879. }
  880. },
  881. timeout: 2500
  882. }).catch(err => {
  883. settingsChangelogText.innerHTML = 'Failed to load release notes.'
  884. })
  885. }
  886. /**
  887. * Prepare account tab for display.
  888. */
  889. function prepareAboutTab(){
  890. populateVersionInformation()
  891. populateReleaseNotes()
  892. }
  893. /**
  894. * Settings preparation functions.
  895. */
  896. /**
  897. * Prepare the entire settings UI.
  898. *
  899. * @param {boolean} first Whether or not it is the first load.
  900. */
  901. function prepareSettings(first = false) {
  902. if(first){
  903. setupSettingsTabs()
  904. initSettingsValidators()
  905. } else {
  906. prepareModsTab()
  907. }
  908. initSettingsValues()
  909. prepareAccountsTab()
  910. prepareJavaTab()
  911. prepareAboutTab()
  912. }
  913. // Prepare the settings UI on startup.
  914. prepareSettings(true)