diff --git a/base/terminal/internal/library/lib/ioscatalyst-amd64/libghostty-vt.dylib b/base/terminal/internal/library/lib/ioscatalyst-amd64/libghostty-vt.dylib new file mode 100644 index 0000000000..ac05fef7d8 Binary files /dev/null and b/base/terminal/internal/library/lib/ioscatalyst-amd64/libghostty-vt.dylib differ diff --git a/base/terminal/internal/library/lib/ioscatalyst-arm64/libghostty-vt.dylib b/base/terminal/internal/library/lib/ioscatalyst-arm64/libghostty-vt.dylib new file mode 100644 index 0000000000..8e2a5286df Binary files /dev/null and b/base/terminal/internal/library/lib/ioscatalyst-arm64/libghostty-vt.dylib differ diff --git a/base/terminal/internal/library/lib/iossimulator-amd64/libghostty-vt.dylib b/base/terminal/internal/library/lib/iossimulator-amd64/libghostty-vt.dylib new file mode 100644 index 0000000000..1dc2a8d347 Binary files /dev/null and b/base/terminal/internal/library/lib/iossimulator-amd64/libghostty-vt.dylib differ diff --git a/base/terminal/internal/library/library.go b/base/terminal/internal/library/library.go index 148e3ebce6..14f1bee5ce 100644 --- a/base/terminal/internal/library/library.go +++ b/base/terminal/internal/library/library.go @@ -3,10 +3,7 @@ // desktops the build for the platform the package embeds, written once // into the user's cache. // -// The builds in lib/ come from Ghostty's sources at the commit the -// terminal binds, built by `go run ./tools/libghostty`. The nsgo tool -// signs them into iOS apps as GhosttyVT.framework and into macOS apps' -// Frameworks. +// The builds in lib/ come from Ghostty's sources at the commit the terminal binds, built by `go run ./tools/libghostty`. The nsgo tool signs them into iOS apps as GhosttyVT.framework and into macOS apps' Frameworks, stages it beside Windows and Linux executables, and supplies an iOS host's companion GhosttyVT.xcframework. package library import ( @@ -31,15 +28,8 @@ func Find() (string, error) { return p, nil } if exe, err := os.Executable(); err == nil { - dir := filepath.Dir(exe) - paths := []string{filepath.Join(dir, "Frameworks", "GhosttyVT.framework", "GhosttyVT")} - if name != "" { - paths = append(paths, filepath.Join(dir, "..", "Frameworks", name), filepath.Join(dir, name)) - } - for _, p := range paths { - if _, err := os.Stat(p); err == nil { - return p, nil - } + if path := findInApp(exe); path != "" { + return path, nil } } if embedded == nil { @@ -87,3 +77,21 @@ func extract() (string, error) { } return path, nil } + +// findInApp searches the host bundle as well as a standalone executable's directory. Catalyst uses a macOS bundle layout even though its terminal takes the iOS path. +func findInApp(executable string) string { + dir := filepath.Dir(executable) + paths := []string{ + filepath.Join(dir, "Frameworks", "GhosttyVT.framework", "GhosttyVT"), + filepath.Join(dir, "..", "Frameworks", "GhosttyVT.framework", "GhosttyVT"), + } + if name != "" { + paths = append(paths, filepath.Join(dir, "..", "Frameworks", name), filepath.Join(dir, name)) + } + for _, path := range paths { + if info, err := os.Stat(path); err == nil && info.Mode().IsRegular() { + return path + } + } + return "" +} diff --git a/base/terminal/internal/library/library_test.go b/base/terminal/internal/library/library_test.go new file mode 100644 index 0000000000..cc1516cf0f --- /dev/null +++ b/base/terminal/internal/library/library_test.go @@ -0,0 +1,30 @@ +//go:build !js + +package library + +import ( + "os" + "path/filepath" + "testing" +) + +func TestFindInEmbeddedHostBundle(t *testing.T) { + for _, layout := range []struct{ name, executable, library string }{ + {"ios", "Host.app/Host", "Host.app/Frameworks/GhosttyVT.framework/GhosttyVT"}, + {"catalyst", "Host.app/Contents/MacOS/Host", "Host.app/Contents/Frameworks/GhosttyVT.framework/GhosttyVT"}, + } { + t.Run(layout.name, func(t *testing.T) { + root := t.TempDir() + library := filepath.Join(root, layout.library) + if err := os.MkdirAll(filepath.Dir(library), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(library, []byte("fixture"), 0o755); err != nil { + t.Fatal(err) + } + if got := findInApp(filepath.Join(root, layout.executable)); got != library { + t.Errorf("findInApp = %q, want %q", got, library) + } + }) + } +} diff --git a/base/terminal/terminal.go b/base/terminal/terminal.go index 5856611554..3f797f29bd 100644 --- a/base/terminal/terminal.go +++ b/base/terminal/terminal.go @@ -152,11 +152,7 @@ func Load() error { return load.err } -// LibraryPath returns the libghostty-vt the terminal loads, the first of: -// the file $NSGO_GHOSTTY_VT names; the one beside the executable, or in -// its macOS bundle's Frameworks or Resources; the build the package -// embeds for the platform, written once into the user's cache -// (/nsgo/libghostty-vt//). +// LibraryPath returns the libghostty-vt the terminal loads, the first of: the file $NSGO_GHOSTTY_VT names; the one beside the executable, or in its iOS or Catalyst GhosttyVT.framework or macOS Frameworks; the build the package embeds for the platform, written once into the user's cache (/nsgo/libghostty-vt//). func LibraryPath() (string, error) { return library.Find() } // New makes a terminal running opts.Command, or connected to opts.Conn. diff --git a/changelog.d/terminal-package-libraries-1454.md b/changelog.d/terminal-package-libraries-1454.md new file mode 100644 index 0000000000..1fe0914544 --- /dev/null +++ b/changelog.d/terminal-package-libraries-1454.md @@ -0,0 +1,3 @@ +### Fixed + +- Include libghostty-vt beside Windows and Linux executables in arm64 AARs and as a companion XCFramework for embedded iOS and Mac Catalyst apps (#1454 by @houko). diff --git a/cmd/nsgo/android.go b/cmd/nsgo/android.go index 7e4382ae3a..7a56a9ced0 100644 --- a/cmd/nsgo/android.go +++ b/cmd/nsgo/android.go @@ -11,6 +11,7 @@ import ( "go/parser" "go/token" "io" + "io/fs" "os" "os/exec" "path/filepath" @@ -227,6 +228,31 @@ const geometryReader = "github.com/nsgo-dev/nsgo/core.(*Env).Geometry" // nsgoInternal is the import path prefix of NSGo's internal packages. const nsgoInternal = "github.com/nsgo-dev/nsgo/internal/" +// androidGhosttyLibrary returns the prebuilt libghostty-vt for an app that links base/terminal. Android's loader searches the APK's ABI directory, so the library is a sibling of libnsgo.so rather than a Go-embedded payload. +func androidGhosttyLibrary(ctx context.Context, p *project, goarch, abi string) (apk.File, error) { + dir, err := linkedDir(ctx, p, []string{"GOOS=android", "GOARCH=" + goarch, "CGO_ENABLED=0"}, ghosttyPackage) + if err != nil { + return apk.File{}, err + } + if dir == "" { + return apk.File{}, nil + } + return androidGhosttyFile(dir, goarch, abi) +} + +func androidGhosttyFile(dir, goarch, abi string) (apk.File, error) { + path := filepath.Join(dir, "lib", "android-"+goarch, "libghostty-vt.so") + data, err := os.ReadFile(path) + if errors.Is(err, fs.ErrNotExist) { + // Until #1452 commits an Android prebuild the package has none for this ABI; the AAR builds without it, as before, rather than failing every embedded app that links the terminal. + return apk.File{}, nil + } + if err != nil { + return apk.File{}, fmt.Errorf("base/terminal: read Android libghostty-vt: %w", err) + } + return apk.File{Name: "lib/" + abi + "/libghostty-vt.so", Data: data}, nil +} + // androidLibraries are the device's libraries app, the app's linked executable for goarch, uses where the device has them: the window extensions for an app that reads its fold geometry, so no other app declares them. The name in the function table alone does not tell, as reflection may have kept it, so the app's sources must also select a Geometry. func androidLibraries(ctx context.Context, p *project, goarch string, app []byte) ([]string, error) { if !bytes.Contains(app, []byte(geometryReader)) { diff --git a/cmd/nsgo/build.go b/cmd/nsgo/build.go index ecbacda8b2..2c51357233 100644 --- a/cmd/nsgo/build.go +++ b/cmd/nsgo/build.go @@ -1017,7 +1017,7 @@ func buildWindows(ctx context.Context, p *project, dir, arch string) error { if err := addWinSparkle(ctx, p, dir, arch); err != nil { return err } - return p.addNativeLibraries(ctx, "windows_"+goArchName(arch), dir) + return addDesktopLibraries(ctx, p, dir, "windows", arch) } // buildLinux writes / with the resources and icon beside it. @@ -1033,7 +1033,7 @@ func buildLinux(ctx context.Context, p *project, dir, arch string) error { if err := writeLinuxIcon(p, dir); err != nil { return err } - return p.addNativeLibraries(ctx, "linux_"+goArchName(arch), dir) + return addDesktopLibraries(ctx, p, dir, "linux", arch) } // buildFPS is -fps: the site starts its app with --nsgo-fps, which a page diff --git a/cmd/nsgo/embed.go b/cmd/nsgo/embed.go index 48c2bb50aa..182b8d71b8 100644 --- a/cmd/nsgo/embed.go +++ b/cmd/nsgo/embed.go @@ -325,7 +325,10 @@ func buildIOSFramework(ctx context.Context, p *project, dir string) error { if err := os.MkdirAll(resources, 0o755); err != nil { return err } - return copyResources(p, resources) + if err := copyResources(p, resources); err != nil { + return err + } + return addIOSEmbeddedLibraries(ctx, p, dir, tmp, minimum) } // iosLinks are a static library's module map's link lines: what Go's @@ -354,20 +357,17 @@ func writeIOSHeaders(dir, header, modulemap string) error { // its binary left to the caller: iOS's flat, Mac Catalyst's in macOS's // versioned layout. It returns the bundle's path. func writeIOSFramework(slice, module, id, header, minimum string, catalyst bool) (string, error) { + return writeFrameworkBundle(slice, module, id, header, minimum, catalyst) +} + +// writeFrameworkBundle writes a dynamic framework bundle; an empty header makes a runtime-only framework, loaded through purego. +func writeFrameworkBundle(slice, module, id, header, minimum string, catalyst bool) (string, error) { fw := filepath.Join(slice, module+".framework") root := fw if catalyst { root = filepath.Join(fw, "Versions/A") } - modulemap := fmt.Sprintf("framework module %s {\n\tumbrella header \"NSGo.h\"\n\texport *\n}\n", module) - if err := writeIOSHeaders(filepath.Join(root, "Headers"), header, ""); err != nil { - return "", err - } - os.Remove(filepath.Join(root, "Headers", "module.modulemap")) - if err := os.MkdirAll(filepath.Join(root, "Modules"), 0o755); err != nil { - return "", err - } - if err := os.WriteFile(filepath.Join(root, "Modules", "module.modulemap"), []byte(modulemap), 0o644); err != nil { + if err := writeIOSFrameworkHeaders(root, module, header); err != nil { return "", err } plistDir := root @@ -396,15 +396,40 @@ func writeIOSFramework(slice, module, id, header, minimum string, catalyst bool) } if catalyst { for link, to := range map[string]string{"Versions/Current": "A", module: "Versions/Current/" + module, - "Headers": "Versions/Current/Headers", "Modules": "Versions/Current/Modules", "Resources": "Versions/Current/Resources"} { + "Resources": "Versions/Current/Resources"} { if err := os.Symlink(to, filepath.Join(fw, link)); err != nil { return "", err } } + if header != "" { + for _, name := range []string{"Headers", "Modules"} { + if err := os.Symlink("Versions/Current/"+name, filepath.Join(fw, name)); err != nil { + return "", err + } + } + } } return fw, nil } +func writeIOSFrameworkHeaders(root, module, header string) error { + if header == "" { + return nil + } + modulemap := fmt.Sprintf("framework module %s {\n\tumbrella header \"NSGo.h\"\n\texport *\n}\n", module) + if err := writeIOSHeaders(filepath.Join(root, "Headers"), header, ""); err != nil { + return err + } + os.Remove(filepath.Join(root, "Headers", "module.modulemap")) + if err := os.MkdirAll(filepath.Join(root, "Modules"), 0o755); err != nil { + return err + } + if err := os.WriteFile(filepath.Join(root, "Modules", "module.modulemap"), []byte(modulemap), 0o644); err != nil { + return err + } + return nil +} + // aarManifest is the library's manifest, which a host's build merges into its own: the runtime starts the app from the native library directory, so native libraries must be extracted, the provider of the files the app hands other apps is named after the host's package, the receiver of scheduled notifications' alarms hears the boot to set them again, and the device's libraries the app uses (androidLibraries) are declared without being required. An app that shows overlays over other apps (androidOverlay) asks for SYSTEM_ALERT_WINDOW and declares the overlay's foreground service with its permissions, which no other library does. func aarManifest(overlay bool, libraries []string) string { perms, services := "", "" @@ -478,6 +503,10 @@ func buildAndroidAAR(ctx context.Context, p *project, dir, goarch string) error if err != nil { return err } + ghostty, err := androidGhosttyLibrary(ctx, p, goarch, abi) + if err != nil { + return err + } stage(ctx, "packaging the AAR") f, err := os.Create(filepath.Join(dir, p.Name+".aar")) if err != nil { @@ -505,6 +534,11 @@ func buildAndroidAAR(ctx context.Context, p *project, dir, goarch string) error return err } } + if ghostty.Name != "" { + if err := add("jni/"+strings.TrimPrefix(ghostty.Name, "lib/"), ghostty.Data); err != nil { + return err + } + } err = walkResources(p, func(rel string, data []byte) error { return add("assets/"+rel, data) }) if err != nil { return err diff --git a/cmd/nsgo/natives.go b/cmd/nsgo/natives.go index 36632768a8..7e01370f43 100644 --- a/cmd/nsgo/natives.go +++ b/cmd/nsgo/natives.go @@ -153,3 +153,89 @@ func copyLibrary(src, dst string) error { } return os.WriteFile(dst, data, 0o755) } + +// addDesktopLibraries places terminal and package-declared libraries beside the executable before signing and installer assembly. +func addDesktopLibraries(ctx context.Context, p *project, dir, system, arch string) error { + env := []string{"GOOS=" + system, "GOARCH=" + arch, "CGO_ENABLED=0"} + source, err := linkedDir(ctx, p, env, ghosttyPackage) + if err != nil { + return err + } + target := system + "_" + goArchName(arch) + if source != "" { + name := "libghostty-vt.so" + if system == "windows" { + name = "ghostty-vt.dll" + } + source = filepath.Join(source, "lib", system+"-"+arch, name) + if err := validateNativeBinary(source, target); err != nil { + return fmt.Errorf("libghostty-vt: %w", err) + } + if err := copyLibrary(source, filepath.Join(dir, name)); err != nil { + return err + } + } + return p.addNativeLibraries(ctx, target, dir) +} + +// addIOSEmbeddedLibraries supplies the host with a companion XCFramework whenever its app links the terminal, for static and dynamic embedding alike. +func addIOSEmbeddedLibraries(ctx context.Context, p *project, dir, tmp, minimum string) error { + args := []string{"-create-xcframework"} + for _, sl := range iosSlices { + var libraries []string + for _, arch := range sl.archs { + env := []string{"GOOS=" + sl.goos, "GOARCH=" + arch, "CGO_ENABLED=1"} + tags := []string{"nsgoembed"} + if sl.catalyst { + tags = append(tags, "ios") + } + source, err := linkedDir(ctx, p, env, ghosttyPackage, tags...) + if err != nil { + return err + } + if source == "" { + continue + } + platform := "ios" + if sl.catalyst { + platform = "ioscatalyst" + } else if sl.sdk == "iphonesimulator" { + platform = "iossimulator" + } + libraries = append(libraries, filepath.Join(source, "lib", platform+"-"+arch, "libghostty-vt.dylib")) + } + if len(libraries) == 0 { + continue + } + fw, err := writeFrameworkBundle(filepath.Join(tmp, "ghostty", sl.sdk), "GhosttyVT", p.ID+".ghosttyvt", "", frameworkMinimum(minimum, sl.catalyst), sl.catalyst) + if err != nil { + return err + } + binary, install := filepath.Join(fw, "GhosttyVT"), "@rpath/"+ghosttyFramework+"/GhosttyVT" + if sl.catalyst { + binary = filepath.Join(fw, "Versions/A/GhosttyVT") + install = "@rpath/" + ghosttyFramework + "/Versions/A/GhosttyVT" + } + if err := run(ctx, "lipo", append([]string{"-create", "-output", binary}, libraries...)...); err != nil { + return err + } + if err := run(ctx, "install_name_tool", "-id", install, binary); err != nil { + return err + } + if err := run(ctx, "codesign", "--force", "--sign", "-", fw); err != nil { + return err + } + args = append(args, "-framework", fw) + } + if len(args) > 1 && embedModule(p) == "GhosttyVT" { + return fmt.Errorf("the app framework name GhosttyVT conflicts with the terminal companion: choose another app name") + } + framework := filepath.Join(dir, "GhosttyVT.xcframework") + if err := os.RemoveAll(framework); err != nil { + return err + } + if len(args) == 1 { + return nil + } + return run(ctx, "xcodebuild", append(args, "-output", framework)...) +} diff --git a/cmd/nsgo/natives_test.go b/cmd/nsgo/natives_test.go new file mode 100644 index 0000000000..ca0513bca5 --- /dev/null +++ b/cmd/nsgo/natives_test.go @@ -0,0 +1,219 @@ +package main + +import ( + "archive/zip" + "bytes" + "io" + "os" + "os/exec" + "path/filepath" + "runtime" + "testing" +) + +func ghosttyProject(t *testing.T, linked bool) *project { + t.Helper() + t.Setenv("GOWORK", "off") + t.Setenv("GOFLAGS", "-mod=mod") + cwd, err := os.Getwd() + if err != nil { + t.Fatal(err) + } + root, err := filepath.Abs(filepath.Join(cwd, "../..")) + if err != nil { + t.Fatal(err) + } + dir := t.TempDir() + main := "package main\nfunc main(){}\n" + if linked { + main = "package main\nimport _ \"github.com/nsgo-dev/nsgo/base/terminal\"\nfunc main(){}\n" + } + writeFiles(t, dir, map[string]string{ + "go.mod": "module example.com/ghosttyfixture\ngo 1.27.3\nrequire github.com/nsgo-dev/nsgo v0.0.0\nreplace github.com/nsgo-dev/nsgo => " + filepath.ToSlash(root) + "\n", + "main.go": main, + }) + return &project{Dir: dir, Name: "GhosttyFixture", ID: "dev.nsgo.test.ghostty1454", Version: "1.0.0", packageLicenses: true} +} + +func TestDesktopTerminalLibrariesFollowLinkedPackage(t *testing.T) { + for _, system := range []string{"linux", "windows"} { + for _, arch := range []string{"amd64", "arm64"} { + t.Run(system+"/"+arch, func(t *testing.T) { + p := ghosttyProject(t, true) + out := t.TempDir() + if err := addDesktopLibraries(t.Context(), p, out, system, arch); err != nil { + t.Fatal(err) + } + name := "libghostty-vt.so" + if system == "windows" { + name = "ghostty-vt.dll" + } + got, err := os.ReadFile(filepath.Join(out, name)) + if err != nil { + t.Fatal(err) + } + want, err := os.ReadFile(filepath.Join("../../base/terminal/internal/library/lib", system+"-"+arch, name)) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, want) { + t.Error("packaged library differs from its selected target build") + } + if err := validateNativeBinary(filepath.Join(out, name), system+"_"+goArchName(arch)); err != nil { + t.Fatal(err) + } + p = ghosttyProject(t, false) + empty := t.TempDir() + if err := addDesktopLibraries(t.Context(), p, empty, system, arch); err != nil { + t.Fatal(err) + } + entries, err := os.ReadDir(empty) + if err != nil || len(entries) != 0 { + t.Fatalf("an app without the terminal ships native files: %v %v", entries, err) + } + }) + } + } +} + +// TestTerminalDesktopPackageLoads builds and runs the host's real package with an empty cache. LibraryPath plus the live emulator prove the sidecar was selected. +func TestTerminalDesktopPackageLoads(t *testing.T) { + if os.Getenv("NSGO_TERMINAL_PACKAGE_NATIVE") != "1" { + t.Skip("set NSGO_TERMINAL_PACKAGE_NATIVE=1 on a Linux or Windows host") + } + if runtime.GOOS != "linux" && runtime.GOOS != "windows" { + t.Skip("requires a Linux or Windows host") + } + p := ghosttyProject(t, true) + writeFiles(t, p.Dir, map[string]string{"main.go": `package main +import ( + "fmt" + "io" + "os" + "path/filepath" + "strings" + "github.com/nsgo-dev/nsgo/base/terminal" +) +type connection struct { done chan struct{} } +func (c *connection) Read(p []byte) (int,error) { <-c.done; return 0,io.EOF } +func (c *connection) Write(p []byte) (int,error) { return len(p),nil } +func (c *connection) Close() error { close(c.done); return nil } +func main() { + path,err:=terminal.LibraryPath(); if err!=nil { panic(err) } + exe,err:=os.Executable(); if err!=nil { panic(err) } + if filepath.Dir(path)!=filepath.Dir(exe) { panic("library came from outside the package: "+path) } + term,err:=terminal.New(terminal.Options{Conn:&connection{make(chan struct{})}}); if err!=nil { panic(err) } + term.Feed([]byte("\x1b[31mPACKAGED-TERMINAL-1454\x1b[0m")) + if !strings.Contains(term.Text(),"PACKAGED-TERMINAL-1454") { panic("emulator did not consume output") } + term.Close(); <-term.Done() + if err:=os.WriteFile(os.Getenv("NSGO_TERMINAL_WITNESS"),[]byte(fmt.Sprintf("library=%s\ntext=PACKAGED-TERMINAL-1454\n",path)),0600); err!=nil { panic(err) } +} +`}) + out := t.TempDir() + var err error + executable := filepath.Join(out, p.Name) + if runtime.GOOS == "windows" { + err = buildWindows(t.Context(), p, out, runtime.GOARCH) + executable += ".exe" + } else { + err = buildLinux(t.Context(), p, out, runtime.GOARCH) + } + if err != nil { + t.Fatal(err) + } + cache, witness := t.TempDir(), filepath.Join(t.TempDir(), "witness.txt") + cmd := exec.CommandContext(t.Context(), executable) + cmd.Env = append(os.Environ(), "NSGO_GHOSTTY_VT=", "XDG_CACHE_HOME="+cache, "LOCALAPPDATA="+cache, "NSGO_TERMINAL_WITNESS="+witness) + if output, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("package: %v\n%s", err, output) + } + data, err := os.ReadFile(witness) + if err != nil { + t.Fatal(err) + } + t.Log(string(data)) + if _, err := os.Stat(filepath.Join(cache, "nsgo", "libghostty-vt")); !os.IsNotExist(err) { + t.Fatalf("package extracted a fallback library: %v", err) + } +} + +func TestTerminalCompanionXCFramework(t *testing.T) { + if os.Getenv("NSGO_TERMINAL_PACKAGE_NATIVE") != "1" || runtime.GOOS != "darwin" { + t.Skip("set NSGO_TERMINAL_PACKAGE_NATIVE=1 on a Mac with Xcode") + } + out := t.TempDir() + if err := addIOSEmbeddedLibraries(t.Context(), ghosttyProject(t, true), out, t.TempDir(), "15.0"); err != nil { + t.Fatal(err) + } + framework := filepath.Join(out, "GhosttyVT.xcframework") + if entries, err := os.ReadDir(framework); err == nil { + for _, entry := range entries { + t.Log(entry.Name()) + } + } + for _, platform := range []string{"ios-arm64", "ios-arm64_x86_64-simulator", "ios-arm64_x86_64-maccatalyst"} { + fw := filepath.Join(framework, platform, ghosttyFramework) + binary := filepath.Join(fw, "GhosttyVT") + if info, err := os.Stat(binary); err != nil || info.Size() == 0 { + t.Fatalf("missing %s: %v", platform, err) + } + if output, err := exec.CommandContext(t.Context(), "codesign", "--verify", "--strict", fw).CombinedOutput(); err != nil { + t.Fatalf("signature %s: %v %s", platform, err, output) + } + if _, err := os.Stat(filepath.Join(fw, "Headers", "NSGo.h")); !os.IsNotExist(err) { + t.Fatalf("runtime framework exposes app headers: %v", err) + } + output, err := exec.CommandContext(t.Context(), "lipo", "-archs", binary).CombinedOutput() + if err != nil { + t.Fatal(err) + } + t.Logf("%s: %s", platform, output) + } + if err := addIOSEmbeddedLibraries(t.Context(), ghosttyProject(t, false), out, t.TempDir(), "15.0"); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(framework); !os.IsNotExist(err) { + t.Fatalf("stale terminal companion remains for a build without terminal: %v", err) + } +} + +func TestTerminalAAR(t *testing.T) { + if os.Getenv("NSGO_TERMINAL_PACKAGE_NATIVE") != "1" { + t.Skip("set NSGO_TERMINAL_PACKAGE_NATIVE=1 with the Android prebuild available") + } + for _, linked := range []bool{true, false} { + p := ghosttyProject(t, linked) + out := t.TempDir() + if err := buildAndroidAAR(t.Context(), p, out, "arm64"); err != nil { + t.Fatal(err) + } + archive, err := zip.OpenReader(filepath.Join(out, p.Name+".aar")) + if err != nil { + t.Fatal(err) + } + defer archive.Close() + found := false + for _, file := range archive.File { + if file.Name != "jni/arm64-v8a/libghostty-vt.so" { + continue + } + found = true + reader, err := file.Open() + if err != nil { + t.Fatal(err) + } + data, err := io.ReadAll(reader) + reader.Close() + if err != nil { + t.Fatal(err) + } + want, err := os.ReadFile("../../base/terminal/internal/library/lib/android-arm64/libghostty-vt.so") + if err != nil || !bytes.Equal(data, want) { + t.Fatalf("AAR library differs from the selected prebuild: %v", err) + } + } + if found != linked { + t.Fatalf("terminal linked=%v, AAR library present=%v", linked, found) + } + } +} diff --git a/docs/architecture/embedding.md b/docs/architecture/embedding.md index e76a5a636f..a34b6c127f 100644 --- a/docs/architecture/embedding.md +++ b/docs/architecture/embedding.md @@ -2,6 +2,8 @@ NSGo apps run inside apps of their own: Go desktop programs make views with `nsgo.NewView`, and iOS and Android apps link the framework and library `nsgo build -embed` makes. NSH's design is in `nsh/docs/dev/embedding.md`. Read this before changing views, the host channel, `-embed` packages or the iOS and Android faces. +An app linking `base/terminal` also receives a runtime-only `GhosttyVT.xcframework` beside its app XCFramework, with the same device, simulator and Catalyst architectures. Hosts embed and sign the companion for static and dynamic apps; the terminal discovers its framework in flat iOS and versioned Catalyst host bundles. An arm64 AAR includes `jni/arm64-v8a/libghostty-vt.so` beside `libnsgo.so` once #1452 supplies its Android prebuild; its loader and device acceptance belong to that issue. + ## Views A view is one surface and one engine; `nsgo.Run` runs one engine with its loop, whose windows are surfaces of it ([application and windows](application.md)). A host makes as many as it likes, in one window or several, so backends keep a surface's state on the surface. What is the process's by nature stays process-wide: the standalone app's runner, window and controller, registries keyed by native object (views, widgets, menu targets), observers that report to every live surface, fonts, the image cache and file storage per data directory. diff --git a/docs/architecture/terminal.md b/docs/architecture/terminal.md index 3c08245cb5..63f512f116 100644 --- a/docs/architecture/terminal.md +++ b/docs/architecture/terminal.md @@ -17,7 +17,7 @@ It is a package under `base` because it links what an app without it should not, ## The library -libghostty-vt is built from Ghostty's sources at the commit the binding names, by `go run ./tools/libghostty` on a Mac with Xcode: it clones Ghostty into the user's cache, downloads the Zig its `build.zig.zon` asks for from ziglang.org, checked against the index's SHA-256, and builds every desktop target, iOS devices and the simulator, stripping the Linux builds' debug sections. The builds are committed in `internal/library/lib/`, as users have no Zig ([principles](../../AGENTS.md#principles)), so nothing is downloaded at run time. A desktop's is embedded in the apps that link the terminal, so `go run` and `go test` find it; the nsgo tool also signs it into macOS apps, where hardened apps load only signed libraries, and into iOS apps as a framework, the only way iOS loads native code ([tool](tool.md#packages)). The command also writes `ghostty_themes.go`, the themes Ghostty ships; `-themes` writes them alone. +libghostty-vt is built from Ghostty's sources at the commit the binding names, by `go run ./tools/libghostty` on a Mac with Xcode: it clones Ghostty into the user's cache, downloads the Zig its `build.zig.zon` asks for from ziglang.org, checked against the index's SHA-256, and builds every desktop target, iOS devices, both simulator architectures and Mac Catalyst, stripping the Linux builds' debug sections. The builds are committed in `internal/library/lib/`, as users have no Zig ([principles](../../AGENTS.md#principles)), so nothing is downloaded at run time. A desktop's is embedded in the apps that link the terminal, so `go run` and `go test` find it; the nsgo tool also signs it into macOS apps, where hardened apps load only signed libraries, and into iOS apps as a framework, the only way iOS loads native code ([tool](tool.md#packages)). Windows and Linux packages put the library beside their executable; iOS `-embed` writes a companion `GhosttyVT.xcframework` with all app slices, which hosts embed and sign for static and dynamic apps alike. An arm64 AAR carries the Android library supplied by #1452 in its JNI ABI directory. `-target` selects comma-separated library storage keys, such as `iossimulator-amd64,ioscatalyst-arm64`, or `all` (the default). The command also writes `ghostty_themes.go`, the themes Ghostty ships; `-themes` writes them alone. The library runs on macOS 13 or later, Linux with glibc 2.28 or later (Debian 10, Ubuntu 20.04) and Windows 10 1809 or later, whose ConPTY runs the program. diff --git a/docs/architecture/tool.md b/docs/architecture/tool.md index cabb590dd0..815f6d3e85 100644 --- a/docs/architecture/tool.md +++ b/docs/architecture/tool.md @@ -136,7 +136,7 @@ NSGo adds optional offline web delivery to NSH's content-addressed site layout. `resources/` ships at each package's resource root: beside the executable on Windows and Linux, beside the page on the web, in the bundle's `Contents/Resources` on macOS, at the bundle's root on iOS and in the APK's assets on Android, which with iOS leave out the paths `mobile.exclude_resources` lists. `imageload.ResourceRoot`, the web backend and Android's APK reader resolve `asset:` and font paths against it. App icons are drawn in Go; an Apple TV's is `icon.tvos`, Xcode's brand assets collection or a wide image, else the PNG over its own edges' color, as a two-layer image stack with top shelf images, since `actool` compiles no `.icon` for tvOS; an Apple Watch's is `icon.watchos`, its own `.icon` or square image, else `icon.apple`, which actool draws in circles; `actool` compiles Apple's `.icon` files, its output kept in the user cache by its version and the icon's content, and a Windows icon links from a `.syso` in the app's package directory, the only place Go links one from. -Native libraries come with the packages that hold them (`natives.go`): when the app's build links `base/terminal`'s library package, as `go list -deps` tells, libghostty-vt goes into a macOS app's `Contents/Frameworks` and an iOS app's `Frameworks/GhosttyVT.framework`, signed before the app so its signature seals them: ad hoc for macOS and the simulator, with the store's identity, or in Xcode's signing script for a device. `-embed` frameworks, Android and tvOS packages carry none yet ([roadmap](../roadmap.md#terminal)). +Native libraries come with the packages that hold them (`natives.go`): when the app's build links `base/terminal`'s library package, as `go list -deps` tells, libghostty-vt goes into a macOS app's `Contents/Frameworks` and an iOS app's `Frameworks/GhosttyVT.framework`, signed before the app so its signature seals them: ad hoc for macOS and the simulator, with the store's identity, or in Xcode's signing script for a device. Windows and Linux put it beside the executable before installer assembly. iOS `-embed` writes `GhosttyVT.xcframework` beside the app framework for hosts to embed and sign, with device, dual-architecture simulator and dual-architecture Catalyst slices; this applies to static and dynamic app frameworks. The arm64 AAR puts the Android prebuild beside `libnsgo.so` in its JNI ABI directory; #1452 supplies that prebuild and its loader. Android x86_64 and tvOS terminal libraries remain unavailable ([roadmap](../roadmap.md#terminal)). `build_number` sets `CFBundleVersion` and `versionCode`, else they follow `version`. `android.permissions` adds `uses-permission`s to the APK's manifest beyond the runtime's, a name without a dot under `android.permission.`, and a direct channel's APK asks for `REQUEST_INSTALL_PACKAGES` as well, for `updater`'s installs; `android.recording` declares the runtime's `RecordingService`, a foreground service of the microphone type, with `RECORD_AUDIO`, `FOREGROUND_SERVICE`, `FOREGROUND_SERVICE_MICROPHONE` and `POST_NOTIFICATIONS`, without which its notification does not show from Android 13, in the APK's and the bundle's manifest, which an app recording with `microphone.RecordWAV` needs and Google Play asks an app to justify, so no other app declares it ([Android recording](android-recording.md)); `-embed` libraries leave both to the host's manifest. An app that reads `core.Env.Geometry`, as its executable and its sources both tell, declares the device's `androidx.window.extensions` library without requiring it, in its APK, bundle or AAR, and no other app does ([foldable displays](foldable.md#platforms)). Listing `SYSTEM_ALERT_WINDOW` declares the overlay's `specialUse` foreground service with `FOREGROUND_SERVICE` and `FOREGROUND_SERVICE_SPECIAL_USE`, in the APK's manifest and the `-embed` library's, and no other app declares them ([Android floating windows](android-floating-windows.md)). Listing `FOREGROUND_SERVICE_LOCATION` declares the runtime's `LocationService`, a foreground service of the location type that background location streams run in, in the APK's and the bundle's manifest, and no other app declares it; `-embed` libraries leave it to the host's manifest ([location and motion](location-motion.md#permissions-and-packaging)). `apple.info` adds scalar, array and dictionary entries to the Info.plist of macOS and iOS packages, such as the `NSMicrophoneUsageDescription` recording needs; a string entry whose key is a message of the app's catalogs is localized in each language's `InfoPlist.strings` ([languages](languages.md)). Device bundles for iOS, tvOS and watchOS add Xcode's SDK metadata and `UIRequiredDeviceCapabilities` for `arm64` to the app and extensions; simulator bundles omit these device-only entries, and an `apple.info` value wins over generated metadata. `apple.requires_full_screen` sets the iOS package's `UIRequiresFullScreen`, true unless it is false, which lets an iPad run the app in Split View, Slide Over and Stage Manager and declares all four orientations in `UISupportedInterfaceOrientations~ipad`, as App Store Connect requires of an iPad app that multitasks; `apple.orientations` lists them for a full-screen app instead, and must list all four for one that multitasks. `apple.info` may set neither key. `file_types` registers documents in macOS's and iOS's `CFBundleDocumentTypes`, Windows's NSIS and MSIX packages, and Linux desktop entries with `MimeType` and `%F` (`filetypes.go`, `linuxfiletypes.go`): macOS and iOS export app-owned IDs and import others, with custom document icons currently on macOS alone; App Clips and tvOS leave the declarations out. NSIS records app-specific ProgIDs and extensions for guarded upgrade/uninstall cleanup; Linux uses the fixed `internal/mimeinfo` extension table or explicit `mime` references to system types, generating `application/x-` and MIME-info XML for unknown owned extensions. Debian/Arch refresh caches after installation and removal; Flatpak installs the definition for export; AppImage bundles it for integration. Other targets leave the declarations out ([roadmap](../roadmap.md#application-and-windows)). `windows.command_line` adds a console-subsystem `.com` beside the GUI `.exe` (`windows_command.go`), forwarding arguments, standard streams and the exit code to it, so command lookup can run the app without changing its Explorer and Start menu behavior; the console's Ctrl+C and close reach the companion alone, which ends the app, as does the job it puts the app in when the companion is killed. Win+R, Task Manager's "Run new task" and Explorer's address bar look a bare name up through `Path` too and find the `.com` first, giving it a console of its own; with no other process on that console and its output not redirected, the companion starts the app untied to it and exits, so the console closes instead of staying open beside the app as a window whose close would end it. Store builds leave it out, since an MSIX installs where no command lookup finds it. Every MSIX declares a disabled `NSGoStartup` task (`msix.go`), which `desktop.SetLaunchAtLogin` enables through WinRT instead of a package's virtualized Run key. `appearance` starts the app light or dark through `-X`, and sets `UIUserInterfaceStyle`, macOS's Aqua appearance, Android's activity theme and the page's `color-scheme`. `-run` starts the package of the first target this machine runs: the app, the iPhone's or Apple TV's, the simulator's, the Android device's, or the site served with a CDN's cache headers. `-device` picks the device as `nsgo dev`'s does; Xcode signs the iPhone's package again for `-team`, as in the dev loop, since devices install only development builds. diff --git a/docs/public/en/building.md b/docs/public/en/building.md index e9e71cd41a..eb45316b2e 100644 --- a/docs/public/en/building.md +++ b/docs/public/en/building.md @@ -163,6 +163,8 @@ licenses: ## Libraries from Go packages +Apps that import `base/terminal` also ship libghostty-vt: Windows and Linux packages place the library beside the executable; macOS and iOS bundles sign it into their frameworks. [Embedding](embedding.md) explains the companion XCFramework for iOS hosts. + A dependency can declare prebuilt desktop shared libraries in `nsgo-natives.yaml`. NSGo verifies their SHA-256, copies them into the app before signing and includes them in installers; the app author runs no extra step. [Native libraries](native-libraries.md) describes the package author's format and loading paths. ## Installers diff --git a/docs/public/en/embedding.md b/docs/public/en/embedding.md index b20faeffbd..7392d4efa6 100644 --- a/docs/public/en/embedding.md +++ b/docs/public/en/embedding.md @@ -19,6 +19,8 @@ The iOS build writes `.xcframework` and `Resources`; the Android bui ## iOS +When the app imports `base/terminal`, the build also writes `GhosttyVT.xcframework` beside the app framework. Add this companion to the host target with **Embed & Sign**, for both static and `-dynamic` app frameworks. It contains device, Intel and Apple silicon simulator, and Mac Catalyst libraries; keep its `GhosttyVT.framework` name. + Add the framework to the app target as a static library (do not embed it) and the resources folder as a folder reference, then `import `. Call `NSGoStart()` once as the app launches, before the first view. The static library's code is the host app's, so the host's privacy manifest declares the required-reason APIs NSGo uses: user defaults (`CA92.1`), file timestamps (`C617.1`) and system boot time (`35F9.1`); a `-dynamic` framework carries them in its own `PrivacyInfo.xcprivacy`. ```swift @@ -52,6 +54,8 @@ The host can also return the view's `preferredScreenEdgesDeferringSystemGestures ## Android +For an arm64 app importing `base/terminal`, the AAR includes `jni/arm64-v8a/libghostty-vt.so` beside `libnsgo.so`; the host keeps native-library extraction enabled. The Android prebuild and terminal loader require [#1452](https://github.com/nsgo-dev/nsgo/issues/1452); x86_64 terminal libraries are not available yet. + Add the AAR to the app module and package native libraries extracted, so the runtime finds them: ```kotlin diff --git a/docs/public/zh/building.md b/docs/public/zh/building.md index 74880ae0ec..ca2c6080ac 100644 --- a/docs/public/zh/building.md +++ b/docs/public/zh/building.md @@ -576,4 +576,6 @@ apple: ## 嵌入其他应用 +导入 `base/terminal` 的应用也会附带 libghostty-vt:Windows 和 Linux 包将库放在可执行文件旁,macOS 和 iOS 则将其签入应用的框架目录。[嵌入](embedding.md)介绍了 iOS 宿主使用的配套 XCFramework。 + `-embed` 把应用打包给你自己的 iOS 或 Android 应用使用:一个 XCFramework(加 `-dynamic` 时由动态框架组成)或 AAR,通过其中的 `NSGoView` 或 `NsgoView` 显示应用。Go 桌面程序用 `nsgo.NewView` 显示应用,网页则用站点的 `nsgo.js`,其主机为页面所在的主机,或 `nsgo.yaml` 中 `web.host` 指定的主机。仓库中的 `examples/embed-*` 分别给出了示例;宿主侧见[嵌入](embedding.md)。 diff --git a/docs/public/zh/embedding.md b/docs/public/zh/embedding.md index 8e23c53e36..c2617e97de 100644 --- a/docs/public/zh/embedding.md +++ b/docs/public/zh/embedding.md @@ -19,6 +19,8 @@ iOS 构建写出 `.xcframework` 和 `Resources`;Android 构建写 ## iOS +应用导入 `base/terminal` 时,构建还会在应用框架旁生成 `GhosttyVT.xcframework`。无论应用框架是静态还是 `-dynamic` 动态形式,都要将此配套框架加入宿主目标并选择 **Embed & Sign**。它包含真机、Intel 和 Apple 芯片模拟器及 Mac Catalyst 的库;保留 `GhosttyVT.framework` 名称。 + 把框架作为静态库加入应用目标(不要嵌入),把资源目录作为文件夹引用加入,然后 `import `。在应用启动时、第一个视图之前调用一次 `NSGoStart()`。静态库的代码属于宿主应用,因此由宿主应用的隐私清单声明 NSGo 用到的需要理由的 API:用户默认设置(`CA92.1`)、文件时间戳(`C617.1`)和系统启动时间(`35F9.1`);`-dynamic` 框架则在自己的 `PrivacyInfo.xcprivacy` 中声明它们。 ```swift @@ -51,6 +53,8 @@ view.register(component: "host.badge") { context in Badge(context) } ## Android +arm64 应用导入 `base/terminal` 时,AAR 会将 `jni/arm64-v8a/libghostty-vt.so` 放在 `libnsgo.so` 旁;宿主须保留本地库提取设置。Android 预编译库和终端加载器依赖 [#1452](https://github.com/nsgo-dev/nsgo/issues/1452);目前没有 x86_64 终端库。 + 把 AAR 加入应用模块,并让原生库被解压,以便运行时找到它们: ```kotlin diff --git a/docs/roadmap.md b/docs/roadmap.md index 73e2775860..92fb192d04 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -239,7 +239,7 @@ What `base/terminal` still lacks of a terminal app's features, Ghostty's the ref | --- | --- | --- | | Android | [#1452](https://github.com/nsgo-dev/nsgo/issues/1452) | An Android app's remote session runs: libghostty-vt built for `aarch64-linux-android` (Ghostty's build takes the NDK's sysroot, which `tools/libghostty` would download) goes into the APK's native libraries, and the Go process, which has no cgo on arm64, loads it: purego loads libraries on Android only through cgo, so this needs a loader for bionic without cgo, checked on a device | | iOS on a device | [#1453](https://github.com/nsgo-dev/nsgo/issues/1453) | The full-gallery `TestTerminalPhone` passes on a physical iPhone with its signed framework and software keyboard; device proof applies [#2119](https://github.com/nsgo-dev/nsgo/pull/2119)'s startup fix and omits widget/live-activity configuration because the available profile lacks App Groups | -| `-embed` frameworks and other packages | [#1454](https://github.com/nsgo-dev/nsgo/issues/1454) | `-embed` XCFrameworks and AARs, and Windows and Linux packages, carry libghostty-vt beside the app, as macOS and iOS apps do | +| Embedded Android terminal acceptance | [#1454](https://github.com/nsgo-dev/nsgo/issues/1454) | Windows/Linux sidecars and the complete companion XCFramework run natively, with iOS host acceptance using the safe-area fix from #1434; the arm64 AAR carries #1452’s prebuild, pending its loader and a real Android host. Android x86_64 has no prebuild | | The web | [#1455](https://github.com/nsgo-dev/nsgo/issues/1455) | A page runs a remote session over a WebSocket with libghostty-vt built for WebAssembly, which the browser runs, through the binding's calls | | Mouse reports and the wheel on full-screen programs | `mouse-reporting`, `mouse-scroll-multiplier`, [#1456](https://github.com/nsgo-dev/nsgo/issues/1456) | A program that takes the mouse gets presses, moves and the wheel as it asks, and the alternate screen gets the wheel as arrows | | Clipboard protocols | `clipboard-read`, `clipboard-write`, [#1458](https://github.com/nsgo-dev/nsgo/issues/1458) | Programs copy with OSC 52 and read the clipboard as the app allows, and the Kitty clipboard protocol offers pasted images | diff --git a/skills/nsgo/SKILL.md b/skills/nsgo/SKILL.md index 45d8207f1f..3444c5eab5 100644 --- a/skills/nsgo/SKILL.md +++ b/skills/nsgo/SKILL.md @@ -39,6 +39,8 @@ On `ios_simulator`, Go-only dev rebuilds of the main app replace the installed e Use `-host 127.0.0.1` to bind the dev server to loopback only, including with Android's `adb reverse`. +Apps importing `base/terminal` ship libghostty-vt beside Windows/Linux executables and in Apple frameworks. An iOS `-embed` build also writes `GhosttyVT.xcframework`; hosts add this companion with Embed & Sign for static and dynamic app frameworks alike. An arm64 AAR carries the Android prebuild from #1452 beside `libnsgo.so`; x86_64 terminal libraries are unavailable. [Embedding](https://nsgo.dev/docs/embedding.md) covers the host setup. + Go dependencies can ship prebuilt desktop shared libraries through their package's `nsgo-natives.yaml`: NSGo verifies checksums, bundles licenses, signs and includes them in installers without app configuration. Package authors declare target names, URL or local files, SHA-256 and license paths, and preserve these files with `go:embed` for vendoring. [Native libraries](https://nsgo.dev/docs/native-libraries.md) gives the contract and loading directories. For terminal apps, use `go tool nsgo dev -target tui` and `go tool nsgo test -target tui` in an interactive terminal with `nsgotest.Main`. Choose cell-sized styles explicitly (8×16 points per cell); Control is `mod` on every host. Diagnostics go to `.nsgo/tui.log`; media/canvas/native hosted views are not implemented. [Terminal targets](https://nsgo.dev/docs/building.md#terminal) diff --git a/tools/libghostty/main.go b/tools/libghostty/main.go index e48bc4d90a..98af1e3466 100644 --- a/tools/libghostty/main.go +++ b/tools/libghostty/main.go @@ -21,6 +21,7 @@ import ( "encoding/hex" "encoding/json" "flag" + "fmt" "io" "log" "os" @@ -28,6 +29,7 @@ import ( "path/filepath" "regexp" "runtime" + "slices" "strings" ) @@ -38,11 +40,13 @@ const commit = "befcdfd2c3a1cb24d9ec886e93c95b2b5daa7028" // libDir is where the libraries go, by GOOS-GOARCH. const libDir = "base/terminal/internal/library/lib" -var targets = []struct { +type libraryTarget struct { goos, goarch, zig string // name is the library's file; built is where Zig puts it. name, built string -}{ +} + +var targets = []libraryTarget{ {"darwin", "arm64", "aarch64-macos", "libghostty-vt.dylib", "lib/libghostty-vt.dylib"}, {"darwin", "amd64", "x86_64-macos", "libghostty-vt.dylib", "lib/libghostty-vt.dylib"}, // The glibc of Debian 10 and Ubuntu 20.04, and later. @@ -54,12 +58,16 @@ var targets = []struct { // framework. {"ios", "arm64", "aarch64-ios", "libghostty-vt.dylib", "lib/libghostty-vt.dylib"}, {"iossimulator", "arm64", "aarch64-ios-simulator", "libghostty-vt.dylib", "lib/libghostty-vt.dylib"}, + {"iossimulator", "amd64", "x86_64-ios-simulator", "libghostty-vt.dylib", "lib/libghostty-vt.dylib"}, + {"ioscatalyst", "arm64", "aarch64-maccatalyst", "libghostty-vt.dylib", "lib/libghostty-vt.dylib"}, + {"ioscatalyst", "amd64", "x86_64-maccatalyst", "libghostty-vt.dylib", "lib/libghostty-vt.dylib"}, } func main() { log.SetFlags(0) src := flag.String("src", "", "a checkout of Ghostty at the commit (cloned into the user's cache when empty)") themes := flag.Bool("themes", false, "only write the themes") + targetNames := flag.String("target", "all", "comma-separated library targets (goos-goarch), or all") flag.Parse() if _, err := os.Stat("base/terminal"); err != nil { log.Fatal("run it from the repository's root") @@ -68,18 +76,27 @@ func main() { writeThemes(*src) return } + selected, err := selectTargets(*targetNames) + if err != nil { + log.Fatal(err) + } if *src == "" { *src = checkout() } zig := zigFor(*src) - for _, t := range targets { + buildLibraries(*src, zig, selected) + writeThemes(*src) +} + +func buildLibraries(src, zig string, selected []libraryTarget) { + for _, t := range selected { prefix, err := os.MkdirTemp("", "libghostty-vt-") if err != nil { log.Fatal(err) } defer os.RemoveAll(prefix) log.Printf("building %s/%s", t.goos, t.goarch) - run(*src, zig, "build", "-Demit-lib-vt", "-Dtarget="+t.zig, "-Doptimize=ReleaseFast", "-Dstrip=true", "--prefix", prefix) + run(src, zig, "build", "-Demit-lib-vt", "-Dtarget="+t.zig, "-Doptimize=ReleaseFast", "-Dstrip=true", "--prefix", prefix) built := filepath.Join(prefix, t.built) if t.goos == "linux" { // The build keeps the debug information of ELF libraries, @@ -92,7 +109,6 @@ func main() { } log.Printf(" %s %s", dst, copyFile(built, dst)) } - writeThemes(*src) } // cacheDir is NSGo's directory in the user's cache. @@ -255,3 +271,22 @@ func stripELF(path string) string { } return stripped } + +func selectTargets(names string) ([]libraryTarget, error) { + var selected []libraryTarget + for _, name := range strings.Split(names, ",") { + name = strings.TrimSpace(name) + if name == "all" { + selected = append([]libraryTarget(nil), targets...) + continue + } + index := slices.IndexFunc(targets, func(t libraryTarget) bool { return t.goos+"-"+t.goarch == name }) + if index < 0 { + return nil, fmt.Errorf("unknown library target %q", name) + } + if !slices.Contains(selected, targets[index]) { + selected = append(selected, targets[index]) + } + } + return selected, nil +} diff --git a/tools/libghostty/main_test.go b/tools/libghostty/main_test.go new file mode 100644 index 0000000000..d94cc0a5ee --- /dev/null +++ b/tools/libghostty/main_test.go @@ -0,0 +1,47 @@ +package main + +import ( + "os" + "path/filepath" + "testing" +) + +func TestSelectLibraryTargets(t *testing.T) { + selected, err := selectTargets("iossimulator-amd64,ioscatalyst-arm64,iossimulator-amd64") + if err != nil || len(selected) != 2 { + t.Fatalf("selected %v: %v", selected, err) + } + if selected[0].zig != "x86_64-ios-simulator" || selected[1].zig != "aarch64-maccatalyst" { + t.Fatalf("wrong Apple targets: %+v", selected) + } + if _, err := selectTargets("missing-arm64"); err == nil { + t.Error("unknown target accepted") + } + if selected, err := selectTargets("all"); err != nil || len(selected) != len(targets) { + t.Fatalf("all: %v %v", selected, err) + } +} + +// TestRebuildSelectedLibraries invokes the generator's real build path through nsgo test. Source and compiler are explicit so native rebuilds remain opt-in. +func TestRebuildSelectedLibraries(t *testing.T) { + names := os.Getenv("NSGO_GHOSTTY_REBUILD_TARGETS") + if names == "" { + t.Skip("set NSGO_GHOSTTY_REBUILD_TARGETS with explicit NSGO_GHOSTTY_SRC and NSGO_GHOSTTY_ZIG") + } + selected, err := selectTargets(names) + if err != nil { + t.Fatal(err) + } + src, zig := os.Getenv("NSGO_GHOSTTY_SRC"), os.Getenv("NSGO_GHOSTTY_ZIG") + if !filepath.IsAbs(src) || !filepath.IsAbs(zig) { + t.Fatal("source and Zig must be explicit absolute paths") + } + t.Chdir("../..") + buildLibraries(src, zig, selected) + for _, target := range selected { + path := filepath.Join(libDir, target.goos+"-"+target.goarch, target.name) + if info, err := os.Stat(path); err != nil || info.Size() == 0 { + t.Fatalf("rebuilt %s: %v", path, err) + } + } +}