uibinder.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. /**
  2. * Initialize UI functions which depend on internal modules.
  3. * Loaded after core UI functions are initialized in uicore.js.
  4. */
  5. // Requirements
  6. const path = require('path')
  7. const AuthManager = require('./assets/js/authmanager')
  8. const ConfigManager = require('./assets/js/configmanager')
  9. const DistroManager = require('./assets/js/distromanager')
  10. const Lang = require('./assets/js/langloader')
  11. let rscShouldLoad = false
  12. let fatalStartupError = false
  13. // Mapping of each view to their container IDs.
  14. const VIEWS = {
  15. landing: '#landingContainer',
  16. loginOptions: '#loginOptionsContainer',
  17. login: '#loginContainer',
  18. settings: '#settingsContainer',
  19. welcome: '#welcomeContainer',
  20. waiting: '#waitingContainer'
  21. }
  22. // The currently shown view container.
  23. let currentView
  24. /**
  25. * Switch launcher views.
  26. *
  27. * @param {string} current The ID of the current view container.
  28. * @param {*} next The ID of the next view container.
  29. * @param {*} currentFadeTime Optional. The fade out time for the current view.
  30. * @param {*} nextFadeTime Optional. The fade in time for the next view.
  31. * @param {*} onCurrentFade Optional. Callback function to execute when the current
  32. * view fades out.
  33. * @param {*} onNextFade Optional. Callback function to execute when the next view
  34. * fades in.
  35. */
  36. function switchView(current, next, currentFadeTime = 500, nextFadeTime = 500, onCurrentFade = () => {}, onNextFade = () => {}){
  37. currentView = next
  38. $(`${current}`).fadeOut(currentFadeTime, () => {
  39. onCurrentFade()
  40. $(`${next}`).fadeIn(nextFadeTime, () => {
  41. onNextFade()
  42. })
  43. })
  44. }
  45. /**
  46. * Get the currently shown view container.
  47. *
  48. * @returns {string} The currently shown view container.
  49. */
  50. function getCurrentView(){
  51. return currentView
  52. }
  53. function showMainUI(data){
  54. if(!isDev){
  55. loggerAutoUpdater.log('Initializing..')
  56. ipcRenderer.send('autoUpdateAction', 'initAutoUpdater', ConfigManager.getAllowPrerelease())
  57. }
  58. prepareSettings(true)
  59. updateSelectedServer(data.getServer(ConfigManager.getSelectedServer()))
  60. refreshServerStatus()
  61. setTimeout(() => {
  62. document.getElementById('frameBar').style.backgroundColor = 'rgba(0, 0, 0, 0.5)'
  63. document.body.style.backgroundImage = `url('assets/images/backgrounds/${document.body.getAttribute('bkid')}.jpg')`
  64. $('#main').show()
  65. const isLoggedIn = Object.keys(ConfigManager.getAuthAccounts()).length > 0
  66. // If this is enabled in a development environment we'll get ratelimited.
  67. // The relaunch frequency is usually far too high.
  68. if(!isDev && isLoggedIn){
  69. validateSelectedAccount()
  70. }
  71. if(ConfigManager.isFirstLaunch()){
  72. currentView = VIEWS.welcome
  73. $(VIEWS.welcome).fadeIn(1000)
  74. } else {
  75. if(isLoggedIn){
  76. currentView = VIEWS.landing
  77. $(VIEWS.landing).fadeIn(1000)
  78. } else {
  79. loginOptionsCancelEnabled(false)
  80. loginOptionsViewOnLoginSuccess = VIEWS.landing
  81. loginOptionsViewOnLoginCancel = VIEWS.loginOptions
  82. currentView = VIEWS.loginOptions
  83. $(VIEWS.loginOptions).fadeIn(1000)
  84. }
  85. }
  86. setTimeout(() => {
  87. $('#loadingContainer').fadeOut(500, () => {
  88. $('#loadSpinnerImage').removeClass('rotating')
  89. })
  90. }, 250)
  91. }, 750)
  92. // Disable tabbing to the news container.
  93. initNews().then(() => {
  94. $('#newsContainer *').attr('tabindex', '-1')
  95. })
  96. }
  97. function showFatalStartupError(){
  98. setTimeout(() => {
  99. $('#loadingContainer').fadeOut(250, () => {
  100. document.getElementById('overlayContainer').style.background = 'none'
  101. setOverlayContent(
  102. 'Fatal Error: Unable to Load Distribution Index',
  103. 'A connection could not be established to our servers to download the distribution index. No local copies were available to load. <br><br>The distribution index is an essential file which provides the latest server information. The launcher is unable to start without it. Ensure you are connected to the internet and relaunch the application.',
  104. 'Close'
  105. )
  106. setOverlayHandler(() => {
  107. const window = remote.getCurrentWindow()
  108. window.close()
  109. })
  110. toggleOverlay(true)
  111. })
  112. }, 750)
  113. }
  114. /**
  115. * Common functions to perform after refreshing the distro index.
  116. *
  117. * @param {Object} data The distro index object.
  118. */
  119. function onDistroRefresh(data){
  120. updateSelectedServer(data.getServer(ConfigManager.getSelectedServer()))
  121. refreshServerStatus()
  122. initNews()
  123. syncModConfigurations(data)
  124. }
  125. /**
  126. * Sync the mod configurations with the distro index.
  127. *
  128. * @param {Object} data The distro index object.
  129. */
  130. function syncModConfigurations(data){
  131. const syncedCfgs = []
  132. for(let serv of data.getServers()){
  133. const id = serv.getID()
  134. const mdls = serv.getModules()
  135. const cfg = ConfigManager.getModConfiguration(id)
  136. if(cfg != null){
  137. const modsOld = cfg.mods
  138. const mods = {}
  139. for(let mdl of mdls){
  140. const type = mdl.getType()
  141. if(type === DistroManager.Types.ForgeMod || type === DistroManager.Types.LiteMod || type === DistroManager.Types.LiteLoader){
  142. if(!mdl.getRequired().isRequired()){
  143. const mdlID = mdl.getVersionlessID()
  144. if(modsOld[mdlID] == null){
  145. mods[mdlID] = scanOptionalSubModules(mdl.getSubModules(), mdl)
  146. } else {
  147. mods[mdlID] = mergeModConfiguration(modsOld[mdlID], scanOptionalSubModules(mdl.getSubModules(), mdl), false)
  148. }
  149. } else {
  150. if(mdl.hasSubModules()){
  151. const mdlID = mdl.getVersionlessID()
  152. const v = scanOptionalSubModules(mdl.getSubModules(), mdl)
  153. if(typeof v === 'object'){
  154. if(modsOld[mdlID] == null){
  155. mods[mdlID] = v
  156. } else {
  157. mods[mdlID] = mergeModConfiguration(modsOld[mdlID], v, true)
  158. }
  159. }
  160. }
  161. }
  162. }
  163. }
  164. syncedCfgs.push({
  165. id,
  166. mods
  167. })
  168. } else {
  169. const mods = {}
  170. for(let mdl of mdls){
  171. const type = mdl.getType()
  172. if(type === DistroManager.Types.ForgeMod || type === DistroManager.Types.LiteMod || type === DistroManager.Types.LiteLoader){
  173. if(!mdl.getRequired().isRequired()){
  174. mods[mdl.getVersionlessID()] = scanOptionalSubModules(mdl.getSubModules(), mdl)
  175. } else {
  176. if(mdl.hasSubModules()){
  177. const v = scanOptionalSubModules(mdl.getSubModules(), mdl)
  178. if(typeof v === 'object'){
  179. mods[mdl.getVersionlessID()] = v
  180. }
  181. }
  182. }
  183. }
  184. }
  185. syncedCfgs.push({
  186. id,
  187. mods
  188. })
  189. }
  190. }
  191. ConfigManager.setModConfigurations(syncedCfgs)
  192. ConfigManager.save()
  193. }
  194. /**
  195. * Recursively scan for optional sub modules. If none are found,
  196. * this function returns a boolean. If optional sub modules do exist,
  197. * a recursive configuration object is returned.
  198. *
  199. * @returns {boolean | Object} The resolved mod configuration.
  200. */
  201. function scanOptionalSubModules(mdls, origin){
  202. if(mdls != null){
  203. const mods = {}
  204. for(let mdl of mdls){
  205. const type = mdl.getType()
  206. // Optional types.
  207. if(type === DistroManager.Types.ForgeMod || type === DistroManager.Types.LiteMod || type === DistroManager.Types.LiteLoader){
  208. // It is optional.
  209. if(!mdl.getRequired().isRequired()){
  210. mods[mdl.getVersionlessID()] = scanOptionalSubModules(mdl.getSubModules(), mdl)
  211. } else {
  212. if(mdl.hasSubModules()){
  213. const v = scanOptionalSubModules(mdl.getSubModules(), mdl)
  214. if(typeof v === 'object'){
  215. mods[mdl.getVersionlessID()] = v
  216. }
  217. }
  218. }
  219. }
  220. }
  221. if(Object.keys(mods).length > 0){
  222. const ret = {
  223. mods
  224. }
  225. if(!origin.getRequired().isRequired()){
  226. ret.value = origin.getRequired().isDefault()
  227. }
  228. return ret
  229. }
  230. }
  231. return origin.getRequired().isDefault()
  232. }
  233. /**
  234. * Recursively merge an old configuration into a new configuration.
  235. *
  236. * @param {boolean | Object} o The old configuration value.
  237. * @param {boolean | Object} n The new configuration value.
  238. * @param {boolean} nReq If the new value is a required mod.
  239. *
  240. * @returns {boolean | Object} The merged configuration.
  241. */
  242. function mergeModConfiguration(o, n, nReq = false){
  243. if(typeof o === 'boolean'){
  244. if(typeof n === 'boolean') return o
  245. else if(typeof n === 'object'){
  246. if(!nReq){
  247. n.value = o
  248. }
  249. return n
  250. }
  251. } else if(typeof o === 'object'){
  252. if(typeof n === 'boolean') return typeof o.value !== 'undefined' ? o.value : true
  253. else if(typeof n === 'object'){
  254. if(!nReq){
  255. n.value = typeof o.value !== 'undefined' ? o.value : true
  256. }
  257. const newMods = Object.keys(n.mods)
  258. for(let i=0; i<newMods.length; i++){
  259. const mod = newMods[i]
  260. if(o.mods[mod] != null){
  261. n.mods[mod] = mergeModConfiguration(o.mods[mod], n.mods[mod])
  262. }
  263. }
  264. return n
  265. }
  266. }
  267. // If for some reason we haven't been able to merge,
  268. // wipe the old value and use the new one. Just to be safe
  269. return n
  270. }
  271. function refreshDistributionIndex(remote, onSuccess, onError){
  272. if(remote){
  273. DistroManager.pullRemote()
  274. .then(onSuccess)
  275. .catch(onError)
  276. } else {
  277. DistroManager.pullLocal()
  278. .then(onSuccess)
  279. .catch(onError)
  280. }
  281. }
  282. async function validateSelectedAccount(){
  283. const selectedAcc = ConfigManager.getSelectedAccount()
  284. if(selectedAcc != null){
  285. const val = await AuthManager.validateSelected()
  286. if(!val){
  287. ConfigManager.removeAuthAccount(selectedAcc.uuid)
  288. ConfigManager.save()
  289. const accLen = Object.keys(ConfigManager.getAuthAccounts()).length
  290. setOverlayContent(
  291. 'Failed to Refresh Login',
  292. `We were unable to refresh the login for <strong>${selectedAcc.displayName}</strong>. Please ${accLen > 0 ? 'select another account or ' : ''} login again.`,
  293. 'Login',
  294. 'Select Another Account'
  295. )
  296. setOverlayHandler(() => {
  297. const isMicrosoft = selectedAcc.type === 'microsoft'
  298. if(isMicrosoft) {
  299. // Empty for now
  300. } else {
  301. // Mojang
  302. // For convenience, pre-populate the username of the account.
  303. document.getElementById('loginUsername').value = selectedAcc.username
  304. validateEmail(selectedAcc.username)
  305. }
  306. loginOptionsViewOnLoginSuccess = getCurrentView()
  307. loginOptionsViewOnLoginCancel = VIEWS.loginOptions
  308. if(accLen > 0) {
  309. loginOptionsViewOnCancel = getCurrentView()
  310. loginOptionsViewCancelHandler = () => {
  311. if(isMicrosoft) {
  312. ConfigManager.addMicrosoftAuthAccount(
  313. selectedAcc.uuid,
  314. selectedAcc.accessToken,
  315. selectedAcc.username,
  316. selectedAcc.expiresAt,
  317. selectedAcc.microsoft.access_token,
  318. selectedAcc.microsoft.refresh_token,
  319. selectedAcc.microsoft.expires_at
  320. )
  321. } else {
  322. ConfigManager.addMojangAuthAccount(selectedAcc.uuid, selectedAcc.accessToken, selectedAcc.username, selectedAcc.displayName)
  323. }
  324. ConfigManager.save()
  325. validateSelectedAccount()
  326. }
  327. loginOptionsCancelEnabled(true)
  328. } else {
  329. loginOptionsCancelEnabled(false)
  330. }
  331. toggleOverlay(false)
  332. switchView(getCurrentView(), VIEWS.loginOptions)
  333. })
  334. setDismissHandler(() => {
  335. if(accLen > 1){
  336. prepareAccountSelectionList()
  337. $('#overlayContent').fadeOut(250, () => {
  338. bindOverlayKeys(true, 'accountSelectContent', true)
  339. $('#accountSelectContent').fadeIn(250)
  340. })
  341. } else {
  342. const accountsObj = ConfigManager.getAuthAccounts()
  343. const accounts = Array.from(Object.keys(accountsObj), v => accountsObj[v])
  344. // This function validates the account switch.
  345. setSelectedAccount(accounts[0].uuid)
  346. toggleOverlay(false)
  347. }
  348. })
  349. toggleOverlay(true, accLen > 0)
  350. } else {
  351. return true
  352. }
  353. } else {
  354. return true
  355. }
  356. }
  357. /**
  358. * Temporary function to update the selected account along
  359. * with the relevent UI elements.
  360. *
  361. * @param {string} uuid The UUID of the account.
  362. */
  363. function setSelectedAccount(uuid){
  364. const authAcc = ConfigManager.setSelectedAccount(uuid)
  365. ConfigManager.save()
  366. updateSelectedAccount(authAcc)
  367. validateSelectedAccount()
  368. }
  369. // Synchronous Listener
  370. document.addEventListener('readystatechange', function(){
  371. if (document.readyState === 'interactive' || document.readyState === 'complete'){
  372. if(rscShouldLoad){
  373. rscShouldLoad = false
  374. if(!fatalStartupError){
  375. const data = DistroManager.getDistribution()
  376. showMainUI(data)
  377. } else {
  378. showFatalStartupError()
  379. }
  380. }
  381. }
  382. }, false)
  383. // Actions that must be performed after the distribution index is downloaded.
  384. ipcRenderer.on('distributionIndexDone', (event, res) => {
  385. if(res) {
  386. const data = DistroManager.getDistribution()
  387. syncModConfigurations(data)
  388. if(document.readyState === 'interactive' || document.readyState === 'complete'){
  389. showMainUI(data)
  390. } else {
  391. rscShouldLoad = true
  392. }
  393. } else {
  394. fatalStartupError = true
  395. if(document.readyState === 'interactive' || document.readyState === 'complete'){
  396. showFatalStartupError()
  397. } else {
  398. rscShouldLoad = true
  399. }
  400. }
  401. })