Skip to content
Open
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: 3 additions & 0 deletions changelog.d/desktop-launch-files.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Fixed

- Let Windows and Linux apps control launch file delivery, with the default scan stopping at `--` (#2264 by @J4ck1e2000).
5 changes: 3 additions & 2 deletions docs/architecture/application.md
Original file line number Diff line number Diff line change
Expand Up @@ -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\<scheme>` 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/<scheme>` 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\<scheme>` 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/<scheme>` 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.
Expand Down
4 changes: 4 additions & 0 deletions docs/public/en/building.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 4 additions & 0 deletions docs/public/zh/building.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 的历史记录设置。
Expand Down
2 changes: 2 additions & 0 deletions internal/backend/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
2 changes: 1 addition & 1 deletion internal/backend/run_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -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})
}
2 changes: 1 addition & 1 deletion internal/backend/run_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -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})
}
45 changes: 36 additions & 9 deletions internal/engine/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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)
}
Expand Down
Loading
Loading