Compare commits
4
Commits
trust/v0.2.0
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
586e76889c | ||
|
|
5dd4a86b68 | ||
|
|
975340b5f7 | ||
|
|
5d141c7cef |
No files matched your search
@@ -55,6 +55,28 @@ speculatively.
|
|||||||
size and maximized state across starts (macOS and Windows;
|
size and maximized state across starts (macOS and Windows;
|
||||||
`gui/v0.2.0`, 2026-11-15).
|
`gui/v0.2.0`, 2026-11-15).
|
||||||
- [ ] `core/gui`: Linux/FreeBSD backend (WebKitGTK) -- see gui/README.md.
|
- [ ] `core/gui`: Linux/FreeBSD backend (WebKitGTK) -- see gui/README.md.
|
||||||
|
- [ ] `core/gui`: resident app with a prewarmed WebView, for a start
|
||||||
|
under 300 ms (proposal from yamc, 2026-11-29, for its H-STARTUP;
|
||||||
|
see yamc `docs/spec/gui-comparison.md`). Measured on macOS (Apple
|
||||||
|
Silicon, warm): NSApp setup ~65 ms, WKWebView init ~45 ms, window
|
||||||
|
~25 ms, then ~190 ms until the web content process asks for the
|
||||||
|
first resource and ~150 ms for WebKit's first paint -- ~550 ms to
|
||||||
|
the first frame, ~340 ms of it WebKit's own, which only advances
|
||||||
|
while the main run loop runs. Tried without effect (yamc,
|
||||||
|
2026-11-29): `loadRequest` right after the WKWebView exists
|
||||||
|
(before the window is built, also before `finishLaunching`),
|
||||||
|
spinning the run loop after it, building the app's state in
|
||||||
|
parallel -- the first request still comes ~200 ms after the main
|
||||||
|
thread is free. So a fresh process stays at ~500 ms or more.
|
||||||
|
Proposal: keep the process alive after its last window (macOS: a
|
||||||
|
normal Dock app; Windows: a background process), hold one hidden
|
||||||
|
WebView with the page loaded in reserve, and let a new start hand
|
||||||
|
its arguments to the running instance (single instance, e.g. a
|
||||||
|
socket in the runtime dir), which shows the reserve window and
|
||||||
|
prepares the next. Needs several windows per process, a
|
||||||
|
reserve-window API, and the same on WebView2. The first start
|
||||||
|
stays at ~550 ms. Only worth it once a program needs it (yamc's
|
||||||
|
Gio-vs-WebView choice is still open).
|
||||||
- [x] `core/tui`: shared TUI kernel (themes, styles, Paint/Outer,
|
- [x] `core/tui`: shared TUI kernel (themes, styles, Paint/Outer,
|
||||||
ListState, text helpers) as the nested module
|
ListState, text helpers) as the nested module
|
||||||
`yetano.dev/yetano/core/tui` (`tui/v0.1.0`).
|
`yetano.dev/yetano/core/tui` (`tui/v0.1.0`).
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
// Yetano program standard (docs/program-conventions.md and ADR-0012 in
|
// Yetano program standard (docs/program-conventions.md and ADR-0012 in
|
||||||
// the yetano meta-repository):
|
// the yetano meta-repository):
|
||||||
//
|
//
|
||||||
// <program> config create [--minimal|--full] [--force] [--output <file>]
|
// <program> config create [--minimal|--full] [--force] [--output <file>|-]
|
||||||
// <program> config validate
|
// <program> config validate
|
||||||
// <program> config upgrade [--write]
|
// <program> config upgrade [--write]
|
||||||
// <program> config path
|
// <program> config path
|
||||||
@@ -201,7 +201,7 @@ func usage(s Spec, w io.Writer) {
|
|||||||
}
|
}
|
||||||
fmt.Fprintf(w, `usage: %[1]s config <subcommand> [--config <file>]
|
fmt.Fprintf(w, `usage: %[1]s config <subcommand> [--config <file>]
|
||||||
|
|
||||||
create [--minimal|--full] [--force] [--output <file>]
|
create [--minimal|--full] [--force] [--output <file>|-]
|
||||||
write a commented starter configuration (minimal by default)
|
write a commented starter configuration (minimal by default)
|
||||||
validate check the configuration file the program would use
|
validate check the configuration file the program would use
|
||||||
upgrade [--write]
|
upgrade [--write]
|
||||||
@@ -342,7 +342,7 @@ func (s Spec) create(explicit string, args []string, stdout, stderr io.Writer) i
|
|||||||
minimal := fs.Bool("minimal", false, "write the minimal starter configuration (default)")
|
minimal := fs.Bool("minimal", false, "write the minimal starter configuration (default)")
|
||||||
full := fs.Bool("full", false, "write the fully commented reference configuration")
|
full := fs.Bool("full", false, "write the fully commented reference configuration")
|
||||||
force := fs.Bool("force", false, "overwrite the file if it already exists")
|
force := fs.Bool("force", false, "overwrite the file if it already exists")
|
||||||
output := fs.String("output", "", "file to write (default: --config, else the file the program would use, else "+s.filename()+" in the user config directory -- the system one as root)")
|
output := fs.String("output", "", "file to write, - for stdout (default: --config, else the file the program would use, else "+s.filename()+" in the user config directory -- the system one as root)")
|
||||||
if code := parse(fs, args); code >= 0 {
|
if code := parse(fs, args); code >= 0 {
|
||||||
return code
|
return code
|
||||||
}
|
}
|
||||||
@@ -356,6 +356,10 @@ func (s Spec) create(explicit string, args []string, stdout, stderr io.Writer) i
|
|||||||
}
|
}
|
||||||
|
|
||||||
path := *output
|
path := *output
|
||||||
|
if path == "-" { // the template on stdout, nothing written
|
||||||
|
io.WriteString(stdout, content)
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
if path == "" {
|
if path == "" {
|
||||||
var err error
|
var err error
|
||||||
if path, err = s.defaultCreatePath(explicit); err != nil {
|
if path, err = s.defaultCreatePath(explicit); err != nil {
|
||||||
|
|||||||
@@ -190,6 +190,27 @@ func TestCreateExplicitAndOutput(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --output - prints the template and writes no file (not one named "-").
|
||||||
|
func TestCreateOutputStdout(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
s := testSpec(root)
|
||||||
|
work := filepath.Join(root, "work")
|
||||||
|
if err := os.MkdirAll(work, 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Chdir(work)
|
||||||
|
code, out, errOut := run(t, s, "", "create", "--full", "--output", "-")
|
||||||
|
if code != ExitOK || out != fullTemplate || errOut != "" {
|
||||||
|
t.Fatalf("create --output -: exit %d, stdout %q, stderr %q", code, out, errOut)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(work, "-")); !errors.Is(err, os.ErrNotExist) {
|
||||||
|
t.Errorf("create --output - wrote a file named \"-\": %v", err)
|
||||||
|
}
|
||||||
|
if code, out, _ := run(t, s, "", "create", "--output=-"); code != ExitOK || out != minimalTemplate {
|
||||||
|
t.Errorf("create --output=-: exit %d, stdout %q", code, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestValidate(t *testing.T) {
|
func TestValidate(t *testing.T) {
|
||||||
root := t.TempDir()
|
root := t.TempDir()
|
||||||
s := testSpec(root)
|
s := testSpec(root)
|
||||||
|
|||||||
+1
-1
@@ -38,7 +38,7 @@ the main module's `vX.Y.Z` tags do not version this one. Never move a tag.
|
|||||||
| `gui/assets` | `NewResolver(sources...)` over `NewFSSource` (embed.FS), `NewDirSource` (os.Root), `NewZipFileSource`/`NewZipBytesSource`; first source that has a file wins, a read error does not fall through. `ValidatePath` (checked, never cleaned), `Join`, `DetectMIME`. |
|
| `gui/assets` | `NewResolver(sources...)` over `NewFSSource` (embed.FS), `NewDirSource` (os.Root), `NewZipFileSource`/`NewZipBytesSource`; first source that has a file wins, a read error does not fall through. `ValidatePath` (checked, never cleaned), `Join`, `DetectMIME`. |
|
||||||
| `gui/document` | `Prepare(ctx, res, entry, html, Options{Link})`: rewrites `assets:` / relative references in HTML and CSS (`img`, `srcset`, `script`, `link`, `style`, CSS `url()`/`@import`). Link mode -> `/assets/...` URLs, validated against the resolver; inline mode -> typed `data:` URLs (entry <= 1.5 MiB). |
|
| `gui/document` | `Prepare(ctx, res, entry, html, Options{Link})`: rewrites `assets:` / relative references in HTML and CSS (`img`, `srcset`, `script`, `link`, `style`, CSS `url()`/`@import`). Link mode -> `/assets/...` URLs, validated against the resolver; inline mode -> typed `data:` URLs (entry <= 1.5 MiB). |
|
||||||
| `gui/bridge` | `NewRouter(res)`, `Router.Handle("POST /rpc/x", h)`, `Router.SetDocument`, `Router.ServeNative` (for the window's resource handler), `Router.HTML` (Go-rendered fragments through `document`). `NewSession(router, Options)` speaks protocol v1 with the page (`hello`/`ready`, `req`/`res`, `chunk`/`end` streams, `abort`, generations). `InitScript(PageConfig)` is the page side (`bridge.js`). |
|
| `gui/bridge` | `NewRouter(res)`, `Router.Handle("POST /rpc/x", h)`, `Router.SetDocument`, `Router.ServeNative` (for the window's resource handler), `Router.HTML` (Go-rendered fragments through `document`). `NewSession(router, Options)` speaks protocol v1 with the page (`hello`/`ready`, `req`/`res`, `chunk`/`end` streams, `abort`, generations). `InitScript(PageConfig)` is the page side (`bridge.js`). |
|
||||||
| `gui/window` | `New(Options{Title, Width, Height, Debug, DataPath, OnMessage, Resource, FrameFile})`, `Init`, `Navigate`, `Run`, `Dispatch`, `Eval`, `Terminate`, `Destroy`, `BaseURL`, `Snapshot` (macOS), `SetAppearance`, `SetAppIcon`, `AccentColor`. |
|
| `gui/window` | `New(Options{Title, Width, Height, Debug, DataPath, OnMessage, Resource, FrameFile})`, `Init`, `Navigate`, `Run`, `Dispatch`, `Eval`, `Terminate`, `Destroy`, `BaseURL`, `Snapshot` (macOS), `SetAppearance`, `SetAppIcon`, `AccentColor`, `ShowFileDialog` (UI thread) / `ChooseFile` (any goroutine, waits): a native open or save dialog (`FileDialog{Save, Title, Directory, Name, Extensions}`; macOS NSOpenPanel/NSSavePanel as a sheet, Windows GetOpenFileNameW/GetSaveFileNameW), "" when cancelled -- it only returns a path, nothing is read or written. |
|
||||||
|
|
||||||
## Wiring
|
## Wiring
|
||||||
|
|
||||||
|
|||||||
@@ -18,5 +18,6 @@ void yt_snapshot(void *h, const char *path);
|
|||||||
void yt_set_appearance(void *h, int mode);
|
void yt_set_appearance(void *h, int mode);
|
||||||
void yt_accent_color(char *buf, int n);
|
void yt_accent_color(char *buf, int n);
|
||||||
void yt_set_app_icon(const void *png, int n);
|
void yt_set_app_icon(const void *png, int n);
|
||||||
|
void yt_file_dialog(void *h, int save, const char *title, const char *dir, const char *name, const char *types);
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
@@ -9,6 +9,7 @@
|
|||||||
// marshalled with dispatch_async onto the main queue.
|
// marshalled with dispatch_async onto the main queue.
|
||||||
#import <Cocoa/Cocoa.h>
|
#import <Cocoa/Cocoa.h>
|
||||||
#import <WebKit/WebKit.h>
|
#import <WebKit/WebKit.h>
|
||||||
|
#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
|
||||||
#include "darwin.h"
|
#include "darwin.h"
|
||||||
|
|
||||||
// Implemented in Go (window_darwin.go).
|
// Implemented in Go (window_darwin.go).
|
||||||
@@ -19,6 +20,7 @@ extern void ytGoDispatch(uintptr_t fn);
|
|||||||
extern void ytGoClosed(uintptr_t h);
|
extern void ytGoClosed(uintptr_t h);
|
||||||
extern void ytGoSnapshotDone(uintptr_t h, const char *err);
|
extern void ytGoSnapshotDone(uintptr_t h, const char *err);
|
||||||
extern void ytGoFrame(uintptr_t h, int x, int y, int w, int hgt, int zoomed);
|
extern void ytGoFrame(uintptr_t h, int x, int y, int w, int hgt, int zoomed);
|
||||||
|
extern void ytGoFileDone(uintptr_t h, const char *path);
|
||||||
|
|
||||||
// YTWebView takes the first mouse click in an inactive window: without
|
// YTWebView takes the first mouse click in an inactive window: without
|
||||||
// it the click only activates the window, so a page (a dialog shown at
|
// it the click only activates the window, so a page (a dialog shown at
|
||||||
@@ -327,3 +329,40 @@ void yt_set_app_icon(const void *png, int n) {
|
|||||||
if (img) NSApp.applicationIconImage = img;
|
if (img) NSApp.applicationIconImage = img;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- file dialogs ------------------------------------------------------------
|
||||||
|
|
||||||
|
// yt_file_dialog shows an open (save = 0) or save panel as a sheet on the
|
||||||
|
// window. dir: the folder to start in, name: a save panel's suggested file
|
||||||
|
// name, types: allowed file extensions, comma-separated ("" = any). The
|
||||||
|
// chosen path, or NULL when cancelled, goes to ytGoFileDone.
|
||||||
|
void yt_file_dialog(void *h, int save, const char *title, const char *dir, const char *name, const char *types) {
|
||||||
|
YTHost *host = (__bridge YTHost *)h;
|
||||||
|
uintptr_t gh = host.goHandle;
|
||||||
|
NSSavePanel *panel;
|
||||||
|
if (save) {
|
||||||
|
panel = [NSSavePanel savePanel];
|
||||||
|
if (name && name[0]) panel.nameFieldStringValue = str(name);
|
||||||
|
} else {
|
||||||
|
NSOpenPanel *open = [NSOpenPanel openPanel];
|
||||||
|
open.canChooseFiles = YES;
|
||||||
|
open.canChooseDirectories = NO;
|
||||||
|
open.allowsMultipleSelection = NO;
|
||||||
|
open.resolvesAliases = YES;
|
||||||
|
panel = open;
|
||||||
|
}
|
||||||
|
if (title && title[0]) { panel.title = str(title); panel.message = str(title); }
|
||||||
|
if (dir && dir[0]) panel.directoryURL = [NSURL fileURLWithPath:str(dir) isDirectory:YES];
|
||||||
|
if (types && types[0]) {
|
||||||
|
NSMutableArray<UTType *> *uts = [NSMutableArray array];
|
||||||
|
for (NSString *ext in [str(types) componentsSeparatedByString:@","]) {
|
||||||
|
UTType *t = [UTType typeWithFilenameExtension:ext];
|
||||||
|
if (t) [uts addObject:t];
|
||||||
|
}
|
||||||
|
if (uts.count) panel.allowedContentTypes = uts;
|
||||||
|
}
|
||||||
|
[panel beginSheetModalForWindow:host.window completionHandler:^(NSModalResponse r) {
|
||||||
|
if (r != NSModalResponseOK || !panel.URL) { ytGoFileDone(gh, NULL); return; }
|
||||||
|
ytGoFileDone(gh, panel.URL.path.fileSystemRepresentation);
|
||||||
|
}];
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
//go:build windows
|
||||||
|
|
||||||
|
package window
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"golang.org/x/sys/windows"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
comdlg32 = windows.NewLazySystemDLL("comdlg32.dll")
|
||||||
|
pGetOpenFile = comdlg32.NewProc("GetOpenFileNameW")
|
||||||
|
pGetSaveFile = comdlg32.NewProc("GetSaveFileNameW")
|
||||||
|
pCommDlgExtErr = comdlg32.NewProc("CommDlgExtendedError")
|
||||||
|
errNoFileDialog = fmt.Errorf("window: file dialog failed")
|
||||||
|
)
|
||||||
|
|
||||||
|
// openFileName is OPENFILENAMEW (commdlg.h).
|
||||||
|
type openFileName struct {
|
||||||
|
lStructSize uint32
|
||||||
|
hwndOwner uintptr
|
||||||
|
hInstance uintptr
|
||||||
|
lpstrFilter *uint16
|
||||||
|
lpstrCustomFilter *uint16
|
||||||
|
nMaxCustFilter uint32
|
||||||
|
nFilterIndex uint32
|
||||||
|
lpstrFile *uint16
|
||||||
|
nMaxFile uint32
|
||||||
|
lpstrFileTitle *uint16
|
||||||
|
nMaxFileTitle uint32
|
||||||
|
lpstrInitialDir *uint16
|
||||||
|
lpstrTitle *uint16
|
||||||
|
flags uint32
|
||||||
|
nFileOffset uint16
|
||||||
|
nFileExtension uint16
|
||||||
|
lpstrDefExt *uint16
|
||||||
|
lCustData uintptr
|
||||||
|
lpfnHook uintptr
|
||||||
|
lpTemplateName *uint16
|
||||||
|
pvReserved uintptr
|
||||||
|
dwReserved uint32
|
||||||
|
flagsEx uint32
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
ofnOverwritePrompt = 0x00000002
|
||||||
|
ofnNoChangeDir = 0x00000008
|
||||||
|
ofnPathMustExist = 0x00000800
|
||||||
|
ofnFileMustExist = 0x00001000
|
||||||
|
ofnExplorer = 0x00080000
|
||||||
|
)
|
||||||
|
|
||||||
|
// fileFilter is the dialog's filter list: the allowed extensions, then
|
||||||
|
// all files; pairs of display text and pattern, each NUL-terminated,
|
||||||
|
// the list ending with an extra NUL.
|
||||||
|
func fileFilter(exts []string) []uint16 {
|
||||||
|
var b strings.Builder
|
||||||
|
if len(exts) > 0 {
|
||||||
|
pats := make([]string, len(exts))
|
||||||
|
for i, e := range exts {
|
||||||
|
pats[i] = "*." + strings.TrimPrefix(e, ".")
|
||||||
|
}
|
||||||
|
p := strings.Join(pats, ";")
|
||||||
|
b.WriteString(p + " (" + p + ")\x00" + p + "\x00")
|
||||||
|
}
|
||||||
|
b.WriteString("All files (*.*)\x00*.*\x00\x00")
|
||||||
|
return windows.StringToUTF16(b.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// FileDialog shows the common open or save dialog, modal to the window
|
||||||
|
// (it runs its own message loop on the UI thread); done runs right after.
|
||||||
|
func (b *winBackend) FileDialog(d FileDialog, done func(string, error)) {
|
||||||
|
buf := make([]uint16, 32768)
|
||||||
|
if d.Save && d.Name != "" {
|
||||||
|
copy(buf[:len(buf)-1], windows.StringToUTF16(d.Name))
|
||||||
|
}
|
||||||
|
filter := fileFilter(d.Extensions)
|
||||||
|
ofn := openFileName{
|
||||||
|
hwndOwner: b.hwnd,
|
||||||
|
lpstrFilter: &filter[0],
|
||||||
|
nFilterIndex: 1,
|
||||||
|
lpstrFile: &buf[0],
|
||||||
|
nMaxFile: uint32(len(buf)),
|
||||||
|
flags: ofnExplorer | ofnNoChangeDir | ofnPathMustExist,
|
||||||
|
}
|
||||||
|
ofn.lStructSize = uint32(unsafe.Sizeof(ofn))
|
||||||
|
if d.Title != "" {
|
||||||
|
ofn.lpstrTitle, _ = windows.UTF16PtrFromString(d.Title)
|
||||||
|
}
|
||||||
|
if d.Directory != "" {
|
||||||
|
ofn.lpstrInitialDir, _ = windows.UTF16PtrFromString(d.Directory)
|
||||||
|
}
|
||||||
|
proc := pGetOpenFile
|
||||||
|
if d.Save {
|
||||||
|
proc = pGetSaveFile
|
||||||
|
ofn.flags |= ofnOverwritePrompt
|
||||||
|
if len(d.Extensions) > 0 {
|
||||||
|
ofn.lpstrDefExt, _ = windows.UTF16PtrFromString(strings.TrimPrefix(d.Extensions[0], "."))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
ofn.flags |= ofnFileMustExist
|
||||||
|
}
|
||||||
|
if r, _, _ := proc.Call(uintptr(unsafe.Pointer(&ofn))); r == 0 {
|
||||||
|
if code, _, _ := pCommDlgExtErr.Call(); code != 0 {
|
||||||
|
done("", fmt.Errorf("%w: CommDlgExtendedError 0x%x", errNoFileDialog, code))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
done("", nil) // cancelled
|
||||||
|
return
|
||||||
|
}
|
||||||
|
done(windows.UTF16ToString(buf), nil)
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
//go:build windows
|
||||||
|
|
||||||
|
package window
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestFileFilter(t *testing.T) {
|
||||||
|
raw := fileFilter([]string{"pdf", ".txt"})
|
||||||
|
s := string(utf16Runes(raw))
|
||||||
|
want := "*.pdf;*.txt (*.pdf;*.txt)\x00*.pdf;*.txt\x00All files (*.*)\x00*.*\x00\x00\x00"
|
||||||
|
if s != want {
|
||||||
|
t.Errorf("filter = %q, want %q", s, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func utf16Runes(u []uint16) []rune {
|
||||||
|
r := make([]rune, len(u))
|
||||||
|
for i, c := range u {
|
||||||
|
r[i] = rune(c)
|
||||||
|
}
|
||||||
|
return r
|
||||||
|
}
|
||||||
@@ -219,6 +219,63 @@ func SetAppIcon(png []byte) { setAppIcon(png) }
|
|||||||
// unknown. Safe to call before a window exists.
|
// unknown. Safe to call before a window exists.
|
||||||
func AccentColor() string { return accentColor() }
|
func AccentColor() string { return accentColor() }
|
||||||
|
|
||||||
|
// FileDialog describes a native open or save dialog.
|
||||||
|
type FileDialog struct {
|
||||||
|
Save bool // a save dialog; otherwise open one existing file
|
||||||
|
Title string // the prompt; "" for the system's
|
||||||
|
Directory string // the folder to start in; "" for the system's choice
|
||||||
|
Name string // save: the suggested file name
|
||||||
|
Extensions []string // allowed extensions without the dot ("pdf"); empty: any file
|
||||||
|
}
|
||||||
|
|
||||||
|
// ErrDialogOpen: a file dialog of this window is already open.
|
||||||
|
var ErrDialogOpen = errors.New("window: a file dialog is already open")
|
||||||
|
|
||||||
|
// fileDialoger is implemented by backends with native file dialogs.
|
||||||
|
type fileDialoger interface {
|
||||||
|
FileDialog(d FileDialog, done func(path string, err error))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShowFileDialog shows a native open or save dialog for the window (UI
|
||||||
|
// thread; one at a time). done runs on the UI thread with the chosen
|
||||||
|
// path, or "" and a nil error when the user cancelled. A save dialog
|
||||||
|
// has asked about replacing an existing file already; nothing is read
|
||||||
|
// or written here -- that is the program's choice.
|
||||||
|
func (w *Window) ShowFileDialog(d FileDialog, done func(path string, err error)) {
|
||||||
|
f, ok := w.b.(fileDialoger)
|
||||||
|
if !ok {
|
||||||
|
done("", errors.New("window: file dialogs not supported by "+w.name))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
f.FileDialog(d, done)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ChooseFile shows a file dialog from any goroutine and waits for the
|
||||||
|
// user: the chosen path, or "" and nil when cancelled. ctx ending (the
|
||||||
|
// request was dropped) stops the wait, not the dialog.
|
||||||
|
func (w *Window) ChooseFile(ctx context.Context, d FileDialog) (string, error) {
|
||||||
|
type result struct {
|
||||||
|
path string
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
ch := make(chan result, 1)
|
||||||
|
w.mu.Lock()
|
||||||
|
alive := w.alive
|
||||||
|
w.mu.Unlock()
|
||||||
|
if !alive {
|
||||||
|
return "", errors.New("window: destroyed")
|
||||||
|
}
|
||||||
|
w.Dispatch(func() {
|
||||||
|
w.ShowFileDialog(d, func(p string, err error) { ch <- result{p, err} })
|
||||||
|
})
|
||||||
|
select {
|
||||||
|
case r := <-ch:
|
||||||
|
return r.path, r.err
|
||||||
|
case <-ctx.Done():
|
||||||
|
return "", ctx.Err()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// DroppedDispatches counts Dispatch calls that arrived after Destroy.
|
// DroppedDispatches counts Dispatch calls that arrived after Destroy.
|
||||||
func (w *Window) DroppedDispatches() int {
|
func (w *Window) DroppedDispatches() int {
|
||||||
w.mu.Lock()
|
w.mu.Lock()
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ package window
|
|||||||
|
|
||||||
/*
|
/*
|
||||||
#cgo CFLAGS: -x objective-c -fobjc-arc
|
#cgo CFLAGS: -x objective-c -fobjc-arc
|
||||||
#cgo LDFLAGS: -framework Cocoa -framework WebKit
|
#cgo LDFLAGS: -framework Cocoa -framework WebKit -framework UniformTypeIdentifiers
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include "darwin.h"
|
#include "darwin.h"
|
||||||
*/
|
*/
|
||||||
@@ -16,6 +16,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"runtime"
|
"runtime"
|
||||||
"runtime/cgo"
|
"runtime/cgo"
|
||||||
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
)
|
)
|
||||||
@@ -35,6 +36,7 @@ type darwinBackend struct {
|
|||||||
mu sync.RWMutex // guards h against Destroy while a goroutine calls into ObjC
|
mu sync.RWMutex // guards h against Destroy while a goroutine calls into ObjC
|
||||||
|
|
||||||
snapDone func(error)
|
snapDone func(error)
|
||||||
|
fileDone func(path string, err error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// with runs f with the live host pointer, or not at all after Destroy.
|
// with runs f with the live host pointer, or not at all after Destroy.
|
||||||
@@ -298,3 +300,49 @@ func (t *darwinTask) Close(err error) {
|
|||||||
}
|
}
|
||||||
t.b.with(func(h unsafe.Pointer) { C.yt_task_finish(h, C.long(t.id), ce) })
|
t.b.with(func(h unsafe.Pointer) { C.yt_task_finish(h, C.long(t.id), ce) })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// FileDialog shows a native open or save panel as a sheet on the window;
|
||||||
|
// done runs on the UI thread.
|
||||||
|
func (b *darwinBackend) FileDialog(d FileDialog, done func(string, error)) {
|
||||||
|
b.mu.Lock()
|
||||||
|
if b.fileDone != nil {
|
||||||
|
b.mu.Unlock()
|
||||||
|
done("", ErrDialogOpen)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
b.fileDone = done
|
||||||
|
b.mu.Unlock()
|
||||||
|
save := 0
|
||||||
|
if d.Save {
|
||||||
|
save = 1
|
||||||
|
}
|
||||||
|
title, dir, name, types := cstr(d.Title), cstr(d.Directory), cstr(d.Name), cstr(strings.Join(d.Extensions, ","))
|
||||||
|
defer func() {
|
||||||
|
for _, c := range []*C.char{title, dir, name, types} {
|
||||||
|
C.free(unsafe.Pointer(c))
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
if !b.with(func(h unsafe.Pointer) { C.yt_file_dialog(h, C.int(save), title, dir, name, types) }) {
|
||||||
|
b.mu.Lock()
|
||||||
|
b.fileDone = nil
|
||||||
|
b.mu.Unlock()
|
||||||
|
done("", errUnavailable("file dialog: the window is gone"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//export ytGoFileDone
|
||||||
|
func ytGoFileDone(h C.uintptr_t, path *C.char) {
|
||||||
|
b := cgo.Handle(h).Value().(*darwinBackend)
|
||||||
|
b.mu.Lock()
|
||||||
|
done := b.fileDone
|
||||||
|
b.fileDone = nil
|
||||||
|
b.mu.Unlock()
|
||||||
|
if done == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if path == nil {
|
||||||
|
done("", nil)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
done(C.GoString(path), nil)
|
||||||
|
}
|
||||||
@@ -67,6 +67,7 @@ const (
|
|||||||
wmDestroy = 0x0002
|
wmDestroy = 0x0002
|
||||||
wmMove = 0x0003
|
wmMove = 0x0003
|
||||||
wmSize = 0x0005
|
wmSize = 0x0005
|
||||||
|
wmSetFocus = 0x0007
|
||||||
wmClose = 0x0010
|
wmClose = 0x0010
|
||||||
wmQuit = 0x0012
|
wmQuit = 0x0012
|
||||||
wmMoving = 0x0216
|
wmMoving = 0x0216
|
||||||
@@ -193,6 +194,7 @@ func newBackend(opt Options) (backend, string, string, error) {
|
|||||||
return nil, "", "", errors.New("window: WebView2 could not be created (is the Microsoft Edge WebView2 Runtime installed?)")
|
return nil, "", "", errors.New("window: WebView2 could not be created (is the Microsoft Edge WebView2 Runtime installed?)")
|
||||||
}
|
}
|
||||||
c.Resize()
|
c.Resize()
|
||||||
|
c.Focus() // the window got WM_SETFOCUS before the control existed
|
||||||
if s, err := c.GetSettings(); err == nil {
|
if s, err := c.GetSettings(); err == nil {
|
||||||
_ = s.PutAreDevToolsEnabled(opt.Debug)
|
_ = s.PutAreDevToolsEnabled(opt.Debug)
|
||||||
_ = s.PutAreDefaultContextMenusEnabled(opt.Debug)
|
_ = s.PutAreDefaultContextMenusEnabled(opt.Debug)
|
||||||
@@ -220,6 +222,14 @@ func wndproc(hwnd, msg, wp, lp uintptr) uintptr {
|
|||||||
_ = b.chromium.NotifyParentWindowPositionChanged()
|
_ = b.chromium.NotifyParentWindowPositionChanged()
|
||||||
}
|
}
|
||||||
b.reportFrame()
|
b.reportFrame()
|
||||||
|
case wmSetFocus:
|
||||||
|
// The keyboard focus belongs in the WebView2 control (its own
|
||||||
|
// child window): without this a page gets no keys after the
|
||||||
|
// start or after Alt-Tab until it is clicked.
|
||||||
|
if b.chromium != nil {
|
||||||
|
b.chromium.Focus()
|
||||||
|
}
|
||||||
|
return 0
|
||||||
case wmApp:
|
case wmApp:
|
||||||
b.runQueue()
|
b.runQueue()
|
||||||
return 0
|
return 0
|
||||||
|
|||||||
Reference in new issue
Block a user