feat: add some funcs

This commit is contained in:
lucasdpt
2026-06-14 14:23:37 +02:00
parent 48fa508540
commit 4756420f8d
11 changed files with 240 additions and 44 deletions
+9 -2
View File
@@ -6,6 +6,7 @@ import {
type DeviceCodeInfo,
type UpdateStatus
} from '../shared/ipc'
import * as logger from './logger'
/** Fenêtre principale, définie au démarrage (src/main/index.ts). */
let mainWindow: BrowserWindow | null = null
@@ -21,8 +22,14 @@ function send(channel: string, payload: unknown): void {
}
export const emit = {
progress: (e: ProgressEvent): void => send(IPC_EVENT.progress, e),
gameLog: (l: GameLogLine): void => send(IPC_EVENT.gameLog, l),
progress: (e: ProgressEvent): void => {
if (e.phase === 'error') logger.write(`[ERREUR] ${e.message}`)
send(IPC_EVENT.progress, e)
},
gameLog: (l: GameLogLine): void => {
logger.write(l.line)
send(IPC_EVENT.gameLog, l)
},
gameClosed: (code: number | null): void => send(IPC_EVENT.gameClosed, code),
authCode: (info: DeviceCodeInfo): void => send(IPC_EVENT.authCode, info),
updateStatus: (s: UpdateStatus): void => send(IPC_EVENT.updateStatus, s)
+7 -3
View File
@@ -1,9 +1,10 @@
import { app, shell, BrowserWindow, ipcMain } from 'electron'
import { join } from 'path'
import { setMainWindow } from './events'
import { IPC, type UserSettings } from '../shared/ipc'
import { IPC, type UserSettings, type PlayOptions } from '../shared/ipc'
import { login, logout, restoreSession, getCurrent } from './auth'
import { play } from './play'
import { play, stopGame } from './play'
import { getPackMetaCached } from './modpack'
import { getSettings, setSettings } from './settings'
import { paths } from './paths'
import { initUpdater, quitAndInstallUpdate } from './updater'
@@ -50,11 +51,14 @@ function registerIpc(): void {
ipcMain.handle(IPC.authGetProfile, async () => {
return getCurrent()?.profile ?? (await restoreSession())
})
ipcMain.handle(IPC.play, () => play())
ipcMain.handle(IPC.play, (_e, opts: PlayOptions | undefined) => play(opts))
ipcMain.handle(IPC.playStop, () => stopGame())
ipcMain.handle(IPC.packGet, () => getPackMetaCached())
ipcMain.handle(IPC.settingsGet, () => getSettings())
ipcMain.handle(IPC.settingsSet, (_e, s: UserSettings) => setSettings(s))
ipcMain.handle(IPC.appVersion, () => app.getVersion())
ipcMain.handle(IPC.openInstanceDir, () => shell.openPath(paths.instanceDir))
ipcMain.handle(IPC.openLogsDir, () => shell.openPath(paths.logsDir))
ipcMain.handle(IPC.updateInstall, () => quitAndInstallUpdate())
}
+49 -19
View File
@@ -1,8 +1,10 @@
import { existsSync } from 'fs'
import { join } from 'path'
import { getVersionList, install, installNeoForged } from '@xmcl/installer'
import { getVersionList, installTask, installNeoForgedTask } from '@xmcl/installer'
import type { Task } from '@xmcl/task'
import { paths } from './paths'
import { emit } from './events'
import { type LaunchPhase } from '../shared/ipc'
import { downloadDispatcher, DOWNLOAD_CONCURRENCY, withRetries } from './net'
/** Options de téléchargement communes : dispatcher tolérant + concurrence bridée. */
@@ -12,6 +14,25 @@ const downloadOptions = {
librariesDownloadConcurrency: DOWNLOAD_CONCURRENCY
}
/**
* Exécute une task @xmcl en émettant sa progression réelle (0..1) vers le
* renderer. On lit la progression cumulée de la task racine ; on n'émet qu'au
* changement de pourcentage entier pour ne pas inonder l'IPC.
*/
async function runWithProgress<T>(phase: LaunchPhase, message: string, task: Task<T>): Promise<T> {
let lastPct = -1
return task.startAndWait({
onUpdate() {
if (task.total <= 0) return
const ratio = task.progress / task.total
const pct = Math.floor(ratio * 100)
if (pct === lastPct) return
lastPct = pct
emit.progress({ phase, message, progress: Math.min(1, ratio) })
}
})
}
/**
* Installe le runtime Minecraft (vanilla 1.21.1) puis NeoForge dans
* paths.gameRoot. Les deux étapes sont idempotentes : si la version est déjà
@@ -25,25 +46,27 @@ function versionInstalled(id: string): boolean {
return existsSync(join(paths.gameRoot, 'versions', id, `${id}.json`))
}
/** Installe Minecraft vanilla <version> (json + jar + assets + libraries). */
export async function installMinecraft(version: string): Promise<void> {
if (versionInstalled(version)) return
/**
* Installe Minecraft vanilla <version> (json + jar + assets + libraries).
* `force` saute le court-circuit "déjà installé" pour revalider/réparer les
* fichiers (l'install @xmcl ignore les fichiers déjà valides par checksum).
*/
export async function installMinecraft(version: string, force = false): Promise<void> {
if (!force && versionInstalled(version)) return
emit.progress({ phase: 'minecraft', message: `Minecraft ${version} : métadonnées…`, progress: undefined })
const list = await getVersionList()
const meta = list.versions.find((v) => v.id === version)
if (!meta) throw new Error(`Version Minecraft introuvable : ${version}`)
emit.progress({
phase: 'minecraft',
message: `Installation de Minecraft ${version} (assets + libs)…`,
progress: undefined
})
const label = force
? `Vérification de Minecraft ${version}`
: `Installation de Minecraft ${version} (assets + libs)…`
// ~3700 assets : on réessaie l'install entière plusieurs fois. Chaque passe
// ignore les fichiers déjà valides et ne reprend que les manquants.
await withRetries(
() => install(meta, paths.gameRoot, downloadOptions),
() => runWithProgress('minecraft', label, installTask(meta, paths.gameRoot, downloadOptions)),
5,
(attempt) =>
emit.progress({
@@ -61,26 +84,33 @@ export async function installMinecraft(version: string): Promise<void> {
export async function installNeoForge(
neoforge: string,
minecraft: string,
javaPath: string
javaPath: string,
force = false
): Promise<string> {
// @xmcl nomme la version installée "neoforge-<version>" (ex. neoforge-21.1.224).
// Si elle est déjà présente, on saute l'install (idempotent, comme Minecraft).
const expectedId = `neoforge-${neoforge}`
if (versionInstalled(expectedId)) {
if (!force && versionInstalled(expectedId)) {
void minecraft
return expectedId
}
emit.progress({ phase: 'neoforge', message: `Installation de NeoForge ${neoforge}`, progress: undefined })
const label = force
? `Vérification de NeoForge ${neoforge}`
: `Installation de NeoForge ${neoforge}`
// installNeoForged retourne l'id de version installée à lancer.
// installNeoForgedTask retourne l'id de version installée à lancer.
const versionId = await withRetries(
() =>
installNeoForged('neoforge', neoforge, paths.gameRoot, {
java: javaPath,
dispatcher: downloadDispatcher,
librariesDownloadConcurrency: DOWNLOAD_CONCURRENCY
}),
runWithProgress(
'neoforge',
label,
installNeoForgedTask('neoforge', neoforge, paths.gameRoot, {
java: javaPath,
dispatcher: downloadDispatcher,
librariesDownloadConcurrency: DOWNLOAD_CONCURRENCY
})
),
3,
(attempt) =>
emit.progress({
+30
View File
@@ -0,0 +1,30 @@
import { createWriteStream, type WriteStream } from 'fs'
import { paths } from './paths'
/**
* Journalisation sur disque du launcher (logs/launcher.log).
*
* Capture tout ce qui transite par `events.ts` (sortie jeu + packwiz + messages
* de phase + erreurs), pour pouvoir dépanner un joueur à distance. Le fichier
* est tronqué au début de chaque session "Jouer".
*/
let stream: WriteStream | null = null
function ts(): string {
return new Date().toISOString()
}
/** Ouvre (en tronquant) un nouveau fichier de log et écrit un en-tête. */
export function startSession(): void {
stream?.end()
stream = createWriteStream(paths.launcherLogFile, { flags: 'w' })
stream.write(`=== Session OFLauncher ${ts()} ===\n`)
}
/** Ajoute une ligne au log courant (no-op si aucune session ouverte). */
export function write(line: string): void {
if (!stream) return
const text = line.endsWith('\n') ? line : `${line}\n`
stream.write(text)
}
+16 -6
View File
@@ -4,6 +4,9 @@ import { paths } from './paths'
import { config } from '../shared/config'
import { fetchText } from './download'
import { emit } from './events'
import type { PackMeta } from '../shared/ipc'
export type { PackMeta }
/**
* Gestion du modpack côté launcher :
@@ -15,11 +18,17 @@ import { emit } from './events'
* comportement "pas de re-download complet à chaque update" recherché.
*/
export interface PackMeta {
name: string
version: string
minecraft: string
neoforge: string
/** Dernière PackMeta lue avec succès (pour l'affichage UI, y compris hors flux Jouer). */
let lastMeta: PackMeta | null = null
/** Renvoie la dernière PackMeta connue, ou la récupère si jamais lue. Tolérant au offline. */
export async function getPackMetaCached(): Promise<PackMeta | null> {
if (lastMeta) return lastMeta
try {
return await fetchPackMeta()
} catch {
return null
}
}
/** Télécharge et parse le pack.toml distant. */
@@ -47,12 +56,13 @@ export async function fetchPackMeta(): Promise<PackMeta> {
)
}
return {
lastMeta = {
name: data.name ?? 'Modpack',
version: data.version ?? '0',
minecraft,
neoforge
}
return lastMeta
}
/**
+10
View File
@@ -41,6 +41,16 @@ class LauncherPaths {
return join(this.root, 'settings.json')
}
/** Dossier des logs du launcher (install/Java/packwiz/jeu). */
get logsDir(): string {
return this.ensure(join(this.root, 'logs'))
}
/** Fichier de log courant du launcher. */
get launcherLogFile(): string {
return join(this.logsDir, 'launcher.log')
}
/** jar packwiz-installer-bootstrap embarqué dans les resources. */
get packwizBootstrapJar(): string {
// En prod, electron-builder copie resources/ via extraResources.
+15 -3
View File
@@ -7,6 +7,8 @@ import { syncModpack } from './modpack'
import { launchGame } from './launch'
import { getSettings } from './settings'
import { emit } from './events'
import * as logger from './logger'
import type { PlayOptions } from '../shared/ipc'
/** Process de jeu courant (un seul à la fois). */
let gameProcess: ChildProcess | null = null
@@ -20,7 +22,7 @@ let gameProcess: ChildProcess | null = null
* idempotentes, donc à partir du 2e lancement seules les nouveautés du modpack
* sont téléchargées.
*/
export async function play(): Promise<void> {
export async function play(opts?: PlayOptions): Promise<void> {
if (gameProcess) {
throw new Error('Le jeu est déjà en cours.')
}
@@ -30,11 +32,14 @@ export async function play(): Promise<void> {
throw new Error('Non connecté. Connecte-toi avec ton compte Microsoft dabord.')
}
const repair = opts?.repair ?? false
logger.startSession()
try {
const meta = await fetchPackMeta()
const javaPath = await ensureJava()
await installMinecraft(meta.minecraft)
const versionId = await installNeoForge(meta.neoforge, meta.minecraft, javaPath)
await installMinecraft(meta.minecraft, repair)
const versionId = await installNeoForge(meta.neoforge, meta.minecraft, javaPath, repair)
await syncModpack(javaPath)
const settings = await getSettings()
@@ -48,3 +53,10 @@ export async function play(): Promise<void> {
throw e
}
}
/** Tue le process de jeu courant. Renvoie true si un process tournait. */
export function stopGame(): boolean {
if (!gameProcess) return false
gameProcess.kill()
return true
}