Skip to content

[Tech/Demo] Migrate Wine Manager status state to Zustand #3428

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,8 @@
"steam-shortcut-editor": "3.1.3",
"tslib": "2.5.0",
"xvfb-maybe": "^0.2.1",
"zod": "3.22.3"
"zod": "3.22.3",
"zustand": "^4.4.7"
},
"devDependencies": {
"@electron/notarize": "^2.3.0",
Expand Down
287 changes: 174 additions & 113 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

21 changes: 8 additions & 13 deletions src/backend/api/wine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@ import {
RuntimeName,
ToolArgs,
WineVersionInfo,
ProgressInfo,
State,
Runner
Runner,
type WineManagerStatus
} from 'common/types'

export const toggleDXVK = async (args: ToolArgs) =>
Expand All @@ -27,11 +26,10 @@ export const showItemInFolder = (installDir: string) =>
ipcRenderer.send('showItemInFolder', installDir)
export const installWineVersion = async (
release: WineVersionInfo
): Promise<'error' | 'abort' | 'success'> =>
ipcRenderer.invoke('installWineVersion', release)
): Promise<void> => ipcRenderer.invoke('installWineVersion', release)
export const removeWineVersion = async (
release: WineVersionInfo
): Promise<boolean> => ipcRenderer.invoke('removeWineVersion', release)
): Promise<void> => ipcRenderer.invoke('removeWineVersion', release)
export const refreshWineVersionInfo = async (fetch?: boolean): Promise<void> =>
ipcRenderer.invoke('refreshWineVersionInfo', fetch)

Expand All @@ -48,18 +46,15 @@ export const handleProgressOfWinetricks = (
}

export const handleProgressOfWineManager = (
version: string,
callback: (
e: Electron.IpcRendererEvent,
progress: {
state: State
progress: ProgressInfo
}
version: string,
progress: WineManagerStatus
) => void
): (() => void) => {
ipcRenderer.on('progressOfWineManager' + version, callback)
ipcRenderer.on('progressOfWineManager', callback)
return () => {
ipcRenderer.removeListener('progressOfWineManager' + version, callback)
ipcRenderer.removeListener('progressOfWineManager', callback)
}
}

Expand Down
10 changes: 3 additions & 7 deletions src/backend/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ import {
Release,
GameInfo,
GameSettings,
State,
ProgressInfo,
GameStatus
} from 'common/types'
import axios from 'axios'
Expand Down Expand Up @@ -89,6 +87,7 @@ import {
deviceNameCache,
vendorNameCache
} from './utils/systeminfo/gpu/pci_ids'
import type { WineManagerStatus } from 'common/types'

const execAsync = promisify(exec)

Expand Down Expand Up @@ -898,11 +897,8 @@ export async function downloadDefaultWine() {
}

// download the latest version
const onProgress = (state: State, progress?: ProgressInfo) => {
sendFrontendMessage(`progressOfWineManager${release.version}`, {
state,
progress
})
const onProgress = (state: WineManagerStatus) => {
sendFrontendMessage('progressOfWineManager', release.version, state)
}
const result = await installWineVersion(release, onProgress)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ jest.mock('@xhmikosr/decompress-targz', () => {
jest.mock('@felipecrs/decompress-tarxz', () => {
return jest.fn().mockImplementation(() => {})
})
const workDir = process.cwd()

describe('Utilities - Unzip', () => {
test('unzip file fails because of invalid archive path', async () => {
Expand All @@ -36,9 +35,7 @@ describe('Utilities - Unzip', () => {
unzipDir: __dirname,
onProgress: progress
})
).rejects.toStrictEqual(
`Archive path ${workDir}/src/backend/wine/manager/downloader/__tests__/utilities is not a file!`
)
).rejects.toStrictEqual(`Archive path ${__dirname} is not a file!`)
})

test('unzip file fails because of invalid install path', async () => {
Expand Down Expand Up @@ -67,7 +64,7 @@ describe('Utilities - Unzip', () => {
onProgress: progress
})
).resolves.toStrictEqual(
`Succesfully unzip ${workDir}/src/backend/wine/manager/downloader/__tests__/utilities/../test_data/test.tar.xz to ${workDir}/src/backend/wine/manager/downloader/__tests__/utilities/test_unzip.`
`Succesfully unzip ${__dirname}/../test_data/test.tar.xz to ${installDir}.`
)

if (existsSync(installDir)) {
Expand All @@ -90,7 +87,7 @@ describe('Utilities - Unzip', () => {
onProgress: progress
})
).resolves.toStrictEqual(
`Succesfully unzip ${workDir}/src/backend/wine/manager/downloader/__tests__/utilities/../test_data/test.tar.gz to ${workDir}/src/backend/wine/manager/downloader/__tests__/utilities/test_unzip.`
`Succesfully unzip ${__dirname}/../test_data/test.tar.gz to ${installDir}.`
)

if (existsSync(installDir)) {
Expand All @@ -113,7 +110,7 @@ describe('Utilities - Unzip', () => {
onProgress: progress
})
).resolves.toStrictEqual(
`Succesfully unzip ${workDir}/src/backend/wine/manager/downloader/__tests__/utilities/../test_data/test.tar.gz to ${workDir}/src/backend/wine/manager/downloader/__tests__/utilities/test_unzip.`
`Succesfully unzip ${__dirname}/../test_data/test.tar.gz to ${installDir}.`
)

await expect(
Expand All @@ -124,14 +121,14 @@ describe('Utilities - Unzip', () => {
onProgress: progress
})
).resolves.toStrictEqual(
`Succesfully unzip ${workDir}/src/backend/wine/manager/downloader/__tests__/utilities/../test_data/test.tar.gz to ${workDir}/src/backend/wine/manager/downloader/__tests__/utilities/test_unzip.`
`Succesfully unzip ${__dirname}/../test_data/test.tar.gz to ${installDir}.`
)

if (existsSync(installDir)) {
rmSync(installDir, { recursive: true })
}

expect(progress).toBeCalledWith('unzipping')
expect(progress).toBeCalledWith('idle')
expect(progress).toBeCalledWith({ status: 'unzipping' })
expect(progress).toBeCalledWith({ status: 'idle' })
})
})
8 changes: 5 additions & 3 deletions src/backend/wine/manager/downloader/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,15 @@ import {
WINECROSSOVER_URL,
WINESTAGINGMACOS_URL
} from './constants'
import { VersionInfo, Repositorys, State, ProgressInfo } from 'common/types'
import { VersionInfo, Repositorys } from 'common/types'
import {
fetchReleases,
getFolderSize,
unlinkFile,
unzipFile
} from './utilities'
import { axiosClient, calculateEta, downloadFile } from 'backend/utils'
import type { WineManagerStatus } from 'common/types'

interface getVersionsProps {
repositorys?: Repositorys[]
Expand Down Expand Up @@ -150,7 +151,7 @@ interface installProps {
versionInfo: VersionInfo
installDir: string
overwrite?: boolean
onProgress?: (state: State, progress?: ProgressInfo) => void
onProgress?: (state: WineManagerStatus) => void
abortSignal?: AbortSignal
}

Expand Down Expand Up @@ -247,7 +248,8 @@ async function installVersion({
versionInfo.downsize
)

onProgress('downloading', {
onProgress({
status: 'downloading',
percentage,
eta: eta!,
avgSpeed: downloadSpeed
Expand Down
10 changes: 5 additions & 5 deletions src/backend/wine/manager/downloader/utilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { isMac } from '../../../constants'
import { existsSync, statSync, unlinkSync } from 'graceful-fs'
import { spawnSync } from 'child_process'

import { ProgressInfo, State, VersionInfo, Type } from 'common/types'
import { VersionInfo, Type, type WineManagerStatus } from 'common/types'
import { axiosClient, extractFiles } from 'backend/utils'

interface fetchProps {
Expand Down Expand Up @@ -116,7 +116,7 @@ interface unzipProps {
filePath: string
unzipDir: string
overwrite?: boolean
onProgress: (state: State, progress?: ProgressInfo) => void
onProgress: (state: WineManagerStatus) => void
abortSignal?: AbortSignal
}

Expand Down Expand Up @@ -151,15 +151,15 @@ async function unzipFile({

extractFiles({ path: filePath, destination: unzipDir, strip: 1 })
.then(() => {
onProgress('idle')
onProgress({ status: 'idle' })
resolve(`Succesfully unzip ${filePath} to ${unzipDir}.`)
})
.catch((error) => {
onProgress('idle')
onProgress({ status: 'idle' })
reject(`Unzip of ${filePath} failed with:\n ${error}!`)
})

onProgress('unzipping')
onProgress({ status: 'unzipping' })
})
}

Expand Down
44 changes: 34 additions & 10 deletions src/backend/wine/manager/ipc_handler.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,45 @@
import { ipcMain } from 'electron'
import { ProgressInfo, State } from 'common/types'
import {
installWineVersion,
removeWineVersion,
updateWineVersionInfos
} from './utils'
import { logError, LogPrefix } from '../../logger/logger'
import { sendFrontendMessage } from '../../main_window'
import type { WineManagerStatus } from 'common/types'
import { notify } from '../../dialog/dialog'
import { t } from 'i18next'

ipcMain.handle('installWineVersion', async (e, release) => {
const onProgress = (state: State, progress?: ProgressInfo) => {
sendFrontendMessage(`progressOfWineManager${release.version}`, {
state,
progress
})
const onProgress = (state: WineManagerStatus) => {
sendFrontendMessage('progressOfWineManager', release.version, state)
}

notify({ title: release.version, body: t('notify.install.startInstall') })
onProgress({
status: 'downloading',
percentage: 0,
avgSpeed: 0,
eta: '00:00:00'
})

const result = await installWineVersion(release, onProgress)
return result

let notifyBody: string | null = null
switch (result) {
case 'error':
notifyBody = t('notify.install.error')
break
case 'abort':
notifyBody = t('notify.install.canceled')
break
case 'success':
notifyBody = t('notify.install.finished')
}
if (notifyBody) notify({ title: release.version, body: notifyBody })
onProgress({
status: 'idle'
})
})

ipcMain.handle('refreshWineVersionInfo', async (e, fetch?) => {
Expand All @@ -29,6 +52,7 @@ ipcMain.handle('refreshWineVersionInfo', async (e, fetch?) => {
}
})

ipcMain.handle('removeWineVersion', async (e, release) =>
removeWineVersion(release)
)
ipcMain.handle('removeWineVersion', async (e, release) => {
const result = await removeWineVersion(release)
if (result) notify({ title: release.version, body: t('notify.uninstalled') })
})
7 changes: 3 additions & 4 deletions src/backend/wine/manager/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,9 @@ import { existsSync, mkdirSync, rmSync } from 'graceful-fs'
import { logError, logInfo, LogPrefix, logWarning } from '../../logger/logger'
import {
WineVersionInfo,
ProgressInfo,
Repositorys,
State,
VersionInfo
VersionInfo,
WineManagerStatus
} from 'common/types'

import { getAvailableVersions, installVersion } from './downloader/main'
Expand Down Expand Up @@ -89,7 +88,7 @@ async function updateWineVersionInfos(

async function installWineVersion(
release: WineVersionInfo,
onProgress: (state: State, progress?: ProgressInfo) => void
onProgress: (status: WineManagerStatus) => void
) {
let updatedInfo: WineVersionInfo
const variant = release.hasUpdate ? 'update' : 'installation'
Expand Down
6 changes: 2 additions & 4 deletions src/common/typedefs/ipcBridge.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,11 +224,9 @@ interface AsyncIPCFunctions {
}) => Promise<void>
isNative: (args: { appName: string; runner: Runner }) => boolean
getLogContent: (appNameOrRunner: string) => string
installWineVersion: (
release: WineVersionInfo
) => Promise<'error' | 'abort' | 'success'>
installWineVersion: (release: WineVersionInfo) => Promise<void>
refreshWineVersionInfo: (fetch?: boolean) => Promise<void>
removeWineVersion: (release: WineVersionInfo) => Promise<boolean>
removeWineVersion: (release: WineVersionInfo) => Promise<void>
shortcutsExists: (appName: string, runner: Runner) => boolean
addToSteam: (appName: string, runner: Runner) => Promise<boolean>
removeFromSteam: (appName: string, runner: Runner) => Promise<void>
Expand Down
16 changes: 3 additions & 13 deletions src/common/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -714,19 +714,9 @@ export enum Repositorys {
WINESTAGINGMACOS
}

/**
* Type for the progress callback state
*/
export type State = 'downloading' | 'unzipping' | 'idle'

/**
* Interface for the information that progress callback returns
*/
export interface ProgressInfo {
percentage: number
avgSpeed: number
eta: string
}
export type WineManagerStatus =
| { status: 'idle' | 'unzipping' }
| { status: 'downloading'; percentage: number; avgSpeed: number; eta: string }

export interface WineManagerUISettings {
value: string
Expand Down
8 changes: 2 additions & 6 deletions src/common/types/frontend_messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,9 @@ import type {
DownloadManagerState,
GameInfo,
GameStatus,
ProgressInfo,
RecentGame,
Runner,
State
WineManagerStatus
} from 'common/types'

type FrontendMessages = {
Expand Down Expand Up @@ -42,13 +41,10 @@ type FrontendMessages = {
messages: string[]
installingComponent: string
}) => void
progressOfWineManager: (version: string, progress: WineManagerStatus) => void
'installing-winetricks-component': (component: string) => void

[key: `progressUpdate${string}`]: (progress: GameStatus) => void
[key: `progressOfWineManager${string}`]: (progress: {
state: State
progress?: ProgressInfo
}) => void

// Used inside tests, so we can be a bit lenient with the type checking here
message: (...params: unknown[]) => void
Expand Down
Loading
Loading