diff --git a/changelog.d/desktop-launch-files.md b/changelog.d/desktop-launch-files.md new file mode 100644 index 000000000..448cd9c96 --- /dev/null +++ b/changelog.d/desktop-launch-files.md @@ -0,0 +1,3 @@ +### Fixed + +- Let Windows and Linux apps control launch file delivery, with the default scan stopping at `--` (#2264 by @J4ck1e2000). diff --git a/docs/architecture/application.md b/docs/architecture/application.md index fffeb83f5..ea8bf78e4 100644 --- a/docs/architecture/application.md +++ b/docs/architecture/application.md @@ -64,8 +64,9 @@ The engine runs one graph with a tree per surface (`core.Tree`). Where the platf - `nsgo.SetMainView` sets the main view: it opens the main window at `nsgo.WindowSize` and makes it main, and a later call replaces the view in it. `nsgo.Run(Root)` is `SetMainView(Root)`. - `OnReopen` hears a click on the Dock icon and a second launch (`EventReopen`); without a handler the main window shows and takes the focus, on Windows and Linux the app's one window, restored if minimized. Windows' named mutex and pipe and Linux's Unix socket, beside its lock in `$XDG_RUNTIME_DIR` (in a Flatpak, `$XDG_RUNTIME_DIR/app/$FLATPAK_ID`, which the app's instances share) or else in a private directory of the user's in the temporary one, hand a second launch to the running process before it creates a second engine, which dispatches `OnReopen` and its file arguments to `OnOpenFiles` and its links to `OnOpenLinks`; on Windows the second launch lets the running process take the foreground before it hands over. - `nsgo.InstanceKey("profile")` scopes that Windows or Linux lock and handoff channel to the app ID plus key: launches with the same key still hand over, while a different key starts its own engine. An empty key keeps the default one instance per app ID; macOS and other targets ignore the option. -- `OnOpenFiles` hears files the system opens with the app (`EventOpenFiles`): on macOS `application:openURLs:` for the types `file_types` registers, on Windows and Linux the files named on the command line, and on iOS the file URLs in scene connection options or `scene:openURLContexts:`. iOS coordinates reads on a serial worker, balances each security scope and delivers app-owned temporary copies with their original names. Its path-only callback has no scope-release contract, so imports follow the document picker's copy model rather than retaining provider grants indefinitely; links remain `EventOpenLinks`. Launch files can arrive before the first handler; the core keeps them until one registers and posts them to it. -- `OnOpenLinks` hears links of the app's own URL schemes (`EventOpenLinks`). `url_schemes` registers them as the macOS package's `CFBundleURLTypes`, under `HKCU\Software\Classes\` with `URL Protocol` in the NSIS installer, which records them with its uninstall entry to remove them, as a `windows.protocol` in MSIX, and as `x-scheme-handler/` with `%U` in the Linux desktop entry. On macOS Launch Services hands their links to the running app, launching it first when needed, and `application:openURLs:` sends every URL that isn't a file's as a link. Windows and Linux start the app with the link, after `--` on Windows so a link that breaks out of its quotes reaches no flag, and there a launch that names a link takes no files, which such a link could otherwise name: `engine.LaunchLinks` takes every argument that is an absolute URL of a scheme longer than a drive letter and not `file`, whose URLs `LaunchFiles` takes as files, and the one-instance claim hands the running app `{"files": [...], "links": [...]}`. A launch with links alone brings its window to the front if it shows, as activating an app does on macOS, rather than dispatching `EventReopen`. The app filters links by scheme, so a development build, which registers none, takes those it is started with; a restart drops them, as they asked for something once. The core keeps the links that launched the app until a handler registers, as it keeps files. On iOS the app's `CFBundleURLTypes` register its schemes, and the scene delegate sends the URLs it opens. On Android each scheme adds a browsable `ACTION_VIEW` intent filter to the launcher activity, which uses `singleTask` to reuse the running app from another task. `onCreate` and `onNewIntent` deliver matching links, with arrivals before the first mount held by the native view. +- `OnOpenFiles` hears files the system opens with the app (`EventOpenFiles`): on macOS `application:openURLs:` for the types `file_types` registers, on Windows and Linux command-line file arguments, and on iOS the file URLs in scene connection options or `scene:openURLContexts:`. iOS coordinates reads on a serial worker, balances each security scope and delivers app-owned temporary copies with their original names. Its path-only callback has no scope-release contract, so imports follow the document picker's copy model rather than retaining provider grants indefinitely; links remain `EventOpenLinks`. Launch files can arrive before the first handler; the core keeps them until one registers and posts them to it. +- `engine.Launched` builds the Windows or Linux launch payload once, after the backend strips engine flags, for either initial delivery or single-instance handoff. By default it resolves existing regular files and local file URLs before the first `--` to absolute paths, without interpreting the app's CLI. `nsgo.LaunchFiles(parse)` replaces that scan with the app's parser, called in the launching process with only that read-only prefix (without the executable); the app returns absolute filesystem paths used as-is. `nsgo.LaunchFiles(nil)` disables command-line file delivery. A link launch on Windows bypasses file parsing even with this option. +- `OnOpenLinks` hears links of the app's own URL schemes (`EventOpenLinks`). `url_schemes` registers them as the macOS package's `CFBundleURLTypes`, under `HKCU\Software\Classes\` with `URL Protocol` in the NSIS installer, which records them with its uninstall entry to remove them, as a `windows.protocol` in MSIX, and as `x-scheme-handler/` with `%U` in the Linux desktop entry. On macOS Launch Services hands their links to the running app, launching it first when needed, and `application:openURLs:` sends every URL that isn't a file's as a link. On Windows and Linux the engine checks the whole command line, including after `--`, for absolute URLs with a scheme longer than a drive letter and other than `file` that do not name an existing path. The Windows registration puts the link after `--` so a link that breaks out of its quotes reaches no engine flag; a launch with a link there takes no files. The one-instance claim hands the running app `{"files": [...], "links": [...]}` (plus a Windows Jump List task label if present). A launch with links alone brings its window to the front if it shows, as activating an app does on macOS, rather than dispatching `EventReopen`. The app filters links by scheme, so a development build, which registers none, takes those it is started with; a restart drops them, as they asked for something once. The core keeps the links that launched the app until a handler registers, as it keeps files. On iOS the app's `CFBundleURLTypes` register its schemes, and the scene delegate sends the URLs it opens. On Android each scheme adds a browsable `ACTION_VIEW` intent filter to the launcher activity, which uses `singleTask` to reuse the running app from another task. `onCreate` and `onNewIntent` deliver matching links, with arrivals before the first mount held by the native view. - Android's `app_links` hosts add separate HTTPS `autoVerify` filters to the launcher, which keeps `singleTask` for warm delivery. The app's server owns Digital Asset Links verification; the tool declares the hosts, and embedded hosts declare their own filters. Once an accepted link reaches `NsgoView.openLink`, its environment latches the URL before rendering or delivering `OnOpenLinks`; the optional environment tail follows the display so old runtimes remain readable. Authentication callback consumers must run before this ordinary-link path. A whole-page web surface reads `location.href` into the same `OpenedURL` field before rendering, then refreshes it after hash edits, traversals and its own history writes. Embedded surfaces leave the containing page's address out. This is NSGo's `mobile.OpenedURL` environment API; NSH exposes the page's address through its URL-scheme state instead. - Packages register `file_types` on macOS, iOS, Windows (the setup and MSIX) and Linux. iOS reuses the exported/imported type declarations and content-type matching, omitting macOS-only icon keys; App Clips and tvOS declare none. The Windows setup adds per-app ProgIDs and extension Open With values under `HKCU\Software\Classes`, retaining the user's defaults; upgrade and uninstall remove only entries whose commands still match the installation's records and notify the Shell. Linux desktop entries pass `%F`, name their MIME types, and deb/Arch install owned custom MIME definitions with cache hooks; Flatpak exports them, and AppImage carries them for desktop integration. - `nsgo.HideDock` starts the app as an accessory app, before AppKit's loop runs, so its icon never shows in the Dock; `SetDockVisible` changes the activation policy later, as apps do while their settings show. macOS runs one instance of a bundle and reopens it. diff --git a/docs/public/en/building.md b/docs/public/en/building.md index 9c8a02f55..3b4bb5f9f 100644 --- a/docs/public/en/building.md +++ b/docs/public/en/building.md @@ -521,6 +521,10 @@ The app hears the files with `desktop.OnOpenFiles`, including a later Windows or desktop.OnOpenFiles(cx, func(paths []string) { open(paths[0]) }) ``` +On Windows and Linux, both first and later launches take arguments naming existing regular files (including local `file:` URLs) before the first `--`, after NSGo removes its flags. The handler receives absolute paths. The default scan does not interpret subcommands or flags, so `app -- editor scene.flow` keeps both arguments out of file delivery. + +For a CLI that needs to distinguish documents from subcommands or flag values, pass `nsgo.LaunchFiles(parse)` to `nsgo.Run`. The parser gets the read-only arguments before `--`, without the executable or NSGo's flags, and returns absolute filesystem paths, which NSGo uses as returned. Return `nil` to open no files for that launch, or pass `nsgo.LaunchFiles(nil)` to disable command-line file opens entirely, including Open With. Links still reach `OnOpenLinks` after `--`; on Windows a link launch never opens files or calls the parser. + On iOS, regular documents are imported into app-owned temporary files with their original names. File-provider reads are coordinated off the UI thread, and their security scopes end before the handler runs. Move an import into `cx.DataDir()` to keep it; edits affect the copy. iOS uses the app's document icon; `icon` applies on macOS. App Clips and tvOS packages register no document types. File opens stay separate from `OnOpenLinks`. `desktop.AddRecentFile(cx, path)` records a document the user opened: in the Dock menu and File › Open Recent on macOS, the Jump List's Recent category on Windows, and the desktop's recently used files on Linux. A choice reaches the same handler. `desktop.ClearRecentFiles` forgets the app's registrations, keeping other apps' history of shared files on Linux; Linux also respects GTK's history setting. diff --git a/docs/public/zh/building.md b/docs/public/zh/building.md index 5d4155d65..a377fc2a9 100644 --- a/docs/public/zh/building.md +++ b/docs/public/zh/building.md @@ -430,6 +430,10 @@ Windows 安装程序把应用加进“打开方式”,不替换用户的默认 desktop.OnOpenFiles(cx, func(paths []string) { open(paths[0]) }) ``` +在 Windows 和 Linux 上,无论是首次启动还是应用运行时再次启动,NSGo 都会先移除自己的标志,再扫描第一个 `--` 之前的参数,只把指向现有普通文件的路径(包括本地 `file:` URL)以绝对路径交给处理函数。默认扫描不解析应用的子命令或标志,所以 `app -- editor scene.flow` 中的两个参数都不会被当作文件打开。 + +如果需要区分文档、子命令和标志的值,可以向 `nsgo.Run` 传入 `nsgo.LaunchFiles(parse)`。解析函数收到第一个 `--` 之前的只读参数,不含可执行文件名和 NSGo 自己的标志;它应返回绝对文件路径,NSGo 会原样交付。返回 `nil` 可让本次启动不打开文件;传入 `nsgo.LaunchFiles(nil)` 可完全禁用命令行文件打开,包括系统的“打开方式”。`--` 之后的链接仍会交给 `OnOpenLinks`;在 Windows 上,由链接触发的启动不会打开文件,也不会调用解析函数。 + iOS 把普通文档导入为应用自有的临时文件,保留原来的文件名。读取文件提供程序时会在 UI 线程之外协调访问,并在处理函数执行前结束安全作用域。要长期保留,请把导入文件移到 `cx.DataDir()`;编辑只影响副本。iOS 使用应用的文档图标,`icon` 只用于 macOS。App Clip 和 tvOS 包不登记文档类型。文件不会混入 `OnOpenLinks`。 `desktop.AddRecentFile(cx, path)` 记录用户打开过的文档:macOS 上列进程序坞菜单和“文件 › 打开最近使用”,Windows 上列进跳转列表的“最近”,Linux 上记录到桌面的最近使用文件。选中后同样交给这个处理函数。`desktop.ClearRecentFiles` 清除应用自己的登记,Linux 上保留其他应用对同一文件的记录,也遵循 GTK 的历史记录设置。 diff --git a/internal/backend/backend.go b/internal/backend/backend.go index 4325fa907..815a099c3 100644 --- a/internal/backend/backend.go +++ b/internal/backend/backend.go @@ -40,6 +40,8 @@ type Options struct { Simulate core.OS // InstanceKey scopes the Windows and Linux instance lock; empty keeps one per app ID. InstanceKey string + // LaunchFiles replaces the Windows and Linux command-line file scan; nil keeps the default. + LaunchFiles func(args []string) []string // HideDock starts the app out of the Dock (macOS). HideDock bool // Transparent, NoShadow and SkipTaskbar are the main window's (core.WindowOptions). diff --git a/internal/backend/run_linux.go b/internal/backend/run_linux.go index 6de7a8366..5a3e62cf9 100644 --- a/internal/backend/run_linux.go +++ b/internal/backend/run_linux.go @@ -16,5 +16,5 @@ func run(root engine.App, app func(*core.Scope), o Options) { linux.Run(rootOf(root, app), linux.Options{Title: name, Name: core.App().Name, Width: o.Width, Height: o.Height, Hidden: app != nil, MainHidden: o.Hidden, ID: id, Components: o.Components, Constraints: o.Constraints, Fonts: o.Fonts, Appearance: o.Appearance, Perf: o.Monitor, Transparent: o.Transparent, NoShadow: o.NoShadow, SkipTaskbar: o.SkipTaskbar, - Updates: updates, LaunchedAtLogin: launch.launchedAtLogin, InstanceKey: o.InstanceKey}) + Updates: updates, LaunchedAtLogin: launch.launchedAtLogin, InstanceKey: o.InstanceKey, LaunchFiles: o.LaunchFiles}) } diff --git a/internal/backend/run_windows.go b/internal/backend/run_windows.go index 82425ba78..0d4ec17d1 100644 --- a/internal/backend/run_windows.go +++ b/internal/backend/run_windows.go @@ -13,5 +13,5 @@ func run(root engine.App, app func(*core.Scope), o Options) { windows.Run(rootOf(root, app), windows.Options{Title: name, Width: o.Width, Height: o.Height, Frame: o.Frame, Hidden: app != nil, MainHidden: o.Hidden, ID: id, Components: o.Components, Material: o.Material, Constraints: o.Constraints, Fonts: o.Fonts, Appearance: o.Appearance, Perf: o.Monitor, Transparent: o.Transparent, NoShadow: o.NoShadow, SkipTaskbar: o.SkipTaskbar, - Updates: updateConfig(), RegisterToast: launch.registerToast, UnregisterToast: launch.unregisterToast, DockTask: launch.dockTask, LaunchedAtLogin: launch.launchedAtLogin, InstanceKey: o.InstanceKey}) + Updates: updateConfig(), RegisterToast: launch.registerToast, UnregisterToast: launch.unregisterToast, DockTask: launch.dockTask, LaunchedAtLogin: launch.launchedAtLogin, InstanceKey: o.InstanceKey, LaunchFiles: o.LaunchFiles}) } diff --git a/internal/engine/engine.go b/internal/engine/engine.go index 9e22f6fb4..d2a3f3132 100644 --- a/internal/engine/engine.go +++ b/internal/engine/engine.go @@ -988,16 +988,39 @@ type Launch struct { Links []string `json:"links,omitempty"` } -// Launched returns what this process's command line asks the app to open. -func Launched() Launch { return Launch{Files: LaunchFiles(), Links: LaunchLinks()} } - -// LaunchFiles returns the files the command line names, as absolute paths, also those named by file URLs, as a desktop entry's %U passes them: what Windows and Linux launch an app with to open, which their backends send it as EventOpenFiles. Other arguments are left to the app. On Windows a launch that names a link opens no files: the shell puts a link into the registered command line as it is, inside quotes it may close, so a link could otherwise name local files for the app to open. -func LaunchFiles() []string { - if runtime.GOOS == "windows" && len(LaunchLinks()) > 0 { - return nil +// Launched returns what this process's command line asks the app to open, +// after the backend has removed engine flags. A nil parseFiles uses the +// default file scan. +func Launched(parseFiles func([]string) []string) Launch { + return parseLaunch(os.Args[1:], parseFiles, runtime.GOOS == "windows") +} + +func parseLaunch(args []string, parseFiles func([]string) []string, preferLinks bool) Launch { + launch := Launch{Links: launchLinks(args)} + // The Windows shell inserts a link into a quoted argument. If the + // link breaks out of the quotes, it still cannot name files to open. + if preferLinks && len(launch.Links) > 0 { + return launch + } + if i := slices.Index(args, "--"); i >= 0 { + args = args[:i] + } + if len(args) == 0 { + return launch + } + if parseFiles != nil { + launch.Files = parseFiles(args[:len(args):len(args)]) + } else { + launch.Files = launchFiles(args) } + return launch +} + +// launchFiles takes existing regular files (including local file URLs, as a +// Linux desktop entry's %U passes them) and returns their absolute paths. +func launchFiles(args []string) []string { var paths []string - for _, arg := range os.Args[1:] { + for _, arg := range args { if path, ok := fileURLPath(arg); ok { arg = path } @@ -1013,8 +1036,12 @@ func LaunchFiles() []string { // LaunchLinks returns the links the command line names (IsLink): what Windows and Linux launch an app with to open a link of a URL scheme its package registers, which their backends send it as EventOpenLinks. The app filters them by scheme itself, so a build that registers none, as a development one, takes those it is started with too. func LaunchLinks() []string { + return launchLinks(os.Args[1:]) +} + +func launchLinks(args []string) []string { var links []string - for _, arg := range os.Args[1:] { + for _, arg := range args { if IsLink(arg) { links = append(links, arg) } diff --git a/internal/engine/launch_test.go b/internal/engine/launch_test.go index 98cf323ba..77adf255d 100644 --- a/internal/engine/launch_test.go +++ b/internal/engine/launch_test.go @@ -4,12 +4,10 @@ import ( "net/url" "os" "path/filepath" - "runtime" "slices" "testing" ) -// TestLaunchSortsFilesFromLinks takes a desktop launch's arguments apart: files, also as the file URLs a desktop entry's %U passes, and links of any scheme but file's, leaving drive letters, flags and plain words to the app. On Windows a launch with a link opens no files. func TestLaunchSortsFilesFromLinks(t *testing.T) { dir := t.TempDir() doc, spaced := filepath.Join(dir, "notes.txt"), filepath.Join(dir, "日本 語.flow") @@ -18,30 +16,100 @@ func TestLaunchSortsFilesFromLinks(t *testing.T) { t.Fatal(err) } } - fileURL := (&url.URL{Scheme: "file", Path: filepath.ToSlash(spaced)}).String() + urlPath := filepath.ToSlash(spaced) if filepath.VolumeName(spaced) != "" { - fileURL = (&url.URL{Scheme: "file", Path: "/" + filepath.ToSlash(spaced)}).String() + urlPath = "/" + urlPath } - saved := os.Args - t.Cleanup(func() { os.Args = saved }) + fileURL := (&url.URL{Scheme: "file", Path: urlPath}).String() + otherArgs := []string{`C:\Users\a.txt`, "file://otherhost/a.txt", "words", dir} + // A Windows file association passes a path, and a Linux desktop entry + // can pass a path or a file URL, without a separator. + for _, preferLinks := range []bool{false, true} { + got := parseLaunch(append([]string{doc, fileURL}, otherArgs...), nil, preferLinks) + if want := []string{doc, spaced}; !slices.Equal(got.Files, want) || len(got.Links) != 0 { + t.Errorf("document launch = %+v, want files %q and no links", got, want) + } + } + links := []string{"umapp://connect?endpoint=https%3A%2F%2Fexample.com&key=k", "Umapp:settings", "https://example.com/a"} - os.Args = []string{"app", "-v", "--", doc, fileURL, links[0], links[1], links[2], `C:\Users\a.txt`, "file://otherhost/a.txt", "words", dir} - wantFiles := []string{doc, spaced} - if runtime.GOOS == "windows" { - // A link may have closed the quotes Windows put it in and named the files after it. - wantFiles = nil + args := append([]string{links[0], doc, "--", spaced, fileURL, links[1], "--", links[2]}, otherArgs...) + if got := parseLaunch(args, nil, false); !slices.Equal(got.Files, []string{doc}) || !slices.Equal(got.Links, links) { + t.Errorf("launch with separator = %+v, want only %q and links %q", got, doc, links) } - if got := LaunchFiles(); !slices.Equal(got, wantFiles) { - t.Errorf("files %q, want %q", got, wantFiles) + if got := parseLaunch([]string{"--", doc, fileURL}, nil, true); len(got.Files) != 0 || len(got.Links) != 0 { + t.Errorf("launch with only arguments after -- = %+v, want no files or links", got) } + + // LaunchLinks is also used independently of file activation. + saved := os.Args + t.Cleanup(func() { os.Args = saved }) + os.Args = append([]string{"app"}, args...) if got := LaunchLinks(); !slices.Equal(got, links) { t.Errorf("links %q, want %q", got, links) } - if got := Launched(); !slices.Equal(got.Files, wantFiles) || !slices.Equal(got.Links, links) { - t.Errorf("launched %+v", got) +} + +func TestLaunchFilesCustomParser(t *testing.T) { + t.Chdir(t.TempDir()) + for _, name := range []string{"editor", "settings.yaml", "scene.flow"} { + if err := os.WriteFile(name, nil, 0o600); err != nil { + t.Fatal(err) + } + } + args := []string{"editor", "-config", "settings.yaml", "scene.flow", "--", "editor"} + absolute := func(name string) string { + t.Helper() + path, err := filepath.Abs(name) + if err != nil { + t.Fatal(err) + } + return path + } + doc := absolute("scene.flow") + if got, want := parseLaunch(args, nil, false).Files, []string{absolute("editor"), absolute("settings.yaml"), doc}; !slices.Equal(got, want) { + t.Errorf("default files = %q, want %q", got, want) + } + calls := 0 + got := parseLaunch(args, func(args []string) []string { + calls++ + if want := []string{"editor", "-config", "settings.yaml", "scene.flow"}; !slices.Equal(args, want) { + t.Fatalf("parser arguments = %q, want %q", args, want) + } + // The app's CLI owns the subcommand and the flag with its value. + return []string{absolute(args[3])} + }, false) + if calls != 1 || !slices.Equal(got.Files, []string{doc}) { + t.Errorf("custom launch = %+v with %d parser calls, want %q with one call", got, calls, doc) + } + got = parseLaunch(args, func([]string) []string { return nil }, false) + if len(got.Files) != 0 || len(got.Links) != 0 { + t.Errorf("disabled launch = %+v, want no files or links", got) + } + got = parseLaunch([]string{"--", "editor"}, func(args []string) []string { + t.Fatalf("no file arguments before --, but called parser with %q", args) + return nil + }, false) + if len(got.Files) != 0 { + t.Errorf("separated launch = %+v, want no files", got) + } +} + +func TestLaunchWindowsLinkPrecedence(t *testing.T) { + doc := filepath.Join(t.TempDir(), "notes.txt") + if err := os.WriteFile(doc, nil, 0o600); err != nil { + t.Fatal(err) } - os.Args = []string{"app", "-v", "--", doc, fileURL, `C:\Users\a.txt`, "file://otherhost/a.txt", "words", dir} - if got, want := LaunchFiles(), []string{doc, spaced}; !slices.Equal(got, want) { - t.Errorf("files without links %q, want %q", got, want) + link := "umapp://settings" + args := []string{doc, "--", link, doc} + for _, parse := range []func([]string) []string{ + nil, + func(args []string) []string { + t.Fatalf("Windows link launch called the file parser with %q", args) + return nil + }, + } { + if got := parseLaunch(args, parse, true); len(got.Files) != 0 || !slices.Equal(got.Links, []string{link}) { + t.Errorf("Windows link launch = %+v, want only link %q", got, link) + } } } diff --git a/internal/platform/linux/linux.go b/internal/platform/linux/linux.go index 76f3a6fb2..dc361fbc0 100644 --- a/internal/platform/linux/linux.go +++ b/internal/platform/linux/linux.go @@ -64,6 +64,8 @@ type Options struct { Name string // InstanceKey scopes the single-instance lock; empty keeps one lock per ID. InstanceKey string + // LaunchFiles replaces the command-line file scan (nsgo.LaunchFiles). + LaunchFiles func(args []string) []string // Components are the native components Native elements name. Components driver.NativeComponents // Fonts are font files under the app's resources, registered before @@ -415,11 +417,12 @@ func InstalledBy() string { // Run opens a window showing app and runs GTK's main loop. Call it from // main; it returns when the window closes. func Run(app engine.App, opts Options) { + args := engine.Launched(opts.LaunchFiles) // One copy runs per app ID; an app without one, as a test's window, runs as many as it is started. var instance *instance if opts.ID != "" && opts.test == nil { var alreadyRunning bool - if instance, alreadyRunning = claimInstance(opts.ID, opts.InstanceKey, engine.Launched()); alreadyRunning { + if instance, alreadyRunning = claimInstance(opts.ID, opts.InstanceKey, args); alreadyRunning { return } defer instance.close() @@ -435,11 +438,11 @@ func Run(app engine.App, opts Options) { instance.setDelivery(func(args engine.Launch) { w.post(func() { w.launched(args) }) }) } // The core keeps them until the app's first handlers register. - if paths := engine.LaunchFiles(); len(paths) > 0 { - w.engine.Dispatch(driver.Event{Kind: driver.EventOpenFiles, Data: paths}) + if len(args.Files) > 0 { + w.engine.Dispatch(driver.Event{Kind: driver.EventOpenFiles, Data: args.Files}) } - if links := engine.LaunchLinks(); len(links) > 0 { - w.engine.Dispatch(driver.Event{Kind: driver.EventOpenLinks, Data: links}) + if len(args.Links) > 0 { + w.engine.Dispatch(driver.Event{Kind: driver.EventOpenLinks, Data: args.Links}) } registerLiveWindow(w) defer w.stop() diff --git a/internal/platform/windows/instance.go b/internal/platform/windows/instance.go index 14b8801b9..5f27fde2e 100644 --- a/internal/platform/windows/instance.go +++ b/internal/platform/windows/instance.go @@ -62,11 +62,6 @@ type launch struct { Task string `json:"task,omitempty"` } -// launchArguments is what this launch hands the running app. -func launchArguments(task string) launch { - return launch{Launch: engine.Launched(), Task: task} -} - func claimInstance(id, key string, args launch) (*instance, bool) { mutexName, pipeName := instanceNames(id, key) h, _, err := createMutexW.Call(0, 1, uintptr(unsafe.Pointer(mutexName))) diff --git a/internal/platform/windows/windows.go b/internal/platform/windows/windows.go index 172684d8c..a42a6dc6e 100644 --- a/internal/platform/windows/windows.go +++ b/internal/platform/windows/windows.go @@ -71,6 +71,8 @@ type Options struct { ID string // InstanceKey scopes the single-instance lock; empty keeps one lock per ID. InstanceKey string + // LaunchFiles replaces the command-line file scan (nsgo.LaunchFiles). + LaunchFiles func(args []string) []string // Components are the native components Native elements name. Components driver.NativeComponents // Material is the material behind the window's content, where the app @@ -649,7 +651,7 @@ func wide(s string) *uint16 { return p } -// launched hands the running app what a second launch asked of it (launchArguments): a Jump List task chooses its item, a launch to open links alone brings the app's window to the front, as opening a link does on macOS, any other launch reopens the app, and the files and links it names open. +// launched hands the running app what a second launch asked of it: a Jump List task chooses its item, a launch to open links alone brings the app's window to the front, as opening a link does on macOS, any other launch reopens the app, and the files and links it names open. func (w *window) launched(args launch) { switch { case args.Task != "": @@ -689,11 +691,15 @@ func Run(app engine.App, opts Options) { unregisterToast(opts.ID) return } + var args launch + if opts.test == nil { + args = launch{Launch: engine.Launched(opts.LaunchFiles), Task: opts.DockTask} + } // One copy runs per app ID; an app without one, as a test's window, runs as many as it is started. var single *instance if opts.ID != "" && opts.test == nil { var alreadyRunning bool - if single, alreadyRunning = claimInstance(opts.ID, opts.InstanceKey, launchArguments(opts.DockTask)); alreadyRunning { + if single, alreadyRunning = claimInstance(opts.ID, opts.InstanceKey, args); alreadyRunning { return } defer single.close() @@ -799,16 +805,16 @@ func Run(app engine.App, opts Options) { w.showFirst.arm(opts.Hidden) if opts.test != nil { opts.test.ready <- w - } else if opts.DockTask != "" { + } else if args.Task != "" { // The core keeps it until the app sets its menu. - w.engine.Dispatch(driver.Event{Kind: driver.EventDockMenu, Text: opts.DockTask}) + w.engine.Dispatch(driver.Event{Kind: driver.EventDockMenu, Text: args.Task}) } else { // The core keeps them until the app's first handlers register. - if paths := engine.LaunchFiles(); len(paths) > 0 { - w.engine.Dispatch(driver.Event{Kind: driver.EventOpenFiles, Data: paths}) + if len(args.Files) > 0 { + w.engine.Dispatch(driver.Event{Kind: driver.EventOpenFiles, Data: args.Files}) } - if links := engine.LaunchLinks(); len(links) > 0 { - w.engine.Dispatch(driver.Event{Kind: driver.EventOpenLinks, Data: links}) + if len(args.Links) > 0 { + w.engine.Dispatch(driver.Event{Kind: driver.EventOpenLinks, Data: args.Links}) } } if opts.test == nil { diff --git a/nsgo.go b/nsgo.go index bad86f5c7..d989874f3 100644 --- a/nsgo.go +++ b/nsgo.go @@ -105,6 +105,30 @@ func InstanceKey(key string) Option { return func(o *options) { o.platform.InstanceKey = key } } +// LaunchFiles replaces Run's command-line file scan on Windows and Linux. +// By default the scan takes existing regular files (including local file +// URLs) before the first "--" and delivers their absolute paths to +// desktop.OnOpenFiles. It does not interpret the app's flags or subcommands. +// +// When there are arguments to classify, parse gets the read-only arguments +// after the engine removes its flags, excluding the executable name, "--" +// and everything after it. +// Return the absolute filesystem paths to deliver, not URLs; they are used +// as returned. +// A nil parser disables command-line file delivery, and a parser returning +// nil opens no files for that launch. The launching process makes this +// choice even when it hands the result to a running instance. +// +// Links are still read on both sides of "--". On Windows, a launch with +// a link opens no files and never calls parse. Other platforms ignore this +// option. +func LaunchFiles(parse func(args []string) []string) Option { + if parse == nil { + parse = func([]string) []string { return nil } + } + return func(o *options) { o.platform.LaunchFiles = parse } +} + // WindowFrame opens the main window with frame f, as desktop.Frame // reported it, instead of centered at WindowSize: an app restores its // window with it. A window no screen would show, as on a screen that diff --git a/skills/nsgo/SKILL.md b/skills/nsgo/SKILL.md index aa8a52926..2f0a7d6bf 100644 --- a/skills/nsgo/SKILL.md +++ b/skills/nsgo/SKILL.md @@ -116,7 +116,7 @@ func main() { nsgo.Run(Root) } - Use `cx.SetImageCacheLimit(bytes)` to bound retained image bytes (32 MiB by default); `cx.KeepImage` pins an atlas until release or scope disposal. This does not cap decoded pixels or live draws ([images](https://nsgo.dev/docs/images.md)). - Set `HitTestAlpha` (TSX `hitTestAlpha`) above 0 for transparent pixels to pass the pointer through painted windows. Images support it on macOS and Windows. Untransformed videos without controls support it on macOS. [Services](https://nsgo.dev/docs/services.md) - For an iOS App Clip handoff, configure `app_clip` and explicit `apple.app_group`: clip and full app share `cx.DataDir()` and `cx.Storage()`, with separate caches. Both signing profiles must grant the group. Enabling it does not migrate old sandbox data; an explicit host data directory still wins. [App Clips](https://nsgo.dev/docs/building.md#app-clips) -- Declare `file_types` for documents opened on macOS, iOS, Windows and Linux and handle them with `cx.OnOpenFiles`. iOS delivers temporary imported copies; move them to `cx.DataDir()` to retain them. App Clips and tvOS register none. [File types](https://nsgo.dev/docs/building.md#file-types) +- Declare `file_types` for documents opened on macOS, iOS, Windows and Linux and handle them with `cx.OnOpenFiles`. Windows and Linux scan existing regular files and local file URLs only before `--`, including on a second launch. Use `nsgo.LaunchFiles(parse)` to apply your CLI's rules and return absolute paths, or `nsgo.LaunchFiles(nil)` to opt out. iOS delivers temporary imported copies; move them to `cx.DataDir()` to retain them. App Clips and tvOS register none. [File types](https://nsgo.dev/docs/building.md#file-types) - Gate `desktop.QuickLook` on `desktop.CanQuickLook`: macOS uses its panel, Windows registered file preview handlers, and Linux an available GNOME Sushi service. A true return means the request was sent; formats depend on the previewer. Linux arrow selection and owner-close require Sushi ownership signals and X11. [Desktop services](https://nsgo.dev/docs/services.md) - Use `cx.OpenPermissionSettings` for sensor permissions: macOS opens Location Services or Motion & Fitness; iOS and Android open the app's settings. Opening settings does not grant access ([permissions](https://nsgo.dev/docs/permissions.md)). - Use `cx.ScanCode` on macOS, iOS and Android. Gate the action on `cx.Env().CanScanCode()`, and give Apple builds an `NSCameraUsageDescription` in `apple.info` or Android builds `CAMERA` in `android.permissions`. [Photos and files](https://nsgo.dev/docs/services.md#photos-and-files)