@mun-ui/ui 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/README.md +11 -1
  2. package/bin/desktop.mjs +143 -0
  3. package/bin/mun.mjs +27 -10
  4. package/native/mun-native/src/host_services.rs +202 -0
  5. package/native/mun-native/src/lib.rs +209 -42
  6. package/native/mun-native/src/text.rs +107 -16
  7. package/native/mun-runtime/src/collection.rs +18 -1
  8. package/native/mun-runtime/src/ir.rs +71 -1
  9. package/native/mun-runtime/src/layout.rs +85 -0
  10. package/native/mun-runtime/src/layout_cache.rs +6 -6
  11. package/native/mun-runtime/src/lib.rs +7 -4
  12. package/native/mun-runtime/src/runtime.rs +388 -17
  13. package/native/mun-runtime/src/scene.rs +37 -0
  14. package/native/mun-runtime/tests/host_services.rs +107 -0
  15. package/native/mun-runtime/tests/minimum_window_size.rs +80 -0
  16. package/native/mun-runtime/tests/priority_proposals.rs +69 -0
  17. package/native/mun-runtime/tests/text_proposals.rs +42 -0
  18. package/native/mun-runtime/tests/typography.rs +63 -0
  19. package/package.json +19 -16
  20. package/schemas/semantic-ui-ir-v1.schema.json +89 -0
  21. package/templates/desktop/gitignore +5 -0
  22. package/templates/desktop/package.json +10 -0
  23. package/templates/desktop/src-tauri/Cargo.toml +14 -0
  24. package/templates/desktop/src-tauri/build.rs +1 -0
  25. package/templates/desktop/src-tauri/capabilities/main.json +12 -0
  26. package/templates/desktop/src-tauri/icons/icon.icns +0 -0
  27. package/templates/desktop/src-tauri/icons/icon.ico +0 -0
  28. package/templates/desktop/src-tauri/icons/icon.png +0 -0
  29. package/templates/desktop/src-tauri/src/main.rs +2 -0
  30. package/templates/desktop/src-tauri/tauri.conf.json +42 -0
  31. package/templates/desktop/vite.config.ts +10 -0
  32. package/templates/project/package.json +3 -0
  33. package/templates/project/src/index.css +9 -0
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Mün UI
2
2
 
3
- Mün is a **SwiftUI-like frontend language for web applications**. Author UI and
3
+ Mün is a **SwiftUI-like frontend language for web and desktop applications**. Author UI and
4
4
  application behavior in `.mun` using Views, state, bindings, identity and ordered
5
5
  modifiers. The compiler targets JavaScript and the existing `@mun-ui/web` HTML/DOM
6
6
  runtime. React, Vue and native toolchains are optional integrations.
@@ -59,6 +59,15 @@ You can also author Views directly in JavaScript or TypeScript, without the
59
59
  `mount` / `renderToHTML` from `@mun-ui/web`. Rendering is explicitly separate from
60
60
  View composition; `@mun-ui/core/compat` remains an alias for existing imports.
61
61
 
62
+ ## Desktop target
63
+
64
+ `mun create MyApp --target desktop` uses the same Mün web runtime inside a Tauri 2
65
+ system WebView. `mun dev` opens a native window; `mun package` produces an actual
66
+ application bundle. The optional `@mun-ui/desktop` module supplies picker-scoped
67
+ native file services. See [desktop setup and APIs](docs/DESKTOP.md) and
68
+ [validation boundaries](docs/DESKTOP_VALIDATION.md). The older `--target native`
69
+ GPU/IR implementation remains explicitly experimental.
70
+
62
71
  ## Local development
63
72
 
64
73
  ```bash
@@ -100,6 +109,7 @@ also optional research infrastructure, not the core authoring model.
100
109
  - [Rendering reliability, URL safety and release gates](docs/rendering-reliability.md)
101
110
  - [API](docs/API.md)
102
111
  - [Built-ins and opt-in features](docs/BUILTINS_AND_OPT_IN.md)
112
+ - [Web/WKWebView parity and limitations](docs/WEB_DESKTOP_PARITY.md)
103
113
  - [SwiftUI parity](docs/SWIFTUI_PARITY.md)
104
114
  - [Local development](docs/LOCAL_DEVELOPMENT.md)
105
115
  - [Migration](docs/MIGRATION.md)
@@ -0,0 +1,143 @@
1
+ import { spawn, spawnSync } from 'node:child_process'
2
+ import { existsSync, readFileSync } from 'node:fs'
3
+ import { dirname, resolve } from 'node:path'
4
+ import { createRequire } from 'node:module'
5
+ import { pathToFileURL } from 'node:url'
6
+
7
+ /** Nearest explicit project wins. Never reinterpret a legacy mun.toml as web. */
8
+ export function detectProjectTarget(start = process.cwd()) {
9
+ let root = resolve(start)
10
+ while (true) {
11
+ const native = existsSync(resolve(root, 'mun.toml'))
12
+ const file = resolve(root, 'package.json')
13
+ const manifest = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : undefined
14
+ const explicit = manifest?.mun?.target
15
+ if (explicit && !['web', 'desktop', 'native'].includes(explicit)) throw new Error(`Unknown Mün project target ${explicit} in ${file}.`)
16
+ if (native && explicit && explicit !== 'native') throw new Error(`Ambiguous Mün project in ${root}: mun.toml is legacy native but package.json declares ${explicit}. Move the web/desktop port to a separate project.`)
17
+ if (native || explicit === 'native') return { root, target: 'native', manifest }
18
+ if (explicit) return { root, target: explicit, manifest }
19
+ const dependencies = { ...manifest?.dependencies, ...manifest?.devDependencies }
20
+ if (manifest?.name !== '@mun-ui/ui' && dependencies['@mun-ui/vite']) return { root, target: 'web', manifest }
21
+ const parent = dirname(root)
22
+ if (parent === root) return undefined
23
+ root = parent
24
+ }
25
+ }
26
+
27
+ function resolver(project) { return createRequire(resolve(project.root, 'package.json')) }
28
+ async function viteFor(project) {
29
+ try { return await import(pathToFileURL(resolver(project).resolve('vite')).href) }
30
+ catch (error) { throw new Error(`Install project dependencies before running Mün (${project.root}): ${error.message}`) }
31
+ }
32
+ function tauriCLI(project) {
33
+ try { return resolver(project).resolve('@tauri-apps/cli/tauri.js') }
34
+ catch { throw new Error('Missing @tauri-apps/cli. Run your package manager install in this desktop project.') }
35
+ }
36
+
37
+ /** Own the whole child process group; Vite is closed even on signals or failed startup. */
38
+ export async function runChild(command, args, { cwd, env = process.env } = {}) {
39
+ const child = spawn(command, args, { cwd, env, stdio: 'inherit', detached: process.platform !== 'win32' })
40
+ let interrupted = false
41
+ let killTimer
42
+ const stop = () => {
43
+ interrupted = true
44
+ if (!child.pid) return
45
+ try {
46
+ if (process.platform === 'win32') spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' })
47
+ else {
48
+ process.kill(-child.pid, 'SIGTERM')
49
+ killTimer ??= setTimeout(() => { try { process.kill(-child.pid, 'SIGKILL') } catch {} }, 3000)
50
+ killTimer.unref()
51
+ }
52
+ } catch (error) { if (error.code !== 'ESRCH') throw error }
53
+ }
54
+ process.once('SIGINT', stop); process.once('SIGTERM', stop)
55
+ try {
56
+ return await new Promise((done, reject) => {
57
+ child.once('error', reject)
58
+ child.once('close', code => done(interrupted ? 130 : code ?? 1))
59
+ })
60
+ } finally {
61
+ clearTimeout(killTimer)
62
+ process.removeListener('SIGINT', stop); process.removeListener('SIGTERM', stop)
63
+ // A CLI can terminate before its host. Clean up remaining group members too.
64
+ if (process.platform !== 'win32' && child.pid) { try { process.kill(-child.pid, 'SIGTERM') } catch {} }
65
+ }
66
+ }
67
+
68
+ export function doctor(project, options = {}) {
69
+ let errors = 0
70
+ const check = (label, ok, remedy, detail = '') => { console.log(`${ok ? 'OK' : 'ERROR'} ${label}${detail ? `: ${detail}` : ''}${ok ? '' : ` — ${remedy}`}`); if (!ok) errors++ }
71
+ const command = (label, executable, args, remedy) => {
72
+ const result = spawnSync(executable, args, { encoding: 'utf8', timeout: 10000 })
73
+ check(label, result.status === 0, remedy, result.status === 0 ? result.stdout.trim().split('\n')[0] : '')
74
+ }
75
+ console.log(`Mün ${project.target}; ${process.platform}/${process.arch}; ${project.root}`)
76
+ const [major, minor] = process.versions.node.split('.').map(Number)
77
+ check('Node', (major === 20 && minor >= 19) || (major === 22 && minor >= 12) || major >= 23, 'Install Node 22.12+ or a current LTS.', process.version)
78
+ const pm = options.packageManager ?? project.manifest.packageManager?.split('@')[0] ?? (existsSync(resolve(project.root, 'pnpm-lock.yaml')) || existsSync(resolve(project.root, 'pnpm-workspace.yaml')) ? 'pnpm' : existsSync(resolve(project.root, 'yarn.lock')) ? 'yarn' : existsSync(resolve(project.root, 'bun.lock')) ? 'bun' : 'npm')
79
+ command('Package manager', pm, ['--version'], `Install ${pm}.`)
80
+ for (const dependency of ['vite', '@mun-ui/compiler', '@mun-ui/web', ...(project.target === 'desktop' ? ['@mun-ui/desktop', '@tauri-apps/cli'] : [])]) {
81
+ try {
82
+ const found = resolver(project).resolve.paths(dependency).map(base => resolve(base, dependency, 'package.json')).find(existsSync)
83
+ if (!found) throw new Error('missing')
84
+ const manifest = JSON.parse(readFileSync(found, 'utf8'))
85
+ const entry = manifest.main ?? manifest.exports?.['.']?.import
86
+ if (entry && !existsSync(resolve(dirname(found), entry))) throw new Error('not built')
87
+ check(dependency, true)
88
+ }
89
+ catch { check(dependency, false, `Run ${pm} install (use mun link --local-root <checkout> for local sources).`) }
90
+ }
91
+ if (project.target === 'desktop') {
92
+ check('Tauri configuration', existsSync(resolve(project.root, 'src-tauri/tauri.conf.json')), 'Restore src-tauri from a mun create --target desktop scaffold.')
93
+ command('Rust', 'rustc', ['--version'], 'Install Rust with rustup: https://rustup.rs')
94
+ command('Cargo', 'cargo', ['--version'], 'Install the Rust stable toolchain with rustup.')
95
+ if (process.platform === 'darwin') {
96
+ const osVersion = spawnSync('sw_vers', ['-productVersion'], { encoding: 'utf8' })
97
+ check('macOS runtime', osVersion.status === 0 && Number(osVersion.stdout.trim().split('.')[0]) >= 13, 'The default desktop frontend requires macOS 13+ / Safari 16+.', osVersion.stdout?.trim())
98
+ command('Xcode developer tools', 'xcode-select', ['-p'], 'Run xcode-select --install, or select your full Xcode installation.')
99
+ command('macOS SDK / WKWebView', 'xcrun', ['--show-sdk-path'], 'Install a macOS SDK and accept the Xcode license; WKWebView is supplied by macOS.')
100
+ } else if (process.platform === 'linux') {
101
+ command('WebKitGTK and GTK development packages', 'pkg-config', ['--modversion', 'webkit2gtk-4.1', 'gtk+-3.0'], 'Install libwebkit2gtk-4.1-dev, libgtk-3-dev, build-essential, libssl-dev, librsvg2-dev (distribution names vary).')
102
+ } else if (process.platform === 'win32') {
103
+ command('MSVC toolchain', 'where.exe', ['cl.exe'], 'Install Visual Studio C++ Build Tools and use its developer shell.')
104
+ command('WebView2 runtime', 'reg.exe', ['query', 'HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\EdgeUpdate\\Clients', '/s', '/f', 'WebView2'], 'Install Microsoft Edge WebView2 Evergreen Runtime (a per-user installation may require manual verification).')
105
+ } else check('Platform', false, 'Supported desktop platforms are macOS, Windows, and Linux.')
106
+ }
107
+ return errors ? 1 : 0
108
+ }
109
+
110
+ export async function frontendCommand(command, project, options = {}) {
111
+ if (command === 'doctor') return doctor(project, options)
112
+ if (!['dev', 'run', 'build', 'package', 'check'].includes(command)) throw new Error(`mun ${command} is a legacy native command; ${project.target} projects use Vite and web compiler diagnostics.`)
113
+ if (project.target === 'web' && command === 'package') throw new Error('Web applications build to dist. Use mun build, or create a separate --target desktop project to package an application.')
114
+ if ((options.sign || options.notarizeProfile) && (command !== 'package' || project.target !== 'desktop' || process.platform !== 'darwin')) throw new Error('Signing options apply to desktop mun package on macOS.')
115
+ if (options.notarizeProfile) throw new Error('Desktop notarization uses Tauri signing environment configuration (APPLE_ID/APPLE_PASSWORD/APPLE_TEAM_ID or API key). --notarize-profile remains a legacy native option; see docs/DESKTOP.md.')
116
+ const vite = await viteFor(project)
117
+ if (command === 'dev' || command === 'run') {
118
+ const server = await vite.createServer({ root: project.root, ...(project.target === 'desktop' ? { server: { host: '127.0.0.1', strictPort: true } } : {}) })
119
+ try {
120
+ await server.listen()
121
+ server.printUrls()
122
+ if (project.target === 'web') {
123
+ await new Promise(done => {
124
+ const stop = () => { process.removeListener('SIGINT', stop); process.removeListener('SIGTERM', stop); done() }
125
+ process.once('SIGINT', stop); process.once('SIGTERM', stop)
126
+ })
127
+ return 0
128
+ }
129
+ const url = server.resolvedUrls?.local[0]
130
+ if (!url || new URL(url).hostname !== '127.0.0.1') throw new Error('Desktop development requires a loopback Vite server at 127.0.0.1.')
131
+ console.log(`Mün desktop → ${url}`)
132
+ return await runChild(process.execPath, [tauriCLI(project), 'dev', '--no-watch', '--config', JSON.stringify({ build: { devUrl: url } })], { cwd: project.root })
133
+ } finally { await server.close() }
134
+ }
135
+ // Use Vite's actual resolved output directory, including custom project config.
136
+ const config = await vite.resolveConfig({ root: project.root }, 'build')
137
+ await vite.build({ root: project.root })
138
+ if (project.target === 'web' || command === 'check') return 0
139
+ const args = [tauriCLI(project), 'build', '--config', JSON.stringify({ build: { frontendDist: resolve(config.root, config.build.outDir) } })]
140
+ if (command === 'build') args.push('--no-bundle')
141
+ else if (process.platform === 'darwin') args.push('--bundles', 'app')
142
+ return runChild(process.execPath, args, { cwd: project.root, env: { ...process.env, ...(options.sign ? { APPLE_SIGNING_IDENTITY: options.sign } : {}) } })
143
+ }
package/bin/mun.mjs CHANGED
@@ -1,13 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  import { spawnSync } from 'node:child_process'
4
- import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
4
+ import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
5
5
  import { basename, dirname, relative, resolve, sep } from 'node:path'
6
6
  import { fileURLToPath } from 'node:url'
7
7
  import { updatePnpmWorkspaceOverrides } from './pnpm-workspace.mjs'
8
8
  import { installEditors } from '../editors/install.mjs'
9
9
  import { runNativeSource } from './native.mjs'
10
10
  import { projectCommand } from './workflow.mjs'
11
+ import { detectProjectTarget, frontendCommand } from './desktop.mjs'
11
12
 
12
13
  const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..')
13
14
  const packageManifest = JSON.parse(readFileSync(resolve(packageRoot, 'package.json'), 'utf8'))
@@ -110,6 +111,7 @@ const localPackagePaths = {
110
111
  '@mun-ui/astro': 'packages/astro',
111
112
  '@mun-ui/animation': 'packages/animation',
112
113
  '@mun-ui/core': 'packages/core',
114
+ '@mun-ui/desktop': 'packages/desktop',
113
115
  '@mun-ui/compiler': 'packages/compiler',
114
116
  '@mun-ui/execution': 'packages/execution',
115
117
  '@mun-ui/legacy-react': 'packages/legacy-react',
@@ -131,6 +133,7 @@ function writeTemplates(projectRoot, files) {
131
133
  mkdirSync(dirname(target), { recursive: true })
132
134
  writeFileSync(target, template(source)
133
135
  .replaceAll('__MUN_PROJECT_NAME__', projectName(projectRoot))
136
+ .replaceAll('__MUN_PROJECT_CRATE__', projectName(projectRoot).replace(/[^a-z0-9-]/gu, '-'))
134
137
  .replaceAll('__MUN_PROJECT_APP_NAME__', projectAppName(projectRoot)))
135
138
  }
136
139
  }
@@ -272,6 +275,7 @@ function configureLocalDependencies(projectRoot, localRoot, renderer = 'react',
272
275
  // project resolve it from the registry.
273
276
  const linkRootPackage = includeRootPackage || manifest.dependencies['@mun-ui/ui'] !== undefined
274
277
  if (linkRootPackage) manifest.dependencies['@mun-ui/ui'] = linkSpecifier(localRoot)
278
+ if (manifest.devDependencies['@mun-ui/ui']) manifest.devDependencies['@mun-ui/ui'] = linkSpecifier(localRoot)
275
279
  manifest.dependencies[`@mun-ui/${renderer}`] = linkSpecifier(resolve(localRoot, `packages/${renderer}`))
276
280
  manifest.devDependencies['@mun-ui/vite'] = linkSpecifier(resolve(localRoot, 'packages/vite'))
277
281
 
@@ -292,6 +296,7 @@ function configureLocalDependencies(projectRoot, localRoot, renderer = 'react',
292
296
  delete manifest.pnpm.overrides
293
297
  if (Object.keys(manifest.pnpm).length === 0) delete manifest.pnpm
294
298
  }
299
+ if (manifest.dependencies['@mun-ui/desktop']) manifest.dependencies['@mun-ui/desktop'] = linkSpecifier(resolve(localRoot, 'packages/desktop'))
295
300
  const selectedOverrideNames = [
296
301
  '@mun-ui/animation',
297
302
  '@mun-ui/core',
@@ -301,6 +306,7 @@ function configureLocalDependencies(projectRoot, localRoot, renderer = 'react',
301
306
  '@mun-ui/vite',
302
307
  `@mun-ui/${renderer}`,
303
308
  ]
309
+ if (manifest.dependencies['@mun-ui/desktop']) selectedOverrideNames.push('@mun-ui/desktop')
304
310
  if (linkRootPackage) selectedOverrideNames.push('@mun-ui/progressive-blur')
305
311
  const overridePaths = includeRootPackage
306
312
  ? localPackagePaths
@@ -322,12 +328,12 @@ function printHelp() {
322
328
  console.log(`Mün UI CLI
323
329
 
324
330
  Usage:
325
- mun new <directory> [--target native|web]
326
- mun create <directory> [--target native|web]
327
- mun init [--target native|web]
328
- mun dev [--verbose] # experimental native project
331
+ mun new <directory> [--target native|web|desktop]
332
+ mun create <directory> [--target native|web|desktop]
333
+ mun init [--target native|web|desktop]
334
+ mun dev [--verbose] # detected project target
329
335
  mun inspect [--values] [--json]
330
- mun run [input.mun] # experimental native host
336
+ mun run [input.mun] # project target (source file: legacy native)
331
337
  mun check
332
338
  mun fmt [--check]
333
339
  mun build
@@ -352,7 +358,7 @@ Initializer aliases after publishing:
352
358
  npm create mun <directory>
353
359
  pnpm create mun <directory>
354
360
 
355
- new/create/init scaffold a web application with Vite by default. Use --target native for the experimental native runtime.
361
+ new/create/init scaffold a web application with Vite by default. Use --target desktop for the Tauri system WebView, or --target native for the experimental native runtime.
356
362
  --local rewrites Mün dependencies to link: paths pointing at the source checkout.
357
363
  Local source mode always uses pnpm because it relies on pnpm workspace overrides.
358
364
  --no-install leaves dependency installation to you and prints the exact commands to continue.
@@ -375,7 +381,7 @@ function compileCommand() {
375
381
 
376
382
  function runCommand() {
377
383
  if (positionals.length > 1) throw new Error('Usage: mun run [input.mun]')
378
- return positionals.length ? runNativeSource(positionals[0]) : projectCommand('run', options)
384
+ return positionals.length ? runNativeSource(positionals[0]) : dispatchProjectCommand('run')
379
385
  }
380
386
 
381
387
  function editorCommand() {
@@ -407,7 +413,7 @@ function scaffold(projectRoot, commandName) {
407
413
  }
408
414
 
409
415
  const target = options.target ?? (options.renderer === 'native' ? 'native' : 'web')
410
- if (!['native', 'web'].includes(target)) throw new Error(`Unsupported project target: ${target}. Use native or web.`)
416
+ if (!['native', 'web', 'desktop'].includes(target)) throw new Error(`Unsupported project target: ${target}. Use native, web, or desktop.`)
411
417
  if (target === 'native') {
412
418
  if (options.renderer && options.renderer !== 'native') throw new Error('Native scaffolds do not use a Web renderer.')
413
419
  if (options.packageManager) packageManagerFor(projectRoot)
@@ -432,6 +438,12 @@ function scaffold(projectRoot, commandName) {
432
438
 
433
439
  mkdirSync(projectRoot, { recursive: true })
434
440
  writeTemplates(projectRoot, projectFiles)
441
+ if (target === 'desktop') {
442
+ const files = ['package.json', 'vite.config.ts', 'gitignore', 'src-tauri/Cargo.toml', 'src-tauri/build.rs', 'src-tauri/src/main.rs', 'src-tauri/tauri.conf.json', 'src-tauri/capabilities/main.json']
443
+ mkdirSync(resolve(projectRoot, 'src-tauri/icons'), { recursive: true })
444
+ for (const icon of ['icon.png', 'icon.icns', 'icon.ico']) cpSync(resolve(packageRoot, `templates/desktop/src-tauri/icons/${icon}`), resolve(projectRoot, `src-tauri/icons/${icon}`))
445
+ writeTemplates(projectRoot, files.map(file => [`templates/desktop/${file}`, file === 'gitignore' ? '.gitignore' : file]))
446
+ }
435
447
  if (localRoot) configureLocalDependencies(projectRoot, localRoot, 'web', { includeRootPackage: false })
436
448
  console.log(`Created Mün app in ${projectRoot}`)
437
449
  if (!options.noInstall) {
@@ -463,6 +475,11 @@ function linkProject(target) {
463
475
  return 0
464
476
  }
465
477
 
478
+ function dispatchProjectCommand(command) {
479
+ const project = detectProjectTarget(options.projectRoot ?? process.cwd())
480
+ return project && project.target !== 'native' ? frontendCommand(command, project, options) : projectCommand(command, options)
481
+ }
482
+
466
483
  function main() {
467
484
  if (command === '--version' || command === '-v') { console.log(packageManifest.version); return 0 }
468
485
  if (command === '--help' || command === '-h') { printHelp(); return 0 }
@@ -470,7 +487,7 @@ function main() {
470
487
  if (options.version) { console.log(packageManifest.version); return 0 }
471
488
  if (['check', 'fmt', 'build', 'package', 'doctor', 'dev', 'inspect'].includes(command)) {
472
489
  if (positionals.length) throw new Error(`Usage: mun ${command} [--project <directory>]`)
473
- return projectCommand(command, options)
490
+ return dispatchProjectCommand(command)
474
491
  }
475
492
  if (options.help || !command) {
476
493
  printHelp()
@@ -0,0 +1,202 @@
1
+ //! Desktop implementation of the Mün `HostServices` contract: a small,
2
+ //! path-based file-system service and a workspace service that hands paths
3
+ //! and URLs to the operating system. The runtime only sees JSON values.
4
+
5
+ use mun_runtime::HostServices;
6
+ use serde_json::{Value, json};
7
+ use std::{fs, path::PathBuf, process::Command};
8
+
9
+ #[derive(Default)]
10
+ pub struct DesktopHostServices;
11
+
12
+ fn text(arguments: &[Value], index: usize, role: &str) -> Result<String, String> {
13
+ match arguments.get(index) {
14
+ Some(Value::String(value)) => Ok(value.clone()),
15
+ Some(Value::Null) | None => Err(format!("missing {role} (argument {})", index + 1)),
16
+ Some(other) => Ok(match other {
17
+ Value::Number(number) => number.to_string(),
18
+ Value::Bool(flag) => flag.to_string(),
19
+ _ => return Err(format!("{role} must be text, got {other}")),
20
+ }),
21
+ }
22
+ }
23
+
24
+ fn home() -> Result<PathBuf, String> {
25
+ std::env::var_os("HOME")
26
+ .or_else(|| std::env::var_os("USERPROFILE"))
27
+ .map(PathBuf::from)
28
+ .ok_or_else(|| "no home directory is set".to_string())
29
+ }
30
+
31
+ /// Expand a leading `~` and resolve relative paths against the home directory
32
+ /// so a packaged app never depends on its launch directory.
33
+ fn resolve(path: &str) -> Result<PathBuf, String> {
34
+ let path = path.trim();
35
+ if path.is_empty() {
36
+ return Err("path is empty".to_string());
37
+ }
38
+ if path == "~" {
39
+ return home();
40
+ }
41
+ if let Some(rest) = path.strip_prefix("~/") {
42
+ return Ok(home()?.join(rest));
43
+ }
44
+ let path = PathBuf::from(path);
45
+ if path.is_absolute() {
46
+ Ok(path)
47
+ } else {
48
+ Ok(home()?.join(path))
49
+ }
50
+ }
51
+
52
+ fn path_string(path: &std::path::Path) -> String {
53
+ path.to_string_lossy().into_owned()
54
+ }
55
+
56
+ fn io(context: &str, path: &std::path::Path, error: std::io::Error) -> String {
57
+ format!("{context} {}: {error}", path.display())
58
+ }
59
+
60
+ fn list(path: &std::path::Path) -> Result<Value, String> {
61
+ let mut entries = Vec::new();
62
+ for entry in fs::read_dir(path).map_err(|error| io("cannot list", path, error))? {
63
+ let entry = entry.map_err(|error| io("cannot list", path, error))?;
64
+ let metadata = match entry.metadata() {
65
+ Ok(metadata) => metadata,
66
+ Err(_) => continue,
67
+ };
68
+ let name = entry.file_name().to_string_lossy().into_owned();
69
+ entries.push((
70
+ !metadata.is_dir(),
71
+ name.to_lowercase(),
72
+ json!({
73
+ "name": name,
74
+ "path": path_string(&entry.path()),
75
+ "isDirectory": metadata.is_dir(),
76
+ "size": metadata.len(),
77
+ "hidden": entry.file_name().to_string_lossy().starts_with('.'),
78
+ }),
79
+ ));
80
+ }
81
+ entries.sort_by(|a, b| (a.0, &a.1).cmp(&(b.0, &b.1)));
82
+ Ok(Value::Array(
83
+ entries.into_iter().map(|(_, _, value)| value).collect(),
84
+ ))
85
+ }
86
+
87
+ fn open_with_system(target: &str, reveal: bool) -> Result<Value, String> {
88
+ #[cfg(target_os = "macos")]
89
+ let mut command = {
90
+ let mut command = Command::new("open");
91
+ if reveal {
92
+ command.arg("-R");
93
+ }
94
+ command.arg(target);
95
+ command
96
+ };
97
+ #[cfg(target_os = "windows")]
98
+ let mut command = {
99
+ let mut command = Command::new("explorer");
100
+ if reveal {
101
+ command.arg(format!("/select,{target}"));
102
+ } else {
103
+ command.arg(target);
104
+ }
105
+ command
106
+ };
107
+ #[cfg(not(any(target_os = "macos", target_os = "windows")))]
108
+ let mut command = {
109
+ let mut command = Command::new("xdg-open");
110
+ let shown = if reveal {
111
+ std::path::Path::new(target)
112
+ .parent()
113
+ .map(path_string)
114
+ .unwrap_or_else(|| target.to_string())
115
+ } else {
116
+ target.to_string()
117
+ };
118
+ command.arg(shown);
119
+ command
120
+ };
121
+ command
122
+ .spawn()
123
+ .map(|_| Value::Null)
124
+ .map_err(|error| format!("cannot open {target}: {error}"))
125
+ }
126
+
127
+ impl HostServices for DesktopHostServices {
128
+ fn call(
129
+ &mut self,
130
+ service: &str,
131
+ operation: &str,
132
+ arguments: &[Value],
133
+ ) -> Result<Value, String> {
134
+ match (service, operation) {
135
+ ("files", "homeDirectory") => home().map(|path| Value::String(path_string(&path))),
136
+ ("files", "list") => list(&resolve(&text(arguments, 0, "a directory path")?)?),
137
+ ("files", "exists") => Ok(Value::Bool(
138
+ resolve(&text(arguments, 0, "a path")?)?.exists(),
139
+ )),
140
+ ("files", "readText") => {
141
+ let path = resolve(&text(arguments, 0, "a file path")?)?;
142
+ fs::read_to_string(&path)
143
+ .map(Value::String)
144
+ .map_err(|error| io("cannot read", &path, error))
145
+ }
146
+ ("files", "writeText") => {
147
+ let path = resolve(&text(arguments, 0, "a file path")?)?;
148
+ let contents = text(arguments, 1, "text to write")?;
149
+ if let Some(parent) = path.parent() {
150
+ fs::create_dir_all(parent)
151
+ .map_err(|error| io("cannot create", parent, error))?;
152
+ }
153
+ fs::write(&path, contents)
154
+ .map(|_| Value::Null)
155
+ .map_err(|error| io("cannot write", &path, error))
156
+ }
157
+ ("files", "createDirectory") => {
158
+ let path = resolve(&text(arguments, 0, "a directory path")?)?;
159
+ fs::create_dir_all(&path)
160
+ .map(|_| Value::Null)
161
+ .map_err(|error| io("cannot create", &path, error))
162
+ }
163
+ ("files", "remove") => {
164
+ let path = resolve(&text(arguments, 0, "a path")?)?;
165
+ let result = if path.is_dir() {
166
+ fs::remove_dir(&path)
167
+ } else {
168
+ fs::remove_file(&path)
169
+ };
170
+ result
171
+ .map(|_| Value::Null)
172
+ .map_err(|error| io("cannot remove", &path, error))
173
+ }
174
+ ("files", "parent") => {
175
+ let path = resolve(&text(arguments, 0, "a path")?)?;
176
+ Ok(Value::String(path_string(path.parent().unwrap_or(&path))))
177
+ }
178
+ ("files", "join") => {
179
+ let base = resolve(&text(arguments, 0, "a base path")?)?;
180
+ Ok(Value::String(path_string(&base.join(text(
181
+ arguments,
182
+ 1,
183
+ "a path component",
184
+ )?))))
185
+ }
186
+ ("workspace", "reveal") => {
187
+ let path = resolve(&text(arguments, 0, "a path")?)?;
188
+ open_with_system(&path_string(&path), true)
189
+ }
190
+ ("workspace", "open") => {
191
+ let target = text(arguments, 0, "a path or URL")?;
192
+ let target = if target.contains("://") {
193
+ target
194
+ } else {
195
+ path_string(&resolve(&target)?)
196
+ };
197
+ open_with_system(&target, false)
198
+ }
199
+ _ => Err(format!("unknown host service {service}.{operation}")),
200
+ }
201
+ }
202
+ }