feat: port the client to MyGo native UI (0.3.0)
Switch from Asuka to MyGo, keeping the API client and the feature set: - servers: saved servers, passwordless and password login, proxy, self-signed certificates, per-server device tokens (Keystore), connect form, instance list sheet with switch/disconnect - sessions: virtualized list, search, new session, rename/archive/delete, running indicator, event stream keeps it live - chat: pushed window with system back bar, streaming Markdown via ui/markdown, reasoning and tool rows with image previews, footer menu (read aloud via a Kotlin TTS plugin, copy, fork), user message menu (copy, revert, fork), context usage ring and detail sheet, attachments (photos/files via the document picker), permissions - release builds allow plain http:// LAN servers (Go's net/http dials directly, no cleartext manifest needed) - a local fork of MyGo (third_party/mygo) lowers the Android host's minSdk to 24 (Android 7.0); Go 1.27.4 via mise Version 0.3.0.
This commit is contained in:
1 parent
2fb4a8ea79
commit
6c0ee61750
2538 files changed
+675779
-4792
No files matched your search
+417
@@ -0,0 +1,417 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
// Backend is the Linux (GTK 3 + WebKitGTK) implementation of
|
||||
// platform.Backend.
|
||||
type Backend struct {
|
||||
h platform.AppHandler
|
||||
name string
|
||||
running bool
|
||||
|
||||
windows map[int]*window
|
||||
// flyouts are the flyouts that show on Wayland, in the order they
|
||||
// showed: each popup's parent is the one before or a toplevel.
|
||||
flyouts []*window
|
||||
byWebView map[ptr]*window
|
||||
// webViews are the web views under surfaces (webview.go), by id.
|
||||
webViews map[int]*window
|
||||
nextID int
|
||||
// frames are the window manager's frames seen last around a decorated
|
||||
// window in its normal state that the user cannot resize and one they
|
||||
// can, which windows that have not shown yet expect (see
|
||||
// window.frameExtents).
|
||||
frames [2]extents
|
||||
|
||||
appMenu *platform.Menu
|
||||
// stores are the web contexts of sessions (session.go); schemes,
|
||||
// below, the custom schemes registered on the default web context.
|
||||
stores []*dataStore
|
||||
// languages are those SetLanguages told, which the web context
|
||||
// takes as the first web view is made (webLanguages).
|
||||
languages []string
|
||||
webLanguages bool
|
||||
schemes map[string]bool
|
||||
signaled atomic.Bool
|
||||
quitLoops []ptr
|
||||
popups []ptr // context menus being shown
|
||||
modals []modal
|
||||
trays map[int]*tray
|
||||
nextTray int
|
||||
grabs map[int]grab // global shortcuts on X11
|
||||
portal portalShortcuts // global shortcuts elsewhere
|
||||
// Whether global shortcuts go through the portal under XWayland, once
|
||||
// asked (shortcutsThroughPortal).
|
||||
portalAsked, portalOnX11 bool
|
||||
themeHooks bool
|
||||
|
||||
// signalable is set once Init has bound GLib and made the callbacks.
|
||||
// A Signal before then, from a goroutine posting while the app starts,
|
||||
// leaves the queue to the Signal Init sends as it is set.
|
||||
signalable atomic.Bool
|
||||
// onX11 reports an X11 display, where windows have positions, and
|
||||
// wmName names its window manager.
|
||||
onX11 bool
|
||||
wmName func(screen ptr) ptr
|
||||
// x11ID returns a GdkWindow's X11 window (gdk_x11_window_get_xid).
|
||||
x11ID func(window ptr) ptr
|
||||
// compositorDecorates reports a Wayland compositor that decorates
|
||||
// windows itself, whose title bar shows no buttons of GTK's (titlebar.go).
|
||||
compositorDecorates bool
|
||||
// announceCSD tells a Wayland compositor that a window decorates
|
||||
// itself, so that it draws no title bar (gdk_wayland_window_announce_csd).
|
||||
announceCSD func(window ptr)
|
||||
// waylandSurface returns a GdkWindow's wl_surface on Wayland
|
||||
// (gdk_wayland_window_get_wl_surface; see damageGLPaint).
|
||||
waylandSurface func(window ptr) ptr
|
||||
|
||||
// What the launcher entry shows (Window.SetProgressBar, badges).
|
||||
launcher struct {
|
||||
badge string
|
||||
progress float64
|
||||
showing bool // progress
|
||||
}
|
||||
}
|
||||
|
||||
var theBackend *Backend
|
||||
|
||||
// New creates the Linux backend. Libraries are loaded by Init so that
|
||||
// programs still start (and report a clear error) on machines without GTK.
|
||||
func New() *Backend {
|
||||
return &Backend{
|
||||
windows: map[int]*window{},
|
||||
byWebView: map[ptr]*window{},
|
||||
webViews: map[int]*window{},
|
||||
schemes: map[string]bool{},
|
||||
trays: map[int]*tray{},
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Backend) Name() string { return "linux/webkitgtk" }
|
||||
|
||||
// windowManager reports an X11 window manager, which places windows once
|
||||
// they show; Wayland compositors do not tell where windows are.
|
||||
func (b *Backend) windowManager(win ptr) bool {
|
||||
return b.onX11 && goStr(b.wmName(gtkWidgetGetScreen(win))) != "unknown"
|
||||
}
|
||||
|
||||
// IsMainThread reports whether the caller runs on the thread the process
|
||||
// started with, whose thread id is the process id. Package mygo locks the
|
||||
// main goroutine to it, so this holds before Init too.
|
||||
func (b *Backend) IsMainThread() bool {
|
||||
return syscall.Gettid() == syscall.Getpid()
|
||||
}
|
||||
|
||||
func (b *Backend) Init(h platform.AppHandler, opts platform.AppOptions) error {
|
||||
b.h = h
|
||||
b.name = opts.Name
|
||||
theBackend = b
|
||||
if err := load(); err != nil {
|
||||
return err
|
||||
}
|
||||
if disableDMABUF(opts.DMABUFRenderer, os.Getenv, "/") {
|
||||
_ = os.Setenv("WEBKIT_DISABLE_DMABUF_RENDERER", "1")
|
||||
}
|
||||
// The program is its executable, by whichever name started it, as a
|
||||
// link in /usr/bin of another name (linux.command): GTK names the class
|
||||
// of the windows and the app id after the program, which the desktop
|
||||
// entry names too (StartupWMClass), and WebKitGTK the directories of
|
||||
// the pages' data. An app that named the program itself before Run
|
||||
// (g_set_prgname), as one does to give its windows the reverse-DNS ID
|
||||
// of its desktop entry, keeps its name: GLib leaves the name unset until
|
||||
// gtk_init_check takes argv[0], so a name here is the app's own.
|
||||
if exe, err := os.Executable(); err == nil && gGetPrgname() == 0 {
|
||||
gSetPrgname(cs(filepath.Base(exe)))
|
||||
}
|
||||
if !gtkInitCheck(0, 0) {
|
||||
return errors.New("mygo: cannot open display (is DISPLAY or WAYLAND_DISPLAY set?)")
|
||||
}
|
||||
// Before any page loads, so that the first already has the desktop's
|
||||
// prefers-color-scheme; Run then applies a source the app set.
|
||||
followSystemScheme(gtkSettingsGetDefault())
|
||||
var x11Type func() uintptr
|
||||
b.onX11 = bind(libGDK, &x11Type, "gdk_x11_display_get_type") && gTypeCheckInstanceIsA(gdkDisplayGetDefault(), x11Type()) &&
|
||||
bind(libGDK, &b.wmName, "gdk_x11_screen_get_window_manager_name")
|
||||
if b.onX11 {
|
||||
bind(libGDK, &b.x11ID, "gdk_x11_window_get_xid")
|
||||
}
|
||||
// GTK has the compositor's default decoration mode once the display is
|
||||
// open, and decides with it which windows it decorates.
|
||||
var waylandType func() uintptr
|
||||
var prefersSSD func(display ptr) bool
|
||||
onWayland := bind(libGDK, &waylandType, "gdk_wayland_display_get_type") &&
|
||||
gTypeCheckInstanceIsA(gdkDisplayGetDefault(), waylandType())
|
||||
b.compositorDecorates = onWayland &&
|
||||
bind(libGDK, &prefersSSD, "gdk_wayland_display_prefers_ssd") && prefersSSD(gdkDisplayGetDefault())
|
||||
if onWayland {
|
||||
bind(libGDK, &b.announceCSD, "gdk_wayland_window_announce_csd")
|
||||
bind(libGDK, &b.waylandSurface, "gdk_wayland_window_get_wl_surface")
|
||||
}
|
||||
initCallbacks()
|
||||
// Something may have posted while GLib was loading: dispatch it.
|
||||
b.signalable.Store(true)
|
||||
b.Signal()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *Backend) Run() error {
|
||||
b.running = true
|
||||
gIdleAddFull(0, readyCallback, 0, 0)
|
||||
gtkMain()
|
||||
b.running = false
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *Backend) Quit() {
|
||||
// Dialogs and popups run nested main loops, which gtk_main_quit does
|
||||
// not end: dismiss them so gtk_main can return.
|
||||
for _, m := range b.modals {
|
||||
if m.native {
|
||||
gtkNativeDialogHide(m.dialog)
|
||||
} else {
|
||||
gtkWidgetHide(m.dialog)
|
||||
}
|
||||
}
|
||||
for _, l := range b.quitLoops {
|
||||
gMainLoopQuit(l)
|
||||
}
|
||||
if b.running {
|
||||
gtkMainQuit()
|
||||
}
|
||||
}
|
||||
|
||||
// modal is a dialog running its own main loop.
|
||||
type modal struct {
|
||||
dialog ptr
|
||||
native bool // a GtkNativeDialog, else a GtkDialog
|
||||
}
|
||||
|
||||
// runDialog runs a GtkDialog (native false) or a GtkNativeDialog until it
|
||||
// is answered, or dismissed by Quit.
|
||||
func (b *Backend) runDialog(d ptr, native bool) int32 {
|
||||
b.modals = append(b.modals, modal{d, native})
|
||||
defer func() { b.modals = b.modals[:len(b.modals)-1] }()
|
||||
if native {
|
||||
return gtkNativeDialogRun(d)
|
||||
}
|
||||
return gtkDialogRun(d)
|
||||
}
|
||||
|
||||
func (b *Backend) Signal() {
|
||||
// Before Init is done, GLib may be bound and dispatchCallback still
|
||||
// unmade: g_idle_add_full rejects a nil function, and signaled would
|
||||
// stay set with nothing to clear it, so that no post ran again.
|
||||
if !b.signalable.Load() || !b.signaled.CompareAndSwap(false, true) {
|
||||
return
|
||||
}
|
||||
gIdleAddFull(0, dispatchCallback, 0, 0)
|
||||
}
|
||||
|
||||
func (b *Backend) Step() { gMainContextIteration(0, true) }
|
||||
|
||||
func (b *Backend) Wake() {
|
||||
if gMainContextWakeup != nil {
|
||||
gMainContextWakeup(0)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Backend) App() platform.AppController { return appController{b} }
|
||||
func (b *Backend) Dialogs() platform.Dialogs { return dialogs{b} }
|
||||
func (b *Backend) Clipboard() platform.Clipboard {
|
||||
return clipboard{}
|
||||
}
|
||||
func (b *Backend) Shell() platform.Shell { return shell{} }
|
||||
func (b *Backend) Screen() platform.Screen { return screen{} }
|
||||
func (b *Backend) Theme() platform.Theme { return theme{b} }
|
||||
func (b *Backend) Power() platform.Power { return power{b} }
|
||||
func (b *Backend) Secrets() platform.Secrets { return secrets{} }
|
||||
|
||||
// Callbacks are created once; purego callbacks are never freed.
|
||||
var (
|
||||
callbacksOnce sync.Once
|
||||
readyCallback ptr
|
||||
dispatchCallback ptr
|
||||
)
|
||||
|
||||
func initCallbacks() {
|
||||
callbacksOnce.Do(func() {
|
||||
readyCallback = purego.NewCallback(func(data ptr) int32 {
|
||||
theBackend.h.Ready()
|
||||
return 0 // G_SOURCE_REMOVE
|
||||
})
|
||||
dispatchCallback = purego.NewCallback(func(data ptr) int32 {
|
||||
theBackend.signaled.Store(false)
|
||||
theBackend.h.Dispatch()
|
||||
return 0
|
||||
})
|
||||
initWindowCallbacks()
|
||||
initFlyoutCallbacks()
|
||||
initSurfaceCallbacks()
|
||||
initDownloadCallbacks()
|
||||
initAuthCallbacks()
|
||||
initContextMenuCallbacks()
|
||||
initMenuCallbacks()
|
||||
initSystemCallbacks()
|
||||
initClipboardCallbacks()
|
||||
})
|
||||
}
|
||||
|
||||
type appController struct{ b *Backend }
|
||||
|
||||
func (a appController) SetActivationPolicy(string) {}
|
||||
|
||||
func (a appController) AllowForeground() {}
|
||||
|
||||
func (a appController) WithActivationToken(token string, fn func()) { withActivationToken(token, fn) }
|
||||
|
||||
func (a appController) Activate() {
|
||||
for _, w := range a.b.windows {
|
||||
if gtkWidgetGetVisible(w.win) {
|
||||
gtkWindowPresent(w.win)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a appController) Hide() {
|
||||
for _, w := range a.b.windows {
|
||||
gtkWidgetHide(w.win)
|
||||
}
|
||||
}
|
||||
|
||||
func (a appController) Unhide() {
|
||||
for _, w := range a.b.windows {
|
||||
gtkWidgetShow(w.win)
|
||||
}
|
||||
}
|
||||
|
||||
func (a appController) IsHidden() bool { return false }
|
||||
|
||||
// IsActive reports whether a window of the app has the keyboard.
|
||||
func (a appController) IsActive() bool {
|
||||
for _, w := range a.b.windows {
|
||||
if !w.closed && gtkWindowIsActive(w.win) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (a appController) SetBadge(label string) {
|
||||
a.b.launcher.badge = label
|
||||
a.b.updateLauncherEntry()
|
||||
}
|
||||
|
||||
func (a appController) Badge() string { return a.b.launcher.badge }
|
||||
|
||||
func (a appController) Bounce(critical bool) int {
|
||||
for _, w := range a.b.windows {
|
||||
gtkWindowSetUrgencyHint(w.win, true)
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
func (a appController) CancelBounce(int) {
|
||||
for _, w := range a.b.windows {
|
||||
gtkWindowSetUrgencyHint(w.win, false)
|
||||
}
|
||||
}
|
||||
|
||||
// SetDockMenu does nothing: there is no Dock.
|
||||
func (a appController) SetDockMenu(*platform.Menu) {}
|
||||
|
||||
func (a appController) SetDockIcon(png []byte) error {
|
||||
pix, err := pixbufFromPNG(png)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer gObjectUnref(pix)
|
||||
gtkWindowSetDefaultIcon(pix)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a appController) ShowAboutPanel(o platform.AboutPanelOptions) {
|
||||
d := gtkAboutDialogNew()
|
||||
gtkAboutDialogSetProgramName(d, cs(o.ApplicationName))
|
||||
version := o.ApplicationVersion
|
||||
if o.Version != "" {
|
||||
version += " (" + o.Version + ")"
|
||||
}
|
||||
gtkAboutDialogSetVersion(d, optCS(version))
|
||||
gtkAboutDialogSetCopyright(d, optCS(o.Copyright))
|
||||
gtkAboutDialogSetComments(d, optCS(o.Credits))
|
||||
a.b.runDialog(d, false)
|
||||
gtkWidgetDestroy(d)
|
||||
}
|
||||
|
||||
func (a appController) Package() (platform.PackageInfo, bool) { return platform.PackageInfo{}, false }
|
||||
|
||||
func (a appController) ClearBrowsingData(store platform.DataStore, types platform.SiteData, done func(error)) {
|
||||
// Web views of earlier runs kept their data on disk: WebKitGTK clears
|
||||
// it, loaded for that when no window has shown a web page yet.
|
||||
if webKit() != nil {
|
||||
done(nil) // no web view kept any data
|
||||
return
|
||||
}
|
||||
manager := webkitWebContextGetWebsiteDataManager(webContext(store))
|
||||
id := pending.add(func(source, res ptr) {
|
||||
var gerr ptr
|
||||
webkitWebsiteDataManagerClearFinish(source, res, &gerr)
|
||||
done(gErr(gerr))
|
||||
})
|
||||
webkitWebsiteDataManagerClear(manager, websiteDataTypes(types), 0, 0, cbAsyncReady, id)
|
||||
}
|
||||
|
||||
func (a appController) AddRecentDocument(path string) error {
|
||||
uri := fileURI(path)
|
||||
if uri == "" {
|
||||
return fmt.Errorf("mygo: cannot record %q as a recent document", path)
|
||||
}
|
||||
// GTK records the item asynchronously, under the application name, so
|
||||
// a failure to write the list is not reported here.
|
||||
if !gtkRecentManagerAddItem(gtkRecentManagerGetDefault(), cs(uri)) {
|
||||
return fmt.Errorf("mygo: the recent files list refused %q", path)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ClearRecentDocuments removes the items of the shared list that this
|
||||
// application registered, including those of earlier runs, and leaves the
|
||||
// other applications' items alone.
|
||||
func (a appController) ClearRecentDocuments() error {
|
||||
m := gtkRecentManagerGetDefault()
|
||||
name := gGetApplicationName()
|
||||
if name == 0 {
|
||||
return nil
|
||||
}
|
||||
var uris []string
|
||||
list := gtkRecentManagerGetItems(m)
|
||||
for node := list; node != 0; node = field[ptr](node, 8) {
|
||||
info := field[ptr](node, 0)
|
||||
if gtkRecentInfoHasApplication(info, name) {
|
||||
uris = append(uris, goStr(gtkRecentInfoGetURI(info)))
|
||||
}
|
||||
gtkRecentInfoUnref(info)
|
||||
}
|
||||
gListFree(list)
|
||||
for _, uri := range uris {
|
||||
gtkRecentManagerRemoveItem(m, cs(uri), 0)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (appController) SetJumpList(platform.JumpList) error { return nil }
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
var (
|
||||
appsOnce sync.Once
|
||||
|
||||
gAppInfoGetAll func() ptr
|
||||
gAppInfoShouldShow func(info ptr) bool
|
||||
gAppInfoGetDisplayName func(info ptr) ptr
|
||||
gAppInfoLaunch func(info, files, ctx ptr, gerr *ptr) bool
|
||||
gDesktopAppInfoGetFilename func(info ptr) ptr
|
||||
gFileInfoGetContentType func(info ptr) ptr
|
||||
gdkDisplayGetAppLaunchContext func(d ptr) ptr
|
||||
)
|
||||
|
||||
var (
|
||||
launchOnce sync.Once
|
||||
|
||||
gAppLaunchContextGetStartupID func(ctx, info, files ptr) ptr
|
||||
gAppLaunchContextLaunchFailed func(ctx ptr, id *byte)
|
||||
)
|
||||
|
||||
// loadLaunch binds what launches an application with the display's launch
|
||||
// context, apart from loadApps, which Shell's openers do without.
|
||||
func loadLaunch() {
|
||||
launchOnce.Do(func() {
|
||||
mustBind(libGDK, &gdkDisplayGetAppLaunchContext, "gdk_display_get_app_launch_context")
|
||||
mustBind(libGIO, &gAppLaunchContextGetStartupID, "g_app_launch_context_get_startup_notify_id")
|
||||
mustBind(libGIO, &gAppLaunchContextLaunchFailed, "g_app_launch_context_launch_failed")
|
||||
})
|
||||
}
|
||||
|
||||
func loadApps() {
|
||||
appsOnce.Do(func() {
|
||||
loadIcons() // g_desktop_app_info_new_from_filename
|
||||
mustBind(libGIO, &gAppInfoGetAll, "g_app_info_get_all")
|
||||
mustBind(libGIO, &gAppInfoShouldShow, "g_app_info_should_show")
|
||||
mustBind(libGIO, &gAppInfoGetDisplayName, "g_app_info_get_display_name")
|
||||
mustBind(libGIO, &gAppInfoLaunch, "g_app_info_launch")
|
||||
mustBind(libGIO, &gDesktopAppInfoGetFilename, "g_desktop_app_info_get_filename")
|
||||
mustBind(libGIO, &gFileInfoGetContentType, "g_file_info_get_content_type")
|
||||
loadLaunch()
|
||||
})
|
||||
}
|
||||
|
||||
// Applications lists the applications of the desktop entries that menus
|
||||
// show (g_app_info_should_show: not NoDisplay or Hidden, and meant for this
|
||||
// desktop), with their names in the user's language, their desktop file
|
||||
// IDs and the paths of their entries. GIO is thread-safe.
|
||||
func (b *Backend) Applications() ([]platform.Application, error) {
|
||||
loadApps()
|
||||
var apps []platform.Application
|
||||
list := gAppInfoGetAll()
|
||||
for l := list; l != 0; l = field[ptr](l, 8) { // GList: data, next, prev
|
||||
info := field[ptr](l, 0)
|
||||
if gAppInfoShouldShow(info) {
|
||||
if path := goStr(gDesktopAppInfoGetFilename(info)); path != "" {
|
||||
apps = append(apps, platform.Application{
|
||||
Name: goStr(gAppInfoGetDisplayName(info)),
|
||||
ID: goStr(gAppInfoGetID(info)),
|
||||
Path: path,
|
||||
})
|
||||
}
|
||||
}
|
||||
gObjectUnref(info)
|
||||
}
|
||||
gListFree(list)
|
||||
return apps, nil
|
||||
}
|
||||
|
||||
// OpenApplication launches the application of a desktop entry, with the
|
||||
// display's launch context, which gives it startup notification or the
|
||||
// activation token that lets it take the focus.
|
||||
func (shell) OpenApplication(path string) error {
|
||||
loadApps()
|
||||
info := gDesktopAppInfoNewFromFile(cs(path))
|
||||
if info == 0 {
|
||||
return fmt.Errorf("mygo: %q is not a desktop entry of an application", path)
|
||||
}
|
||||
defer gObjectUnref(info)
|
||||
ctx := gdkDisplayGetAppLaunchContext(gdkDisplayGetDefault())
|
||||
defer gObjectUnref(ctx)
|
||||
var gerr ptr
|
||||
if !gAppInfoLaunch(info, 0, ctx, &gerr) {
|
||||
return gErr(gerr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DefaultApp returns the application that opens url: the default handler
|
||||
// for its scheme (g_app_info_get_default_for_uri_scheme), or for a file://
|
||||
// URL or a path, the default handler for the file's content type
|
||||
// (g_app_info_get_default_for_type): the type GIO finds the file to be,
|
||||
// which knows a folder and a file without an extension, or where there is
|
||||
// no such file, the type its name tells (g_content_type_guess).
|
||||
func (shell) DefaultApp(rawURL string) (platform.Application, error) {
|
||||
loadApps()
|
||||
var scheme, path string
|
||||
if u, e := url.Parse(rawURL); e == nil && u.Scheme != "" {
|
||||
if u.Scheme == "file" {
|
||||
path = u.Path
|
||||
} else {
|
||||
scheme = u.Scheme
|
||||
}
|
||||
} else {
|
||||
path = rawURL
|
||||
}
|
||||
var info ptr
|
||||
if scheme != "" {
|
||||
info = gAppInfoGetDefaultForURIScheme(cs(scheme))
|
||||
} else if path != "" {
|
||||
ct := contentType(path)
|
||||
if ct == "" {
|
||||
return platform.Application{}, fmt.Errorf("mygo: no application found for %q", rawURL)
|
||||
}
|
||||
info = gAppInfoGetDefaultForType(cs(ct), false)
|
||||
} else {
|
||||
return platform.Application{}, fmt.Errorf("mygo: invalid URL %q", rawURL)
|
||||
}
|
||||
if info == 0 {
|
||||
return platform.Application{}, fmt.Errorf("mygo: no application found for %q", rawURL)
|
||||
}
|
||||
defer gObjectUnref(info)
|
||||
entry := goStr(gDesktopAppInfoGetFilename(info))
|
||||
id := goStr(gAppInfoGetID(info))
|
||||
if entry == "" {
|
||||
entry = id
|
||||
}
|
||||
return platform.Application{
|
||||
Name: goStr(gAppInfoGetDisplayName(info)),
|
||||
ID: id,
|
||||
Path: entry,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// contentType returns the content type of the file at path, as GIO finds
|
||||
// it (standard::content-type, from its name and its first bytes, and
|
||||
// inode/directory for a folder), or what its name tells where there is no
|
||||
// such file.
|
||||
func contentType(path string) string {
|
||||
f := gFileNewForPath(cs(path))
|
||||
info := gFileQueryInfo(f, cs("standard::content-type"), 0, 0, nil)
|
||||
gObjectUnref(f)
|
||||
if info != 0 {
|
||||
defer gObjectUnref(info)
|
||||
return goStr(gFileInfoGetContentType(info))
|
||||
}
|
||||
ct := gContentTypeGuess(cs(filepath.Base(path)), 0, 0, nil)
|
||||
defer gFree(ct)
|
||||
return goStr(ct)
|
||||
}
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"unsafe"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
// HTTP authentication and server certificates of pages: the web view's
|
||||
// authenticate and load-failed-with-tls-errors signals.
|
||||
|
||||
var (
|
||||
webkitAuthenticationRequestGetHost func(req ptr) ptr
|
||||
webkitAuthenticationRequestGetPort func(req ptr) uint32
|
||||
webkitAuthenticationRequestGetRealm func(req ptr) ptr
|
||||
webkitAuthenticationRequestGetScheme func(req ptr) int32
|
||||
webkitAuthenticationRequestIsForProxy func(req ptr) bool
|
||||
webkitAuthenticationRequestAuthenticate func(req, credential ptr)
|
||||
webkitAuthenticationRequestCancel func(req ptr)
|
||||
webkitCredentialNew func(user, password *byte, persistence int32) ptr
|
||||
webkitCredentialFree func(credential ptr)
|
||||
webkitWebViewGetContext func(wv ptr) ptr
|
||||
webkitWebContextAllowTLSCertificate func(ctx, cert ptr, host *byte)
|
||||
gByteArrayUnref func(a ptr)
|
||||
|
||||
cbAuthenticate, cbTLSErrors, cbTLSRetry ptr
|
||||
)
|
||||
|
||||
func bindAuth() {
|
||||
w := libWebKit
|
||||
mustBind(w, &webkitAuthenticationRequestGetHost, "webkit_authentication_request_get_host")
|
||||
mustBind(w, &webkitAuthenticationRequestGetPort, "webkit_authentication_request_get_port")
|
||||
mustBind(w, &webkitAuthenticationRequestGetRealm, "webkit_authentication_request_get_realm")
|
||||
mustBind(w, &webkitAuthenticationRequestGetScheme, "webkit_authentication_request_get_scheme")
|
||||
mustBind(w, &webkitAuthenticationRequestIsForProxy, "webkit_authentication_request_is_for_proxy")
|
||||
mustBind(w, &webkitAuthenticationRequestAuthenticate, "webkit_authentication_request_authenticate")
|
||||
mustBind(w, &webkitAuthenticationRequestCancel, "webkit_authentication_request_cancel")
|
||||
mustBind(w, &webkitCredentialNew, "webkit_credential_new")
|
||||
mustBind(w, &webkitCredentialFree, "webkit_credential_free")
|
||||
mustBind(w, &webkitWebViewGetContext, "webkit_web_view_get_context")
|
||||
mustBind(w, &webkitWebContextAllowTLSCertificate, "webkit_web_context_allow_tls_certificate_for_host")
|
||||
mustBind(libGLib, &gByteArrayUnref, "g_byte_array_unref")
|
||||
}
|
||||
|
||||
// authScheme names WebKitAuthenticationScheme's HTTP schemes, "" the
|
||||
// others, which get WebKit's default handling. Client certificates are
|
||||
// asked about apart, in clientCertificate.
|
||||
func authScheme(scheme int32) string {
|
||||
switch scheme {
|
||||
case 1, 2: // DEFAULT, HTTP_BASIC
|
||||
return "basic"
|
||||
case 3:
|
||||
return "digest"
|
||||
case 5:
|
||||
return "ntlm"
|
||||
case 6:
|
||||
return "negotiate"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// tlsErrors words the GTlsCertificateFlags a certificate failed with.
|
||||
var tlsErrors = []string{
|
||||
"the certificate's issuer is not known",
|
||||
"the certificate does not match the host",
|
||||
"the certificate is not valid yet",
|
||||
"the certificate expired",
|
||||
"the certificate was revoked",
|
||||
"the certificate's algorithm is insecure",
|
||||
"the certificate is invalid",
|
||||
}
|
||||
|
||||
func initAuthCallbacks() {
|
||||
b := func() *Backend { return theBackend }
|
||||
// Returning false leaves the request to WebKit: its sign-in dialog.
|
||||
cbAuthenticate = purego.NewCallback(func(web, req, data ptr) bool {
|
||||
w := b().window(data)
|
||||
if w == nil {
|
||||
return false
|
||||
}
|
||||
if webkitAuthenticationRequestGetScheme(req) == 7 { // CLIENT_CERTIFICATE_REQUESTED
|
||||
return w.clientCertificate(req)
|
||||
}
|
||||
scheme := authScheme(webkitAuthenticationRequestGetScheme(req))
|
||||
if scheme == "" {
|
||||
return false
|
||||
}
|
||||
resp := w.h.AuthRequested(platform.AuthRequest{
|
||||
Host: goStr(webkitAuthenticationRequestGetHost(req)),
|
||||
Port: int(webkitAuthenticationRequestGetPort(req)),
|
||||
Realm: goStr(webkitAuthenticationRequestGetRealm(req)),
|
||||
Scheme: scheme,
|
||||
IsProxy: webkitAuthenticationRequestIsForProxy(req),
|
||||
})
|
||||
switch {
|
||||
case resp.Default:
|
||||
return false
|
||||
case resp.Username == "" && resp.Password == "":
|
||||
// Without credentials: the server's refusal.
|
||||
webkitAuthenticationRequestAuthenticate(req, 0)
|
||||
default:
|
||||
const forSession = 1 // WEBKIT_CREDENTIAL_PERSISTENCE_FOR_SESSION
|
||||
c := webkitCredentialNew(cs(resp.Username), cs(resp.Password), forSession)
|
||||
webkitAuthenticationRequestAuthenticate(req, c)
|
||||
webkitCredentialFree(c)
|
||||
}
|
||||
return true
|
||||
})
|
||||
// Returning false fails the load (load-failed), as without a handler.
|
||||
cbTLSErrors = purego.NewCallback(func(web, uri, cert ptr, flags uint32, data ptr) bool {
|
||||
w := b().window(data)
|
||||
if w == nil || cert == 0 || !w.h.HandlesCertificateErrors() {
|
||||
return false
|
||||
}
|
||||
failing := goStr(uri)
|
||||
u, err := url.Parse(failing)
|
||||
if err != nil || u.Hostname() == "" {
|
||||
return false
|
||||
}
|
||||
e := platform.CertificateError{URL: failing, Host: u.Hostname(), Error: "the certificate does not verify"}
|
||||
for i, text := range tlsErrors {
|
||||
if flags&(1<<i) != 0 {
|
||||
e.Error = text
|
||||
break
|
||||
}
|
||||
}
|
||||
// GTlsCertificate's certificate property, a GByteArray: guint8
|
||||
// *data, guint len.
|
||||
var der ptr
|
||||
gObjectGetPtr(cert, cs("certificate"), unsafe.Pointer(&der), 0)
|
||||
if der != 0 {
|
||||
p := field[unsafe.Pointer](der, 0)
|
||||
e.Certificate = append([]byte(nil), unsafe.Slice((*byte)(p), field[uint32](der, 8))...)
|
||||
gByteArrayUnref(der)
|
||||
}
|
||||
if !w.h.CertificateError(e) {
|
||||
return false
|
||||
}
|
||||
webkitWebContextAllowTLSCertificate(webkitWebViewGetContext(web), cert, cs(e.Host))
|
||||
// WebKit finishes the failed load after the signal: load the page
|
||||
// again after that.
|
||||
w.tlsRetry = failing
|
||||
gIdleAddFull(0, cbTLSRetry, data, 0)
|
||||
return true
|
||||
})
|
||||
cbTLSRetry = purego.NewCallback(func(data ptr) int32 {
|
||||
if w := b().window(data); w != nil && w.tlsRetry != "" {
|
||||
uri := w.tlsRetry
|
||||
w.tlsRetry = ""
|
||||
w.LoadURL(uri)
|
||||
}
|
||||
return 0 // G_SOURCE_REMOVE
|
||||
})
|
||||
}
|
||||
|
||||
// clientCertificate asks the app about a server that asks for a client
|
||||
// certificate. WebKitGTK lists none to offer, so an answer can only
|
||||
// refuse; leaving the challenge alone (a nil handler, resp.Default) is
|
||||
// WebKit's own certificate chooser. Refusing is
|
||||
// webkit_authentication_request_cancel: the load ends as a
|
||||
// cancellation, which OnDidFailLoad does not report, as a stop does not.
|
||||
// Answering with a certificate of one's own takes
|
||||
// webkit_credential_new_for_certificate, which nothing offers it.
|
||||
func (w *window) clientCertificate(req ptr) bool {
|
||||
resp := w.h.ClientCertificateRequested(platform.ClientCertificateRequest{
|
||||
Host: goStr(webkitAuthenticationRequestGetHost(req)),
|
||||
Port: int(webkitAuthenticationRequestGetPort(req)),
|
||||
IsProxy: webkitAuthenticationRequestIsForProxy(req),
|
||||
})
|
||||
if resp.Default {
|
||||
return false
|
||||
}
|
||||
webkitAuthenticationRequestCancel(req)
|
||||
return true
|
||||
}
|
||||
|
||||
// connectAuth connects the signals of the web view's authentication.
|
||||
func (w *window) connectAuth(data ptr) {
|
||||
connect(w.web, "authenticate", cbAuthenticate, data)
|
||||
connect(w.web, "load-failed-with-tls-errors", cbTLSErrors, data)
|
||||
}
|
||||
+281
@@ -0,0 +1,281 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"slices"
|
||||
"strings"
|
||||
"unsafe"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
"github.com/egoist/mygo/transfer"
|
||||
)
|
||||
|
||||
var (
|
||||
gtkClipboardSetWithData func(ptr, unsafe.Pointer, uint32, ptr, ptr, ptr) bool
|
||||
gtkClipboardSetCanStore func(ptr, unsafe.Pointer, int32)
|
||||
gtkClipboardStore func(ptr)
|
||||
gdkClipboardPersistence func(ptr) bool
|
||||
cbClipboardGet, cbClipboardClear, cbClipboardOwner ptr
|
||||
gtkClipboardSources = map[ptr]*gtkClipboardSource{}
|
||||
gtkClipboardCurrent *gtkClipboardSource
|
||||
clipboardID ptr
|
||||
clipboardGeneration uint64
|
||||
clipboardConnected bool
|
||||
clipboardChanged func()
|
||||
)
|
||||
|
||||
type gtkClipboardSource struct {
|
||||
id ptr
|
||||
data transfer.Data
|
||||
concealed bool
|
||||
released func()
|
||||
}
|
||||
|
||||
// gtkPasswordManagerHint is KDE's target of confidential content, offered
|
||||
// next to the content with the value "secret", which Klipper and other
|
||||
// clipboard managers leave out of their histories.
|
||||
const gtkPasswordManagerHint = "x-kde-passwordManagerHint"
|
||||
|
||||
func initClipboardCallbacks() {
|
||||
// Clipboard-only apps may never create a surface or initialize its drag
|
||||
// adapter. Bind the shared selection primitives independently of it.
|
||||
mustBind(libGTK, >kSelectionDataSet, "gtk_selection_data_set")
|
||||
mustBind(libGTK, >kSelectionDataTarget, "gtk_selection_data_get_target")
|
||||
mustBind(libGTK, >kClipboardSetWithData, "gtk_clipboard_set_with_data")
|
||||
mustBind(libGTK, >kClipboardSetCanStore, "gtk_clipboard_set_can_store")
|
||||
mustBind(libGTK, >kClipboardStore, "gtk_clipboard_store")
|
||||
mustBind(libGDK, &gdkClipboardPersistence, "gdk_display_supports_clipboard_persistence")
|
||||
cbClipboardGet = purego.NewCallback(func(board, sel ptr, info uint32, data ptr) {
|
||||
s := gtkClipboardSources[data]
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
atom := gtkSelectionDataTarget(sel)
|
||||
name := takeStr(gdkAtomName(atom))
|
||||
if name == gtkPasswordManagerHint && s.concealed {
|
||||
secret := []byte("secret")
|
||||
gtkSelectionDataSet(sel, atom, 8, &secret[0], int32(len(secret)))
|
||||
return
|
||||
}
|
||||
f := gtkFormat(name)
|
||||
b, err := s.data.Read(f)
|
||||
if errors.Is(err, transfer.ErrFormat) && f == transfer.URIList {
|
||||
b, err = s.data.Read(transfer.FileList)
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if len(b) == 0 {
|
||||
b = []byte{0}
|
||||
gtkSelectionDataSet(sel, atom, 8, &b[0], 0)
|
||||
} else {
|
||||
gtkSelectionDataSet(sel, atom, 8, &b[0], int32(len(b)))
|
||||
}
|
||||
})
|
||||
cbClipboardClear = purego.NewCallback(func(board, data ptr) {
|
||||
if s := gtkClipboardSources[data]; s != nil {
|
||||
delete(gtkClipboardSources, data)
|
||||
if gtkClipboardCurrent == s {
|
||||
gtkClipboardCurrent = nil
|
||||
}
|
||||
s.data = transfer.Data{}
|
||||
s.release()
|
||||
}
|
||||
})
|
||||
cbClipboardOwner = purego.NewCallback(func(board, event, data ptr) {
|
||||
clipboardGeneration++
|
||||
if clipboardChanged != nil {
|
||||
clipboardChanged()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (clipboard) WatchChanges(changed func()) (func(), error) {
|
||||
// This signal is already needed to detect ownership changes during
|
||||
// reads. Removing the watch leaves that lightweight guard connected.
|
||||
clip()
|
||||
clipboardChanged = changed
|
||||
return func() { clipboardChanged = nil }, nil
|
||||
}
|
||||
|
||||
func (s *gtkClipboardSource) release() {
|
||||
if fn := s.released; fn != nil {
|
||||
s.released = nil
|
||||
fn()
|
||||
}
|
||||
}
|
||||
|
||||
func (c clipboard) WriteData(data transfer.Data, concealed bool, released func()) error {
|
||||
if len(data.Formats()) == 0 {
|
||||
c.Clear()
|
||||
if released != nil {
|
||||
released()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
clipboardID++
|
||||
s := >kClipboardSource{id: clipboardID, data: data, concealed: concealed, released: released}
|
||||
gtkClipboardSources[s.id] = s
|
||||
targets := gtkTargets(data.Formats())
|
||||
if concealed {
|
||||
targets = append(targets, gtkTargetEntry{target: cs(gtkPasswordManagerHint), info: uint32(len(targets))})
|
||||
}
|
||||
if !gtkClipboardSetWithData(clip(), unsafe.Pointer(&targets[0]), uint32(len(targets)), cbClipboardGet, cbClipboardClear, s.id) {
|
||||
delete(gtkClipboardSources, s.id)
|
||||
return errors.New("mygo: cannot own the clipboard selection")
|
||||
}
|
||||
gtkClipboardCurrent = s
|
||||
gtkClipboardSetCanStore(clip(), nil, 0)
|
||||
return nil
|
||||
}
|
||||
|
||||
func clipboardTargets() ([]transfer.Format, map[transfer.Format]ptr) {
|
||||
var atoms ptr
|
||||
var n int32
|
||||
out := []transfer.Format{}
|
||||
targets := map[transfer.Format]ptr{}
|
||||
if !gtkClipboardWaitForTargets(clip(), &atoms, &n) || atoms == 0 {
|
||||
return out, targets
|
||||
}
|
||||
defer gFree(atoms)
|
||||
if n < 0 || n > 4096 {
|
||||
return out, targets
|
||||
}
|
||||
for i := range int(n) {
|
||||
atom := field[ptr](atoms, uintptr(i)*unsafe.Sizeof(ptr(0)))
|
||||
name := takeStr(gdkAtomName(atom))
|
||||
if name == "" || strings.ContainsAny(name, "\x00\r\n") {
|
||||
continue
|
||||
}
|
||||
switch name {
|
||||
case "TARGETS", "MULTIPLE", "TIMESTAMP", "SAVE_TARGETS":
|
||||
continue
|
||||
}
|
||||
f := gtkFormat(name)
|
||||
if f == platform.DragSessionFormat {
|
||||
continue
|
||||
}
|
||||
if !slices.Contains(out, f) {
|
||||
out = append(out, f)
|
||||
}
|
||||
// Prefer canonical MIME targets over aliases where both are offered,
|
||||
// except for text: a bare text/plain is compound text, whose encoding
|
||||
// escapes characters outside Latin-1 as \uXXXX literals, so the UTF-8
|
||||
// targets always win.
|
||||
switch {
|
||||
case f == transfer.Text && (name == "UTF8_STRING" || name == "text/plain;charset=utf-8"):
|
||||
targets[f] = atom
|
||||
case targets[f] == 0 || (f != transfer.Text && name == string(f)):
|
||||
targets[f] = atom
|
||||
}
|
||||
if f == transfer.URIList && targets[transfer.FileList] == 0 {
|
||||
targets[transfer.FileList] = atom
|
||||
if !slices.Contains(out, transfer.FileList) {
|
||||
out = append(out, transfer.FileList)
|
||||
}
|
||||
}
|
||||
if strings.HasPrefix(name, "image/") && !slices.Contains(out, transfer.PNG) {
|
||||
out = append(out, transfer.PNG)
|
||||
}
|
||||
}
|
||||
return out, targets
|
||||
}
|
||||
|
||||
func (clipboard) Formats() []transfer.Format {
|
||||
formats, _ := clipboardTargets()
|
||||
if s := gtkClipboardCurrent; s != nil {
|
||||
return s.data.Formats()
|
||||
}
|
||||
return formats
|
||||
}
|
||||
|
||||
func (c clipboard) ReadData(formats []transfer.Format) (transfer.Data, error) {
|
||||
generation := clipboardGeneration
|
||||
offered, targets := clipboardTargets()
|
||||
if generation != clipboardGeneration {
|
||||
return transfer.Data{}, platform.ErrClipboardChanged
|
||||
}
|
||||
if s := gtkClipboardCurrent; s != nil {
|
||||
if len(formats) == 0 {
|
||||
formats = s.data.Formats()
|
||||
}
|
||||
d, err := s.data.Materialize(formats)
|
||||
if generation != clipboardGeneration || gtkClipboardCurrent != s {
|
||||
return transfer.Data{}, platform.ErrClipboardChanged
|
||||
}
|
||||
return d, err
|
||||
}
|
||||
if len(formats) == 0 {
|
||||
formats = offered
|
||||
if len(formats) == 0 {
|
||||
return transfer.Data{}, nil
|
||||
}
|
||||
}
|
||||
var reps []transfer.Representation
|
||||
for n, f := range formats {
|
||||
if slices.Contains(formats[:n], f) || !slices.Contains(offered, f) {
|
||||
continue
|
||||
}
|
||||
var b []byte
|
||||
if f == transfer.PNG && targets[f] == 0 {
|
||||
b = c.ReadImage()
|
||||
if b == nil {
|
||||
return transfer.Data{}, errors.New("mygo: cannot convert clipboard image")
|
||||
}
|
||||
} else {
|
||||
sd := gtkClipboardWaitForContents(clip(), targets[f])
|
||||
if sd == 0 {
|
||||
return transfer.Data{}, transfer.ErrFormat
|
||||
}
|
||||
length, p := gtkSelectionDataGetLength(sd), gtkSelectionDataGetData(sd)
|
||||
if length < 0 || length > 64<<20 || (length != 0 && p == 0) {
|
||||
gtkSelectionDataFree(sd)
|
||||
return transfer.Data{}, errors.New("mygo: invalid or oversized clipboard representation")
|
||||
}
|
||||
b = bytes.Clone(unsafe.Slice(*(**byte)(unsafe.Pointer(&p)), int(length)))
|
||||
gtkSelectionDataFree(sd)
|
||||
}
|
||||
if generation != clipboardGeneration {
|
||||
return transfer.Data{}, platform.ErrClipboardChanged
|
||||
}
|
||||
reps = append(reps, transfer.Bytes(f, b))
|
||||
}
|
||||
if len(reps) == 0 {
|
||||
return transfer.Data{}, transfer.ErrFormat
|
||||
}
|
||||
return transfer.New(transfer.NewItem(reps...)), nil
|
||||
}
|
||||
|
||||
func (clipboard) Flush() error {
|
||||
s := gtkClipboardCurrent
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
generation := clipboardGeneration
|
||||
d, err := s.data.Materialize(s.data.Formats())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if gtkClipboardCurrent != s || generation != clipboardGeneration {
|
||||
return platform.ErrClipboardChanged
|
||||
}
|
||||
// GTK still serves eager bytes if no clipboard manager is available;
|
||||
// provider closures and their resources can be released in either case.
|
||||
s.data = d
|
||||
s.release()
|
||||
if !gdkClipboardPersistence(gdkDisplayGetDefault()) {
|
||||
return platform.ErrClipboardPersistence
|
||||
}
|
||||
gtkClipboardStore(clip())
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c clipboard) Close() {
|
||||
if gtkClipboardCurrent != nil {
|
||||
c.Clear()
|
||||
}
|
||||
}
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
var (
|
||||
filterStoreNew func(path *byte) ptr
|
||||
filterStoreSave func(store ptr, identifier *byte, source, cancellable, cb, data ptr)
|
||||
filterStoreLoad, filterStoreRemove func(store ptr, identifier *byte, cancellable, cb, data ptr)
|
||||
filterStoreSaveFinish, filterStoreLoadFinish func(store, result ptr, err *ptr) ptr
|
||||
filterStoreRemoveFinish func(store, result ptr, err *ptr) int32
|
||||
filterStoreFetchIdentifiers func(store, cancellable, cb, data ptr)
|
||||
filterStoreFetchIdentifiersFinish func(store, result ptr) ptr
|
||||
userContentManagerAddFilter func(ucm, filter ptr)
|
||||
userContentManagerRemoveAllFilters func(ucm ptr)
|
||||
gBytesNew func(data *byte, size uintptr) ptr
|
||||
gBytesUnref func(bytes ptr)
|
||||
contentFiltersOnce sync.Once
|
||||
contentFilterStore ptr
|
||||
errContentFilters error
|
||||
)
|
||||
|
||||
// contentRules is the code of content rules, which LinkContentRules
|
||||
// links: the backend's methods are linked into every app, and only call
|
||||
// it.
|
||||
var contentRules struct {
|
||||
compile func(id, identifier, rules string, done func(any, error))
|
||||
set func(w *window, lists []any)
|
||||
}
|
||||
|
||||
// LinkContentRules links the code of content rules, when the app first
|
||||
// compiles rules.
|
||||
func LinkContentRules() {
|
||||
contentRules.compile, contentRules.set = compileContentRules, setContentRules
|
||||
}
|
||||
|
||||
func (a appController) CompileContentRules(id, identifier, rules string, done func(any, error)) {
|
||||
if contentRules.compile == nil {
|
||||
done(nil, platform.ErrUnsupported)
|
||||
return
|
||||
}
|
||||
contentRules.compile(id, identifier, rules, done)
|
||||
}
|
||||
|
||||
func (w *window) SetContentRules(lists []any) {
|
||||
if contentRules.set != nil {
|
||||
contentRules.set(w, lists)
|
||||
}
|
||||
}
|
||||
|
||||
// contentFilters binds WebKitGTK's content filters, from 2.24 on, and
|
||||
// opens the store that keeps compiled filters in the app's user data
|
||||
// directory, the first time the app compiles rules.
|
||||
func contentFilters() (ptr, error) {
|
||||
if err := webKit(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
contentFiltersOnce.Do(func() {
|
||||
w := libWebKit
|
||||
if !bind(w, &filterStoreNew, "webkit_user_content_filter_store_new") ||
|
||||
!bind(w, &filterStoreSave, "webkit_user_content_filter_store_save") ||
|
||||
!bind(w, &filterStoreSaveFinish, "webkit_user_content_filter_store_save_finish") ||
|
||||
!bind(w, &filterStoreLoad, "webkit_user_content_filter_store_load") ||
|
||||
!bind(w, &filterStoreLoadFinish, "webkit_user_content_filter_store_load_finish") ||
|
||||
!bind(w, &filterStoreRemove, "webkit_user_content_filter_store_remove") ||
|
||||
!bind(w, &filterStoreRemoveFinish, "webkit_user_content_filter_store_remove_finish") ||
|
||||
!bind(w, &filterStoreFetchIdentifiers, "webkit_user_content_filter_store_fetch_identifiers") ||
|
||||
!bind(w, &filterStoreFetchIdentifiersFinish, "webkit_user_content_filter_store_fetch_identifiers_finish") ||
|
||||
!bind(w, &userContentManagerAddFilter, "webkit_user_content_manager_add_filter") ||
|
||||
!bind(w, &userContentManagerRemoveAllFilters, "webkit_user_content_manager_remove_all_filters") ||
|
||||
!bind(libGLib, &gBytesNew, "g_bytes_new") || !bind(libGLib, &gBytesUnref, "g_bytes_unref") {
|
||||
errContentFilters = fmt.Errorf("content rules need WebKitGTK 2.24 or newer: %w", platform.ErrUnsupported)
|
||||
return
|
||||
}
|
||||
dir, err := os.UserConfigDir()
|
||||
if err != nil {
|
||||
errContentFilters = err
|
||||
return
|
||||
}
|
||||
dir = filepath.Join(dir, theBackend.name, "content-rules")
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
errContentFilters = err
|
||||
return
|
||||
}
|
||||
contentFilterStore = filterStoreNew(cs(dir))
|
||||
})
|
||||
return contentFilterStore, errContentFilters
|
||||
}
|
||||
|
||||
// compileContentRules loads the filter the store keeps as identifier,
|
||||
// else compiles rules into it and removes id's earlier filters. The
|
||||
// handle is the WebKitUserContentFilter, whose reference it keeps.
|
||||
func compileContentRules(id, identifier, rules string, done func(any, error)) {
|
||||
store, err := contentFilters()
|
||||
if err != nil {
|
||||
done(nil, err)
|
||||
return
|
||||
}
|
||||
save := func() {
|
||||
source := gBytesNew(unsafe.StringData(rules), uintptr(len(rules)))
|
||||
defer gBytesUnref(source)
|
||||
request := pending.add(func(_, result ptr) {
|
||||
var ge ptr
|
||||
filter := filterStoreSaveFinish(store, result, &ge)
|
||||
if err := gErr(ge); err != nil || filter == 0 {
|
||||
if err == nil {
|
||||
err = fmt.Errorf("WebKitGTK made no filter")
|
||||
}
|
||||
done(nil, err)
|
||||
return
|
||||
}
|
||||
removeStaleContentFilters(store, id, identifier)
|
||||
done(filter, nil)
|
||||
})
|
||||
// GBytes copies the rules.
|
||||
filterStoreSave(store, cs(identifier), source, 0, cbAsyncReady, request)
|
||||
}
|
||||
request := pending.add(func(_, result ptr) {
|
||||
var ge ptr
|
||||
filter := filterStoreLoadFinish(store, result, &ge)
|
||||
if gErr(ge) != nil || filter == 0 {
|
||||
save()
|
||||
return
|
||||
}
|
||||
done(filter, nil)
|
||||
})
|
||||
filterStoreLoad(store, cs(identifier), 0, cbAsyncReady, request)
|
||||
}
|
||||
|
||||
// removeStaleContentFilters removes the filters the store keeps for id
|
||||
// but current.
|
||||
func removeStaleContentFilters(store ptr, id, current string) {
|
||||
request := pending.add(func(_, result ptr) {
|
||||
list := filterStoreFetchIdentifiersFinish(store, result)
|
||||
if list == 0 {
|
||||
return
|
||||
}
|
||||
for i := uintptr(0); ; i++ {
|
||||
s := field[ptr](list, i*8)
|
||||
if s == 0 {
|
||||
break
|
||||
}
|
||||
if name := goStr(s); platform.StaleContentRules(id, current, name) {
|
||||
removed := pending.add(func(_, result ptr) {
|
||||
var ge ptr
|
||||
filterStoreRemoveFinish(store, result, &ge)
|
||||
gErr(ge)
|
||||
})
|
||||
filterStoreRemove(store, cs(name), 0, cbAsyncReady, removed)
|
||||
}
|
||||
}
|
||||
gStrfreev(list)
|
||||
})
|
||||
filterStoreFetchIdentifiers(store, 0, cbAsyncReady, request)
|
||||
}
|
||||
|
||||
// setContentRules replaces the filters of the window's content manager.
|
||||
func setContentRules(w *window, lists []any) {
|
||||
if w.ucm == 0 || w.closed || userContentManagerRemoveAllFilters == nil {
|
||||
return
|
||||
}
|
||||
userContentManagerRemoveAllFilters(w.ucm)
|
||||
for _, l := range lists {
|
||||
if filter, ok := l.(ptr); ok {
|
||||
userContentManagerAddFilter(w.ucm, filter)
|
||||
}
|
||||
}
|
||||
}
|
||||
+397
@@ -0,0 +1,397 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
// A page's context menu: the web view's context-menu signal hands over the
|
||||
// WebKitContextMenu it is about to show, which MyGo changes in place as the
|
||||
// core answers, and a hit test, which tells what was clicked but the
|
||||
// selection. The menu's items are WebKit's own, which do what they do
|
||||
// wherever MyGo puts them; the app's are items of a GAction each, which
|
||||
// WebKitGTK shows without a shortcut or an icon.
|
||||
|
||||
var (
|
||||
webkitContextMenuNew func() ptr
|
||||
webkitContextMenuGetItems func(menu ptr) ptr
|
||||
webkitContextMenuAppend func(menu, item ptr)
|
||||
webkitContextMenuRemoveAll func(menu ptr)
|
||||
webkitContextMenuItemIsSeparator func(item ptr) bool
|
||||
webkitContextMenuItemGetStockAction func(item ptr) int32
|
||||
webkitContextMenuItemGetSubmenu func(item ptr) ptr
|
||||
webkitContextMenuItemGetAction func(item ptr) ptr // GtkAction, which holds the label
|
||||
webkitContextMenuItemGetGAction func(item ptr) ptr
|
||||
webkitContextMenuItemNewFromStockActionWithLabel func(action int32, label *byte) ptr
|
||||
webkitContextMenuItemNewFromGAction func(action ptr, label *byte, target ptr) ptr
|
||||
webkitContextMenuItemNewSeparator func() ptr
|
||||
webkitContextMenuItemNewWithSubmenu func(label *byte, submenu ptr) ptr
|
||||
webkitHitTestResultGetContext func(hit ptr) uint32
|
||||
webkitHitTestResultGetLinkURI func(hit ptr) ptr
|
||||
webkitHitTestResultGetLinkLabel func(hit ptr) ptr
|
||||
webkitHitTestResultGetImageURI func(hit ptr) ptr
|
||||
webkitHitTestResultGetMediaURI func(hit ptr) ptr
|
||||
webkitContextMenuActionGetType func() uintptr
|
||||
gtkActionGetLabel func(action ptr) ptr
|
||||
gActionGetEnabled func(action ptr) bool
|
||||
gActionGetState func(action ptr) ptr
|
||||
gSimpleActionNew func(name *byte, parameter ptr) ptr
|
||||
gSimpleActionNewStateful func(name *byte, parameter, state ptr) ptr
|
||||
gSimpleActionSetEnabled func(action ptr, enabled bool)
|
||||
gSimpleActionSetState func(action, state ptr)
|
||||
gSimpleActionGetType func() uintptr
|
||||
gTypeClassRef func(typ uintptr) ptr
|
||||
gEnumGetValue func(class ptr, value int32) ptr
|
||||
|
||||
cbContextMenu, cbContextActivate ptr
|
||||
)
|
||||
|
||||
// bindContextMenus binds what a context menu with a listener needs, the
|
||||
// first time one opens, and reports whether WebKitGTK has it all
|
||||
// (webkit_context_menu_item_get_gaction is from 2.18).
|
||||
func bindContextMenus() bool {
|
||||
bindContextMenusOnce.Do(func() {
|
||||
w, o, i := libWebKit, libGObject, libGIO
|
||||
contextMenusBound = bind(w, &webkitContextMenuNew, "webkit_context_menu_new") &&
|
||||
bind(w, &webkitContextMenuGetItems, "webkit_context_menu_get_items") &&
|
||||
bind(w, &webkitContextMenuAppend, "webkit_context_menu_append") &&
|
||||
bind(w, &webkitContextMenuRemoveAll, "webkit_context_menu_remove_all") &&
|
||||
bind(w, &webkitContextMenuItemIsSeparator, "webkit_context_menu_item_is_separator") &&
|
||||
bind(w, &webkitContextMenuItemGetStockAction, "webkit_context_menu_item_get_stock_action") &&
|
||||
bind(w, &webkitContextMenuItemGetSubmenu, "webkit_context_menu_item_get_submenu") &&
|
||||
bind(w, &webkitContextMenuItemGetAction, "webkit_context_menu_item_get_action") &&
|
||||
bind(w, &webkitContextMenuItemGetGAction, "webkit_context_menu_item_get_gaction") &&
|
||||
bind(w, &webkitContextMenuItemNewFromStockActionWithLabel, "webkit_context_menu_item_new_from_stock_action_with_label") &&
|
||||
bind(w, &webkitContextMenuItemNewFromGAction, "webkit_context_menu_item_new_from_gaction") &&
|
||||
bind(w, &webkitContextMenuItemNewSeparator, "webkit_context_menu_item_new_separator") &&
|
||||
bind(w, &webkitContextMenuItemNewWithSubmenu, "webkit_context_menu_item_new_with_submenu") &&
|
||||
bind(w, &webkitHitTestResultGetContext, "webkit_hit_test_result_get_context") &&
|
||||
bind(w, &webkitHitTestResultGetLinkURI, "webkit_hit_test_result_get_link_uri") &&
|
||||
bind(w, &webkitHitTestResultGetLinkLabel, "webkit_hit_test_result_get_link_label") &&
|
||||
bind(w, &webkitHitTestResultGetImageURI, "webkit_hit_test_result_get_image_uri") &&
|
||||
bind(w, &webkitHitTestResultGetMediaURI, "webkit_hit_test_result_get_media_uri") &&
|
||||
bind(w, &webkitContextMenuActionGetType, "webkit_context_menu_action_get_type") &&
|
||||
bind(libGTK, >kActionGetLabel, "gtk_action_get_label") &&
|
||||
bind(i, &gActionGetEnabled, "g_action_get_enabled") &&
|
||||
bind(i, &gActionGetState, "g_action_get_state") &&
|
||||
bind(i, &gSimpleActionNew, "g_simple_action_new") &&
|
||||
bind(i, &gSimpleActionNewStateful, "g_simple_action_new_stateful") &&
|
||||
bind(i, &gSimpleActionSetEnabled, "g_simple_action_set_enabled") &&
|
||||
bind(i, &gSimpleActionSetState, "g_simple_action_set_state") &&
|
||||
bind(i, &gSimpleActionGetType, "g_simple_action_get_type") &&
|
||||
bind(o, &gTypeClassRef, "g_type_class_ref") &&
|
||||
bind(o, &gEnumGetValue, "g_enum_get_value")
|
||||
})
|
||||
return contextMenusBound
|
||||
}
|
||||
|
||||
var (
|
||||
bindContextMenusOnce sync.Once
|
||||
contextMenusBound bool
|
||||
)
|
||||
|
||||
// contextItem is an item of the app's in the context menu shown last:
|
||||
// its window, and its role.
|
||||
type contextItem struct {
|
||||
window int
|
||||
role string
|
||||
}
|
||||
|
||||
// contextItems are the app's items of the context menu shown last, by
|
||||
// their IDs, which the activation of their actions carries.
|
||||
var contextItems = map[int]contextItem{}
|
||||
|
||||
// initContextMenuCallbacks makes the callback of the context-menu signal,
|
||||
// which every web view connects: it calls the code of context menus,
|
||||
// which an app links as it first listens to them (LinkContextMenus).
|
||||
func initContextMenuCallbacks() {
|
||||
cbContextMenu = purego.NewCallback(func(web, menu, event, hit, data ptr) bool {
|
||||
// The listener the core heard of was added after the code was
|
||||
// linked: HandlesContextMenu, which takes the listeners' lock,
|
||||
// sees showContextMenu set.
|
||||
w := theBackend.window(data)
|
||||
if w == nil || !w.h.HandlesContextMenu() || showContextMenu == nil {
|
||||
return false
|
||||
}
|
||||
return showContextMenu(w, menu, event, hit)
|
||||
})
|
||||
}
|
||||
|
||||
// showContextMenu is (*window).contextMenu once LinkContextMenus linked it.
|
||||
var (
|
||||
showContextMenu func(w *window, menu, event, hit ptr) bool
|
||||
linkContextMenus sync.Once
|
||||
)
|
||||
|
||||
// LinkContextMenus links the code of pages' context menus, when the app
|
||||
// first listens to them (Page.OnContextMenu).
|
||||
func LinkContextMenus() {
|
||||
linkContextMenus.Do(func() {
|
||||
cbContextActivate = purego.NewCallback(func(action, parameter, data ptr) {
|
||||
id := int(data)
|
||||
c, ok := contextItems[id]
|
||||
w := theBackend.window(ptr(c.window))
|
||||
if !ok || w == nil {
|
||||
return
|
||||
}
|
||||
if cmd, ok := editCommands[c.role]; ok {
|
||||
webkitWebViewExecuteEditingCommand(w.web, cs(cmd))
|
||||
return
|
||||
}
|
||||
w.h.MenuItemClicked(id)
|
||||
})
|
||||
showContextMenu = (*window).contextMenu
|
||||
})
|
||||
}
|
||||
|
||||
// contextMenu asks the core about the menu WebKit is about to show, and
|
||||
// changes it as it answers. It returns true to show none.
|
||||
func (w *window) contextMenu(menu, event, hit ptr) bool {
|
||||
if !bindContextMenus() {
|
||||
return false
|
||||
}
|
||||
var natives []ptr
|
||||
defer func() {
|
||||
for _, item := range natives {
|
||||
gObjectUnref(item)
|
||||
}
|
||||
}()
|
||||
m := &platform.ContextMenu{Items: describeContextMenu(menu, &natives)}
|
||||
// A button's event (GdkEventButton: type 0, x 24, y 32), at a point of
|
||||
// the web view's own window; the menu key's has none.
|
||||
if event != 0 {
|
||||
if t := field[int32](event, 0); t >= 4 && t <= 7 { // GDK_BUTTON_PRESS to GDK_BUTTON_RELEASE
|
||||
m.Pointer, m.X, m.Y = true, field[float64](event, 24), field[float64](event, 32)
|
||||
}
|
||||
}
|
||||
if hit != 0 {
|
||||
const editable = 1 << 5 // WEBKIT_HIT_TEST_RESULT_CONTEXT_EDITABLE
|
||||
m.Target = platform.ContextMenuTarget{
|
||||
LinkURL: goStr(webkitHitTestResultGetLinkURI(hit)),
|
||||
LinkText: goStr(webkitHitTestResultGetLinkLabel(hit)),
|
||||
ImageURL: goStr(webkitHitTestResultGetImageURI(hit)),
|
||||
MediaURL: goStr(webkitHitTestResultGetMediaURI(hit)),
|
||||
Editable: webkitHitTestResultGetContext(hit)&editable != 0,
|
||||
}
|
||||
}
|
||||
resp := w.h.ContextMenu(m)
|
||||
switch {
|
||||
case resp.Default:
|
||||
return false
|
||||
case resp.Menu == nil:
|
||||
return true
|
||||
}
|
||||
clear(contextItems)
|
||||
w.fillContextMenu(menu, resp.Menu.Items, natives)
|
||||
return false
|
||||
}
|
||||
|
||||
// describeContextMenu describes WebKit's items of menu and its submenus,
|
||||
// numbering each, and takes a reference to it in natives, which keeps it
|
||||
// while the menus are emptied and filled again.
|
||||
func describeContextMenu(menu ptr, natives *[]ptr) []*platform.MenuItem {
|
||||
var items []*platform.MenuItem
|
||||
for node := webkitContextMenuGetItems(menu); node != 0; node = field[ptr](node, 8) {
|
||||
item := field[ptr](node, 0)
|
||||
*natives = append(*natives, gObjectRef(item))
|
||||
it := &platform.MenuItem{Native: len(*natives), Enabled: true, Visible: true}
|
||||
items = append(items, it)
|
||||
if webkitContextMenuItemIsSeparator(item) {
|
||||
it.Type = platform.MenuItemSeparator
|
||||
continue
|
||||
}
|
||||
it.Name = contextActionName(webkitContextMenuItemGetStockAction(item))
|
||||
if a := webkitContextMenuItemGetAction(item); a != 0 {
|
||||
it.Label = withoutMnemonic(goStr(gtkActionGetLabel(a)))
|
||||
}
|
||||
if a := webkitContextMenuItemGetGAction(item); a != 0 {
|
||||
it.Enabled = gActionGetEnabled(a)
|
||||
if state := gActionGetState(a); state != 0 {
|
||||
if goStr(gVariantGetTypeString(state)) == "b" {
|
||||
it.Type, it.Checked = platform.MenuItemCheckbox, gVariantGetBoolean(state)
|
||||
}
|
||||
gVariantUnref(state)
|
||||
}
|
||||
}
|
||||
if sub := webkitContextMenuItemGetSubmenu(item); sub != 0 {
|
||||
it.Type, it.Submenu = platform.MenuItemSubmenu, &platform.Menu{Items: describeContextMenu(sub, natives)}
|
||||
}
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
// fillContextMenu empties menu and fills it with items: WebKit's (natives,
|
||||
// by number), as the core changed them, and the app's.
|
||||
func (w *window) fillContextMenu(menu ptr, items []*platform.MenuItem, natives []ptr) {
|
||||
webkitContextMenuRemoveAll(menu)
|
||||
for _, it := range items {
|
||||
if !it.Visible {
|
||||
continue
|
||||
}
|
||||
var item ptr
|
||||
if it.Native != 0 && it.Native <= len(natives) {
|
||||
item = w.nativeContextItem(natives[it.Native-1], it, natives)
|
||||
} else {
|
||||
item = w.appContextItem(it, natives)
|
||||
}
|
||||
webkitContextMenuAppend(menu, item)
|
||||
}
|
||||
}
|
||||
|
||||
// nativeContextItem gives WebKit's item the state, the label and the
|
||||
// submenu the core gave it, and returns it, or the item that takes its
|
||||
// place.
|
||||
func (w *window) nativeContextItem(item ptr, it *platform.MenuItem, natives []ptr) ptr {
|
||||
if it.Type == platform.MenuItemSeparator {
|
||||
return item
|
||||
}
|
||||
sub := webkitContextMenuItemGetSubmenu(item)
|
||||
if sub != 0 && it.Submenu != nil {
|
||||
w.fillContextMenu(sub, it.Submenu.Items, natives)
|
||||
}
|
||||
label := ""
|
||||
if a := webkitContextMenuItemGetAction(item); a != 0 {
|
||||
label = withoutMnemonic(goStr(gtkActionGetLabel(a)))
|
||||
}
|
||||
// WebKitGTK renames no item: one of the same stock action, made with
|
||||
// the label, takes its place. Its custom items and submenus keep
|
||||
// theirs.
|
||||
const noAction, custom = 0, 10000
|
||||
if action := webkitContextMenuItemGetStockAction(item); it.Label != label && sub == 0 && action != noAction && action != custom {
|
||||
item = webkitContextMenuItemNewFromStockActionWithLabel(action, cs(mnemonicLabel(it.Label)))
|
||||
}
|
||||
if a := webkitContextMenuItemGetGAction(item); a != 0 && gTypeCheckInstanceIsA(a, gSimpleActionGetType()) {
|
||||
gSimpleActionSetEnabled(a, it.Enabled)
|
||||
if state := gActionGetState(a); state != 0 {
|
||||
if goStr(gVariantGetTypeString(state)) == "b" && gVariantGetBoolean(state) != it.Checked {
|
||||
gSimpleActionSetState(a, gVariantNewBoolean(it.Checked))
|
||||
}
|
||||
gVariantUnref(state)
|
||||
}
|
||||
}
|
||||
return item
|
||||
}
|
||||
|
||||
// appContextItem makes an item of the app's: a separator, a submenu, or
|
||||
// an item of an action of its own, whose activation the app hears.
|
||||
// WebKitGTK shows a checkbox's or a radio item's check from the action's
|
||||
// boolean state, as a check box.
|
||||
func (w *window) appContextItem(it *platform.MenuItem, natives []ptr) ptr {
|
||||
if it.Type == platform.MenuItemSeparator {
|
||||
return webkitContextMenuItemNewSeparator()
|
||||
}
|
||||
label := cs(mnemonicLabel(it.LabelWithSubtitle()))
|
||||
if it.Submenu != nil {
|
||||
sub := webkitContextMenuNew()
|
||||
w.fillContextMenu(sub, it.Submenu.Items, natives)
|
||||
return webkitContextMenuItemNewWithSubmenu(label, sub) // which takes sub
|
||||
}
|
||||
name := cs("mygo-" + strconv.Itoa(it.ID))
|
||||
var action ptr
|
||||
if it.Type == platform.MenuItemCheckbox || it.Type == platform.MenuItemRadio {
|
||||
action = gSimpleActionNewStateful(name, 0, gVariantNewBoolean(it.Checked))
|
||||
} else {
|
||||
action = gSimpleActionNew(name, 0)
|
||||
}
|
||||
gSimpleActionSetEnabled(action, it.Enabled)
|
||||
connect(action, "activate", cbContextActivate, ptr(it.ID))
|
||||
contextItems[it.ID] = contextItem{window: w.id, role: it.Role}
|
||||
item := webkitContextMenuItemNewFromGAction(action, label, 0)
|
||||
gObjectUnref(action) // the item holds it
|
||||
return item
|
||||
}
|
||||
|
||||
// contextActionName names a stock action: MyGo's name for the items other
|
||||
// platforms have, else the nick of WebKitContextMenuAction's value, as
|
||||
// "spelling-guess", "" for an item of no stock action.
|
||||
func contextActionName(action int32) string {
|
||||
switch action {
|
||||
case 0, 10000: // NO_ACTION, CUSTOM
|
||||
return ""
|
||||
case 1:
|
||||
return "openLink"
|
||||
case 2:
|
||||
return "openLinkInNewWindow"
|
||||
case 3:
|
||||
return "downloadLink"
|
||||
case 4:
|
||||
return "copyLink"
|
||||
case 5:
|
||||
return "openImageInNewWindow"
|
||||
case 6:
|
||||
return "downloadImage"
|
||||
case 7:
|
||||
return "copyImage"
|
||||
case 8:
|
||||
return "copyImageURL"
|
||||
case 9:
|
||||
return "openFrameInNewWindow"
|
||||
case 10:
|
||||
return "back"
|
||||
case 11:
|
||||
return "forward"
|
||||
case 13:
|
||||
return "reload"
|
||||
case 18:
|
||||
return "selectAll"
|
||||
case 21:
|
||||
return "spellingGuess"
|
||||
case 31:
|
||||
return "inspect"
|
||||
case 32, 33:
|
||||
return "openMediaInNewWindow"
|
||||
case 34, 35:
|
||||
return "copyMediaURL"
|
||||
case 36:
|
||||
return "mediaControls"
|
||||
case 37:
|
||||
return "mediaLoop"
|
||||
case 38:
|
||||
return "mediaFullScreen"
|
||||
case 42, 43:
|
||||
return "downloadMedia"
|
||||
case 44:
|
||||
return "emoji"
|
||||
case 45:
|
||||
return "pasteAndMatchStyle"
|
||||
}
|
||||
// The others' nicks are MyGo's names too where they have one: stop,
|
||||
// copy, cut, paste, delete.
|
||||
if contextActions == 0 {
|
||||
contextActions = gTypeClassRef(webkitContextMenuActionGetType()) // kept: the type is static
|
||||
}
|
||||
if v := gEnumGetValue(contextActions, action); v != 0 {
|
||||
return goStr(field[ptr](v, 16)) // GEnumValue: value, value_name, value_nick
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// contextActions is the GEnumClass of WebKitContextMenuAction.
|
||||
var contextActions ptr
|
||||
|
||||
// withoutMnemonic returns a GTK label without the underscore before its
|
||||
// mnemonic, as "_Copy" is "Copy".
|
||||
func withoutMnemonic(s string) string {
|
||||
if !strings.Contains(s, "_") {
|
||||
return s
|
||||
}
|
||||
var b strings.Builder
|
||||
for i := 0; i < len(s); i++ {
|
||||
if s[i] == '_' && i+1 < len(s) {
|
||||
i++
|
||||
}
|
||||
b.WriteByte(s[i])
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// mnemonicLabel is the label GTK shows as s, whose underscores would
|
||||
// mark mnemonics.
|
||||
func mnemonicLabel(s string) string { return strings.ReplaceAll(s, "_", "__") }
|
||||
+313
@@ -0,0 +1,313 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
var (
|
||||
soup3 bool
|
||||
cookieManager func(ptr) ptr
|
||||
cookieList func(ptr, ptr, ptr, ptr)
|
||||
cookieListFinish func(ptr, ptr, *ptr) ptr
|
||||
cookieGet func(ptr, *byte, ptr, ptr, ptr)
|
||||
cookieGetFinish func(ptr, ptr, *ptr) ptr
|
||||
cookieSetPersistentStorage func(ptr, *byte, int32)
|
||||
cookieAdd, cookieDelete func(ptr, ptr, ptr, ptr, ptr)
|
||||
cookieAddFinish, cookieDeleteFinish func(ptr, ptr, *ptr) int32
|
||||
soupCookieNew func(*byte, *byte, *byte, *byte, int32) ptr
|
||||
soupCookieFree func(ptr)
|
||||
soupCookieCopy func(ptr) ptr
|
||||
soupCookieName, soupCookieValue, soupCookieDomain, soupCookiePath, soupCookieExpires func(ptr) ptr
|
||||
soupCookieSecure, soupCookieHTTPOnly, soupCookieSameSite func(ptr) int32
|
||||
soupCookieSetSecure, soupCookieSetHTTPOnly, soupCookieSetSameSite func(ptr, int32)
|
||||
soupCookieSetExpires func(ptr, ptr)
|
||||
cookieDateNew func(int64) ptr
|
||||
cookieDateUnix func(ptr) int64
|
||||
cookieDateFree func(ptr)
|
||||
cookieListFree func(ptr)
|
||||
)
|
||||
|
||||
func bindCookies() {
|
||||
bind(libWebKit, &cookieManager, "webkit_web_context_get_cookie_manager")
|
||||
bind(libWebKit, &cookieList, "webkit_cookie_manager_get_all_cookies")
|
||||
bind(libWebKit, &cookieListFinish, "webkit_cookie_manager_get_all_cookies_finish")
|
||||
bind(libWebKit, &cookieGet, "webkit_cookie_manager_get_cookies")
|
||||
bind(libWebKit, &cookieGetFinish, "webkit_cookie_manager_get_cookies_finish")
|
||||
bind(libWebKit, &cookieSetPersistentStorage, "webkit_cookie_manager_set_persistent_storage")
|
||||
bind(libWebKit, &cookieAdd, "webkit_cookie_manager_add_cookie")
|
||||
bind(libWebKit, &cookieAddFinish, "webkit_cookie_manager_add_cookie_finish")
|
||||
bind(libWebKit, &cookieDelete, "webkit_cookie_manager_delete_cookie")
|
||||
bind(libWebKit, &cookieDeleteFinish, "webkit_cookie_manager_delete_cookie_finish")
|
||||
bind(libSoup, &soupCookieNew, "soup_cookie_new")
|
||||
bind(libSoup, &soupCookieFree, "soup_cookie_free")
|
||||
bind(libSoup, &soupCookieCopy, "soup_cookie_copy")
|
||||
bind(libSoup, &soupCookieName, "soup_cookie_get_name")
|
||||
bind(libSoup, &soupCookieValue, "soup_cookie_get_value")
|
||||
bind(libSoup, &soupCookieDomain, "soup_cookie_get_domain")
|
||||
bind(libSoup, &soupCookiePath, "soup_cookie_get_path")
|
||||
bind(libSoup, &soupCookieExpires, "soup_cookie_get_expires")
|
||||
bind(libSoup, &soupCookieSecure, "soup_cookie_get_secure")
|
||||
bind(libSoup, &soupCookieHTTPOnly, "soup_cookie_get_http_only")
|
||||
bind(libSoup, &soupCookieSameSite, "soup_cookie_get_same_site_policy")
|
||||
bind(libSoup, &soupCookieSetSecure, "soup_cookie_set_secure")
|
||||
bind(libSoup, &soupCookieSetHTTPOnly, "soup_cookie_set_http_only")
|
||||
bind(libSoup, &soupCookieSetSameSite, "soup_cookie_set_same_site_policy")
|
||||
bind(libSoup, &soupCookieSetExpires, "soup_cookie_set_expires")
|
||||
bind(libGLib, &cookieListFree, "g_list_free")
|
||||
// GLib 2.80 gdatetime.h and libsoup 2.74 soup-date.h: Soup3 uses
|
||||
// refcounted GDateTime, Soup2 copied SoupDate; time_t is 64-bit on our
|
||||
// supported Linux amd64/arm64 targets. Never share their pointer types.
|
||||
if soup3 {
|
||||
bind(libGLib, &cookieDateNew, "g_date_time_new_from_unix_utc")
|
||||
bind(libGLib, &cookieDateUnix, "g_date_time_to_unix")
|
||||
bind(libGLib, &cookieDateFree, "g_date_time_unref")
|
||||
} else {
|
||||
bind(libSoup, &cookieDateNew, "soup_date_new_from_time_t")
|
||||
bind(libSoup, &cookieDateUnix, "soup_date_to_time_t")
|
||||
bind(libSoup, &cookieDateFree, "soup_date_free")
|
||||
}
|
||||
}
|
||||
|
||||
var cookiesOnce sync.Once
|
||||
|
||||
// persistCookies keeps the cookies of the default web context in
|
||||
// cookies.sqlite of the app's user data directory, as macOS and Windows
|
||||
// keep theirs: WebKitGTK keeps them in memory unless told where to store
|
||||
// them. It runs on the main thread, the first time webKit is called there
|
||||
// with WebKitGTK loaded, before any web view loads a page.
|
||||
func persistCookies() {
|
||||
if cookieManager == nil || cookieSetPersistentStorage == nil {
|
||||
return
|
||||
}
|
||||
dir, err := os.UserConfigDir()
|
||||
if err != nil {
|
||||
log.Printf("mygo: cookies: %v", err)
|
||||
return
|
||||
}
|
||||
dir = filepath.Join(dir, theBackend.name)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
log.Printf("mygo: cookies: %v", err)
|
||||
return
|
||||
}
|
||||
const sqlite = 1 // WEBKIT_COOKIE_PERSISTENT_STORAGE_SQLITE
|
||||
cookieSetPersistentStorage(cookieManager(webkitWebContextGetDefault()), cs(filepath.Join(dir, "cookies.sqlite")), sqlite)
|
||||
}
|
||||
|
||||
// linuxCookieManager loads WebKitGTK and returns the cookie manager of
|
||||
// the web context of store, nil for the default one, when the functions
|
||||
// available checks, once bound, are there.
|
||||
func linuxCookieManager(store platform.DataStore, operation, needs string, available func() bool) (ptr, error) {
|
||||
if err := webKit(); err != nil {
|
||||
return 0, fmt.Errorf("mygo: cookies: %s: %w", operation, err)
|
||||
}
|
||||
if !available() || cookieManager == nil || soupCookieNew == nil || soupCookieFree == nil {
|
||||
return 0, fmt.Errorf("mygo: cookies: %s needs %s: %w", operation, needs, platform.ErrUnsupported)
|
||||
}
|
||||
return cookieManager(webContext(store)), nil
|
||||
}
|
||||
|
||||
// allCookies lists the cookies of the web context of store, those a
|
||||
// request to uri sends unless it is empty. done owns the SoupCookies and
|
||||
// frees them.
|
||||
func allCookies(store platform.DataStore, operation, uri string, done func([]ptr, error)) {
|
||||
manager, err := linuxCookieManager(store, operation, "WebKitGTK 2.42 or newer", func() bool {
|
||||
return cookieList != nil && cookieListFinish != nil && cookieGet != nil && cookieGetFinish != nil && cookieListFree != nil && soupCookieName != nil && soupCookieValue != nil && soupCookieDomain != nil && soupCookiePath != nil && soupCookieExpires != nil && soupCookieSecure != nil && soupCookieHTTPOnly != nil && cookieDateUnix != nil
|
||||
})
|
||||
if err != nil {
|
||||
done(nil, err)
|
||||
return
|
||||
}
|
||||
request := pending.add(func(source, result ptr) {
|
||||
var ge ptr
|
||||
finish := cookieListFinish
|
||||
if uri != "" {
|
||||
finish = cookieGetFinish
|
||||
}
|
||||
list := finish(source, result, &ge)
|
||||
// WebKit transfers the GList (data, next, prev) and its cookies.
|
||||
var cookies []ptr
|
||||
for node := list; node != 0; {
|
||||
entry := *(**[3]ptr)(unsafe.Pointer(&node))
|
||||
cookies = append(cookies, entry[0])
|
||||
node = entry[1]
|
||||
}
|
||||
cookieListFree(list)
|
||||
if err := gErr(ge); err != nil {
|
||||
freeCookies(cookies)
|
||||
done(nil, fmt.Errorf("mygo: cookies: %s: %w", operation, err))
|
||||
return
|
||||
}
|
||||
done(cookies, nil)
|
||||
})
|
||||
if uri != "" {
|
||||
cookieGet(manager, cs(uri), 0, cbAsyncReady, request)
|
||||
return
|
||||
}
|
||||
cookieList(manager, 0, cbAsyncReady, request)
|
||||
}
|
||||
|
||||
func freeCookies(cookies []ptr) {
|
||||
for _, c := range cookies {
|
||||
soupCookieFree(c)
|
||||
}
|
||||
}
|
||||
|
||||
func (a appController) ListCookies(store platform.DataStore, uri string, done func([]platform.Cookie, error)) {
|
||||
allCookies(store, "List", uri, func(cookies []ptr, err error) {
|
||||
if err != nil {
|
||||
done(nil, err)
|
||||
return
|
||||
}
|
||||
values := make([]platform.Cookie, 0, len(cookies))
|
||||
for _, c := range cookies {
|
||||
out := platform.Cookie{Name: goStr(soupCookieName(c)), Value: goStr(soupCookieValue(c)), Domain: goStr(soupCookieDomain(c)), Path: goStr(soupCookiePath(c)), Secure: soupCookieSecure(c) != 0, HTTPOnly: soupCookieHTTPOnly(c) != 0}
|
||||
if d := soupCookieExpires(c); d != 0 {
|
||||
out.Expires = time.Unix(cookieDateUnix(d), 0).UTC()
|
||||
}
|
||||
if soupCookieSameSite != nil {
|
||||
switch soupCookieSameSite(c) {
|
||||
case 0:
|
||||
out.SameSite = "none"
|
||||
case 1:
|
||||
out.SameSite = "lax"
|
||||
case 2:
|
||||
out.SameSite = "strict"
|
||||
}
|
||||
}
|
||||
values = append(values, out)
|
||||
}
|
||||
freeCookies(cookies)
|
||||
done(values, nil)
|
||||
})
|
||||
}
|
||||
|
||||
func (a appController) SetCookie(store platform.DataStore, c platform.Cookie, done func(error)) {
|
||||
manager, err := linuxCookieManager(store, "Set", "WebKitGTK 2.20 and libsoup 2.70 or newer", func() bool {
|
||||
return cookieAdd != nil && cookieAddFinish != nil && soupCookieSetSecure != nil && soupCookieSetHTTPOnly != nil && soupCookieSetSameSite != nil && soupCookieSetExpires != nil && cookieDateNew != nil && cookieDateFree != nil
|
||||
})
|
||||
if err != nil {
|
||||
done(err)
|
||||
return
|
||||
}
|
||||
native := soupCookieNew(cs(c.Name), cs(c.Value), cs(c.Domain), cs(c.Path), -1)
|
||||
if native == 0 {
|
||||
done(fmt.Errorf("mygo: cookies: Set could not construct SoupCookie"))
|
||||
return
|
||||
}
|
||||
var secure, httpOnly int32
|
||||
if c.Secure {
|
||||
secure = 1
|
||||
}
|
||||
if c.HTTPOnly {
|
||||
httpOnly = 1
|
||||
}
|
||||
soupCookieSetSecure(native, secure)
|
||||
soupCookieSetHTTPOnly(native, httpOnly)
|
||||
policy := int32(1)
|
||||
if c.SameSite == "none" {
|
||||
policy = 0
|
||||
} else if c.SameSite == "strict" {
|
||||
policy = 2
|
||||
}
|
||||
soupCookieSetSameSite(native, policy)
|
||||
if !c.Expires.IsZero() {
|
||||
date := cookieDateNew(c.Expires.Unix())
|
||||
if date == 0 {
|
||||
soupCookieFree(native)
|
||||
done(fmt.Errorf("mygo: cookies: Set cannot represent expiration"))
|
||||
return
|
||||
}
|
||||
soupCookieSetExpires(native, date)
|
||||
cookieDateFree(date)
|
||||
}
|
||||
request := pending.add(func(source, result ptr) {
|
||||
var ge ptr
|
||||
ok := cookieAddFinish(source, result, &ge)
|
||||
soupCookieFree(native)
|
||||
done(cookieFinishError("Set", ok, ge))
|
||||
})
|
||||
cookieAdd(manager, native, 0, cbAsyncReady, request)
|
||||
}
|
||||
|
||||
func (a appController) DeleteCookie(store platform.DataStore, key platform.CookieKey, done func(error)) {
|
||||
if err := webKit(); err != nil {
|
||||
done(fmt.Errorf("mygo: cookies: Delete: %w", err))
|
||||
return
|
||||
}
|
||||
if cookieDelete == nil || cookieDeleteFinish == nil || soupCookieCopy == nil {
|
||||
done(fmt.Errorf("mygo: cookies: Delete needs WebKitGTK 2.42 or newer: %w", platform.ErrUnsupported))
|
||||
return
|
||||
}
|
||||
// libsoup deletes the cookie of the same name, path and value: find
|
||||
// the stored one, whose value the key lacks.
|
||||
allCookies(store, "Delete", "", func(cookies []ptr, err error) {
|
||||
if err != nil {
|
||||
done(err)
|
||||
return
|
||||
}
|
||||
defer freeCookies(cookies)
|
||||
var match ptr
|
||||
for _, c := range cookies {
|
||||
if goStr(soupCookieName(c)) == key.Name && strings.ToLower(goStr(soupCookieDomain(c))) == key.Domain && goStr(soupCookiePath(c)) == key.Path {
|
||||
if match != 0 {
|
||||
done(fmt.Errorf("mygo: cookies: ambiguous cookie key"))
|
||||
return
|
||||
}
|
||||
match = c
|
||||
}
|
||||
}
|
||||
if match == 0 {
|
||||
done(nil)
|
||||
return
|
||||
}
|
||||
match = soupCookieCopy(match)
|
||||
request := pending.add(func(source, result ptr) {
|
||||
var ge ptr
|
||||
ok := cookieDeleteFinish(source, result, &ge)
|
||||
soupCookieFree(match)
|
||||
done(cookieFinishError("Delete", ok, ge))
|
||||
})
|
||||
cookieDelete(cookieManager(webContext(store)), match, 0, cbAsyncReady, request)
|
||||
})
|
||||
}
|
||||
|
||||
// ClearCookies clears the cookies of the website data of store's web
|
||||
// context, its other data kept.
|
||||
func (a appController) ClearCookies(store platform.DataStore, done func(error)) {
|
||||
if err := webKit(); err != nil {
|
||||
done(fmt.Errorf("mygo: cookies: Clear: %w", err))
|
||||
return
|
||||
}
|
||||
const cookies = 1 << 8 // WEBKIT_WEBSITE_DATA_COOKIES
|
||||
manager := webkitWebContextGetWebsiteDataManager(webContext(store))
|
||||
id := pending.add(func(source, res ptr) {
|
||||
var ge ptr
|
||||
var ok int32
|
||||
if webkitWebsiteDataManagerClearFinish(source, res, &ge) {
|
||||
ok = 1
|
||||
}
|
||||
done(cookieFinishError("Clear", ok, ge))
|
||||
})
|
||||
webkitWebsiteDataManagerClear(manager, cookies, 0, 0, cbAsyncReady, id)
|
||||
}
|
||||
|
||||
func cookieFinishError(operation string, ok int32, ge ptr) error {
|
||||
if err := gErr(ge); err != nil {
|
||||
return fmt.Errorf("mygo: cookies: %s: %w", operation, err)
|
||||
}
|
||||
if ok == 0 {
|
||||
return fmt.Errorf("mygo: cookies: %s failed", operation)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+255
@@ -0,0 +1,255 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// URL scheme handlers follow the XDG conventions: a desktop entry that
|
||||
// opens URLs with the app, hidden from menus, is made the default handler
|
||||
// of the scheme in the user's mimeapps.list, which is what `xdg-mime
|
||||
// default` does.
|
||||
|
||||
func (a appController) RegisterURLScheme(scheme, id, name string) error {
|
||||
dir, file := handlerEntry(id)
|
||||
path := filepath.Join(dir, file)
|
||||
schemes := handlerSchemes(path)
|
||||
if !slices.Contains(schemes, scheme) {
|
||||
schemes = append(schemes, scheme)
|
||||
}
|
||||
exe, err := executable()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeFileAtomic(path, []byte(handlerDesktopEntry(name, exe, schemes))); err != nil {
|
||||
return err
|
||||
}
|
||||
return setMimeDefault("x-scheme-handler/"+scheme, file, "")
|
||||
}
|
||||
|
||||
func (a appController) UnregisterURLScheme(scheme, id, name string) error {
|
||||
dir, file := handlerEntry(id)
|
||||
path := filepath.Join(dir, file)
|
||||
if schemes := handlerSchemes(path); slices.Contains(schemes, scheme) {
|
||||
schemes = slices.DeleteFunc(schemes, func(s string) bool { return s == scheme })
|
||||
var err error
|
||||
if len(schemes) == 0 {
|
||||
err = os.Remove(path)
|
||||
} else if exe, e := executable(); e != nil {
|
||||
err = e
|
||||
} else {
|
||||
err = writeFileAtomic(path, []byte(handlerDesktopEntry(name, exe, schemes)))
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return setMimeDefault("x-scheme-handler/"+scheme, "", file)
|
||||
}
|
||||
|
||||
func (a appController) IsURLSchemeRegistered(scheme, id, name string) bool {
|
||||
dir, file := handlerEntry(id)
|
||||
return slices.Contains(handlerSchemes(filepath.Join(dir, file)), scheme) &&
|
||||
mimeDefault("x-scheme-handler/"+scheme) == file
|
||||
}
|
||||
|
||||
func xdgDir(env, fallback string) string {
|
||||
if d := os.Getenv(env); filepath.IsAbs(d) {
|
||||
return d
|
||||
}
|
||||
home, _ := os.UserHomeDir()
|
||||
return filepath.Join(home, fallback)
|
||||
}
|
||||
|
||||
// handlerEntry returns where the desktop entry of the app's URL handler
|
||||
// goes, named after the app's identifier.
|
||||
func handlerEntry(id string) (dir, file string) {
|
||||
return filepath.Join(xdgDir("XDG_DATA_HOME", ".local/share"), "applications"), desktopName(id) + ".url-handler.desktop"
|
||||
}
|
||||
|
||||
// desktopName makes an application id usable in a desktop file name.
|
||||
func desktopName(id string) string {
|
||||
return strings.Map(func(r rune) rune {
|
||||
if r < 0x80 && (r == '.' || r == '-' || r == '_' || r >= '0' && r <= '9' || r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z') {
|
||||
return r
|
||||
}
|
||||
return '-'
|
||||
}, id)
|
||||
}
|
||||
|
||||
// executable is the file to run for a URL: the AppImage rather than the
|
||||
// directory it is mounted at while running.
|
||||
func executable() (string, error) {
|
||||
if p := os.Getenv("APPIMAGE"); p != "" {
|
||||
return p, nil
|
||||
}
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if real, err := filepath.EvalSymlinks(exe); err == nil {
|
||||
exe = real
|
||||
}
|
||||
return exe, nil
|
||||
}
|
||||
|
||||
func handlerDesktopEntry(name, exe string, schemes []string) string {
|
||||
var mime strings.Builder
|
||||
for _, s := range schemes {
|
||||
mime.WriteString("x-scheme-handler/" + s + ";")
|
||||
}
|
||||
return "[Desktop Entry]\nType=Application\nName=" + entryString(name) + "\nExec=" + execArg(exe) +
|
||||
" %u\nTerminal=false\nNoDisplay=true\nMimeType=" + mime.String() + "\n"
|
||||
}
|
||||
|
||||
// entryString drops what a desktop entry string value cannot hold.
|
||||
func entryString(s string) string {
|
||||
return strings.Map(func(r rune) rune {
|
||||
if r < ' ' {
|
||||
return -1
|
||||
}
|
||||
return r
|
||||
}, s)
|
||||
}
|
||||
|
||||
// execArg quotes an argument of the Exec key of a desktop entry: quoting
|
||||
// escapes ", `, $ and \ with a backslash, and backslashes are escaped again
|
||||
// because the value is a string; % is doubled for field codes.
|
||||
func execArg(arg string) string {
|
||||
var b strings.Builder
|
||||
b.WriteByte('"')
|
||||
for _, r := range arg {
|
||||
switch r {
|
||||
case '"', '`', '$':
|
||||
b.WriteString(`\\`)
|
||||
b.WriteRune(r)
|
||||
case '\\':
|
||||
b.WriteString(`\\\\`)
|
||||
case '%':
|
||||
b.WriteString("%%")
|
||||
default:
|
||||
b.WriteRune(r)
|
||||
}
|
||||
}
|
||||
b.WriteByte('"')
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// handlerSchemes returns the schemes a handler entry declares.
|
||||
func handlerSchemes(path string) []string {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var schemes []string
|
||||
for _, line := range strings.Split(string(data), "\n") {
|
||||
if v, ok := strings.CutPrefix(strings.TrimSpace(line), "MimeType="); ok {
|
||||
for _, m := range strings.Split(v, ";") {
|
||||
if s, ok := strings.CutPrefix(m, "x-scheme-handler/"); ok && s != "" {
|
||||
schemes = append(schemes, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return schemes
|
||||
}
|
||||
|
||||
const defaultApps = "[Default Applications]"
|
||||
|
||||
func mimeappsList() string {
|
||||
return filepath.Join(xdgDir("XDG_CONFIG_HOME", ".config"), "mimeapps.list")
|
||||
}
|
||||
|
||||
// mimeDefault returns the default application of a MIME type in the
|
||||
// user's mimeapps.list.
|
||||
func mimeDefault(mime string) string {
|
||||
data, _ := os.ReadFile(mimeappsList())
|
||||
section := ""
|
||||
for _, line := range strings.Split(string(data), "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if strings.HasPrefix(line, "[") {
|
||||
section = line
|
||||
continue
|
||||
}
|
||||
if k, v, ok := strings.Cut(line, "="); ok && section == defaultApps && strings.TrimSpace(k) == mime {
|
||||
first, _, _ := strings.Cut(strings.TrimSpace(v), ";")
|
||||
return first
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// setMimeDefault makes file the default application of a MIME type in the
|
||||
// user's mimeapps.list or, when file is "", removes the default if it is
|
||||
// owner.
|
||||
func setMimeDefault(mime, file, owner string) error {
|
||||
path := mimeappsList()
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||
return err
|
||||
}
|
||||
lines := strings.Split(strings.TrimRight(string(data), "\n"), "\n")
|
||||
if len(data) == 0 {
|
||||
lines = nil
|
||||
}
|
||||
start, end := -1, len(lines) // the Default Applications section
|
||||
for i, line := range lines {
|
||||
t := strings.TrimSpace(line)
|
||||
if start >= 0 && strings.HasPrefix(t, "[") {
|
||||
end = i
|
||||
break
|
||||
}
|
||||
if t == defaultApps {
|
||||
start = i
|
||||
}
|
||||
}
|
||||
entry := mime + "=" + file
|
||||
found := -1
|
||||
if start >= 0 {
|
||||
for i := start + 1; i < end; i++ {
|
||||
if k, _, ok := strings.Cut(lines[i], "="); ok && strings.TrimSpace(k) == mime {
|
||||
found = i
|
||||
}
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case file == "":
|
||||
if found < 0 {
|
||||
return nil
|
||||
}
|
||||
if _, v, _ := strings.Cut(lines[found], "="); strings.TrimSuffix(strings.TrimSpace(v), ";") != owner {
|
||||
return nil // another application's
|
||||
}
|
||||
lines = slices.Delete(lines, found, found+1)
|
||||
case found >= 0:
|
||||
lines[found] = entry
|
||||
case start >= 0:
|
||||
lines = slices.Insert(lines, start+1, entry)
|
||||
default:
|
||||
if len(lines) > 0 {
|
||||
lines = append(lines, "")
|
||||
}
|
||||
lines = append(lines, defaultApps, entry)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
return writeFileAtomic(path, []byte(strings.Join(lines, "\n")+"\n"))
|
||||
}
|
||||
|
||||
func writeFileAtomic(path string, data []byte) error {
|
||||
tmp := path + ".tmp"
|
||||
if err := os.WriteFile(tmp, data, 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp, path)
|
||||
}
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
type dialogs struct{ b *Backend }
|
||||
|
||||
const gtkResponseAccept = -3
|
||||
|
||||
func parentWindow(pw platform.Window) ptr {
|
||||
if w, ok := pw.(*window); ok && w != nil && !w.closed {
|
||||
return w.win
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// slistStrings reads and frees a GSList of GLib allocated strings.
|
||||
func slistStrings(list ptr) []string {
|
||||
var out []string
|
||||
for node := list; node != 0; node = field[ptr](node, 8) {
|
||||
out = append(out, takeStr(field[ptr](node, 0)))
|
||||
}
|
||||
if list != 0 {
|
||||
gSlistFree(list)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func setupChooser(fc ptr, defaultPath string, filters []platform.FileFilter, hidden, save bool) {
|
||||
gtkFileChooserSetShowHidden(fc, hidden)
|
||||
if defaultPath != "" {
|
||||
if st, err := os.Stat(defaultPath); err == nil && st.IsDir() {
|
||||
gtkFileChooserSetCurrentFolder(fc, cs(defaultPath))
|
||||
} else {
|
||||
gtkFileChooserSetCurrentFolder(fc, cs(filepath.Dir(defaultPath)))
|
||||
if save {
|
||||
gtkFileChooserSetCurrentName(fc, cs(filepath.Base(defaultPath)))
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, f := range filters {
|
||||
filter := gtkFileFilterNew()
|
||||
name := f.Name
|
||||
if name == "" {
|
||||
name = strings.Join(append(slices.Clip(f.Extensions), f.MIMETypes...), ", ")
|
||||
}
|
||||
gtkFileFilterSetName(filter, cs(name))
|
||||
for _, e := range f.Extensions {
|
||||
e = strings.TrimPrefix(e, ".")
|
||||
if e == "*" {
|
||||
gtkFileFilterAddPattern(filter, cs("*"))
|
||||
continue
|
||||
}
|
||||
gtkFileFilterAddPattern(filter, cs("*."+e))
|
||||
if up := strings.ToUpper(e); up != e {
|
||||
gtkFileFilterAddPattern(filter, cs("*."+up))
|
||||
}
|
||||
}
|
||||
// GTK matches "kind/*" itself, and the portal's file chooser
|
||||
// takes the types as they are.
|
||||
for _, m := range f.MIMETypes {
|
||||
gtkFileFilterAddMimeType(filter, cs(m))
|
||||
}
|
||||
gtkFileChooserAddFilter(fc, filter)
|
||||
}
|
||||
}
|
||||
|
||||
func (d dialogs) ShowOpenDialog(parent platform.Window, o *platform.OpenDialogOptions, cb func([]string, error)) {
|
||||
tx := platform.CurrentTexts()
|
||||
action := int32(0) // GTK_FILE_CHOOSER_ACTION_OPEN
|
||||
title := tx.Open
|
||||
if o.OpenDirectories {
|
||||
action, title = 2, tx.SelectFolder // SELECT_FOLDER
|
||||
}
|
||||
if o.Title != "" {
|
||||
title = o.Title
|
||||
}
|
||||
accept := "_" + tx.Open
|
||||
if o.ButtonLabel != "" {
|
||||
accept = o.ButtonLabel
|
||||
}
|
||||
fc := gtkFileChooserNativeNew(cs(title), parentWindow(parent), action, cs(accept), cs("_"+tx.Cancel))
|
||||
gtkFileChooserSetSelectMultiple(fc, o.Multiple)
|
||||
setupChooser(fc, o.DefaultPath, o.Filters, o.ShowHiddenFiles, false)
|
||||
var paths []string
|
||||
if d.b.runDialog(fc, true) == gtkResponseAccept {
|
||||
paths = slistStrings(gtkFileChooserGetFilenames(fc))
|
||||
}
|
||||
gObjectUnref(fc)
|
||||
cb(paths, nil)
|
||||
}
|
||||
|
||||
func (d dialogs) ShowSaveDialog(parent platform.Window, o *platform.SaveDialogOptions, cb func(string, error)) {
|
||||
tx := platform.CurrentTexts()
|
||||
title := o.Title
|
||||
if title == "" {
|
||||
title = tx.Save
|
||||
}
|
||||
accept := "_" + tx.Save
|
||||
if o.ButtonLabel != "" {
|
||||
accept = o.ButtonLabel
|
||||
}
|
||||
fc := gtkFileChooserNativeNew(cs(title), parentWindow(parent), 1, cs(accept), cs("_"+tx.Cancel)) // SAVE
|
||||
gtkFileChooserSetDoOverwriteConfirm(fc, true)
|
||||
setupChooser(fc, o.DefaultPath, o.Filters, o.ShowHiddenFiles, true)
|
||||
path := ""
|
||||
if d.b.runDialog(fc, true) == gtkResponseAccept {
|
||||
path = takeStr(gtkFileChooserGetFilename(fc))
|
||||
}
|
||||
gObjectUnref(fc)
|
||||
cb(path, nil)
|
||||
}
|
||||
|
||||
func (d dialogs) ShowMessageBox(parent platform.Window, o *platform.MessageBoxOptions, cb func(platform.MessageBoxResult, error)) {
|
||||
kind := int32(4) // GTK_MESSAGE_OTHER
|
||||
switch o.Type {
|
||||
case "info":
|
||||
kind = 0
|
||||
case "warning":
|
||||
kind = 1
|
||||
case "question":
|
||||
kind = 2
|
||||
case "error":
|
||||
kind = 3
|
||||
}
|
||||
message := o.Message
|
||||
if message == "" {
|
||||
message = o.Title
|
||||
}
|
||||
dlg := gtkMessageDialogNew(parentWindow(parent), 1|2, kind, 0, cs("%s"), cs(message)) // MODAL | DESTROY_WITH_PARENT, BUTTONS_NONE
|
||||
if o.Detail != "" {
|
||||
gtkMessageDialogFormatSecondaryText(dlg, cs("%s"), cs(o.Detail))
|
||||
}
|
||||
if o.Title != "" {
|
||||
gtkWindowSetTitle(dlg, cs(o.Title))
|
||||
}
|
||||
for i, label := range o.Buttons {
|
||||
btn := gtkDialogAddButton(dlg, cs(label), int32(i))
|
||||
if slices.Contains(o.DestructiveIDs, i) {
|
||||
gtkStyleContextAddClass(gtkWidgetGetStyleContext(btn), cs("destructive-action"))
|
||||
}
|
||||
}
|
||||
gtkDialogSetDefaultResponse(dlg, int32(o.DefaultID))
|
||||
var check ptr
|
||||
if o.CheckboxLabel != "" {
|
||||
check = gtkCheckButtonNewWithLabel(cs(o.CheckboxLabel))
|
||||
gtkToggleButtonSetActive(check, o.CheckboxChecked)
|
||||
gtkContainerAdd(gtkMessageDialogGetMessageArea(dlg), check)
|
||||
gtkWidgetShow(check)
|
||||
}
|
||||
resp := d.b.runDialog(dlg, false)
|
||||
res := platform.MessageBoxResult{Response: int(resp)}
|
||||
if resp < 0 {
|
||||
// Escape or the window's close button.
|
||||
res.Response = o.CancelID
|
||||
}
|
||||
if check != 0 {
|
||||
res.CheckboxChecked = gtkToggleButtonGetActive(check)
|
||||
}
|
||||
gtkWidgetDestroy(dlg)
|
||||
cb(res, nil)
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// WebKitGTK draws pages with its DMA-BUF renderer where it can, which
|
||||
// shows blank windows on NVIDIA's driver, in virtual machines and in
|
||||
// containers, so MyGo turns it off (WEBKIT_DISABLE_DMABUF_RENDERER=1)
|
||||
// before GTK starts. Pages then draw on the CPU, which scrolls long pages
|
||||
// at a fraction of the frame rate on hosts where the renderer works:
|
||||
// App.SetDMABUFRenderer leaves it on, everywhere ("on") or where the host
|
||||
// is known to draw with it ("auto").
|
||||
|
||||
// dmabufProbe is dmabufSafe, which LinkDMABUFProbe links: Init is linked
|
||||
// into every app, and only calls it.
|
||||
var dmabufProbe func(getenv func(string) string, root string) bool
|
||||
|
||||
// LinkDMABUFProbe links the code that looks at the host, when the app asks
|
||||
// for "auto".
|
||||
func LinkDMABUFProbe() { dmabufProbe = dmabufSafe }
|
||||
|
||||
// disableDMABUF reports whether Init sets WEBKIT_DISABLE_DMABUF_RENDERER=1
|
||||
// for the renderer the app asked for, with getenv the environment and root
|
||||
// the file system's root. The variable, set by the user, always wins.
|
||||
func disableDMABUF(renderer string, getenv func(string) string, root string) bool {
|
||||
if getenv("WEBKIT_DISABLE_DMABUF_RENDERER") != "" {
|
||||
return false
|
||||
}
|
||||
switch renderer {
|
||||
case "on":
|
||||
return false
|
||||
case "auto":
|
||||
return dmabufProbe == nil || !dmabufProbe(getenv, root)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// dmabufSafe reports a host where the DMA-BUF renderer draws: GTK will
|
||||
// open a Wayland display, and OpenGL runs on a GPU of Mesa's, outside
|
||||
// containers and virtual machines.
|
||||
func dmabufSafe(getenv func(string) string, root string) bool {
|
||||
// GDK_BACKEND lists the backends GTK tries, Wayland first by default.
|
||||
if b, _, _ := strings.Cut(getenv("GDK_BACKEND"), ","); b != "" && b != "*" && b != "wayland" {
|
||||
return false
|
||||
}
|
||||
// A display whose socket is gone (a stale variable) does not count.
|
||||
socket := getenv("WAYLAND_DISPLAY")
|
||||
if socket == "" {
|
||||
return false
|
||||
}
|
||||
if !filepath.IsAbs(socket) {
|
||||
dir := getenv("XDG_RUNTIME_DIR")
|
||||
if dir == "" {
|
||||
return false
|
||||
}
|
||||
socket = filepath.Join(dir, socket)
|
||||
}
|
||||
if fi, err := os.Stat(socket); err != nil || fi.Mode()&os.ModeSocket == 0 {
|
||||
return false
|
||||
}
|
||||
// Software OpenGL (llvmpipe).
|
||||
if s := strings.ToLower(getenv("LIBGL_ALWAYS_SOFTWARE")); s != "" && s != "0" && s != "false" {
|
||||
return false
|
||||
}
|
||||
gallium := getenv("GALLIUM_DRIVER")
|
||||
if gallium == "llvmpipe" || gallium == "softpipe" {
|
||||
return false
|
||||
}
|
||||
// NVIDIA's driver, a container, WSL.
|
||||
for _, p := range []string{"sys/module/nvidia", "proc/driver/nvidia/version", "dev/nvidiactl", ".dockerenv", "run/.containerenv", "dev/dxg"} {
|
||||
if _, err := os.Stat(filepath.Join(root, p)); err == nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
// A virtual machine, by its firmware's product or vendor (QEMU names
|
||||
// itself only as the vendor, Hyper-V's product is "Virtual Machine").
|
||||
for _, f := range []string{"product_name", "sys_vendor"} {
|
||||
b, _ := os.ReadFile(filepath.Join(root, "sys/class/dmi/id", f))
|
||||
s := strings.ToLower(string(b))
|
||||
for _, vm := range []string{"virtualbox", "vmware", "qemu", "kvm", "bochs", "parallels", "xen", "hyper-v", "virtual machine", "bhyve"} {
|
||||
if strings.Contains(s, vm) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
// A render node of a driver with 3D (glprobe.go).
|
||||
return gpuDeviceIn(root, gallium)
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDisableDMABUF(t *testing.T) {
|
||||
LinkDMABUFProbe()
|
||||
defer func() { dmabufProbe = nil }()
|
||||
// A Wayland desktop on Intel's GPU: its socket, and a render node of
|
||||
// i915.
|
||||
runtime := t.TempDir()
|
||||
l, err := net.Listen("unix", filepath.Join(runtime, "wayland-1"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer l.Close()
|
||||
os.WriteFile(filepath.Join(runtime, "wayland-stale"), nil, 0o644)
|
||||
host := func(t *testing.T, files map[string]string) string {
|
||||
root := t.TempDir()
|
||||
dev := filepath.Join(root, "sys", "class", "drm", "renderD128", "device")
|
||||
os.MkdirAll(dev, 0o755)
|
||||
if err := os.Symlink(filepath.Join("..", "..", "bus", "pci", "drivers", "i915"), filepath.Join(dev, "driver")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for name, content := range files {
|
||||
p := filepath.Join(root, name)
|
||||
os.MkdirAll(filepath.Dir(p), 0o755)
|
||||
os.WriteFile(p, []byte(content), 0o644)
|
||||
}
|
||||
return root
|
||||
}
|
||||
wayland := map[string]string{"WAYLAND_DISPLAY": "wayland-1", "XDG_RUNTIME_DIR": runtime}
|
||||
with := func(env map[string]string, more ...string) map[string]string {
|
||||
e := map[string]string{}
|
||||
for k, v := range env {
|
||||
e[k] = v
|
||||
}
|
||||
for i := 0; i < len(more); i += 2 {
|
||||
e[more[i]] = more[i+1]
|
||||
}
|
||||
return e
|
||||
}
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
renderer string
|
||||
env map[string]string
|
||||
files map[string]string
|
||||
disable bool
|
||||
}{
|
||||
{"default", "", wayland, nil, true},
|
||||
{"off", "off", wayland, nil, true},
|
||||
{"on", "on", nil, nil, false},
|
||||
{"the user's 1 with on", "on", with(nil, "WEBKIT_DISABLE_DMABUF_RENDERER", "1"), nil, false},
|
||||
{"the user's 0", "", with(nil, "WEBKIT_DISABLE_DMABUF_RENDERER", "0"), nil, false},
|
||||
{"the user's 0 with auto on NVIDIA", "auto", with(wayland, "WEBKIT_DISABLE_DMABUF_RENDERER", "0"), map[string]string{"sys/module/nvidia/version": ""}, false},
|
||||
{"auto on Wayland and Mesa", "auto", wayland, nil, false},
|
||||
{"auto with an absolute socket", "auto", map[string]string{"WAYLAND_DISPLAY": filepath.Join(runtime, "wayland-1")}, nil, false},
|
||||
{"auto with GDK_BACKEND=wayland,x11", "auto", with(wayland, "GDK_BACKEND", "wayland,x11"), nil, false},
|
||||
{"auto on X11", "auto", map[string]string{"DISPLAY": ":0"}, nil, true},
|
||||
{"auto with GDK_BACKEND=x11", "auto", with(wayland, "GDK_BACKEND", "x11"), nil, true},
|
||||
{"auto with a stale socket", "auto", with(wayland, "WAYLAND_DISPLAY", "wayland-stale"), nil, true},
|
||||
{"auto with a missing socket", "auto", with(wayland, "WAYLAND_DISPLAY", "wayland-9"), nil, true},
|
||||
{"auto without XDG_RUNTIME_DIR", "auto", with(wayland, "XDG_RUNTIME_DIR", ""), nil, true},
|
||||
{"auto with LIBGL_ALWAYS_SOFTWARE", "auto", with(wayland, "LIBGL_ALWAYS_SOFTWARE", "1"), nil, true},
|
||||
{"auto with LIBGL_ALWAYS_SOFTWARE=0", "auto", with(wayland, "LIBGL_ALWAYS_SOFTWARE", "0"), nil, false},
|
||||
{"auto with llvmpipe", "auto", with(wayland, "GALLIUM_DRIVER", "llvmpipe"), nil, true},
|
||||
{"auto on NVIDIA", "auto", wayland, map[string]string{"sys/module/nvidia/version": "550.0"}, true},
|
||||
{"auto on NVIDIA's proc", "auto", wayland, map[string]string{"proc/driver/nvidia/version": "NVRM"}, true},
|
||||
{"auto in Docker", "auto", wayland, map[string]string{".dockerenv": ""}, true},
|
||||
{"auto in Podman", "auto", wayland, map[string]string{"run/.containerenv": ""}, true},
|
||||
{"auto in WSL", "auto", wayland, map[string]string{"dev/dxg": ""}, true},
|
||||
{"auto in VirtualBox", "auto", wayland, map[string]string{"sys/class/dmi/id/product_name": "VirtualBox\n"}, true},
|
||||
{"auto in QEMU", "auto", wayland, map[string]string{"sys/class/dmi/id/product_name": "Standard PC (Q35 + ICH9, 2009)\n", "sys/class/dmi/id/sys_vendor": "QEMU\n"}, true},
|
||||
{"auto in Hyper-V", "auto", wayland, map[string]string{"sys/class/dmi/id/product_name": "Virtual Machine\n", "sys/class/dmi/id/sys_vendor": "Microsoft Corporation\n"}, true},
|
||||
{"auto on a laptop", "auto", wayland, map[string]string{"sys/class/dmi/id/product_name": "XPS 13 9380\n", "sys/class/dmi/id/sys_vendor": "Dell Inc.\n"}, false},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
root := host(t, c.files)
|
||||
getenv := func(k string) string { return c.env[k] }
|
||||
if got := disableDMABUF(c.renderer, getenv, root); got != c.disable {
|
||||
t.Errorf("disableDMABUF = %v, want %v", got, c.disable)
|
||||
}
|
||||
})
|
||||
}
|
||||
t.Run("auto without the probe", func(t *testing.T) {
|
||||
dmabufProbe = nil
|
||||
defer LinkDMABUFProbe()
|
||||
getenv := func(k string) string { return wayland[k] }
|
||||
if !disableDMABUF("auto", getenv, host(t, nil)) {
|
||||
t.Error("disableDMABUF = false, want true")
|
||||
}
|
||||
})
|
||||
t.Run("auto without a GPU", func(t *testing.T) {
|
||||
getenv := func(k string) string { return wayland[k] }
|
||||
if !disableDMABUF("auto", getenv, t.TempDir()) {
|
||||
t.Error("disableDMABUF = false, want true")
|
||||
}
|
||||
})
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"unsafe"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
)
|
||||
|
||||
// Downloads: the web context reports them, WebKit asks each where to save
|
||||
// the file, and reports how it ended ("failed" comes before "finished").
|
||||
|
||||
type download struct {
|
||||
w *window
|
||||
url, path string
|
||||
err error
|
||||
}
|
||||
|
||||
var (
|
||||
downloads = map[ptr]*download{}
|
||||
downloadsHooked bool
|
||||
|
||||
cbDownloadStarted, cbDownloadDestination, cbDownloadFinished, cbDownloadFailed ptr
|
||||
)
|
||||
|
||||
func initDownloadCallbacks() {
|
||||
cbDownloadStarted = purego.NewCallback(func(ctx, d, data ptr) {
|
||||
w := theBackend.byWebView[webkitDownloadGetWebView(d)]
|
||||
if w == nil {
|
||||
return
|
||||
}
|
||||
downloads[d] = &download{w: w, url: goStr(webkitURIRequestGetURI(webkitDownloadGetRequest(d)))}
|
||||
connect(d, "decide-destination", cbDownloadDestination, 0)
|
||||
connect(d, "finished", cbDownloadFinished, 0)
|
||||
connect(d, "failed", cbDownloadFailed, 0)
|
||||
})
|
||||
cbDownloadDestination = purego.NewCallback(func(d, suggested, data ptr) bool {
|
||||
dl := downloads[d]
|
||||
if dl == nil {
|
||||
return false
|
||||
}
|
||||
dl.path = dl.w.h.DownloadStarted(dl.url, goStr(suggested))
|
||||
if dl.path == "" {
|
||||
delete(downloads, d)
|
||||
webkitDownloadCancel(d)
|
||||
return true
|
||||
}
|
||||
webkitDownloadSetAllowOverwrite(d, true)
|
||||
webkitDownloadSetDestination(d, cs((&url.URL{Scheme: "file", Path: dl.path}).String()))
|
||||
return true
|
||||
})
|
||||
cbDownloadFailed = purego.NewCallback(func(d, gerr, data ptr) {
|
||||
if dl := downloads[d]; dl != nil {
|
||||
// GError: domain, code, then the message.
|
||||
dl.err = fmt.Errorf("mygo: download failed: %s", goStr(*(*ptr)(unsafe.Add(*(*unsafe.Pointer)(unsafe.Pointer(&gerr)), 8))))
|
||||
}
|
||||
})
|
||||
cbDownloadFinished = purego.NewCallback(func(d, data ptr) {
|
||||
if dl := downloads[d]; dl != nil {
|
||||
delete(downloads, d)
|
||||
dl.w.h.DownloadFinished(dl.url, dl.path, dl.err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// hookDownloads listens to the downloads of the web context once.
|
||||
func hookDownloads() {
|
||||
if !downloadsHooked {
|
||||
downloadsHooked = true
|
||||
connect(webkitWebContextGetDefault(), "download-started", cbDownloadStarted, 0)
|
||||
}
|
||||
}
|
||||
+1055
File diff suppressed because it is too large.
Load diff
+370
@@ -0,0 +1,370 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"sync"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
// A flyout of a tray icon has no parent, which a popup needs on Wayland,
|
||||
// and AppIndicator tells neither clicks nor where its icon is: it is an
|
||||
// undecorated toplevel utility window over the others, in the middle of
|
||||
// the primary display's work area where the platform lets apps place
|
||||
// windows, which a focusable one closes as it loses the keyboard.
|
||||
//
|
||||
// A flyout (WindowOptions.Flyout) is a GTK_WINDOW_POPUP window, as GTK's
|
||||
// menus and tooltips are: override-redirect on X11, where it goes exactly
|
||||
// where Flyout.Place puts it in the work area of a monitor, and an
|
||||
// xdg_popup of its parent on Wayland, which gdk_window_move_to_rect places
|
||||
// with the compositor's positioner and which follows the parent by
|
||||
// itself. Such a window gets the keyboard only through a grab: a
|
||||
// focusable flyout grabs the seat (gdk_seat_grab), which Wayland turns
|
||||
// into the popup's grab, and the application's input (gtk_grab_add), and
|
||||
// closes as GtkMenu does, on a press outside it, when the grab breaks, or
|
||||
// when the compositor dismisses the popup.
|
||||
//
|
||||
// A window modal to a flyout is transient for it, and GTK's modal grab
|
||||
// keeps the input from the flyout, which it keeps open: a tray's does
|
||||
// not close as it loses the keyboard to it, and on X11 a popup lets its
|
||||
// grab go while the window shows, and takes it again as it hides
|
||||
// (enterFlyout, leaveFlyout). On Wayland the compositor decides what
|
||||
// becomes of a popup whose grab another window takes.
|
||||
|
||||
var (
|
||||
flyoutOnce sync.Once
|
||||
|
||||
gtkWindowSetTypeHint func(w ptr, hint int32)
|
||||
gdkWindowSetTransientFor func(w, parent ptr)
|
||||
gdkWindowMoveToRect func(w ptr, r *gdkRectangle, rectAnchor, windowAnchor, hints, dx, dy int32)
|
||||
gdkSeatGrab func(seat, w ptr, caps int32, ownerEvents bool, cursor, event, prepare, data ptr) int32
|
||||
gdkSeatUngrab func(seat ptr)
|
||||
gtkGrabAdd, gtkGrabRemove func(w ptr)
|
||||
gtkWidgetTranslateCoordinates func(src, dst ptr, x, y int32, dx, dy *int32) bool
|
||||
gtkWindowSetAcceptFocus func(w ptr, v bool)
|
||||
gtkWindowSetSkipPagerHint func(w ptr, v bool)
|
||||
|
||||
cbFlyoutPress, cbFlyoutGrabBroken, cbFlyoutUnmap, cbFlyoutPrepare ptr
|
||||
)
|
||||
|
||||
const (
|
||||
typeHintUtility = 5 // GDK_WINDOW_TYPE_HINT_UTILITY
|
||||
typeHintPopupMenu = 9 // GDK_WINDOW_TYPE_HINT_POPUP_MENU
|
||||
anchorHintsAll = 63 // GDK_ANCHOR_FLIP | GDK_ANCHOR_SLIDE | GDK_ANCHOR_RESIZE
|
||||
seatCapabilityAll = 15 // GDK_SEAT_CAPABILITY_ALL
|
||||
)
|
||||
|
||||
func loadFlyouts() {
|
||||
flyoutOnce.Do(func() {
|
||||
t, d := libGTK, libGDK
|
||||
mustBind(t, >kWindowSetTypeHint, "gtk_window_set_type_hint")
|
||||
mustBind(d, &gdkWindowSetTransientFor, "gdk_window_set_transient_for")
|
||||
mustBind(d, &gdkWindowMoveToRect, "gdk_window_move_to_rect")
|
||||
mustBind(d, &gdkSeatGrab, "gdk_seat_grab")
|
||||
mustBind(d, &gdkSeatUngrab, "gdk_seat_ungrab")
|
||||
mustBind(t, >kGrabAdd, "gtk_grab_add")
|
||||
mustBind(t, >kGrabRemove, "gtk_grab_remove")
|
||||
mustBind(t, >kWidgetTranslateCoordinates, "gtk_widget_translate_coordinates")
|
||||
mustBind(t, >kWindowSetAcceptFocus, "gtk_window_set_accept_focus")
|
||||
mustBind(t, >kWindowSetSkipPagerHint, "gtk_window_set_skip_pager_hint")
|
||||
})
|
||||
}
|
||||
|
||||
// gravity returns the GdkGravity of a point of a rectangle.
|
||||
func gravity(g platform.Gravity) int32 { return int32((g.Y+1)*3 + g.X + 1 + 1) }
|
||||
|
||||
// initFlyout makes a new window a flyout, before it shows.
|
||||
func (w *window) initFlyout() {
|
||||
loadFlyouts()
|
||||
data := ptr(w.id)
|
||||
if w.opts.Flyout.Tray != nil {
|
||||
gtkWindowSetTypeHint(w.win, typeHintUtility)
|
||||
gtkWindowSetSkipPagerHint(w.win, true)
|
||||
w.SetAlwaysOnTop(true)
|
||||
gtkWindowSetAcceptFocus(w.win, w.opts.Flyout.Focusable)
|
||||
w.PlaceFlyout(*w.opts.Flyout, platform.Size{Width: w.opts.Width, Height: w.opts.Height})
|
||||
return
|
||||
}
|
||||
gtkWindowSetTypeHint(w.win, typeHintPopupMenu)
|
||||
// Its size is the one asked for, smaller than its content's natural
|
||||
// size too.
|
||||
gtkWindowSetResizable(w.win, true)
|
||||
connect(w.win, "button-press-event", cbFlyoutPress, data)
|
||||
connect(w.win, "grab-broken-event", cbFlyoutGrabBroken, data)
|
||||
connect(w.win, "unmap-event", cbFlyoutUnmap, data)
|
||||
w.PlaceFlyout(*w.opts.Flyout, platform.Size{Width: w.opts.Width, Height: w.opts.Height})
|
||||
}
|
||||
|
||||
// PlaceFlyout places a flyout next to its anchor: on X11 where Flyout.Place
|
||||
// puts it, on Wayland with the compositor's positioner, which takes a
|
||||
// popup's position as it maps: there a flyout that shows maps again,
|
||||
// unless only its parent moved, which the popup follows.
|
||||
func (w *window) PlaceFlyout(f platform.Flyout, size platform.Size) {
|
||||
if w.opts.Flyout != nil && f.Tray != nil && !w.closed {
|
||||
w.flyout, w.flyoutSize, w.placed = f, size, true
|
||||
r := platform.Centered(size, platform.PrimaryWorkArea(screen{}.Displays()))
|
||||
w.SetBounds(r) // Wayland compositors place it themselves
|
||||
return
|
||||
}
|
||||
p, ok := w.opts.Parent.(*window)
|
||||
if w.opts.Flyout == nil || w.closed || !ok || p.closed {
|
||||
return
|
||||
}
|
||||
same := w.placed && f == w.flyout && size == w.flyoutSize
|
||||
w.flyout, w.flyoutSize, w.placed = f, size, true
|
||||
if w.b.onX11 {
|
||||
x, y := p.contentOrigin()
|
||||
anchor := f.Anchor
|
||||
anchor.X += int(x)
|
||||
anchor.Y += int(y)
|
||||
r, _, _ := f.Place(anchor, size, platform.WorkAreaFor(anchor, screen{}.Displays()))
|
||||
w.SetBounds(r)
|
||||
return
|
||||
}
|
||||
visible := gtkWidgetGetVisible(w.win)
|
||||
if visible && same {
|
||||
return
|
||||
}
|
||||
if visible {
|
||||
w.hideFlyout()
|
||||
}
|
||||
gtkWindowResize(w.win, int32(size.Width), int32(size.Height))
|
||||
gtkWidgetRealize(w.win)
|
||||
gdkWin := gtkWidgetGetWindow(w.win)
|
||||
gdkWindowSetTransientFor(gdkWin, gtkWidgetGetWindow(p.win))
|
||||
// Relative to the parent's GdkWindow, its shadows included.
|
||||
var x, y int32
|
||||
gtkWidgetTranslateCoordinates(p.contentWidget(), p.win, int32(f.Anchor.X), int32(f.Anchor.Y), &x, &y)
|
||||
var alloc gdkRectangle
|
||||
gtkWidgetGetAllocation(p.win, &alloc)
|
||||
r := gdkRectangle{X: x + alloc.X, Y: y + alloc.Y, Width: int32(max(f.Anchor.Width, 1)), Height: int32(max(f.Anchor.Height, 1))}
|
||||
ra, wa, dx, dy := f.Gravities()
|
||||
gdkWindowMoveToRect(gdkWin, &r, gravity(ra), gravity(wa), anchorHintsAll, int32(dx), int32(dy))
|
||||
if visible {
|
||||
w.showFlyout(f.Focusable)
|
||||
}
|
||||
}
|
||||
|
||||
// contentOrigin returns where the window's content is on the screen.
|
||||
func (w *window) contentOrigin() (x, y int32) {
|
||||
gtkWidgetRealize(w.win)
|
||||
gdkWindowGetOrigin(gtkWidgetGetWindow(w.win), &x, &y)
|
||||
var dx, dy int32
|
||||
gtkWidgetTranslateCoordinates(w.contentWidget(), w.win, 0, 0, &dx, &dy)
|
||||
return x + dx, y + dy
|
||||
}
|
||||
|
||||
// showFlyout shows a flyout, which takes the keyboard when grab is set.
|
||||
func (w *window) showFlyout(grab bool) {
|
||||
if w.trayFlyout() {
|
||||
w.willShow()
|
||||
gtkWidgetShow(w.win)
|
||||
if grab {
|
||||
gtkWindowPresent(w.win)
|
||||
}
|
||||
return
|
||||
}
|
||||
if gtkWidgetGetVisible(w.win) {
|
||||
return
|
||||
}
|
||||
if !w.b.onX11 {
|
||||
p, _ := w.opts.Parent.(*window)
|
||||
w.b.closePopupsAbove(p)
|
||||
w.b.flyouts = append(w.b.flyouts, w)
|
||||
}
|
||||
w.willShow()
|
||||
if grab && w.modalChild() == nil {
|
||||
w.grab()
|
||||
}
|
||||
gtkWidgetShow(w.win) // unless the grab's prepare function did
|
||||
}
|
||||
|
||||
// grab grabs the seat and the application's input for a focusable flyout.
|
||||
func (w *window) grab() {
|
||||
gtkWidgetRealize(w.win)
|
||||
seat := gdkDisplayGetDefaultSeat(gdkDisplayGetDefault())
|
||||
// The prepare function shows the window: Wayland maps the popup with
|
||||
// the grab.
|
||||
if gdkSeatGrab(seat, gtkWidgetGetWindow(w.win), seatCapabilityAll, true, 0, 0, cbFlyoutPrepare, ptr(w.id)) == 0 {
|
||||
w.grabbed = true
|
||||
gtkGrabAdd(w.win)
|
||||
}
|
||||
}
|
||||
|
||||
// modalChild returns the window modal to w that shows, or nil.
|
||||
func (w *window) modalChild() *window {
|
||||
for _, x := range w.b.windows {
|
||||
if x.opts.Modal && x.opts.Parent == platform.Window(w) && !x.closed && gtkWidgetGetVisible(x.win) {
|
||||
return x
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// flyoutParent returns the flyout w is modal to, or nil.
|
||||
func (w *window) flyoutParent() *window {
|
||||
if p, ok := w.opts.Parent.(*window); ok && p != nil && w.opts.Modal && p.opts.Flyout != nil && !p.closed {
|
||||
return p
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// enterFlyout lets the grab of the popup w is modal to go as w shows, on
|
||||
// X11, so that w gets the input the grab would keep.
|
||||
func (w *window) enterFlyout() {
|
||||
if p := w.flyoutParent(); p != nil && w.b.onX11 {
|
||||
p.ungrab()
|
||||
}
|
||||
}
|
||||
|
||||
// leaveFlyout gives the popup w is modal to its grab back, on X11, once w
|
||||
// no longer shows.
|
||||
func (w *window) leaveFlyout() {
|
||||
p := w.flyoutParent()
|
||||
if p == nil || !w.b.onX11 || p.trayFlyout() || p.grabbed || !p.flyout.Focusable || !gtkWidgetGetVisible(p.win) || p.modalChild() != nil {
|
||||
return
|
||||
}
|
||||
p.grab()
|
||||
}
|
||||
|
||||
// hideFlyout hides a flyout, and lets the grab of a focusable one go.
|
||||
func (w *window) hideFlyout() {
|
||||
w.ungrab()
|
||||
w.b.flyouts = slices.DeleteFunc(w.b.flyouts, func(x *window) bool { return x == w })
|
||||
if gtkWidgetGetMapped(w.win) {
|
||||
w.unmaps++ // its unmap event comes later, maybe once it shows again
|
||||
}
|
||||
gtkWidgetHide(w.win)
|
||||
}
|
||||
|
||||
// closePopupsAbove closes the popups above parent, the topmost first, as
|
||||
// the user dismissing them, or hides those that stay: Wayland maps a popup
|
||||
// only over the topmost one, or a toplevel, which GDK makes its parent.
|
||||
func (b *Backend) closePopupsAbove(parent *window) {
|
||||
for len(b.flyouts) > 0 {
|
||||
top := b.flyouts[len(b.flyouts)-1]
|
||||
if top == parent {
|
||||
return
|
||||
}
|
||||
top.dismissFlyout(false)
|
||||
if !top.closed && gtkWidgetGetVisible(top.win) {
|
||||
top.hideFlyout()
|
||||
}
|
||||
b.flyouts = slices.DeleteFunc(b.flyouts, func(x *window) bool { return x == top })
|
||||
}
|
||||
}
|
||||
|
||||
// dismissFlyouts closes the focusable flyouts that grab the input as
|
||||
// another window takes the keyboard, which their grab keeps from it.
|
||||
func (b *Backend) dismissFlyouts(focus *window) {
|
||||
for _, w := range b.windows {
|
||||
if w.grabbed && w != focus {
|
||||
w.dismissFlyout(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *window) ungrab() {
|
||||
if !w.grabbed {
|
||||
return
|
||||
}
|
||||
w.grabbed = false
|
||||
gtkGrabRemove(w.win)
|
||||
gdkSeatUngrab(gdkDisplayGetDefaultSeat(gdkDisplayGetDefault()))
|
||||
}
|
||||
|
||||
// dismissFlyout closes a flyout the user dismissed, as the user closing
|
||||
// it. One that stays, but lost its popup (the compositor hid it, or its
|
||||
// grab broke), hides.
|
||||
func (w *window) dismissFlyout(lost bool) {
|
||||
if w.closed || w.dismissing {
|
||||
return
|
||||
}
|
||||
w.dismissing = true
|
||||
defer func() { w.dismissing = false }()
|
||||
if w.h.ShouldClose() {
|
||||
w.Close()
|
||||
} else if lost {
|
||||
w.hideFlyout()
|
||||
}
|
||||
}
|
||||
|
||||
func initFlyoutCallbacks() {
|
||||
b := func() *Backend { return theBackend }
|
||||
cbFlyoutPrepare = purego.NewCallback(func(seat, gdkWin, data ptr) {
|
||||
if w := b().window(data); w != nil {
|
||||
gtkWidgetShow(w.win)
|
||||
}
|
||||
})
|
||||
// The application's input goes to a focusable flyout while it grabs
|
||||
// it: a press elsewhere, in another window or, on X11, another app,
|
||||
// closes it.
|
||||
cbFlyoutPress = purego.NewCallback(func(widget, event, data ptr) bool {
|
||||
w := b().window(data)
|
||||
if w == nil || !w.grabbed {
|
||||
return false
|
||||
}
|
||||
// Where the press is on the screen, as GtkMenu looks: the event's
|
||||
// window and coordinates may be the grab's or the window's under
|
||||
// the pointer. GdkEventButton: x_root 64, y_root 72.
|
||||
var ox, oy int32
|
||||
gdkWindowGetOrigin(gtkWidgetGetWindow(w.win), &ox, &oy)
|
||||
var a gdkRectangle
|
||||
gtkWidgetGetAllocation(w.win, &a)
|
||||
x, y := field[float64](event, 64)-float64(ox), field[float64](event, 72)-float64(oy)
|
||||
if x >= 0 && y >= 0 && x < float64(a.Width) && y < float64(a.Height) {
|
||||
return false
|
||||
}
|
||||
w.dismissFlyout(false)
|
||||
return true
|
||||
})
|
||||
cbFlyoutGrabBroken = purego.NewCallback(func(widget, event, data ptr) bool {
|
||||
if w := b().window(data); w != nil && w.grabbed {
|
||||
w.grabbed = false
|
||||
gtkGrabRemove(w.win)
|
||||
w.dismissFlyout(true)
|
||||
}
|
||||
return false
|
||||
})
|
||||
// A Wayland compositor dismissed the popup, and GDK hid its window:
|
||||
// an unmap the backend's own hiding (unmaps) does not account for.
|
||||
// X11 servers do not dismiss popups.
|
||||
cbFlyoutUnmap = purego.NewCallback(func(widget, event, data ptr) bool {
|
||||
w := b().window(data)
|
||||
if w == nil || w.b.onX11 {
|
||||
return false
|
||||
}
|
||||
if w.unmaps > 0 {
|
||||
w.unmaps--
|
||||
return false
|
||||
}
|
||||
if gtkWidgetGetVisible(w.win) {
|
||||
w.ungrab()
|
||||
w.dismissFlyout(true)
|
||||
}
|
||||
return false
|
||||
})
|
||||
}
|
||||
|
||||
// trayFlyout reports a flyout of a tray icon.
|
||||
func (w *window) trayFlyout() bool { return w.opts.Flyout != nil && w.opts.Flyout.Tray != nil }
|
||||
|
||||
// grabbingChild reports whether a flyout of w's grabs the input, and so
|
||||
// has the keyboard w lost to it.
|
||||
func (w *window) grabbingChild() bool {
|
||||
for _, x := range w.b.windows {
|
||||
if !x.grabbed {
|
||||
continue
|
||||
}
|
||||
for p, _ := x.opts.Parent.(*window); p != nil; p, _ = p.opts.Parent.(*window) {
|
||||
if p == w {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
+264
@@ -0,0 +1,264 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"unsafe"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
)
|
||||
|
||||
// Surfaces draw with OpenGL only where it runs on a GPU. A software
|
||||
// renderer, such as Mesa's llvmpipe in virtual machines and in WSL, redraws
|
||||
// the whole window on the CPU every frame, many times the work of drawing
|
||||
// in memory, which redraws what changed; and once a window has a GL
|
||||
// context, GTK composites the window with OpenGL, so the choice is made
|
||||
// before: with a context GDK makes for a window that never shows, as the
|
||||
// surfaces' would be, as the first window of native UI is made.
|
||||
|
||||
var glProbe struct {
|
||||
device, probe sync.Once
|
||||
hasDevice, gpu bool
|
||||
}
|
||||
|
||||
// hasGPUDevice reports whether the system has a device OpenGL could draw
|
||||
// on (gpuDevice), saying once when it has none.
|
||||
func hasGPUDevice() bool {
|
||||
glProbe.device.Do(func() {
|
||||
if glProbe.hasDevice = gpuDevice(); glProbe.hasDevice {
|
||||
return
|
||||
}
|
||||
// Without a GPU device, GL draws on the CPU: the probe, whose
|
||||
// driver stays loaded, would cost memory to say so.
|
||||
if _, err := os.Stat("/dev/dxg"); err == nil {
|
||||
log.Print("mygo: native UI draws without the GPU: Mesa draws on the CPU in WSL, unless GALLIUM_DRIVER=d3d12")
|
||||
} else {
|
||||
log.Print("mygo: native UI draws without the GPU: there is none")
|
||||
}
|
||||
})
|
||||
return glProbe.hasDevice
|
||||
}
|
||||
|
||||
// gdkWindowAttr is GdkWindowAttr, for gdk_window_new.
|
||||
type gdkWindowAttr struct {
|
||||
title ptr
|
||||
eventMask int32
|
||||
x, y, width, height int32
|
||||
wclass int32
|
||||
visual ptr
|
||||
windowType int32
|
||||
cursor ptr
|
||||
wmclassName, wmclassClass ptr
|
||||
overrideRedirect int32
|
||||
typeHint int32
|
||||
}
|
||||
|
||||
// gpuGL reports whether GDK's OpenGL contexts draw on a GPU.
|
||||
func gpuGL() bool {
|
||||
glProbe.probe.Do(func() {
|
||||
// MYGO_GPU=1 draws with OpenGL wherever GDK makes a context, on
|
||||
// the CPU too: tests of the GL surface run so without a GPU. The
|
||||
// renderer calls OpenGL through libepoxy all the same, which GTK
|
||||
// links but a program run by an emulator, as box64, may not load:
|
||||
// a GtkGLArea would then show nothing.
|
||||
if os.Getenv("MYGO_GPU") == "1" {
|
||||
if _, err := purego.Dlopen("libepoxy.so.0", purego.RTLD_NOW|purego.RTLD_GLOBAL); err != nil {
|
||||
log.Print("mygo: native UI draws without the GPU: no libepoxy")
|
||||
return
|
||||
}
|
||||
glProbe.gpu = true
|
||||
return
|
||||
}
|
||||
if !hasGPUDevice() {
|
||||
return
|
||||
}
|
||||
renderer, err := probeGL()
|
||||
switch {
|
||||
case err != "":
|
||||
log.Printf("mygo: native UI draws without the GPU: %s", err)
|
||||
case softwareGL(renderer):
|
||||
log.Printf("mygo: native UI draws without the GPU: OpenGL draws on the CPU (%s)", renderer)
|
||||
default:
|
||||
glProbe.gpu = true
|
||||
}
|
||||
})
|
||||
return glProbe.gpu
|
||||
}
|
||||
|
||||
func softwareGL(renderer string) bool {
|
||||
r := strings.ToLower(renderer)
|
||||
for _, s := range []string{"llvmpipe", "softpipe", "swrast", "software rasterizer"} {
|
||||
if strings.Contains(r, s) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// gdkGL holds GDK's functions of OpenGL contexts.
|
||||
var gdkGL struct {
|
||||
once sync.Once
|
||||
ok bool
|
||||
createContext func(w ptr, err *ptr) ptr
|
||||
requireVersion func(c ptr, major, minor int32)
|
||||
setUseES func(c ptr, use int32) // GTK 3.22
|
||||
realize func(c ptr, err *ptr) bool
|
||||
}
|
||||
|
||||
func loadGDKGL() bool {
|
||||
g := &gdkGL
|
||||
g.once.Do(func() {
|
||||
g.ok = bind(libGDK, &g.createContext, "gdk_window_create_gl_context") &&
|
||||
bind(libGDK, &g.requireVersion, "gdk_gl_context_set_required_version") &&
|
||||
bind(libGDK, &g.realize, "gdk_gl_context_realize")
|
||||
if !bind(libGDK, &g.setUseES, "gdk_gl_context_set_use_es") {
|
||||
g.setUseES = nil
|
||||
}
|
||||
})
|
||||
return g.ok
|
||||
}
|
||||
|
||||
// glContext makes and realizes an OpenGL context for a GdkWindow, as the
|
||||
// renderer draws with: OpenGL 3.3, else OpenGL ES 3.0, for GPUs with
|
||||
// OpenGL ES alone and GDK_GL=gles. It returns the context, or the GError of
|
||||
// the last try.
|
||||
func glContext(win ptr) (ctx, gerr ptr) {
|
||||
if !loadGDKGL() {
|
||||
return 0, 0
|
||||
}
|
||||
g := &gdkGL
|
||||
for _, es := range []bool{false, true} {
|
||||
if es && g.setUseES == nil {
|
||||
break
|
||||
}
|
||||
if gerr != 0 {
|
||||
gErrorFree(gerr)
|
||||
gerr = 0
|
||||
}
|
||||
if ctx = g.createContext(win, &gerr); ctx == 0 {
|
||||
return 0, gerr
|
||||
}
|
||||
if es {
|
||||
g.setUseES(ctx, 1)
|
||||
g.requireVersion(ctx, 3, 0)
|
||||
} else {
|
||||
g.requireVersion(ctx, 3, 3)
|
||||
}
|
||||
if g.realize(ctx, &gerr) {
|
||||
return ctx, 0
|
||||
}
|
||||
gObjectUnref(ctx)
|
||||
}
|
||||
return 0, gerr
|
||||
}
|
||||
|
||||
// probeGL makes an OpenGL context as a GtkGLArea would and returns the name
|
||||
// of its renderer, or why there is none.
|
||||
func probeGL() (renderer, failure string) { return probeGLWith(nil) }
|
||||
|
||||
// probeGLWith is probeGL, which passes the window it makes to made, when
|
||||
// set, for tests to watch.
|
||||
func probeGLWith(made func(win ptr)) (renderer, failure string) {
|
||||
var (
|
||||
windowNew func(parent ptr, attr *gdkWindowAttr, mask int32) ptr
|
||||
windowDestroy func(w ptr)
|
||||
makeCurrent func(c ptr)
|
||||
clearCurrent func()
|
||||
getString func(name uint32) ptr
|
||||
haveSyms = loadGDKGL()
|
||||
)
|
||||
for name, fn := range map[string]any{
|
||||
"gdk_window_new": &windowNew, "gdk_window_destroy": &windowDestroy,
|
||||
"gdk_gl_context_make_current": &makeCurrent, "gdk_gl_context_clear_current": &clearCurrent,
|
||||
} {
|
||||
haveSyms = bind(libGDK, fn, name) && haveSyms
|
||||
}
|
||||
if !haveSyms {
|
||||
return "", "GDK has no OpenGL"
|
||||
}
|
||||
epoxy, err := purego.Dlopen("libepoxy.so.0", purego.RTLD_NOW|purego.RTLD_GLOBAL)
|
||||
if err != nil {
|
||||
return "", "no libepoxy"
|
||||
}
|
||||
// libepoxy exports a pointer to each GL function.
|
||||
sym, err := purego.Dlsym(epoxy, "epoxy_glGetString")
|
||||
if err != nil || sym == 0 {
|
||||
return "", "no glGetString"
|
||||
}
|
||||
purego.RegisterFunc(&getString, **(**uintptr)(unsafe.Pointer(&sym)))
|
||||
|
||||
const inputOutput, toplevel = 0, 1
|
||||
win := windowNew(0, &gdkWindowAttr{width: 1, height: 1, wclass: inputOutput, windowType: toplevel}, 0)
|
||||
if win == 0 {
|
||||
return "", "cannot make a window"
|
||||
}
|
||||
if made != nil {
|
||||
made(win)
|
||||
}
|
||||
// gdk_window_destroy drops the reference gdk_window_new gave, and the
|
||||
// GL context GDK made for painting the window. GDK keeps one of its
|
||||
// own until the window system says the window is gone, X11 with a
|
||||
// DestroyNotify GDK handles later in the main loop: dropping that one
|
||||
// too would free the window before, and have GDK handle the event on
|
||||
// freed memory.
|
||||
defer windowDestroy(win)
|
||||
ctx, gerr := glContext(win)
|
||||
if ctx == 0 {
|
||||
return "", failed(gerr)
|
||||
}
|
||||
defer gObjectUnref(ctx)
|
||||
makeCurrent(ctx)
|
||||
defer clearCurrent()
|
||||
const glRenderer = 0x1F01
|
||||
// GDK realizes contexts it cannot make current on some machines
|
||||
// without a GPU: OpenGL then tells nothing, and libepoxy aborts the
|
||||
// first call of most of its functions.
|
||||
if renderer = goStr(getString(glRenderer)); renderer == "" {
|
||||
return "", "OpenGL has no current context"
|
||||
}
|
||||
return renderer, ""
|
||||
}
|
||||
|
||||
// failed describes a GError of GDK's OpenGL.
|
||||
func failed(gerr ptr) string {
|
||||
if err := gErr(gerr); err != nil {
|
||||
return err.Error()
|
||||
}
|
||||
return "no OpenGL context"
|
||||
}
|
||||
|
||||
// gpuDevice reports whether the system has a device OpenGL could draw on:
|
||||
// NVIDIA's, or a render node of a DRM driver with 3D. Mesa draws on the
|
||||
// CPU, loading as much as the probe would for nothing, on display-only
|
||||
// drivers, as virtual machines and servers have, and on WSL's device
|
||||
// unless GALLIUM_DRIVER=d3d12 gives it the GPU.
|
||||
func gpuDevice() bool { return gpuDeviceIn("/", os.Getenv("GALLIUM_DRIVER")) }
|
||||
|
||||
// displayOnly are DRM drivers that only show what the CPU drew.
|
||||
var displayOnly = map[string]bool{
|
||||
"simpledrm": true, "simple-framebuffer": true, "bochs": true, "bochs-drm": true, "cirrus": true,
|
||||
"cirrus-qemu": true, "vboxvideo": true, "hyperv_drm": true, "ast": true, "mgag200": true, "udl": true,
|
||||
"vkms": true,
|
||||
}
|
||||
|
||||
func gpuDeviceIn(root, gallium string) bool {
|
||||
if m, _ := filepath.Glob(filepath.Join(root, "dev", "nvidia*")); len(m) > 0 {
|
||||
return true
|
||||
}
|
||||
nodes, _ := filepath.Glob(filepath.Join(root, "sys", "class", "drm", "renderD*"))
|
||||
for _, node := range nodes {
|
||||
driver, err := os.Readlink(filepath.Join(node, "device", "driver"))
|
||||
if err != nil || !displayOnly[filepath.Base(driver)] {
|
||||
return true // a GPU's, or one to probe
|
||||
}
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(root, "dev", "dxg")); err == nil {
|
||||
return gallium == "d3d12"
|
||||
}
|
||||
return false
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGPUDevice(t *testing.T) {
|
||||
system := func(t *testing.T, devices []string, drivers map[string]string) string {
|
||||
root := t.TempDir()
|
||||
for _, d := range devices {
|
||||
p := filepath.Join(root, "dev", d)
|
||||
os.MkdirAll(filepath.Dir(p), 0o755)
|
||||
os.WriteFile(p, nil, 0o644)
|
||||
}
|
||||
for node, driver := range drivers {
|
||||
dev := filepath.Join(root, "sys", "class", "drm", node, "device")
|
||||
os.MkdirAll(dev, 0o755)
|
||||
if err := os.Symlink(filepath.Join("..", "..", "bus", "pci", "drivers", driver), filepath.Join(dev, "driver")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return root
|
||||
}
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
devices []string
|
||||
drivers map[string]string
|
||||
gallium string
|
||||
want bool
|
||||
}{
|
||||
{"nothing", nil, nil, "", false},
|
||||
{"Intel", []string{"dri/renderD128"}, map[string]string{"renderD128": "i915"}, "", true},
|
||||
{"AMD and simpledrm", nil, map[string]string{"renderD128": "simpledrm", "renderD129": "amdgpu"}, "", true},
|
||||
{"a virtual machine", []string{"dri/card0"}, map[string]string{"renderD128": "bochs-drm"}, "", false},
|
||||
{"NVIDIA", []string{"nvidia0"}, nil, "", true},
|
||||
{"WSL", []string{"dxg"}, nil, "", false},
|
||||
{"WSL with d3d12", []string{"dxg"}, nil, "d3d12", true},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := gpuDeviceIn(system(t, c.devices, c.drivers), c.gallium); got != c.want {
|
||||
t.Errorf("gpuDevice = %v, want %v", got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+185
@@ -0,0 +1,185 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"unsafe"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
"github.com/egoist/mygo/internal/accelerator"
|
||||
)
|
||||
|
||||
// On X11, global shortcuts grab their keys on the root window, and the key
|
||||
// presses arrive through a GDK event filter. Elsewhere the desktop binds
|
||||
// them through the XDG desktop portal (hotkey_portal.go), and so it does
|
||||
// under XWayland, where a grab gets the keys only while a window of the app
|
||||
// has the focus, when the desktop offers the portal.
|
||||
|
||||
var (
|
||||
x11 struct {
|
||||
loaded, ok bool
|
||||
|
||||
stringToKeysym func(name *byte) uint64
|
||||
keysymToKeycode func(dpy ptr, keysym uint64) uint8
|
||||
grabKey func(dpy ptr, keycode int32, modifiers uint32, window uint64, ownerEvents bool, pointerMode, keyboardMode int32) int32
|
||||
ungrabKey func(dpy ptr, keycode int32, modifiers uint32, window uint64) int32
|
||||
defaultRoot func(dpy ptr) uint64
|
||||
flush func(dpy ptr) int32
|
||||
|
||||
displayType func() uintptr
|
||||
xdisplay func(display ptr) ptr
|
||||
errorTrapPush func(display ptr)
|
||||
errorTrapPop func(display ptr) int32
|
||||
addFilter func(window ptr, fn ptr, data ptr)
|
||||
}
|
||||
cbHotkeyFilter ptr
|
||||
)
|
||||
|
||||
// X modifier masks.
|
||||
const (
|
||||
shiftMask = 1 << 0
|
||||
lockMask = 1 << 1 // Caps Lock
|
||||
controlMask = 1 << 2
|
||||
mod1Mask = 1 << 3 // Alt
|
||||
mod2Mask = 1 << 4 // Num Lock
|
||||
mod4Mask = 1 << 6 // Super
|
||||
)
|
||||
|
||||
type grab struct {
|
||||
keycode uint8
|
||||
mods uint32
|
||||
}
|
||||
|
||||
// loadX11 binds the X11 functions once; it reports whether global
|
||||
// shortcuts can work: GDK runs on an X server.
|
||||
func loadX11() bool {
|
||||
if x11.loaded {
|
||||
return x11.ok
|
||||
}
|
||||
x11.loaded = true
|
||||
lib, err := open("libX11.so.6")
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
ok := bind(lib, &x11.stringToKeysym, "XStringToKeysym") &&
|
||||
bind(lib, &x11.keysymToKeycode, "XKeysymToKeycode") &&
|
||||
bind(lib, &x11.grabKey, "XGrabKey") &&
|
||||
bind(lib, &x11.ungrabKey, "XUngrabKey") &&
|
||||
bind(lib, &x11.defaultRoot, "XDefaultRootWindow") &&
|
||||
bind(lib, &x11.flush, "XFlush") &&
|
||||
bind(libGDK, &x11.displayType, "gdk_x11_display_get_type") &&
|
||||
bind(libGDK, &x11.xdisplay, "gdk_x11_display_get_xdisplay") &&
|
||||
bind(libGDK, &x11.errorTrapPush, "gdk_x11_display_error_trap_push") &&
|
||||
bind(libGDK, &x11.errorTrapPop, "gdk_x11_display_error_trap_pop") &&
|
||||
bind(libGDK, &x11.addFilter, "gdk_window_add_filter")
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
x11.ok = gTypeCheckInstanceIsA(gdkDisplayGetDefault(), x11.displayType())
|
||||
if x11.ok {
|
||||
cbHotkeyFilter = purego.NewCallback(hotkeyFilter)
|
||||
x11.addFilter(0, cbHotkeyFilter, 0)
|
||||
}
|
||||
return x11.ok
|
||||
}
|
||||
|
||||
// hotkeyFilter reports the key presses of grabbed shortcuts.
|
||||
func hotkeyFilter(xevent, event, data ptr) int32 {
|
||||
const keyPress, filterContinue, filterRemove = 2, 0, 2
|
||||
ev := *(*unsafe.Pointer)(unsafe.Pointer(&xevent))
|
||||
if *(*int32)(ev) != keyPress {
|
||||
return filterContinue
|
||||
}
|
||||
// XKeyEvent: state and keycode follow the time.
|
||||
state := *(*uint32)(unsafe.Add(ev, 80)) & (shiftMask | controlMask | mod1Mask | mod4Mask)
|
||||
keycode := uint8(*(*uint32)(unsafe.Add(ev, 84)))
|
||||
for id, g := range theBackend.grabs {
|
||||
if g.keycode == keycode && g.mods == state {
|
||||
theBackend.h.HotkeyPressed(id)
|
||||
return filterRemove
|
||||
}
|
||||
}
|
||||
return filterContinue
|
||||
}
|
||||
|
||||
func (b *Backend) RegisterHotkey(id int, acc, description string) error {
|
||||
a, err := accelerator.Parse(acc, "linux")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if b.shortcutsThroughPortal() {
|
||||
return b.bindShortcut(id, a, description)
|
||||
}
|
||||
display := gdkDisplayGetDefault()
|
||||
dpy := x11.xdisplay(display)
|
||||
keycode := x11.keysymToKeycode(dpy, x11.stringToKeysym(cs(a.Keysym())))
|
||||
if keycode == 0 {
|
||||
return fmt.Errorf("mygo: the keyboard has no key for %q", acc)
|
||||
}
|
||||
var mods uint32
|
||||
for m, x := range map[accelerator.Modifiers]uint32{accelerator.Shift: shiftMask, accelerator.Ctrl: controlMask, accelerator.Alt: mod1Mask, accelerator.Super: mod4Mask} {
|
||||
if a.Has(m) {
|
||||
mods |= x
|
||||
}
|
||||
}
|
||||
g := grab{keycode, mods}
|
||||
root := x11.defaultRoot(dpy)
|
||||
x11.errorTrapPush(display)
|
||||
for _, lock := range []uint32{0, lockMask, mod2Mask, lockMask | mod2Mask} {
|
||||
x11.grabKey(dpy, int32(keycode), mods|lock, root, false, 1, 1) // GrabModeAsync
|
||||
}
|
||||
if x11.errorTrapPop(display) != 0 {
|
||||
b.ungrab(g)
|
||||
return errors.New("mygo: " + acc + " is already a global shortcut of another app")
|
||||
}
|
||||
if b.grabs == nil {
|
||||
b.grabs = map[int]grab{}
|
||||
}
|
||||
b.grabs[id] = g
|
||||
return nil
|
||||
}
|
||||
|
||||
// shortcutsThroughPortal tells whether global shortcuts go through the
|
||||
// portal rather than X11 grabs, asking the desktop for the portal once.
|
||||
func (b *Backend) shortcutsThroughPortal() bool {
|
||||
if portalShortcutsOnly || !loadX11() {
|
||||
return true
|
||||
}
|
||||
if !b.portalAsked {
|
||||
b.portalAsked = true
|
||||
b.portalOnX11 = portalOnX11(os.Getenv, func() bool { return portalVersion(shortcutsPortal) != 0 })
|
||||
}
|
||||
return b.portalOnX11
|
||||
}
|
||||
|
||||
// portalOnX11 tells whether an app whose GDK runs on an X server binds its
|
||||
// global shortcuts through the portal: when the X server is XWayland, in a
|
||||
// Wayland session, and the desktop offers the portal. A grab there gets the
|
||||
// keys only while a window of the app has the focus on GNOME, which sends
|
||||
// XWayland no key presses meant for Wayland windows.
|
||||
func portalOnX11(getenv func(string) string, offered func() bool) bool {
|
||||
return getenv("WAYLAND_DISPLAY") != "" && offered()
|
||||
}
|
||||
|
||||
func (b *Backend) UnregisterHotkey(id int) {
|
||||
if g, ok := b.grabs[id]; ok {
|
||||
delete(b.grabs, id)
|
||||
b.ungrab(g)
|
||||
}
|
||||
b.unbindShortcut(id)
|
||||
}
|
||||
|
||||
func (b *Backend) ungrab(g grab) {
|
||||
display := gdkDisplayGetDefault()
|
||||
dpy := x11.xdisplay(display)
|
||||
root := x11.defaultRoot(dpy)
|
||||
x11.errorTrapPush(display)
|
||||
for _, lock := range []uint32{0, lockMask, mod2Mask, lockMask | mod2Mask} {
|
||||
x11.ungrabKey(dpy, int32(g.keycode), g.mods|lock, root)
|
||||
}
|
||||
x11.flush(dpy)
|
||||
x11.errorTrapPop(display)
|
||||
}
|
||||
+331
@@ -0,0 +1,331 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"slices"
|
||||
"strings"
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/accelerator"
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
// Wayland lets apps grab no keys: the desktop binds global shortcuts for
|
||||
// the apps that ask its GlobalShortcuts portal, in a session. A session
|
||||
// binds its shortcuts once, so a change replaces it with a new session
|
||||
// binding them all. Desktops remember the keys the user picks for each
|
||||
// shortcut id, the canonical accelerator, and may ask the user to confirm
|
||||
// new shortcuts: users may decline them, or pick other keys later, so the
|
||||
// app hears the keys of each shortcut (HotkeyBound) when the desktop bound
|
||||
// them and when they change.
|
||||
|
||||
const shortcutsPortal = "org.freedesktop.portal.GlobalShortcuts"
|
||||
|
||||
// portalShortcuts is the state of the shortcuts bound through the portal.
|
||||
type portalShortcuts struct {
|
||||
available bool
|
||||
shortcuts map[int]portalShortcut
|
||||
session string // the session the shortcuts are bound in
|
||||
busy bool // a session is being created and bound
|
||||
stale bool // the shortcuts changed while busy
|
||||
// changed handles the portal's ShortcutsChanged, from the first
|
||||
// shortcut on: apps without global shortcuts link none of it.
|
||||
changed func(params ptr)
|
||||
}
|
||||
|
||||
// portalShortcut is a shortcut and what it does, in the app's words.
|
||||
type portalShortcut struct {
|
||||
accelerator.Accelerator
|
||||
description string
|
||||
}
|
||||
|
||||
// portalShortcutsOnly makes X11 sessions bind global shortcuts through the
|
||||
// portal too (TestUsePortalShortcuts).
|
||||
var portalShortcutsOnly bool
|
||||
|
||||
var wayland struct {
|
||||
loaded bool
|
||||
displayType func() uintptr
|
||||
setStartupID func(display ptr, id *byte)
|
||||
}
|
||||
|
||||
func (b *Backend) bindShortcut(id int, a accelerator.Accelerator, description string) error {
|
||||
p := &b.portal
|
||||
if !p.available {
|
||||
if portalVersion(shortcutsPortal) == 0 {
|
||||
return fmt.Errorf("mygo: global shortcuts need an X11 session or a desktop with the GlobalShortcuts portal: %w", platform.ErrUnsupported)
|
||||
}
|
||||
p.available = true
|
||||
p.changed = b.shortcutsChanged
|
||||
conn, _ := bus()
|
||||
gDBusConnectionSignalSubscribe(conn, cs(portalName), cs(shortcutsPortal), cs("Activated"), cs(portalPath), nil, 0, cbPortalSignal, 0, 0)
|
||||
gDBusConnectionSignalSubscribe(conn, cs(portalName), cs(shortcutsPortal), cs("ShortcutsChanged"), cs(portalPath), nil, 0, cbPortalSignal, 0, 0)
|
||||
}
|
||||
if p.shortcuts == nil {
|
||||
p.shortcuts = map[int]portalShortcut{}
|
||||
}
|
||||
p.shortcuts[id] = portalShortcut{a, description}
|
||||
if err := b.syncShortcuts(); err != nil {
|
||||
delete(p.shortcuts, id)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *Backend) unbindShortcut(id int) {
|
||||
if _, ok := b.portal.shortcuts[id]; ok {
|
||||
delete(b.portal.shortcuts, id)
|
||||
if err := b.syncShortcuts(); err != nil {
|
||||
log.Printf("mygo: global shortcuts: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// syncShortcuts replaces the session with one binding the shortcuts. A
|
||||
// session on its way binds them once it is created.
|
||||
func (b *Backend) syncShortcuts() error {
|
||||
p := &b.portal
|
||||
if p.busy {
|
||||
p.stale = true
|
||||
return nil
|
||||
}
|
||||
if p.session != "" {
|
||||
if res, err := portalCall(p.session, "org.freedesktop.portal.Session", "Close", 0, ""); err == nil {
|
||||
gVariantUnref(res)
|
||||
}
|
||||
p.session = ""
|
||||
}
|
||||
if len(p.shortcuts) == 0 {
|
||||
return nil
|
||||
}
|
||||
options := []ptr{
|
||||
vardictEntry("session_handle_token", gVariantNewString(cs(shortcutSessionToken()))),
|
||||
// KDE Plasma 5 binds the shortcuts given here, as drafts of the
|
||||
// portal had it; portals before 1.17 pass them on.
|
||||
vardictEntry("shortcuts", p.list()),
|
||||
}
|
||||
err := portalRequest(shortcutsPortal, "CreateSession", nil, options, func(code uint32, results ptr) {
|
||||
session := vardictString(results, "session_handle")
|
||||
if code != 0 || session == "" {
|
||||
p.busy = false
|
||||
log.Printf("mygo: global shortcuts: the desktop portal did not create a session (response %d)", code)
|
||||
b.reportShortcuts(0, false)
|
||||
return
|
||||
}
|
||||
p.stale = false
|
||||
if len(p.shortcuts) == 0 {
|
||||
p.busy = false
|
||||
if res, err := portalCall(session, "org.freedesktop.portal.Session", "Close", 0, ""); err == nil {
|
||||
gVariantUnref(res)
|
||||
}
|
||||
return
|
||||
}
|
||||
p.session = session
|
||||
if err := b.bindShortcuts(); err != nil {
|
||||
p.busy = false
|
||||
log.Printf("mygo: global shortcuts: %v", err)
|
||||
b.reportShortcuts(0, false)
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "Error.NotAllowed") {
|
||||
return fmt.Errorf("mygo: global shortcuts on Wayland need the app installed, with its desktop entry %s: %w", desktopEntryID(), err)
|
||||
}
|
||||
return fmt.Errorf("mygo: global shortcuts: %w", err)
|
||||
}
|
||||
p.busy, p.stale = true, false
|
||||
return nil
|
||||
}
|
||||
|
||||
// bindShortcuts binds the shortcuts in the new session.
|
||||
func (b *Backend) bindShortcuts() error {
|
||||
p := &b.portal
|
||||
args := []ptr{gVariantNewObjectPath(cs(p.session)), p.list(), gVariantNewString(cs(b.portalParent()))}
|
||||
return portalRequest(shortcutsPortal, "BindShortcuts", args, nil, func(code uint32, results ptr) {
|
||||
p.busy = false
|
||||
if code != 0 {
|
||||
// KDE answers so when the user declined every shortcut.
|
||||
log.Printf("mygo: global shortcuts: the desktop did not bind them (response %d)", code)
|
||||
b.reportShortcuts(0, false)
|
||||
} else {
|
||||
list := gVariantLookupValue(results, cs("shortcuts"), 0)
|
||||
b.reportShortcuts(list, false)
|
||||
if list != 0 {
|
||||
gVariantUnref(list)
|
||||
}
|
||||
}
|
||||
if p.stale {
|
||||
if err := b.syncShortcuts(); err != nil {
|
||||
log.Printf("mygo: global shortcuts: %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// portalParent identifies to a portal the window its dialog shows over: the
|
||||
// app's window that has the keyboard, else the first one that shows. GNOME
|
||||
// opens the dialog of an app that names none behind the windows in front.
|
||||
// X11 windows only (x11:XID, XWayland's too): a Wayland window would have
|
||||
// to be exported first (xdg-foreign), which this does not do.
|
||||
func (b *Backend) portalParent() string {
|
||||
if b.x11ID == nil {
|
||||
return ""
|
||||
}
|
||||
var parent *window
|
||||
for _, w := range b.windows {
|
||||
if w.closed || !gtkWidgetGetVisible(w.win) {
|
||||
continue
|
||||
}
|
||||
if gtkWindowIsActive(w.win) {
|
||||
parent = w
|
||||
break
|
||||
}
|
||||
if parent == nil || w.id < parent.id {
|
||||
parent = w
|
||||
}
|
||||
}
|
||||
if parent == nil {
|
||||
return ""
|
||||
}
|
||||
gw := gtkWidgetGetWindow(parent.win)
|
||||
if gw == 0 {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf("x11:%x", b.x11ID(gw))
|
||||
}
|
||||
|
||||
// ids returns the shortcuts' ids in the order they were registered.
|
||||
func (p *portalShortcuts) ids() []int {
|
||||
ids := make([]int, 0, len(p.shortcuts))
|
||||
for id := range p.shortcuts {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
slices.Sort(ids)
|
||||
return ids
|
||||
}
|
||||
|
||||
// list returns the a(sa{sv}) that describes the shortcuts to the portal,
|
||||
// in the order they were registered: the desktop shows a shortcut's
|
||||
// description where it asks the user to confirm it and in its settings.
|
||||
func (p *portalShortcuts) list() ptr {
|
||||
ids := p.ids()
|
||||
items := make([]ptr, len(ids))
|
||||
for i, id := range ids {
|
||||
s := p.shortcuts[id]
|
||||
description := s.description
|
||||
if description == "" {
|
||||
description = s.String()
|
||||
}
|
||||
items[i] = tuple(gVariantNewString(cs(s.String())), vardict(
|
||||
vardictEntry("description", gVariantNewString(cs(description))),
|
||||
vardictEntry("preferred_trigger", gVariantNewString(cs(s.XDGTrigger()))),
|
||||
))
|
||||
}
|
||||
return gVariantNewArray(0, unsafe.Pointer(&items[0]), uintptr(len(items)))
|
||||
}
|
||||
|
||||
// reportShortcuts tells the app the keys the desktop has for its
|
||||
// shortcuts, from the a(sa{sv}) the portal lists them in (0: it bound
|
||||
// none), and logs those it has no keys for: users may decline them, and
|
||||
// KDE Plasma 5 binds none with portals from 1.17 on. A shortcut the list
|
||||
// leaves out has no keys, unless the list is of those that changed.
|
||||
func (b *Backend) reportShortcuts(list ptr, changed bool) {
|
||||
keys := map[string]string{}
|
||||
if list != 0 && goStr(gVariantGetTypeString(list)) == "a(sa{sv})" {
|
||||
for i := uintptr(0); i < gVariantNChildren(list); i++ {
|
||||
item := gVariantGetChildValue(list, i)
|
||||
id, props := gVariantGetChildValue(item, 0), gVariantGetChildValue(item, 1)
|
||||
keys[goStr(gVariantGetString(id, nil))] = vardictString(props, "trigger_description")
|
||||
gVariantUnref(id)
|
||||
gVariantUnref(props)
|
||||
gVariantUnref(item)
|
||||
}
|
||||
}
|
||||
for _, id := range b.portal.ids() {
|
||||
s, ok := b.portal.shortcuts[id]
|
||||
if !ok {
|
||||
continue // unregistered by the app as it heard of another's keys
|
||||
}
|
||||
k, listed := keys[s.String()]
|
||||
if changed && !listed {
|
||||
continue
|
||||
}
|
||||
if k == "" {
|
||||
log.Printf("mygo: global shortcuts: the desktop bound no keys to %s", s.Accelerator)
|
||||
}
|
||||
b.h.HotkeyBound(id, k)
|
||||
}
|
||||
}
|
||||
|
||||
// shortcutsChanged handles the portal's ShortcutsChanged signal, (session
|
||||
// handle, shortcuts), sent when the user gave the shortcuts other keys.
|
||||
func (b *Backend) shortcutsChanged(params ptr) {
|
||||
session := gVariantGetChildValue(params, 0)
|
||||
ours := goStr(gVariantGetString(session, nil)) == b.portal.session
|
||||
gVariantUnref(session)
|
||||
if !ours {
|
||||
return
|
||||
}
|
||||
list := gVariantGetChildValue(params, 1)
|
||||
b.reportShortcuts(list, true)
|
||||
gVariantUnref(list)
|
||||
}
|
||||
|
||||
// shortcutActivated handles the portal's Activated signal: (session
|
||||
// handle, shortcut id, timestamp, options).
|
||||
func (b *Backend) shortcutActivated(params ptr) {
|
||||
str := func(i uintptr) string {
|
||||
v := gVariantGetChildValue(params, i)
|
||||
defer gVariantUnref(v)
|
||||
return goStr(gVariantGetString(v, nil))
|
||||
}
|
||||
if str(0) != b.portal.session {
|
||||
return
|
||||
}
|
||||
name := str(1)
|
||||
options := gVariantGetChildValue(params, 3)
|
||||
token := vardictString(options, "activation_token")
|
||||
gVariantUnref(options)
|
||||
for id, s := range b.portal.shortcuts {
|
||||
if s.String() == name {
|
||||
withActivationToken(token, func() { b.h.HotkeyPressed(id) })
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// shortcutSessionToken names the session after the app: KDE names the
|
||||
// shortcuts of apps without an ID after it, and keeps the keys the user
|
||||
// picked for them.
|
||||
func shortcutSessionToken() string {
|
||||
return "mygo_" + strings.Map(func(r rune) rune {
|
||||
if r < 0x80 && (r >= '0' && r <= '9' || r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z') {
|
||||
return r
|
||||
}
|
||||
return '_'
|
||||
}, strings.TrimSuffix(desktopEntryID(), ".desktop"))
|
||||
}
|
||||
|
||||
// withActivationToken runs fn with the XDG activation token of the key
|
||||
// press that caused it: the window fn shows or focuses first uses it, which
|
||||
// lets it take the focus on Wayland.
|
||||
func withActivationToken(token string, fn func()) {
|
||||
if !wayland.loaded {
|
||||
wayland.loaded = true
|
||||
if !bind(libGDK, &wayland.displayType, "gdk_wayland_display_get_type") ||
|
||||
!bind(libGDK, &wayland.setStartupID, "gdk_wayland_display_set_startup_notification_id") {
|
||||
wayland.setStartupID = nil
|
||||
}
|
||||
}
|
||||
display := gdkDisplayGetDefault()
|
||||
if token == "" || wayland.setStartupID == nil || !gTypeCheckInstanceIsA(display, wayland.displayType()) {
|
||||
fn()
|
||||
return
|
||||
}
|
||||
wayland.setStartupID(display, cs(token))
|
||||
defer wayland.setStartupID(display, nil)
|
||||
fn()
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestPortalOnX11 binds global shortcuts through the portal under XWayland,
|
||||
// where the desktop offers it, and grabs keys on a real X server.
|
||||
func TestPortalOnX11(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
wayland string
|
||||
offered, portal bool
|
||||
}{
|
||||
{"X11 session", "", true, false},
|
||||
{"XWayland with the portal", "wayland-0", true, true},
|
||||
{"XWayland without the portal", "wayland-0", false, false},
|
||||
} {
|
||||
asked := false
|
||||
got := portalOnX11(func(k string) string {
|
||||
if k == "WAYLAND_DISPLAY" {
|
||||
return c.wayland
|
||||
}
|
||||
return ""
|
||||
}, func() bool { asked = true; return c.offered })
|
||||
if got != c.portal {
|
||||
t.Errorf("%s: through the portal %v, want %v", c.name, got, c.portal)
|
||||
}
|
||||
if c.wayland == "" && asked {
|
||||
t.Errorf("%s: asked the desktop for the portal", c.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var (
|
||||
iconOnce sync.Once
|
||||
|
||||
gFileQueryInfo func(file ptr, attributes *byte, flags uint32, cancellable ptr, gerr *ptr) ptr
|
||||
gFileInfoGetIcon func(info ptr) ptr
|
||||
gDesktopAppInfoNewFromFile func(path *byte) ptr
|
||||
gAppInfoGetIcon func(info ptr) ptr
|
||||
gtkIconThemeGetDefault func() ptr
|
||||
gtkIconThemeLookupByGicon func(theme, icon ptr, size int32, flags uint32) ptr
|
||||
gtkIconInfoLoadIcon func(info ptr, gerr *ptr) ptr
|
||||
gContentTypeGuess func(filename *byte, data ptr, size uintptr, uncertain *int32) ptr
|
||||
gContentTypeGetIcon func(contentType ptr) ptr
|
||||
)
|
||||
|
||||
func loadIcons() {
|
||||
iconOnce.Do(func() {
|
||||
mustBind(libGIO, &gFileQueryInfo, "g_file_query_info")
|
||||
mustBind(libGIO, &gFileInfoGetIcon, "g_file_info_get_icon")
|
||||
mustBind(libGIO, &gDesktopAppInfoNewFromFile, "g_desktop_app_info_new_from_filename")
|
||||
mustBind(libGIO, &gAppInfoGetIcon, "g_app_info_get_icon")
|
||||
mustBind(libGTK, >kIconThemeGetDefault, "gtk_icon_theme_get_default")
|
||||
mustBind(libGTK, >kIconThemeLookupByGicon, "gtk_icon_theme_lookup_by_gicon")
|
||||
mustBind(libGTK, >kIconInfoLoadIcon, "gtk_icon_info_load_icon")
|
||||
mustBind(libGIO, &gContentTypeGuess, "g_content_type_guess")
|
||||
mustBind(libGIO, &gContentTypeGetIcon, "g_content_type_get_icon")
|
||||
})
|
||||
}
|
||||
|
||||
// FileIcon returns the icon the file manager shows for a file or a folder,
|
||||
// that of its content type (GIO's standard::icon), or the icon of the
|
||||
// application of a desktop entry, from the icon theme at size by size
|
||||
// pixels. Where the theme has no icon of the application, a desktop entry
|
||||
// gets that of its content type, as other files do.
|
||||
func (shell) FileIcon(path string, size int) ([]byte, error) {
|
||||
if _, err := os.Stat(path); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
loadIcons()
|
||||
if strings.HasSuffix(path, ".desktop") {
|
||||
if app := gDesktopAppInfoNewFromFile(cs(path)); app != 0 {
|
||||
png := themeIcon(gAppInfoGetIcon(app), size)
|
||||
gObjectUnref(app)
|
||||
if png != nil {
|
||||
return png, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
f := gFileNewForPath(cs(path))
|
||||
var gerr ptr
|
||||
info := gFileQueryInfo(f, cs("standard::icon"), 0, 0, &gerr)
|
||||
gObjectUnref(f)
|
||||
if info == 0 {
|
||||
return nil, gErr(gerr)
|
||||
}
|
||||
defer gObjectUnref(info)
|
||||
if png := themeIcon(gFileInfoGetIcon(info), size); png != nil {
|
||||
return png, nil
|
||||
}
|
||||
return nil, fmt.Errorf("mygo: the icon theme has no icon for %q", path)
|
||||
}
|
||||
|
||||
// TypeIcon returns the icon the file manager shows for files with the
|
||||
// extension ext: that of the content type GIO guesses from such a name,
|
||||
// from the icon theme at size by size pixels.
|
||||
func (shell) TypeIcon(ext string, size int) ([]byte, error) {
|
||||
loadIcons()
|
||||
ct := gContentTypeGuess(cs("file."+ext), 0, 0, nil)
|
||||
icon := gContentTypeGetIcon(ct)
|
||||
gFree(ct)
|
||||
png := themeIcon(icon, size)
|
||||
gObjectUnref(icon)
|
||||
if png == nil {
|
||||
return nil, fmt.Errorf("mygo: the icon theme has no icon for files of type %q", ext)
|
||||
}
|
||||
return png, nil
|
||||
}
|
||||
|
||||
// themeIcon draws a GIcon from the icon theme at size by size pixels, or
|
||||
// returns nil where the theme has none of its names.
|
||||
func themeIcon(icon ptr, size int) []byte {
|
||||
if icon == 0 {
|
||||
return nil
|
||||
}
|
||||
// GIO's themed icons list their generic names themselves, and GTK takes
|
||||
// GTK_ICON_LOOKUP_GENERIC_FALLBACK only with names of its own.
|
||||
const flags = 1 << 4 // GTK_ICON_LOOKUP_FORCE_SIZE
|
||||
info := gtkIconThemeLookupByGicon(gtkIconThemeGetDefault(), icon, int32(size), flags)
|
||||
if info == 0 {
|
||||
return nil
|
||||
}
|
||||
defer gObjectUnref(info)
|
||||
pix := gtkIconInfoLoadIcon(info, nil)
|
||||
if pix == 0 {
|
||||
return nil
|
||||
}
|
||||
defer gObjectUnref(pix)
|
||||
return pngFromPixbuf(pix)
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import "github.com/egoist/mygo/internal/platform"
|
||||
|
||||
// An input region (SetInputRegion) lets the pointer through a window but
|
||||
// where its rectangles are, as a desktop pet's window lets clicks through
|
||||
// to the windows under it but on its character: the window's input shape
|
||||
// is the region (applyInputShape), which X11's SHAPE extension and
|
||||
// Wayland's input region of the surface (wl_surface_set_input_region) put
|
||||
// in place of the window's own. The X server and the compositor then hand
|
||||
// a press outside it to what is beneath, another app's window too, as
|
||||
// they would were the window not there.
|
||||
|
||||
// shapeInputRegion is (*window).shapeInputRegion once the app set an
|
||||
// input region, for applyInputShape, which every app has, to call.
|
||||
var shapeInputRegion func(w *window, win ptr)
|
||||
|
||||
func (w *window) SetInputRegion(region []platform.Rect) {
|
||||
shapeInputRegion = (*window).shapeInputRegion
|
||||
w.inputRegion = region
|
||||
w.applyInputShape(true)
|
||||
}
|
||||
|
||||
// shapeInputRegion gives the window's GdkWindow win the input shape of
|
||||
// its region, where the content is in it.
|
||||
func (w *window) shapeInputRegion(win ptr) {
|
||||
region := cairoRegionCreateRectangle(&gdkRectangle{})
|
||||
for _, r := range w.inputRegion {
|
||||
cairoRegionUnionRectangle(region, &gdkRectangle{X: int32(r.X), Y: int32(r.Y), Width: int32(r.Width), Height: int32(r.Height)})
|
||||
}
|
||||
x, y := w.contentInWindow()
|
||||
gdkWindowInputShapeCombineRegion(win, region, x, y)
|
||||
cairoRegionDestroy(region)
|
||||
}
|
||||
|
||||
// contentInWindow returns where the content is in the window's
|
||||
// GdkWindow, which holds the menu bar, and the shadow GTK draws around a
|
||||
// window it decorates itself, as flyouts are placed from it.
|
||||
func (w *window) contentInWindow() (x, y int32) {
|
||||
loadFlyouts() // binds gtk_widget_translate_coordinates
|
||||
if c := w.contentWidget(); c == 0 || !gtkWidgetTranslateCoordinates(c, w.win, 0, 0, &x, &y) {
|
||||
x, y = 0, w.contentInsets().top
|
||||
}
|
||||
var alloc gdkRectangle
|
||||
gtkWidgetGetAllocation(w.win, &alloc)
|
||||
return x + alloc.X, y + alloc.Y
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import "github.com/egoist/mygo/internal/platform"
|
||||
|
||||
// The core reaches a window's input region through the interface alone.
|
||||
var _ platform.InputRegionWindow = (*window)(nil)
|
||||
+210
@@ -0,0 +1,210 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
// gdkEventKey is GTK 3's struct, as physical_key_test.go checks it.
|
||||
type gdkEventKey struct {
|
||||
kind int32
|
||||
window uintptr
|
||||
sendEvent int8
|
||||
time uint32
|
||||
state uint32
|
||||
keyval uint32
|
||||
length int32
|
||||
text uintptr
|
||||
hardwareKeycode uint16
|
||||
group uint8
|
||||
isModifier uint32
|
||||
}
|
||||
|
||||
const (
|
||||
gdkKeyPress = 8
|
||||
gdkKeyRelease = 9
|
||||
|
||||
gdkShiftMask = 1
|
||||
gdkSuperMask = 1 << 26
|
||||
)
|
||||
|
||||
// keySink notes the events a surface sends.
|
||||
type keySink struct {
|
||||
platform.WindowHandler
|
||||
got []platform.SurfaceEvent
|
||||
taken func(platform.SurfaceEvent) bool
|
||||
}
|
||||
|
||||
func (k *keySink) SurfaceEvent(ev platform.SurfaceEvent) bool {
|
||||
k.got = append(k.got, ev)
|
||||
return k.taken != nil && k.taken(ev)
|
||||
}
|
||||
|
||||
// keySurface is a surface with no GTK behind it: what it calls of GDK for a
|
||||
// key stands in for the library.
|
||||
func keySurface(t *testing.T) (*surface, *keySink) {
|
||||
t.Helper()
|
||||
free, copyEvent, toUnicode := gdkEventFree, gdkEventCopy, gdkKeyvalToUnicode
|
||||
t.Cleanup(func() { gdkEventFree, gdkEventCopy, gdkKeyvalToUnicode = free, copyEvent, toUnicode })
|
||||
gdkEventFree = func(ptr) {}
|
||||
gdkEventCopy = func(ptr) ptr { return 0 }
|
||||
gdkKeyvalToUnicode = func(keyval uint32) uint32 {
|
||||
switch {
|
||||
case keyval == 0xffb5: // KP_5
|
||||
return '5'
|
||||
case keyval < 0x100:
|
||||
return keyval
|
||||
}
|
||||
return 0
|
||||
}
|
||||
sink := &keySink{}
|
||||
return &surface{w: &window{h: sink}}, sink
|
||||
}
|
||||
|
||||
func sendKey(s *surface, kind int32, keyval uint32, evdev uint16, state uint32) bool {
|
||||
ev := gdkEventKey{kind: kind, keyval: keyval, hardwareKeycode: evdev + 8, state: state}
|
||||
defer runtime.KeepAlive(&ev)
|
||||
return s.keyEvent(ptr(unsafe.Pointer(&ev)))
|
||||
}
|
||||
|
||||
// A modifier on its own tells the state as ever, then the key by position,
|
||||
// with the side: a lone tap of Super comes through whole.
|
||||
func TestKeyEventSuperTap(t *testing.T) {
|
||||
s, sink := keySurface(t)
|
||||
if sendKey(s, gdkKeyPress, 0xffec, 126, 0) { // Super_R
|
||||
t.Error("taken with nothing taking it")
|
||||
}
|
||||
sendKey(s, gdkKeyRelease, 0xffec, 126, gdkSuperMask)
|
||||
want := []platform.SurfaceEvent{
|
||||
{Kind: platform.ModifiersChanged, Mods: platform.ModSuper},
|
||||
{Kind: platform.RawKeyPressed, Code: platform.CodeSuperRight, Mods: platform.ModSuper},
|
||||
{Kind: platform.ModifiersChanged},
|
||||
{Kind: platform.RawKeyReleased, Code: platform.CodeSuperRight},
|
||||
}
|
||||
checkEvents(t, sink.got, want)
|
||||
}
|
||||
|
||||
// Letting go of one Shift with the other held keeps Shift held.
|
||||
func TestKeyEventBothShifts(t *testing.T) {
|
||||
s, sink := keySurface(t)
|
||||
sendKey(s, gdkKeyPress, 0xffe1, 42, 0)
|
||||
sendKey(s, gdkKeyPress, 0xffe2, 54, gdkShiftMask)
|
||||
sendKey(s, gdkKeyRelease, 0xffe1, 42, gdkShiftMask)
|
||||
sendKey(s, gdkKeyRelease, 0xffe2, 54, gdkShiftMask)
|
||||
want := []platform.SurfaceEvent{
|
||||
{Kind: platform.ModifiersChanged, Mods: platform.ModShift},
|
||||
{Kind: platform.RawKeyPressed, Code: platform.CodeShiftLeft, Mods: platform.ModShift},
|
||||
{Kind: platform.ModifiersChanged, Mods: platform.ModShift},
|
||||
{Kind: platform.RawKeyPressed, Code: platform.CodeShiftRight, Mods: platform.ModShift},
|
||||
{Kind: platform.ModifiersChanged, Mods: platform.ModShift},
|
||||
{Kind: platform.RawKeyReleased, Code: platform.CodeShiftLeft, Mods: platform.ModShift},
|
||||
{Kind: platform.ModifiersChanged},
|
||||
{Kind: platform.RawKeyReleased, Code: platform.CodeShiftRight},
|
||||
}
|
||||
checkEvents(t, sink.got, want)
|
||||
}
|
||||
|
||||
// What keyvals give no Key for comes by position alone, and only raw: for
|
||||
// the content, as before, no KeyPressed.
|
||||
func TestKeyEventRawKeys(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
keyval uint32
|
||||
evdev uint16
|
||||
code platform.KeyCode
|
||||
physical platform.Key
|
||||
}{
|
||||
{"Caps Lock", 0xffe5, 58, platform.CodeCapsLock, platform.KeyUnknown},
|
||||
{"Num Lock", 0xff7f, 69, platform.CodeNumLock, platform.KeyUnknown},
|
||||
{"Scroll Lock", 0xff14, 70, platform.CodeScrollLock, platform.KeyUnknown},
|
||||
{"Print Screen", 0xff61, 99, platform.CodePrintScreen, platform.KeyUnknown},
|
||||
{"Pause", 0xff13, 119, platform.CodePause, platform.KeyUnknown},
|
||||
{"AltGr", 0xfe03, 100, platform.CodeAltRight, platform.KeyUnknown},
|
||||
{"102nd key", '<', 86, platform.CodeIntlBackslash, platform.KeyUnknown},
|
||||
{"keypad 5 without Num Lock", 0xff9d, 76, platform.CodeNumpad5, platform.KeyUnknown},
|
||||
{"keypad +", '+', 78, platform.CodeNumpadAdd, platform.KeyUnknown},
|
||||
} {
|
||||
s, sink := keySurface(t)
|
||||
sendKey(s, gdkKeyPress, c.keyval, c.evdev, 0)
|
||||
sendKey(s, gdkKeyRelease, c.keyval, c.evdev, 0)
|
||||
checkEvents(t, sink.got, []platform.SurfaceEvent{
|
||||
{Kind: platform.RawKeyPressed, Code: c.code, PhysicalKey: c.physical},
|
||||
{Kind: platform.RawKeyReleased, Code: c.code, PhysicalKey: c.physical},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A key the layout types no Key for with a place on a US keyboard, as Shift+1
|
||||
// or AltGr+E: the press comes raw, by position, and the release as it did.
|
||||
func TestKeyEventTypedNoKey(t *testing.T) {
|
||||
s, sink := keySurface(t)
|
||||
sendKey(s, gdkKeyPress, '!', 2, gdkShiftMask)
|
||||
sendKey(s, gdkKeyRelease, '!', 2, gdkShiftMask)
|
||||
checkEvents(t, sink.got, []platform.SurfaceEvent{
|
||||
{Kind: platform.RawKeyPressed, PhysicalKey: platform.Key1, Code: platform.CodeDigit1, Mods: platform.ModShift},
|
||||
{Kind: platform.KeyReleased, PhysicalKey: platform.Key1, Code: platform.CodeDigit1, Mods: platform.ModShift},
|
||||
})
|
||||
}
|
||||
|
||||
// Keys of a name come as they did, with their position added.
|
||||
func TestKeyEventNamedKeys(t *testing.T) {
|
||||
s, sink := keySurface(t)
|
||||
if !sendKey(s, gdkKeyPress, 'a', 30, 0) {
|
||||
t.Error("a key of a name stops at the surface")
|
||||
}
|
||||
sendKey(s, gdkKeyRelease, 'a', 30, 0)
|
||||
sendKey(s, gdkKeyPress, 0xffb5, 76, 0) // KP_5, with Num Lock
|
||||
sendKey(s, gdkKeyPress, 0xff8d, 96, 0) // KP_Enter
|
||||
checkEvents(t, sink.got, []platform.SurfaceEvent{
|
||||
{Kind: platform.KeyPressed, Key: platform.KeyA, PhysicalKey: platform.KeyA, Code: platform.CodeKeyA},
|
||||
{Kind: platform.KeyReleased, Key: platform.KeyA, PhysicalKey: platform.KeyA, Code: platform.CodeKeyA},
|
||||
{Kind: platform.KeyPressed, Key: platform.Key5, Code: platform.CodeNumpad5},
|
||||
{Kind: platform.KeyPressed, Key: platform.KeyEnter, Code: platform.CodeNumpadEnter},
|
||||
})
|
||||
}
|
||||
|
||||
// What the content takes stops at the surface, as Alt before GTK's menu bar
|
||||
// sees it; what it leaves goes on as it did, and an unknown key is left out.
|
||||
func TestKeyEventRawTaken(t *testing.T) {
|
||||
s, sink := keySurface(t)
|
||||
sink.taken = func(ev platform.SurfaceEvent) bool { return ev.Kind == platform.RawKeyPressed }
|
||||
if !sendKey(s, gdkKeyPress, 0xffe9, 56, 0) { // Alt_L
|
||||
t.Error("Alt taken goes on")
|
||||
}
|
||||
sink.taken = nil
|
||||
if sendKey(s, gdkKeyRelease, 0xffe9, 56, 1<<3) {
|
||||
t.Error("Alt left stops")
|
||||
}
|
||||
sink.got = nil
|
||||
if sendKey(s, gdkKeyPress, 0xffffff, 300, 0) || len(sink.got) != 0 {
|
||||
t.Errorf("a key of no code: %+v", sink.got)
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-repeat comes through for raw keys too, told from held keys.
|
||||
func TestKeyEventRawRepeat(t *testing.T) {
|
||||
s, sink := keySurface(t)
|
||||
sendKey(s, gdkKeyPress, 0xff14, 70, 0)
|
||||
sendKey(s, gdkKeyPress, 0xff14, 70, 0)
|
||||
if !sink.got[1].Repeat || sink.got[0].Repeat {
|
||||
t.Errorf("repeats: %+v", sink.got)
|
||||
}
|
||||
}
|
||||
|
||||
func checkEvents(t *testing.T, got, want []platform.SurfaceEvent) {
|
||||
t.Helper()
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("got %d events, want %d:\n%+v", len(got), len(want), got)
|
||||
}
|
||||
for i, w := range want {
|
||||
g := got[i]
|
||||
if g.Kind != w.Kind || g.Key != w.Key || g.PhysicalKey != w.PhysicalKey || g.Code != w.Code || g.Mods != w.Mods || g.Repeat != w.Repeat {
|
||||
t.Errorf("event %d: %+v\nwant %+v", i, g, w)
|
||||
}
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import "slices"
|
||||
|
||||
// keysDown are the hardware keycodes of the keys pressed in a surface and
|
||||
// not let go of yet, by which a press tells an auto-repeat
|
||||
// (SurfaceEvent.Repeat): GdkEventKey flags none, but the repeats of a key
|
||||
// held come as presses with no release between them, on X11 with
|
||||
// detectable auto-repeat, which GDK turns on, and on Wayland, where GTK
|
||||
// repeats the keys itself.
|
||||
type keysDown []uint16
|
||||
|
||||
// press notes the key of hardware keycode code pressed, and reports
|
||||
// whether it was held already: an auto-repeat.
|
||||
func (d *keysDown) press(code uint16) (repeat bool) {
|
||||
if code == 0 {
|
||||
return false
|
||||
}
|
||||
if slices.Contains(*d, code) {
|
||||
return true
|
||||
}
|
||||
*d = append(*d, code)
|
||||
return false
|
||||
}
|
||||
|
||||
// release notes the key of hardware keycode code let go of.
|
||||
func (d *keysDown) release(code uint16) {
|
||||
if i := slices.Index(*d, code); i >= 0 {
|
||||
*d = slices.Delete(*d, i, i+1)
|
||||
}
|
||||
}
|
||||
|
||||
// otherSideHeld reports whether the modifier of hardware keycode code has
|
||||
// its twin of the other side held: evdev's Shift, Control, Alt and Super,
|
||||
// plus X's 8.
|
||||
func (d keysDown) otherSideHeld(code uint16) bool {
|
||||
var other uint16
|
||||
switch code {
|
||||
case 42 + 8:
|
||||
other = 54 + 8
|
||||
case 54 + 8:
|
||||
other = 42 + 8
|
||||
case 29 + 8:
|
||||
other = 97 + 8
|
||||
case 97 + 8:
|
||||
other = 29 + 8
|
||||
case 56 + 8:
|
||||
other = 100 + 8
|
||||
case 100 + 8:
|
||||
other = 56 + 8
|
||||
case 125 + 8:
|
||||
other = 126 + 8
|
||||
case 126 + 8:
|
||||
other = 125 + 8
|
||||
default:
|
||||
return false
|
||||
}
|
||||
return slices.Contains(d, other)
|
||||
}
|
||||
|
||||
// clear lets go of every key, as the surface loses the keyboard, whose
|
||||
// releases go elsewhere.
|
||||
func (d *keysDown) clear() { *d = (*d)[:0] }
|
||||
@@ -0,0 +1,51 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestKeysDownRepeat(t *testing.T) {
|
||||
var d keysDown
|
||||
if d.press(38) {
|
||||
t.Fatal("the first press is no repeat")
|
||||
}
|
||||
if !d.press(38) || !d.press(38) {
|
||||
t.Fatal("presses of a key held with no release between are repeats")
|
||||
}
|
||||
if d.press(39) {
|
||||
t.Fatal("another key's press is no repeat")
|
||||
}
|
||||
d.release(38)
|
||||
if d.press(38) {
|
||||
t.Fatal("a press after the release is no repeat")
|
||||
}
|
||||
d.clear()
|
||||
if d.press(38) || d.press(39) {
|
||||
t.Fatal("presses after losing the keyboard are no repeats")
|
||||
}
|
||||
if d.press(0) || d.press(0) {
|
||||
t.Fatal("a key with no keycode is never a repeat")
|
||||
}
|
||||
}
|
||||
|
||||
func TestKeysDownOtherSideHeld(t *testing.T) {
|
||||
const leftShift, rightShift, leftSuper, rightSuper, a = 42 + 8, 54 + 8, 125 + 8, 126 + 8, 30 + 8
|
||||
var d keysDown
|
||||
if d.otherSideHeld(leftShift) {
|
||||
t.Error("the other Shift is held with nothing held")
|
||||
}
|
||||
d.press(rightShift)
|
||||
d.press(a)
|
||||
if !d.otherSideHeld(leftShift) {
|
||||
t.Error("the right Shift is held")
|
||||
}
|
||||
if d.otherSideHeld(rightShift) {
|
||||
t.Error("the left Shift is not held")
|
||||
}
|
||||
if d.otherSideHeld(leftSuper) || d.otherSideHeld(rightSuper) {
|
||||
t.Error("no Super is held")
|
||||
}
|
||||
if d.otherSideHeld(a) {
|
||||
t.Error("A has no other side")
|
||||
}
|
||||
}
|
||||
+266
@@ -0,0 +1,266 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"math"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
// gtk-layer-shell makes panels surfaces of the wlr-layer-shell protocol
|
||||
// on Wayland compositors that speak it (Sway, Hyprland, KDE Plasma,
|
||||
// COSMIC…), as launchers there do (Ulauncher, Walker, anyrun), and
|
||||
// overlays too (overlayWindow), as on-screen displays there are: above
|
||||
// other windows, full-screen ones too, on the output where they are put,
|
||||
// out of the taskbar. Wayland lets other windows do none of that. The
|
||||
// library is optional: without it, or where the compositor does not speak
|
||||
// the protocol (GNOME), a panel or an overlay is a window as others.
|
||||
var (
|
||||
layerOnce sync.Once
|
||||
layerSupported bool
|
||||
|
||||
gtkLayerIsSupported func() bool
|
||||
gtkLayerInitForWindow func(w ptr)
|
||||
gtkLayerSetNamespace func(w ptr, namespace *byte)
|
||||
gtkLayerSetLayer func(w ptr, layer int32)
|
||||
gtkLayerSetAnchor func(w ptr, edge int32, anchor bool)
|
||||
gtkLayerSetMargin func(w ptr, edge int32, margin int32)
|
||||
gtkLayerSetMonitor func(w ptr, monitor ptr)
|
||||
gtkLayerSetKeyboardMode func(w ptr, mode int32) // 0.6
|
||||
gtkLayerSetExclusiveZone func(w ptr, zone int32)
|
||||
gtkLayerSetKeyboardInteractivity func(w ptr, v bool) // before 0.6
|
||||
gdkDisplayGetMonitorAtPoint func(d ptr, x, y int32) ptr
|
||||
)
|
||||
|
||||
const (
|
||||
layerOverlay = 3 // GTK_LAYER_SHELL_LAYER_OVERLAY
|
||||
|
||||
edgeLeft = 0 // GtkLayerShellEdge
|
||||
edgeTop = 2
|
||||
|
||||
keyboardExclusive = 1 // GtkLayerShellKeyboardMode
|
||||
keyboardOnDemand = 2
|
||||
)
|
||||
|
||||
// loadLayerShell loads gtk-layer-shell once, and reports whether panels
|
||||
// and overlays can be layer surfaces.
|
||||
func loadLayerShell() bool {
|
||||
layerOnce.Do(func() {
|
||||
lib, err := open("libgtk-layer-shell.so.0")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ok := bind(lib, >kLayerIsSupported, "gtk_layer_is_supported") &&
|
||||
bind(lib, >kLayerInitForWindow, "gtk_layer_init_for_window") &&
|
||||
bind(lib, >kLayerSetNamespace, "gtk_layer_set_namespace") &&
|
||||
bind(lib, >kLayerSetLayer, "gtk_layer_set_layer") &&
|
||||
bind(lib, >kLayerSetAnchor, "gtk_layer_set_anchor") &&
|
||||
bind(lib, >kLayerSetMargin, "gtk_layer_set_margin") &&
|
||||
bind(lib, >kLayerSetMonitor, "gtk_layer_set_monitor") &&
|
||||
bind(lib, >kLayerSetExclusiveZone, "gtk_layer_set_exclusive_zone") &&
|
||||
bind(libGDK, &gdkDisplayGetMonitorAtPoint, "gdk_display_get_monitor_at_point")
|
||||
if !bind(lib, >kLayerSetKeyboardMode, "gtk_layer_set_keyboard_mode") {
|
||||
ok = ok && bind(lib, >kLayerSetKeyboardInteractivity, "gtk_layer_set_keyboard_interactivity")
|
||||
}
|
||||
layerSupported = ok && gtkLayerIsSupported()
|
||||
})
|
||||
return layerSupported
|
||||
}
|
||||
|
||||
// initLayer makes a new panel a layer surface where it can be one, before
|
||||
// GTK realizes it, and reports whether it did. Without a position, the
|
||||
// compositor centers it on the output it chooses, the one the user is on.
|
||||
func (w *window) initLayer() bool {
|
||||
if w.b.onX11 || !loadLayerShell() {
|
||||
return false
|
||||
}
|
||||
gtkLayerInitForWindow(w.win)
|
||||
// The namespace tells compositors' rules which surfaces are the app's.
|
||||
name := w.b.name
|
||||
if name == "" {
|
||||
name = filepath.Base(os.Args[0])
|
||||
}
|
||||
gtkLayerSetNamespace(w.win, cs(name))
|
||||
gtkLayerSetLayer(w.win, layerOverlay)
|
||||
w.layer = true
|
||||
w.layerKeyboard(true)
|
||||
if !w.opts.Center {
|
||||
w.placeLayer(w.opts.X, w.opts.Y)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// overlayWindow tells whether a window is one that floats above what the
|
||||
// user watches, as subtitles, a desktop pet or a timer: always on top, out
|
||||
// of the taskbar, without a frame, and nobody's child. Under Wayland,
|
||||
// which ignores keep-above, initOverlay makes it a layer surface.
|
||||
func overlayWindow(o *platform.WindowOptions) bool {
|
||||
return o.AlwaysOnTop && o.SkipTaskbar && o.Frameless && !o.Panel && o.Flyout == nil && o.Parent == nil
|
||||
}
|
||||
|
||||
// initOverlay makes a new always-on-top window a layer surface where it can
|
||||
// be one, before GTK realizes it, and reports whether it did: on the
|
||||
// overlay layer, above full-screen windows too, where the window's bounds
|
||||
// put it on its output, whatever the desktop's panels reserve, and taking
|
||||
// the keyboard only when clicked.
|
||||
func (w *window) initOverlay() bool {
|
||||
w.overlay = true
|
||||
if !w.initLayer() {
|
||||
w.overlay = false
|
||||
return false
|
||||
}
|
||||
gtkLayerSetExclusiveZone(w.win, -1)
|
||||
return true
|
||||
}
|
||||
|
||||
// layerKeyboard asks for the keyboard of a layer surface as it shows,
|
||||
// or not, as ShowInactive shows it. Compositors give the keyboard to a
|
||||
// surface that asks for it alone (exclusive), not to one that would take
|
||||
// it on demand, which only a click on it gets, and Sway takes it back from
|
||||
// a surface that goes from one to the other: a panel keeps the keyboard
|
||||
// while it shows, as launchers do, which blurs it only as it hides.
|
||||
// Before gtk-layer-shell 0.6, a panel always asks for it. An overlay never
|
||||
// asks for it: it takes it on demand, or not at all before 0.6, so that the
|
||||
// app under it keeps the keyboard.
|
||||
func (w *window) layerKeyboard(take bool) {
|
||||
switch {
|
||||
case w.overlay && gtkLayerSetKeyboardMode == nil:
|
||||
gtkLayerSetKeyboardInteractivity(w.win, false)
|
||||
case w.overlay:
|
||||
gtkLayerSetKeyboardMode(w.win, keyboardOnDemand)
|
||||
case gtkLayerSetKeyboardMode == nil:
|
||||
gtkLayerSetKeyboardInteractivity(w.win, true)
|
||||
case take:
|
||||
gtkLayerSetKeyboardMode(w.win, keyboardExclusive)
|
||||
default:
|
||||
gtkLayerSetKeyboardMode(w.win, keyboardOnDemand)
|
||||
}
|
||||
}
|
||||
|
||||
// placeLayer puts a layer surface's top-left corner at x, y, on the output
|
||||
// there, with margins from that output's top and left edges.
|
||||
func (w *window) placeLayer(x, y int) {
|
||||
m := gdkDisplayGetMonitorAtPoint(gdkDisplayGetDefault(), int32(x), int32(y))
|
||||
var g gdkRectangle
|
||||
gdkMonitorGetGeometry(m, &g)
|
||||
gtkLayerSetMonitor(w.win, m)
|
||||
gtkLayerSetAnchor(w.win, edgeTop, true)
|
||||
gtkLayerSetAnchor(w.win, edgeLeft, true)
|
||||
gtkLayerSetMargin(w.win, edgeTop, int32(y)-g.Y)
|
||||
gtkLayerSetMargin(w.win, edgeLeft, int32(x)-g.X)
|
||||
w.layerAt = &platform.Point{X: x, Y: y}
|
||||
}
|
||||
|
||||
// centerLayer lets the compositor center a layer surface on its output.
|
||||
func (w *window) centerLayer() {
|
||||
gtkLayerSetAnchor(w.win, edgeTop, false)
|
||||
gtkLayerSetAnchor(w.win, edgeLeft, false)
|
||||
w.layerAt = nil
|
||||
}
|
||||
|
||||
// setLayerBounds places and sizes a layer surface.
|
||||
func (w *window) setLayerBounds(r platform.Rect) {
|
||||
width, height := w.constrain(int32(r.Width), int32(r.Height))
|
||||
w.placeLayer(r.X, r.Y)
|
||||
w.sizeLayer(width, height)
|
||||
}
|
||||
|
||||
// sizeLayer sizes a layer surface, which gtk-layer-shell sizes as the
|
||||
// window asks to be, not by its default size.
|
||||
func (w *window) sizeLayer(width, height int32) {
|
||||
gtkWidgetSetSizeRequest(w.win, width, height)
|
||||
gtkWindowResize(w.win, width, height)
|
||||
}
|
||||
|
||||
// layerMove is a move of a layer surface by the pointer, or a resize from
|
||||
// one of its edges, which the compositor does for toplevels only.
|
||||
type layerMove struct {
|
||||
edge int32 // the GdkWindowEdge resized, or -1 to move
|
||||
start platform.Rect // the bounds as the button pressed
|
||||
}
|
||||
|
||||
// moveLayer moves or resizes a layer surface after the pointer while the
|
||||
// button stays down, and reports whether it still does. The pointer's
|
||||
// coordinates count from the surface, which moves under it: it has gone
|
||||
// as far as the surface moved, and as the pointer moved in it since the
|
||||
// press.
|
||||
func (w *window) moveLayer(event ptr) bool {
|
||||
// GdkEventMotion: state 48, x_root 64, y_root 72.
|
||||
if field[uint32](event, 48)&(1<<8) == 0 {
|
||||
w.layerMove = nil
|
||||
return false
|
||||
}
|
||||
m, now := w.layerMove, w.layerBounds()
|
||||
dx := now.X - m.start.X + int(math.Round(field[float64](event, 64)-w.press.rootX))
|
||||
dy := now.Y - m.start.Y + int(math.Round(field[float64](event, 72)-w.press.rootY))
|
||||
r := m.start
|
||||
if m.edge < 0 {
|
||||
r.X, r.Y = r.X+dx, r.Y+dy
|
||||
} else {
|
||||
// GdkWindowEdge: NORTH_WEST 0, NORTH 1, NORTH_EAST 2, WEST 3,
|
||||
// EAST 4, SOUTH_WEST 5, SOUTH 6, SOUTH_EAST 7.
|
||||
e := m.edge
|
||||
west, east := e == 0 || e == 3 || e == 5, e == 2 || e == 4 || e == 7
|
||||
north, south := e <= 2, e >= 5
|
||||
switch {
|
||||
case west:
|
||||
r.Width -= dx
|
||||
case east:
|
||||
r.Width += dx
|
||||
}
|
||||
switch {
|
||||
case north:
|
||||
r.Height -= dy
|
||||
case south:
|
||||
r.Height += dy
|
||||
}
|
||||
width, height := w.constrain(int32(r.Width), int32(r.Height))
|
||||
r.Width, r.Height = int(width), int(height)
|
||||
// The opposite edges stay where they were.
|
||||
if west {
|
||||
r.X = m.start.X + m.start.Width - r.Width
|
||||
}
|
||||
if north {
|
||||
r.Y = m.start.Y + m.start.Height - r.Height
|
||||
}
|
||||
}
|
||||
if r.X != now.X || r.Y != now.Y {
|
||||
w.placeLayer(r.X, r.Y)
|
||||
w.h.Moved() // Wayland tells no window where it is: the move does
|
||||
}
|
||||
if m.edge >= 0 && (r.Width != now.Width || r.Height != now.Height) {
|
||||
w.sizeLayer(int32(r.Width), int32(r.Height))
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// layerBounds returns where a layer surface is: where it was put, or the
|
||||
// middle of its output, as the compositor centers it.
|
||||
func (w *window) layerBounds() platform.Rect {
|
||||
var width, height int32
|
||||
gtkWindowGetSize(w.win, &width, &height)
|
||||
r := platform.Rect{Width: int(width), Height: int(height)}
|
||||
if p := w.layerAt; p != nil {
|
||||
r.X, r.Y = p.X, p.Y
|
||||
return r
|
||||
}
|
||||
d := gdkDisplayGetDefault()
|
||||
var m ptr
|
||||
if gw := gtkWidgetGetWindow(w.win); gw != 0 && gtkWidgetGetMapped(w.win) {
|
||||
m = gdkDisplayGetMonitorAtWin(d, gw)
|
||||
}
|
||||
if m == 0 {
|
||||
m = gdkDisplayGetPrimaryMonitor(d)
|
||||
}
|
||||
if m == 0 {
|
||||
return r
|
||||
}
|
||||
var g gdkRectangle
|
||||
gdkMonitorGetGeometry(m, &g)
|
||||
r.X, r.Y = int(g.X)+(int(g.Width)-r.Width)/2, int(g.Y)+(int(g.Height)-r.Height)/2
|
||||
return r
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
// TestOverlayWindow makes a layer surface of a frameless window above
|
||||
// others and out of the taskbar, and of no window with a frame, a parent or
|
||||
// a role of its own.
|
||||
func TestOverlayWindow(t *testing.T) {
|
||||
overlay := func() platform.WindowOptions {
|
||||
return platform.WindowOptions{AlwaysOnTop: true, SkipTaskbar: true, Frameless: true}
|
||||
}
|
||||
if o := overlay(); !overlayWindow(&o) {
|
||||
t.Error("a frameless always-on-top window out of the taskbar is no overlay")
|
||||
}
|
||||
for name, change := range map[string]func(*platform.WindowOptions){
|
||||
"not on top": func(o *platform.WindowOptions) { o.AlwaysOnTop = false },
|
||||
"in the taskbar": func(o *platform.WindowOptions) { o.SkipTaskbar = false },
|
||||
"with a frame": func(o *platform.WindowOptions) { o.Frameless = false },
|
||||
"a panel": func(o *platform.WindowOptions) { o.Panel = true },
|
||||
"a flyout": func(o *platform.WindowOptions) { o.Flyout = &platform.Flyout{} },
|
||||
"a child": func(o *platform.WindowOptions) { o.Parent = &window{} },
|
||||
} {
|
||||
o := overlay()
|
||||
change(&o)
|
||||
if overlayWindow(&o) {
|
||||
t.Errorf("%s: an overlay", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"unsafe"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
// The languages and regional formats of the user are those of the
|
||||
// environment, as gettext and glibc read them: no setting of the desktop
|
||||
// changes them while the app runs.
|
||||
|
||||
// PreferredLanguages returns the languages of the environment as gettext
|
||||
// reads them: LANGUAGE, a list separated by colons, unless the locale is C,
|
||||
// then the locale of messages, LC_ALL, LC_MESSAGES or LANG.
|
||||
func (a appController) PreferredLanguages() []string {
|
||||
locale := envLocale("LC_MESSAGES")
|
||||
var out []string
|
||||
if locale != "" {
|
||||
for _, l := range strings.Split(os.Getenv("LANGUAGE"), ":") {
|
||||
if l != "" {
|
||||
out = append(out, l)
|
||||
}
|
||||
}
|
||||
out = append(out, locale)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// envLocale returns the locale of a category as glibc reads the
|
||||
// environment, LC_ALL, then the category's, then LANG, or "" for the C
|
||||
// locale.
|
||||
func envLocale(category string) string {
|
||||
for _, env := range []string{"LC_ALL", category, "LANG"} {
|
||||
if v := os.Getenv(env); v != "" {
|
||||
if v == "C" || v == "POSIX" || strings.HasPrefix(v, "C.") {
|
||||
return ""
|
||||
}
|
||||
return v
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// SavedLocale and SaveLocale leave the app's language to the core's file.
|
||||
func (a appController) SavedLocale() (string, bool) { return "", false }
|
||||
func (a appController) SaveLocale(string) bool { return false }
|
||||
|
||||
// SetLanguages gives WebKitGTK the languages, as the Accept-Language of
|
||||
// its requests and the navigator.language of pages: now if it is loaded,
|
||||
// else as it loads for the first web view. GTK's widgets, as menus, whose
|
||||
// items take no direction from the window, are laid out in the direction.
|
||||
func (a appController) SetLanguages(tags []string, rtl bool) {
|
||||
dir := int32(1) // GTK_TEXT_DIR_LTR
|
||||
if rtl {
|
||||
dir = 2
|
||||
}
|
||||
if gtkWidgetSetDefaultDirection != nil {
|
||||
gtkWidgetSetDefaultDirection(dir)
|
||||
}
|
||||
a.b.languages = append([]string(nil), tags...)
|
||||
// WebKitGTK may have loaded on another goroutine (WebViewAvailable),
|
||||
// which libWebKit does not tell safely: webKit then makes its first
|
||||
// calls here, on the main thread.
|
||||
if webKitLoaded.Load() && webKit() == nil {
|
||||
a.b.applyWebLanguages()
|
||||
}
|
||||
}
|
||||
|
||||
// applyWebLanguages gives the web contexts, the default one and those of
|
||||
// sessions, the app's languages.
|
||||
func (b *Backend) applyWebLanguages() {
|
||||
if len(b.languages) == 0 || webkitWebContextSetPreferredLanguages == nil {
|
||||
return
|
||||
}
|
||||
strs := make([]*byte, len(b.languages)+1) // NULL-terminated
|
||||
for i, l := range b.languages {
|
||||
strs[i] = cs(l)
|
||||
}
|
||||
webkitWebContextSetPreferredLanguages(webkitWebContextGetDefault(), &strs[0])
|
||||
for _, s := range b.stores {
|
||||
webkitWebContextSetPreferredLanguages(s.ctx, &strs[0])
|
||||
}
|
||||
}
|
||||
|
||||
// Region returns the formats of LC_TIME, as glibc has them for the
|
||||
// environment's locale: the first day of the week and the hour cycle of
|
||||
// its time format. A libc without them, as musl, or a locale the system
|
||||
// has not generated, leaves them to the core.
|
||||
func (a appController) Region() platform.Region {
|
||||
r := platform.Region{Locale: envLocale("LC_TIME"), FirstWeekday: -1}
|
||||
if r.Locale == "" {
|
||||
return r
|
||||
}
|
||||
langinfo.once.Do(loadLanginfo)
|
||||
if langinfo.newlocale == nil {
|
||||
return r
|
||||
}
|
||||
const lcTimeMask = 1 << 2 // LC_TIME is 2 in glibc and musl
|
||||
loc := langinfo.newlocale(lcTimeMask, "", 0)
|
||||
if loc == 0 {
|
||||
return r // not generated
|
||||
}
|
||||
defer langinfo.freelocale(loc)
|
||||
if f := langinfo.get(tFmt, loc); f != 0 {
|
||||
r.HourCycle = hourCycleOf(goStr(f))
|
||||
}
|
||||
// _NL_TIME_FIRST_WEEKDAY counts from _NL_TIME_WEEK_1STDAY, a date: 1
|
||||
// is the day of that date, Sunday for 19971130 and Monday for
|
||||
// 19971201, as GTK's calendar reads them.
|
||||
if first := langinfo.get(nlTimeFirstWeekday, loc); first != 0 {
|
||||
day := int(*(*byte)(*(*unsafe.Pointer)(unsafe.Pointer(&first))))
|
||||
origin := uint32(langinfo.get(nlTimeWeek1stDay, loc))
|
||||
start := -1
|
||||
switch origin {
|
||||
case 19971130:
|
||||
start = 0
|
||||
case 19971201:
|
||||
start = 1
|
||||
}
|
||||
if start >= 0 && day >= 1 && day <= 7 {
|
||||
r.FirstWeekday = (start + day - 1) % 7
|
||||
}
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// Items of nl_langinfo for LC_TIME in glibc: _NL_ITEM(LC_TIME, index).
|
||||
const (
|
||||
tFmt = 2<<16 | 42
|
||||
nlTimeWeek1stDay = 2<<16 | 102
|
||||
nlTimeFirstWeekday = 2<<16 | 104
|
||||
)
|
||||
|
||||
// langinfoLib is libc's locale objects, bound once.
|
||||
type langinfoLib struct {
|
||||
once sync.Once
|
||||
newlocale func(mask int32, locale string, base uintptr) uintptr
|
||||
freelocale func(loc uintptr)
|
||||
langinfoL uintptr
|
||||
}
|
||||
|
||||
var langinfo langinfoLib
|
||||
|
||||
func loadLanginfo() {
|
||||
sym := func(name string) uintptr {
|
||||
p, err := purego.Dlsym(purego.RTLD_DEFAULT, name)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return p
|
||||
}
|
||||
n, f, l := sym("newlocale"), sym("freelocale"), sym("nl_langinfo_l")
|
||||
if n == 0 || f == 0 || l == 0 {
|
||||
return
|
||||
}
|
||||
purego.RegisterFunc(&langinfo.newlocale, n)
|
||||
purego.RegisterFunc(&langinfo.freelocale, f)
|
||||
langinfo.langinfoL = l
|
||||
}
|
||||
|
||||
// get calls nl_langinfo_l, whose result is a string, or for some items a
|
||||
// number, in a pointer.
|
||||
func (l *langinfoLib) get(item int, loc uintptr) uintptr {
|
||||
r, _, _ := purego.SyscallN(l.langinfoL, uintptr(item), loc)
|
||||
if r != 0 && item != nlTimeWeek1stDay && *(*byte)(*(*unsafe.Pointer)(unsafe.Pointer(&r))) == 0 {
|
||||
return 0 // an empty string: an item the libc has not
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// hourCycleOf returns the hour cycle of a strftime format: 12 for %I, %l
|
||||
// and %r, 24 for %H, %k, %R and %T, 0 for none.
|
||||
func hourCycleOf(format string) int {
|
||||
for i := 0; i+1 < len(format); i++ {
|
||||
if format[i] != '%' {
|
||||
continue
|
||||
}
|
||||
i++
|
||||
// Flags and modifiers between % and the conversion.
|
||||
for i < len(format) && strings.IndexByte("_-0^#EO", format[i]) >= 0 {
|
||||
i++
|
||||
}
|
||||
if i >= len(format) {
|
||||
break
|
||||
}
|
||||
switch format[i] {
|
||||
case 'I', 'l', 'r':
|
||||
return 12
|
||||
case 'H', 'k', 'R', 'T':
|
||||
return 24
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
"slices"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHourCycleOf(t *testing.T) {
|
||||
for format, want := range map[string]int{"%H:%M:%S": 24, "%r": 12, "%I:%M:%S %p": 12, "%l:%M %p": 12, "%T": 24, "%-H.%M": 24, "%Ex": 0, "": 0} {
|
||||
if got := hourCycleOf(format); got != want {
|
||||
t.Errorf("hourCycleOf(%q) = %d, want %d", format, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreferredLanguages(t *testing.T) {
|
||||
t.Setenv("LC_ALL", "")
|
||||
t.Setenv("LC_MESSAGES", "de_DE.UTF-8")
|
||||
t.Setenv("LANG", "en_US.UTF-8")
|
||||
t.Setenv("LANGUAGE", "fr:es")
|
||||
if got := (appController{}).PreferredLanguages(); !slices.Equal(got, []string{"fr", "es", "de_DE.UTF-8"}) {
|
||||
t.Errorf("PreferredLanguages() = %q", got)
|
||||
}
|
||||
// LANGUAGE does not count in the C locale.
|
||||
t.Setenv("LC_MESSAGES", "C")
|
||||
if got := (appController{}).PreferredLanguages(); len(got) != 0 {
|
||||
t.Errorf("PreferredLanguages() = %q in the C locale", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRegion reads the formats of locales glibc has, which the system must
|
||||
// have generated (locale-gen): the first day of the week and the hour
|
||||
// cycle.
|
||||
func TestRegion(t *testing.T) {
|
||||
out, _ := exec.Command("locale", "-a").Output()
|
||||
for _, c := range []struct {
|
||||
locale, has string
|
||||
first, cycle int
|
||||
}{
|
||||
{"en_US.UTF-8", "en_US.utf8", 0, 12},
|
||||
{"de_DE.UTF-8", "de_DE.utf8", 1, 24},
|
||||
{"en_GB.UTF-8", "en_GB.utf8", 1, 24},
|
||||
{"ar_EG.UTF-8", "ar_EG.utf8", 6, 12},
|
||||
} {
|
||||
if !slices.Contains(splitLines(string(out)), c.has) {
|
||||
t.Logf("skipping %s, which the system has not generated", c.locale)
|
||||
continue
|
||||
}
|
||||
t.Setenv("LC_ALL", "")
|
||||
t.Setenv("LANG", "C")
|
||||
t.Setenv("LC_TIME", c.locale)
|
||||
r := (appController{}).Region()
|
||||
if r.Locale != c.locale || r.FirstWeekday != c.first || r.HourCycle != c.cycle {
|
||||
t.Errorf("%s: Region() = %+v, want first weekday %d, hours %d", c.locale, r, c.first, c.cycle)
|
||||
}
|
||||
}
|
||||
t.Setenv("LC_TIME", "xx_YY.UTF-8") // not generated
|
||||
if r := (appController{}).Region(); r.FirstWeekday != -1 || r.HourCycle != 0 {
|
||||
t.Errorf("a locale that is not there: %+v", r)
|
||||
}
|
||||
}
|
||||
|
||||
func splitLines(s string) []string {
|
||||
var out []string
|
||||
start := 0
|
||||
for i := range len(s) {
|
||||
if s[i] == '\n' {
|
||||
out = append(out, s[start:i])
|
||||
start = i + 1
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Starting at login follows the XDG autostart specification: a desktop
|
||||
// entry in $XDG_CONFIG_HOME/autostart.
|
||||
|
||||
func autostartEntry(id string) string {
|
||||
return filepath.Join(xdgDir("XDG_CONFIG_HOME", ".config"), "autostart", desktopName(id)+".desktop")
|
||||
}
|
||||
|
||||
func (a appController) SetOpenAtLogin(open bool, id, name, arg string) error {
|
||||
path := autostartEntry(id)
|
||||
if !open {
|
||||
if err := os.Remove(path); err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
exe, err := executable()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
entry := "[Desktop Entry]\nType=Application\nName=" + entryString(name) + "\nExec=" + execArg(exe) + " " + arg +
|
||||
"\nTerminal=false\nX-GNOME-Autostart-enabled=true\n"
|
||||
return writeFileAtomic(path, []byte(entry))
|
||||
}
|
||||
|
||||
func (a appController) OpenAtLogin(id, name, arg string) bool {
|
||||
data, err := os.ReadFile(autostartEntry(id))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
for _, line := range strings.Split(string(data), "\n") {
|
||||
switch strings.TrimSpace(line) {
|
||||
case "Hidden=true", "X-GNOME-Autostart-enabled=false":
|
||||
return false // turned off in the desktop's settings
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// OpenedAtLogin reports false: the autostart entry passes the login
|
||||
// argument instead.
|
||||
func (a appController) OpenedAtLogin() bool { return false }
|
||||
+874
@@ -0,0 +1,874 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/png"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
|
||||
"github.com/egoist/mygo/internal/accelerator"
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
// Native menu items are tracked per owner (a window's menu bar, a popup, a
|
||||
// tray) so they can be updated in place and forgotten when rebuilt.
|
||||
type nativeItem struct {
|
||||
owner int
|
||||
item ptr
|
||||
check bool
|
||||
windowID int // menu bar or popup's window; 0 for a tray
|
||||
// disabled keeps the app's choice when enableEditItems changes the native
|
||||
// item's state.
|
||||
disabled bool
|
||||
// icon is the item's icon; image and label are the widgets of an item
|
||||
// that shows one, or did (menuicon.go).
|
||||
icon *platform.MenuIcon
|
||||
image, label ptr
|
||||
bar bool // an item of a menu bar, which shows no icon
|
||||
}
|
||||
|
||||
var (
|
||||
menuOwners int
|
||||
itemsByID = map[int][]nativeItem{}
|
||||
itemRoles = map[int]string{}
|
||||
// roleKeys are the shortcuts of items with a role, by accel group: the
|
||||
// keyval, lower case, and the modifiers.
|
||||
roleKeys = map[ptr]map[[2]uint32]bool{}
|
||||
|
||||
cbMenuActivate ptr
|
||||
cbMenuDeactivate ptr
|
||||
cbPopupRelease ptr
|
||||
cbMenuMap ptr
|
||||
cbTrayActivate ptr
|
||||
|
||||
// Menu bars that hide (window.menuHides), and the keys of items with a
|
||||
// role.
|
||||
cbMenuKey, cbCanActivateAccel, cbMenuBarDeactivate ptr
|
||||
)
|
||||
|
||||
// modifierMask holds the GDK modifiers that make a key a shortcut: Shift,
|
||||
// Control, Alt, Super, Hyper and Meta.
|
||||
const modifierMask = 1<<0 | 1<<2 | 1<<3 | 1<<26 | 1<<27 | 1<<28
|
||||
|
||||
// editCommands are handled by the focused webview itself.
|
||||
var editCommands = map[string]string{
|
||||
"undo": "Undo", "redo": "Redo", "cut": "Cut", "copy": "Copy", "paste": "Paste",
|
||||
"pasteAndMatchStyle": "PasteAsPlainText", "delete": "Delete", "selectAll": "SelectAll",
|
||||
// The Format menu's.
|
||||
"bold": "Bold", "italic": "Italic", "underline": "Underline", "strikethrough": "Strikethrough",
|
||||
"alignLeft": "JustifyLeft", "alignCenter": "JustifyCenter", "alignRight": "JustifyRight",
|
||||
}
|
||||
|
||||
func initMenuCallbacks() {
|
||||
cbMenuActivate = purego.NewCallback(func(item, data ptr) {
|
||||
if settingState {
|
||||
return
|
||||
}
|
||||
b := theBackend
|
||||
id := int(data)
|
||||
// A submenu may have focus. Resolve this native item's window, as
|
||||
// the same Go item may appear in several windows' menu bars.
|
||||
var w *window
|
||||
for _, n := range itemsByID[id] {
|
||||
if n.item == item && n.windowID != 0 {
|
||||
w = b.window(ptr(n.windowID))
|
||||
if w == nil {
|
||||
return
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
if cmd, ok := editCommands[itemRoles[id]]; ok {
|
||||
if w == nil {
|
||||
for _, x := range b.windows {
|
||||
if !x.closed && gtkWindowIsActive(x.win) {
|
||||
w = x
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
var v *window
|
||||
if w != nil {
|
||||
v = w.focusedWebView()
|
||||
}
|
||||
if v != nil {
|
||||
// The page of a web view in the content has the keyboard.
|
||||
webkitWebViewExecuteEditingCommand(v.web, cs(cmd))
|
||||
} else if w != nil {
|
||||
if w.surface != nil {
|
||||
role := itemRoles[id]
|
||||
w.h.SurfaceEvent(platform.SurfaceEvent{Kind: platform.SurfaceCommand, Text: role})
|
||||
} else {
|
||||
webkitWebViewExecuteEditingCommand(w.web, cs(cmd))
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
if w != nil {
|
||||
w.h.MenuItemClicked(id)
|
||||
} else {
|
||||
b.h.MenuItemClicked(id)
|
||||
}
|
||||
})
|
||||
cbMenuDeactivate = purego.NewCallback(func(menu, loop ptr) {
|
||||
gMainLoopQuit(loop)
|
||||
})
|
||||
// The first release a menu hears, within GTK's MENU_SHELL_TIMEOUT
|
||||
// (500 ms) of the press that opened it, leaves the menu open
|
||||
// (PopupMenu); a later one, as a quick click on an item, goes to GTK.
|
||||
// The time is a GdkEventButton's, at 20.
|
||||
cbPopupRelease = purego.NewCallback(func(menu, event, _ ptr) bool {
|
||||
if menu != opening.menu {
|
||||
return false
|
||||
}
|
||||
opening.menu = 0
|
||||
return field[uint32](event, 20)-opening.at <= 500
|
||||
})
|
||||
cbMenuMap = purego.NewCallback(func(menu, data ptr) {
|
||||
if w := theBackend.window(data); w != nil {
|
||||
w.enableEditItems()
|
||||
}
|
||||
})
|
||||
// Alt pressed and released alone, or F10, show a menu bar that hides.
|
||||
cbMenuKey = purego.NewCallback(func(widget, event, data ptr) bool {
|
||||
w := theBackend.window(data)
|
||||
if w == nil {
|
||||
return false
|
||||
}
|
||||
// The shortcuts of items with a role are the content's keys too, as
|
||||
// Ctrl+C, Edit › Copy's, which interrupts in a terminal: GTK would
|
||||
// run its accelerators first, so the content gets them first, and
|
||||
// GTK runs those it leaves. The app's own items go first, as on macOS.
|
||||
if field[int32](event, 0) == 8 && w.surface != nil { // GDK_KEY_PRESS
|
||||
k := [2]uint32{gdkKeyvalToLower(field[uint32](event, 28)), field[uint32](event, 24) & modifierMask}
|
||||
if roleKeys[w.accel][k] {
|
||||
if gtkWindowPropagateKeyEvent(w.win, event) {
|
||||
return true
|
||||
}
|
||||
// GTK drops the shortcut of an item made insensitive as the
|
||||
// content was when its menu last opened, not as it is now.
|
||||
w.enableEditItems()
|
||||
}
|
||||
}
|
||||
if !w.menuHides() || w.menubar == 0 || gtkWidgetGetVisible(w.menubar) {
|
||||
w.altAlone = false
|
||||
return false
|
||||
}
|
||||
// GdkEventKey: type 0, state 24, keyval 28.
|
||||
press := field[int32](event, 0) == 8 // GDK_KEY_PRESS
|
||||
state, key := field[uint32](event, 24), field[uint32](event, 28)
|
||||
alt := key == 0xffe9 || key == 0xffea // Alt_L, Alt_R
|
||||
switch {
|
||||
case press && key == 0xffc7 && state&modifierMask == 0: // F10
|
||||
w.revealMenu()
|
||||
return true
|
||||
case press:
|
||||
w.altAlone = alt && state&modifierMask == 0
|
||||
case alt && w.altAlone:
|
||||
w.altAlone = false
|
||||
w.revealMenu()
|
||||
default:
|
||||
w.altAlone = false
|
||||
}
|
||||
return false
|
||||
})
|
||||
// GTK activates the shortcuts of widgets on screen only: a menu bar that
|
||||
// hides keeps its own.
|
||||
cbCanActivateAccel = purego.NewCallback(func(widget ptr, signal uint32, data ptr) bool {
|
||||
w := theBackend.window(data)
|
||||
return w != nil && w.menuHides()
|
||||
})
|
||||
cbMenuBarDeactivate = purego.NewCallback(func(shell, data ptr) {
|
||||
if w := theBackend.window(data); w != nil && w.menuHides() {
|
||||
gtkWidgetHide(shell)
|
||||
}
|
||||
})
|
||||
// A panel activates an icon it can tell a double click from: GNOME's
|
||||
// AppIndicator extension sends AppIndicator::activate when its icon is
|
||||
// double-clicked.
|
||||
cbTrayActivate = purego.NewCallback(func(ind, x, y, data ptr) {
|
||||
if t := theBackend.trays[int(data)]; t != nil && t.h != nil {
|
||||
t.h.Clicked()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func newOwner() int {
|
||||
menuOwners++
|
||||
return menuOwners
|
||||
}
|
||||
|
||||
func dropOwner(owner int) {
|
||||
if owner == 0 {
|
||||
return
|
||||
}
|
||||
for id, list := range itemsByID {
|
||||
kept := list[:0]
|
||||
for _, n := range list {
|
||||
if n.owner != owner {
|
||||
kept = append(kept, n)
|
||||
}
|
||||
}
|
||||
if len(kept) == 0 {
|
||||
delete(itemsByID, id)
|
||||
} else {
|
||||
itemsByID[id] = kept
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// buildMenu fills a GtkMenuShell with items; bar is a menu bar's, whose
|
||||
// own items show no icons.
|
||||
func buildMenu(shell ptr, m *platform.Menu, accel ptr, owner, windowID int, bar bool) {
|
||||
for _, it := range m.Items {
|
||||
gtkMenuShellAppend(shell, buildItem(it, accel, owner, windowID, bar))
|
||||
}
|
||||
}
|
||||
|
||||
func buildItem(it *platform.MenuItem, accel ptr, owner, windowID int, bar bool) ptr {
|
||||
var item ptr
|
||||
check := false
|
||||
switch it.Type {
|
||||
case platform.MenuItemSeparator:
|
||||
item = gtkSeparatorMenuItemNew()
|
||||
case platform.MenuItemCheckbox, platform.MenuItemRadio:
|
||||
item = gtkCheckMenuItemNewWithLabel(cs(it.LabelWithSubtitleAndBadge()))
|
||||
gtkCheckMenuItemSetDrawAsRadio(item, it.Type == platform.MenuItemRadio)
|
||||
check = true
|
||||
default:
|
||||
item = gtkMenuItemNewWithLabel(cs(it.LabelWithSubtitleAndBadge()))
|
||||
}
|
||||
if it.Submenu != nil {
|
||||
sub := gtkMenuNew()
|
||||
if windowID != 0 {
|
||||
connect(sub, "map", cbMenuMap, ptr(windowID))
|
||||
}
|
||||
buildMenu(sub, it.Submenu, accel, owner, windowID, false)
|
||||
gtkMenuItemSetSubmenu(item, sub)
|
||||
} else if it.Type != platform.MenuItemSeparator {
|
||||
connect(item, "activate", cbMenuActivate, ptr(it.ID))
|
||||
itemRoles[it.ID] = it.Role
|
||||
if accel != 0 && it.Accelerator != "" {
|
||||
if key, mods, ok := gtkAccelerator(it.Accelerator); ok {
|
||||
gtkWidgetAddAccelerator(item, cs("activate"), accel, key, mods, 1) // GTK_ACCEL_VISIBLE
|
||||
if it.Role != "" {
|
||||
if roleKeys[accel] == nil {
|
||||
roleKeys[accel] = map[[2]uint32]bool{}
|
||||
}
|
||||
roleKeys[accel][[2]uint32{gdkKeyvalToLower(key), mods}] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
applyState(item, it, check)
|
||||
n := nativeItem{owner: owner, item: item, check: check, windowID: windowID, disabled: !it.Enabled, bar: bar}
|
||||
if it.Icon != nil && it.Type != platform.MenuItemSeparator && !bar && setMenuItemIcon != nil {
|
||||
n.icon = it.Icon
|
||||
if windowID != 0 {
|
||||
setMenuItemIcon(&n, it.Icon) // a tray's once its menu is exported
|
||||
}
|
||||
}
|
||||
itemsByID[it.ID] = append(itemsByID[it.ID], n)
|
||||
return item
|
||||
}
|
||||
|
||||
// settingState is true while a check item is changed programmatically:
|
||||
// gtk_check_menu_item_set_active emits "activate" as if the user clicked.
|
||||
var settingState bool
|
||||
|
||||
func applyState(item ptr, it *platform.MenuItem, check bool) {
|
||||
gtkWidgetSetSensitive(item, it.Enabled)
|
||||
gtkWidgetSetNoShowAll(item, !it.Visible)
|
||||
gtkWidgetSetVisible(item, it.Visible)
|
||||
if check {
|
||||
settingState = true
|
||||
gtkCheckMenuItemSetActive(item, it.Checked)
|
||||
settingState = false
|
||||
}
|
||||
if it.ToolTip != "" {
|
||||
gtkWidgetSetTooltipText(item, cs(it.ToolTip))
|
||||
}
|
||||
}
|
||||
|
||||
var gdkKeyNames = map[string]string{
|
||||
"Enter": "Return", "Tab": "Tab", "Space": "space", "Backspace": "BackSpace", "Delete": "Delete",
|
||||
"Insert": "Insert", "Escape": "Escape", "Up": "Up", "Down": "Down", "Left": "Left", "Right": "Right",
|
||||
"Home": "Home", "End": "End", "PageUp": "Page_Up", "PageDown": "Page_Down", "+": "plus",
|
||||
"VolumeUp": "XF86AudioRaiseVolume", "VolumeDown": "XF86AudioLowerVolume", "VolumeMute": "XF86AudioMute",
|
||||
"MediaNextTrack": "XF86AudioNext", "MediaPreviousTrack": "XF86AudioPrev", "MediaStop": "XF86AudioStop",
|
||||
"MediaPlayPause": "XF86AudioPlay", "PrintScreen": "Print", "NumDec": "KP_Decimal", "NumAdd": "KP_Add",
|
||||
"NumSub": "KP_Subtract", "NumMult": "KP_Multiply", "NumDiv": "KP_Divide", "CapsLock": "Caps_Lock",
|
||||
"NumLock": "Num_Lock", "ScrollLock": "Scroll_Lock",
|
||||
}
|
||||
|
||||
// gtkAccelerator converts an accelerator to a GDK keyval and modifier mask.
|
||||
func gtkAccelerator(acc string) (uint32, uint32, bool) {
|
||||
a, err := accelerator.Parse(acc, "linux")
|
||||
if err != nil {
|
||||
return 0, 0, false
|
||||
}
|
||||
var mods uint32
|
||||
if a.Has(accelerator.Shift) {
|
||||
mods |= 1 << 0
|
||||
}
|
||||
if a.Has(accelerator.Ctrl) {
|
||||
mods |= 1 << 2
|
||||
}
|
||||
if a.Has(accelerator.Alt) {
|
||||
mods |= 1 << 3
|
||||
}
|
||||
if a.Has(accelerator.Super) {
|
||||
mods |= 1 << 26
|
||||
}
|
||||
var key uint32
|
||||
switch {
|
||||
case gdkKeyNames[a.Key] != "":
|
||||
key = gdkKeyvalFromName(cs(gdkKeyNames[a.Key]))
|
||||
case strings.HasPrefix(a.Key, "F") && len(a.Key) > 1:
|
||||
key = gdkKeyvalFromName(cs(a.Key))
|
||||
case strings.HasPrefix(a.Key, "Num") && len(a.Key) == 4:
|
||||
key = gdkKeyvalFromName(cs("KP_" + a.Key[3:]))
|
||||
default:
|
||||
r, _ := utf8.DecodeRuneInString(a.Key)
|
||||
key = gdkUnicodeToKeyval(uint32(r))
|
||||
if mods&1 != 0 && !unicode.IsLetter(r) {
|
||||
key = shifted(key)
|
||||
}
|
||||
}
|
||||
return key, mods, key != 0
|
||||
}
|
||||
|
||||
func (b *Backend) SetApplicationMenu(m *platform.Menu) {
|
||||
b.appMenu = m
|
||||
for _, w := range b.windows {
|
||||
if !w.ownMenu && w.hasAppMenu() {
|
||||
w.installMenu(m)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// hasAppMenu tells whether the window shows the application menu in its
|
||||
// menu bar: flyouts and panels show none.
|
||||
func (w *window) hasAppMenu() bool { return w.opts.Flyout == nil && !w.opts.Panel }
|
||||
|
||||
func (w *window) SetMenu(m *platform.Menu) {
|
||||
w.ownMenu = m != nil
|
||||
if m == nil && w.hasAppMenu() {
|
||||
m = w.b.appMenu
|
||||
}
|
||||
w.installMenu(m)
|
||||
}
|
||||
|
||||
// installMenu replaces the menu bar at the top of the window.
|
||||
func (w *window) installMenu(m *platform.Menu) {
|
||||
if w.menubar != 0 {
|
||||
gtkWidgetDestroy(w.menubar)
|
||||
w.menubar = 0
|
||||
dropOwner(w.owner)
|
||||
// Accelerators live in the group; start with a fresh one.
|
||||
gtkWindowRemoveAccelGroup(w.win, w.accel)
|
||||
gObjectUnref(w.accel)
|
||||
delete(roleKeys, w.accel)
|
||||
w.accel = gtkAccelGroupNew()
|
||||
gtkWindowAddAccelGroup(w.win, w.accel)
|
||||
}
|
||||
if m == nil || len(m.Items) == 0 {
|
||||
return
|
||||
}
|
||||
w.owner = newOwner()
|
||||
w.menubar = gtkMenuBarNew()
|
||||
buildMenu(w.menubar, m, w.accel, w.owner, w.id, true)
|
||||
gtkBoxPackStart(w.box, w.menubar, false, false, 0)
|
||||
gtkBoxReorderChild(w.box, w.menubar, 0)
|
||||
gtkWidgetShowAll(w.menubar)
|
||||
// The bar shows as menuHides says, whatever shows the window.
|
||||
gtkWidgetSetNoShowAll(w.menubar, true)
|
||||
gtkWidgetSetVisible(w.menubar, !w.menuHides())
|
||||
data := ptr(w.id)
|
||||
connect(w.menubar, "can-activate-accel", cbCanActivateAccel, data)
|
||||
connect(w.menubar, "deactivate", cbMenuBarDeactivate, data)
|
||||
}
|
||||
|
||||
func (w *window) SetAutoHideMenu(v bool) {
|
||||
w.autoHideMenu = v
|
||||
if w.menubar != 0 {
|
||||
gtkWidgetSetVisible(w.menubar, !w.menuHides())
|
||||
}
|
||||
}
|
||||
|
||||
// menuHides reports whether the menu bar shows only while its menus are
|
||||
// open: one that hides, any in full screen, which leaves the page the
|
||||
// whole screen, and any in a window with a hidden title bar, whose page
|
||||
// draws the title bar at the top of the window, with the window buttons
|
||||
// over it: a bar above would push both down, under the menus. Windows
|
||||
// leaves such a window no menu bar either.
|
||||
func (w *window) menuHides() bool {
|
||||
return w.autoHideMenu || w.state&stateFullscreen != 0 || w.hiddenTitleBar()
|
||||
}
|
||||
|
||||
// revealMenu shows a menu bar that hides and opens its first menu, as F10
|
||||
// does in GTK, while the key event is current: the menu grabs its device.
|
||||
// The bar hides again when its menus close.
|
||||
func (w *window) revealMenu() {
|
||||
gtkWidgetShow(w.menubar)
|
||||
// The menu opens under its item: lay the bar out now.
|
||||
gtkContainerCheckResize(w.win)
|
||||
if item := firstMenu(w.menubar); item != 0 {
|
||||
gtkWidgetMnemonicActivate(item, false) // as the item's mnemonic
|
||||
} else {
|
||||
gtkWidgetHide(w.menubar) // nothing to open, so no deactivate to come
|
||||
}
|
||||
}
|
||||
|
||||
// firstMenu returns the first menu of a menu bar that the user can open,
|
||||
// or 0.
|
||||
func firstMenu(bar ptr) ptr {
|
||||
list := gtkContainerGetChildren(bar)
|
||||
defer gListFree(list)
|
||||
for node := list; node != 0; node = field[ptr](node, 8) {
|
||||
if item := field[ptr](node, 0); gtkWidgetGetVisible(item) && gtkWidgetIsSensitive(item) {
|
||||
return item
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (b *Backend) UpdateMenuItem(it *platform.MenuItem) {
|
||||
// New windows build the application menu as it is now.
|
||||
b.appMenu.Apply(it)
|
||||
for i := range itemsByID[it.ID] {
|
||||
n := &itemsByID[it.ID][i]
|
||||
if it.Type != platform.MenuItemSeparator {
|
||||
if n.label != 0 {
|
||||
gtkLabelSetLabel(n.label, cs(it.LabelWithSubtitleAndBadge()))
|
||||
} else {
|
||||
gtkMenuItemSetLabel(n.item, cs(it.LabelWithSubtitleAndBadge()))
|
||||
}
|
||||
if it.Icon != n.icon && !n.bar && setMenuItemIcon != nil {
|
||||
n.icon = it.Icon
|
||||
setMenuItemIcon(n, it.Icon)
|
||||
}
|
||||
}
|
||||
applyState(n.item, it, n.check)
|
||||
n.disabled = !it.Enabled
|
||||
}
|
||||
}
|
||||
|
||||
// enableEditItems makes the items of the edit roles in the window's menu
|
||||
// bar and popups sensitive as the native UI it shows can act on them.
|
||||
// Those of a page keep the app's state: what a page would do is not known
|
||||
// before.
|
||||
func (w *window) enableEditItems() {
|
||||
native := w.surface != nil && w.focusedWebView() == nil
|
||||
for id, role := range itemRoles {
|
||||
if !platform.EditCommands[role] {
|
||||
continue
|
||||
}
|
||||
for _, n := range itemsByID[id] {
|
||||
if n.windowID != w.id {
|
||||
continue
|
||||
}
|
||||
on := !n.disabled
|
||||
if on && native {
|
||||
on = w.h.SurfaceEvent(platform.SurfaceEvent{Kind: platform.SurfaceCommandEnabled, Text: role})
|
||||
}
|
||||
gtkWidgetSetSensitive(n.item, on)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// opening is the menu shown last by a press, and when the press went
|
||||
// down, until the menu hears its first release (PopupMenu).
|
||||
var opening struct {
|
||||
menu ptr
|
||||
at uint32
|
||||
}
|
||||
|
||||
// PopupMenu shows a context menu and blocks until it is dismissed.
|
||||
func (b *Backend) PopupMenu(m *platform.Menu, pw platform.Window, pos *platform.Point) {
|
||||
// GTK positions menus relative to a window: the given one, else the
|
||||
// active one.
|
||||
w, _ := pw.(*window)
|
||||
if w == nil || w.closed {
|
||||
w = nil
|
||||
for _, x := range b.windows {
|
||||
if !x.closed && gtkWindowIsActive(x.win) {
|
||||
w = x
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if w == nil {
|
||||
return // nowhere to show it
|
||||
}
|
||||
owner := newOwner()
|
||||
defer dropOwner(owner)
|
||||
menu := gtkMenuNew()
|
||||
buildMenu(menu, m, 0, owner, w.id, false)
|
||||
w.enableEditItems()
|
||||
gtkWidgetShowAll(menu)
|
||||
event, anchor := w.popupTrigger(), w.contentWindow()
|
||||
const northWest = 1 // GDK_GRAVITY_NORTH_WEST
|
||||
corner := int32(northWest)
|
||||
if m.RightToLeft {
|
||||
// GTK_TEXT_DIR_RTL lays the menu out from the right (its items
|
||||
// take the default direction, which GTK takes from the locale),
|
||||
// and GDK_GRAVITY_NORTH_EAST opens it to the left of the point.
|
||||
gtkWidgetSetDirection(menu, 2)
|
||||
corner = 3
|
||||
}
|
||||
switch {
|
||||
case pos != nil && anchor != 0:
|
||||
gtkMenuPopupAtRect(menu, anchor, &gdkRectangle{X: int32(pos.X), Y: int32(pos.Y), Width: 1, Height: 1}, northWest, corner, event)
|
||||
case event != 0:
|
||||
gtkMenuPopupAtPointer(menu, event)
|
||||
case anchor != 0:
|
||||
// No mouse press to anchor to: at the pointer.
|
||||
var x, y int32
|
||||
pointer := gdkSeatGetPointer(gdkDisplayGetDefaultSeat(gdkDisplayGetDefault()))
|
||||
gdkWindowGetDevicePosition(anchor, pointer, &x, &y, nil)
|
||||
gtkMenuPopupAtRect(menu, anchor, &gdkRectangle{X: x, Y: y, Width: 1, Height: 1}, northWest, northWest, 0)
|
||||
}
|
||||
if !gtkWidgetGetVisible(menu) {
|
||||
// GTK could not show it: there is no dismissal to wait for.
|
||||
gtkWidgetDestroy(menu)
|
||||
return
|
||||
}
|
||||
if b.onX11 && os.Getenv("WAYLAND_DISPLAY") != "" && event != 0 && field[int32](event, 0) == 4 { // GDK_BUTTON_PRESS
|
||||
// GTK keeps a menu open on the release of the press that opened it,
|
||||
// within MENU_SHELL_TIMEOUT, unless the pointer entered an item
|
||||
// since. Under XWayland it enters one at the release, as the
|
||||
// compositor gives the pointer to the menu's window, and the menu
|
||||
// closed as soon as it opened.
|
||||
outer := opening
|
||||
opening.menu, opening.at = menu, field[uint32](event, 20)
|
||||
defer func() { opening = outer }()
|
||||
connect(menu, "button-release-event", cbPopupRelease, 0)
|
||||
}
|
||||
loop := gMainLoopNew(0, false)
|
||||
connect(menu, "deactivate", cbMenuDeactivate, loop)
|
||||
b.popups = append(b.popups, menu)
|
||||
b.quitLoops = append(b.quitLoops, loop)
|
||||
gMainLoopRun(loop)
|
||||
b.quitLoops = b.quitLoops[:len(b.quitLoops)-1]
|
||||
b.popups = b.popups[:len(b.popups)-1]
|
||||
gMainLoopUnref(loop)
|
||||
gtkWidgetDestroy(menu)
|
||||
}
|
||||
|
||||
// Tray icons use AppIndicator (StatusNotifierItem), which shows a menu on
|
||||
// a click. A panel can activate the icon, a double click on GNOME's
|
||||
// indicators, and the library reports that as the "activate" signal while
|
||||
// a handler is connected.
|
||||
type tray struct {
|
||||
b *Backend
|
||||
h platform.TrayHandler
|
||||
id int
|
||||
name string // the indicator's ID (trayName)
|
||||
ind ptr
|
||||
menu ptr
|
||||
owner int
|
||||
iconDir string
|
||||
icons int
|
||||
// activate is the handler of the "activate" signal, 0 while the icon
|
||||
// does not answer activation.
|
||||
activate uint64
|
||||
// dark is the desktop's color scheme, as last told. image is the PNG
|
||||
// the icon shows, and template whether it is black and transparent,
|
||||
// which the icon shows white while the desktop prefers dark, as macOS
|
||||
// tints a template image.
|
||||
dark bool
|
||||
image []byte
|
||||
template bool
|
||||
// title, tip and spec are the title, tooltip and menu the app set
|
||||
// last, and pending tells that some waited for the watcher
|
||||
// (trayhost.go).
|
||||
title, tip string
|
||||
spec *platform.Menu
|
||||
pending bool
|
||||
}
|
||||
|
||||
func (b *Backend) NewTray(id string, h platform.TrayHandler) (platform.Tray, error) {
|
||||
if appIndicatorNew == nil {
|
||||
return nil, fmt.Errorf("mygo: tray icons need libayatana-appindicator3: %w", platform.ErrUnsupported)
|
||||
}
|
||||
traysAppearanceChanged = b.traysAppearance
|
||||
watchTrayWatcher()
|
||||
b.nextTray++
|
||||
t := &tray{b: b, h: h, id: b.nextTray, dark: desktopDark()}
|
||||
t.name = b.trayName(id, goStr(gGetPrgname()), t.id)
|
||||
t.ind = appIndicatorNew(cs(t.name), cs("application-x-executable"), 0) // APPLICATION_STATUS
|
||||
if t.ind == 0 {
|
||||
return nil, fmt.Errorf("mygo: libayatana-appindicator3 made no tray icon: %w", platform.ErrUnsupported)
|
||||
}
|
||||
appIndicatorSetStatus(t.ind, 1) // ACTIVE
|
||||
// AppIndicator only shows up once it has a menu.
|
||||
t.SetMenu(&platform.Menu{})
|
||||
b.trays[t.id] = t
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// trayName is the indicator's ID, its StatusNotifierItem Id, which the
|
||||
// icon is given as it is made. A panel keeps its settings for an icon by
|
||||
// it, as KDE Plasma keeps whether it shows the icon, and with no watcher
|
||||
// libayatana's fallback window is of that class. An icon of an ID is
|
||||
// named after the program and the ID, which then stays across launches,
|
||||
// and is apart from other apps' icons of that ID; an ID another of the
|
||||
// app's icons has takes a number after it. An icon of no ID is named
|
||||
// after the program and its number among the app's icons, which stays
|
||||
// too as the app makes its icons in the same order.
|
||||
func (b *Backend) trayName(id, program string, n int) string {
|
||||
if id == "" {
|
||||
id = strconv.Itoa(n)
|
||||
}
|
||||
if program == "" {
|
||||
program = "mygo"
|
||||
}
|
||||
base := program + "-" + id
|
||||
taken := func(name string) bool {
|
||||
for _, t := range b.trays {
|
||||
if t.name == name {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
name := base
|
||||
for i := 2; taken(name); i++ {
|
||||
name = fmt.Sprintf("%s-%d", base, i)
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
func (t *tray) SetImage(data []byte, template bool) error {
|
||||
if t.held() {
|
||||
t.image, t.template = data, template
|
||||
return nil
|
||||
}
|
||||
img := data
|
||||
if template && t.dark {
|
||||
var err error
|
||||
if img, err = whiten(data); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if t.iconDir == "" {
|
||||
dir, err := os.MkdirTemp("", "mygo-tray-")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
t.iconDir = dir
|
||||
}
|
||||
// A new file name makes the indicator host reload the icon. The icon
|
||||
// goes by its absolute path, not by a name in IconThemePath: KDE looks
|
||||
// a name up in the icon theme first, falling back from "icon-1" to
|
||||
// "icon", and showed a theme's icon in place of the app's.
|
||||
t.icons++
|
||||
file := filepath.Join(t.iconDir, fmt.Sprintf("icon-%d.png", t.icons))
|
||||
if err := os.WriteFile(file, img, 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
appIndicatorSetIconFull(t.ind, cs(file), cs(""))
|
||||
t.image, t.template = data, template
|
||||
return nil
|
||||
}
|
||||
|
||||
// Dark reports whether the desktop prefers dark. AppIndicator tells
|
||||
// nothing of the panel itself, whose theme can differ from the desktop's.
|
||||
func (t *tray) Dark() bool { return desktopDark() }
|
||||
|
||||
// desktopDark reads the desktop's color scheme from the settings portal:
|
||||
// the system's, not the app's own (Theme.SetSource), which the panel does
|
||||
// not follow. Without a portal it is false.
|
||||
func desktopDark() bool {
|
||||
scheme, ok := portalColorScheme()
|
||||
return ok && scheme == 1
|
||||
}
|
||||
|
||||
// traysAppearance tells the icons that the desktop turned dark or light.
|
||||
func (b *Backend) traysAppearance() {
|
||||
if len(b.trays) == 0 {
|
||||
return
|
||||
}
|
||||
dark := desktopDark()
|
||||
for _, t := range b.trays {
|
||||
t.appearanceChanged(dark)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *tray) appearanceChanged(dark bool) {
|
||||
if dark == t.dark {
|
||||
return
|
||||
}
|
||||
t.dark = dark
|
||||
if t.template && t.image != nil {
|
||||
_ = t.SetImage(t.image, true)
|
||||
}
|
||||
if t.h != nil {
|
||||
t.h.AppearanceChanged()
|
||||
}
|
||||
}
|
||||
|
||||
// traysAppearanceChanged is linked by NewTray: portal settings changes
|
||||
// reach every app, but only those with a tray need its image code.
|
||||
var traysAppearanceChanged func()
|
||||
|
||||
// whiten draws a template image white, keeping its alpha, as the Windows
|
||||
// backend does on a dark taskbar.
|
||||
func whiten(data []byte) ([]byte, error) {
|
||||
src, err := png.Decode(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r := src.Bounds()
|
||||
dst := image.NewNRGBA(r)
|
||||
for y := r.Min.Y; y < r.Max.Y; y++ {
|
||||
for x := r.Min.X; x < r.Max.X; x++ {
|
||||
_, _, _, a := src.At(x, y).RGBA()
|
||||
dst.SetNRGBA(x, y, color.NRGBA{255, 255, 255, uint8(a >> 8)})
|
||||
}
|
||||
}
|
||||
var b bytes.Buffer
|
||||
if err := png.Encode(&b, dst); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return b.Bytes(), nil
|
||||
}
|
||||
|
||||
// SetID does nothing: the indicator's ID is given as it is made
|
||||
// (NewTray), and panels place indicators themselves.
|
||||
func (t *tray) SetID(string) {}
|
||||
|
||||
func (t *tray) SetTitle(title string) {
|
||||
t.title = title
|
||||
if !t.held() {
|
||||
appIndicatorSetLabel(t.ind, cs(title), cs(title))
|
||||
}
|
||||
}
|
||||
|
||||
// SetTitleMonospaced does nothing: a panel draws the label in the font
|
||||
// it chooses.
|
||||
func (t *tray) SetTitleMonospaced(bool) {}
|
||||
|
||||
// SetToolTip sets the hover text. The title is what panels show when they
|
||||
// fall back to it, and setting it announces NewTitle alone: a host that
|
||||
// caches the ToolTip property, such as quickshell, would go on showing the
|
||||
// text it read when the icon appeared. Setting the tooltip as well announces
|
||||
// NewToolTip, so both stay in step.
|
||||
func (t *tray) SetToolTip(tip string) {
|
||||
if t.tip = tip; t.held() {
|
||||
return
|
||||
}
|
||||
if appIndicatorSetTitle != nil {
|
||||
appIndicatorSetTitle(t.ind, cs(tip))
|
||||
}
|
||||
if appIndicatorSetTooltipFull != nil {
|
||||
appIndicatorSetTooltipFull(t.ind, nil, cs(tip), nil)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *tray) SetMenu(m *platform.Menu) {
|
||||
if t.spec = m; t.held() {
|
||||
return
|
||||
}
|
||||
dropOwner(t.owner)
|
||||
t.owner = newOwner()
|
||||
menu := gtkMenuNew()
|
||||
if m != nil {
|
||||
buildMenu(menu, m, 0, t.owner, 0, false)
|
||||
}
|
||||
gtkWidgetShowAll(menu)
|
||||
appIndicatorSetMenu(t.ind, menu)
|
||||
t.menu = menu
|
||||
// The items are exported now: give them their icons.
|
||||
for _, list := range itemsByID {
|
||||
for _, n := range list {
|
||||
if n.owner == t.owner && n.icon != nil {
|
||||
setMenuItemIcon(&n, n.icon)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (t *tray) PopUpMenu(*platform.Menu) {}
|
||||
func (t *tray) Bounds() platform.Rect { return platform.Rect{} }
|
||||
|
||||
// SetActivatable connects or drops the indicator's activate handler, which
|
||||
// is also the answer a panel gets when it asks the icon whether it can be
|
||||
// activated at all: the Activate method of the StatusNotifierItem
|
||||
// interface fails with UNKNOWN_METHOD while no handler is connected. GNOME's
|
||||
// AppIndicator extension then opens the menu on every click; with a
|
||||
// handler it opens the menu on a single click after waiting for a second
|
||||
// one, and the second click arrives here as TrayHandler.Clicked, as on
|
||||
// Telegram's icon.
|
||||
func (t *tray) SetActivatable(on bool) {
|
||||
if t.ind == 0 || on == (t.activate != 0) || !trayActivates() {
|
||||
return
|
||||
}
|
||||
if !on {
|
||||
gSignalHandlerDisconnect(t.ind, t.activate)
|
||||
t.activate = 0
|
||||
return
|
||||
}
|
||||
t.activate = connect(t.ind, "activate", cbTrayActivate, ptr(t.id))
|
||||
}
|
||||
|
||||
// trayActivates tells whether the AppIndicator library has the
|
||||
// "activate" signal, which older libayatana-appindicator3 releases lack:
|
||||
// their icons answer no activation, whatever the app listens to. It is
|
||||
// asked once an indicator exists, which registers the type.
|
||||
var trayActivates = sync.OnceValue(func() bool { return indicatorSignal("activate") != 0 })
|
||||
|
||||
func (t *tray) Destroy() {
|
||||
if t.ind == 0 {
|
||||
return
|
||||
}
|
||||
t.SetActivatable(false)
|
||||
appIndicatorSetStatus(t.ind, 0) // PASSIVE
|
||||
gObjectUnref(t.ind)
|
||||
t.ind, t.pending = 0, false
|
||||
dropOwner(t.owner)
|
||||
delete(t.b.trays, t.id)
|
||||
if t.iconDir != "" {
|
||||
_ = os.RemoveAll(t.iconDir)
|
||||
}
|
||||
}
|
||||
|
||||
// shifted returns the keyval that the key typing keyval types with Shift,
|
||||
// in the keyboard's layout: plus for equal on a US keyboard. GTK matches a
|
||||
// shortcut with Shift by what the key types, Shift consumed, so Alt+Shift+=
|
||||
// is Alt+Shift+plus to it. It returns keyval when no key types it.
|
||||
func shifted(keyval uint32) uint32 {
|
||||
km := gdkKeymapGetForDisplay(gdkDisplayGetDefault())
|
||||
var keys ptr
|
||||
var n int32
|
||||
if km == 0 || !gdkKeymapGetEntriesForKeyval(km, keyval, &keys, &n) || n == 0 {
|
||||
return keyval
|
||||
}
|
||||
defer gFree(keys)
|
||||
// GdkKeymapKey: keycode, group, level, each 4 bytes.
|
||||
for i := range uintptr(n) {
|
||||
code, group, level := field[uint32](keys, i*12), field[int32](keys, i*12+4), field[int32](keys, i*12+8)
|
||||
if level != 0 {
|
||||
continue
|
||||
}
|
||||
var sym, consumed uint32
|
||||
var effGroup, outLevel int32
|
||||
if gdkKeymapTranslateKeyboardState(km, code, 1, group, &sym, &effGroup, &outLevel, &consumed) && sym != 0 {
|
||||
return sym
|
||||
}
|
||||
}
|
||||
return keyval
|
||||
}
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/png"
|
||||
"os"
|
||||
"testing"
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
// TestWhiten draws a template tray image white while the desktop prefers
|
||||
// dark, as macOS tints it, keeping its shape.
|
||||
func TestWhiten(t *testing.T) {
|
||||
src := image.NewNRGBA(image.Rect(0, 0, 2, 1))
|
||||
src.SetNRGBA(0, 0, color.NRGBA{0, 0, 0, 255})
|
||||
src.SetNRGBA(1, 0, color.NRGBA{0, 0, 0, 56})
|
||||
var b bytes.Buffer
|
||||
if err := png.Encode(&b, src); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out, err := whiten(b.Bytes())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
img, err := png.Decode(bytes.NewReader(out))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for x, a := range []uint8{255, 56} {
|
||||
if got := color.NRGBAModel.Convert(img.At(x, 0)).(color.NRGBA); got != (color.NRGBA{255, 255, 255, a}) {
|
||||
t.Errorf("pixel %d is %v, want white with alpha %d", x, got, a)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestTrayTemplateAppearance checks the image given to AppIndicator: a
|
||||
// template turns white before the callback, then returns to the original
|
||||
// black; an image in color is unchanged in either scheme.
|
||||
func TestTrayTemplateAppearance(t *testing.T) {
|
||||
oldSet := appIndicatorSetIconFull
|
||||
t.Cleanup(func() { appIndicatorSetIconFull = oldSet })
|
||||
var shown []byte
|
||||
appIndicatorSetIconFull = func(_ ptr, file, _ *byte) {
|
||||
var err error
|
||||
shown, err = os.ReadFile(goStr(ptr(unsafe.Pointer(file))))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, template := range []bool{true, false} {
|
||||
src := image.NewNRGBA(image.Rect(0, 0, 1, 1))
|
||||
ink := color.NRGBA{40, 90, 140, 102}
|
||||
if template {
|
||||
ink = color.NRGBA{A: 102}
|
||||
}
|
||||
src.SetNRGBA(0, 0, ink)
|
||||
var data bytes.Buffer
|
||||
if err := png.Encode(&data, src); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var observed []color.NRGBA
|
||||
h := &trayAppearanceHandler{changed: func() {
|
||||
img, err := png.Decode(bytes.NewReader(shown))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
observed = append(observed, color.NRGBAModel.Convert(img.At(0, 0)).(color.NRGBA))
|
||||
}}
|
||||
tr := &tray{iconDir: t.TempDir(), h: h}
|
||||
if err := tr.SetImage(data.Bytes(), template); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tr.appearanceChanged(true)
|
||||
tr.appearanceChanged(true) // no duplicate callback
|
||||
tr.appearanceChanged(false)
|
||||
light := ink
|
||||
if template {
|
||||
light = color.NRGBA{255, 255, 255, ink.A}
|
||||
}
|
||||
if len(observed) != 2 || observed[0] != light || observed[1] != ink {
|
||||
t.Errorf("template=%v: callbacks saw %v, want [%v %v]", template, observed, light, ink)
|
||||
}
|
||||
if !bytes.Equal(shown, data.Bytes()) || !bytes.Equal(tr.image, data.Bytes()) {
|
||||
t.Errorf("template=%v: original image was not preserved", template)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type trayAppearanceHandler struct{ changed func() }
|
||||
|
||||
func (*trayAppearanceHandler) Clicked() {}
|
||||
func (*trayAppearanceHandler) RightClicked() {}
|
||||
func (h *trayAppearanceHandler) AppearanceChanged() { h.changed() }
|
||||
|
||||
// TestMenuHides checks that a window with a hidden title bar keeps its menu
|
||||
// bar out of sight, so that the window buttons stay at the top of the
|
||||
// window, in the page's title bar (#730).
|
||||
func TestMenuHides(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
opts platform.WindowOptions
|
||||
full bool
|
||||
want bool
|
||||
}{
|
||||
{"default", platform.WindowOptions{}, false, false},
|
||||
{"frameless", platform.WindowOptions{Frameless: true}, false, false},
|
||||
{"auto hide", platform.WindowOptions{AutoHideMenu: true}, false, true},
|
||||
{"full screen", platform.WindowOptions{}, true, true},
|
||||
{"hidden title bar", platform.WindowOptions{TitleBarStyle: "hidden"}, false, true},
|
||||
{"hidden inset title bar", platform.WindowOptions{TitleBarStyle: "hiddenInset"}, false, true},
|
||||
} {
|
||||
o := tc.opts
|
||||
w := &window{opts: &o, autoHideMenu: o.AutoHideMenu}
|
||||
if tc.full {
|
||||
w.state |= stateFullscreen
|
||||
}
|
||||
if got := w.menuHides(); got != tc.want {
|
||||
t.Errorf("%s: menuHides() = %v, want %v", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestTrayName checks the IDs icons are made with: an icon of an ID is
|
||||
// named after the program and the ID, whatever the process, another icon
|
||||
// of that ID takes a number (#1835), and an icon of no ID is named after
|
||||
// the program and its number among the app's icons, whatever the
|
||||
// process, so that it too stays across launches.
|
||||
func TestTrayName(t *testing.T) {
|
||||
b := &Backend{trays: map[int]*tray{}}
|
||||
if got := b.trayName("main", "notes", 1); got != "notes-main" {
|
||||
t.Errorf("an icon of ID main is %q, want notes-main", got)
|
||||
}
|
||||
b.trays[1] = &tray{id: 1, name: "notes-main"}
|
||||
if got := b.trayName("main", "notes", 2); got != "notes-main-2" {
|
||||
t.Errorf("a second icon of ID main is %q, want notes-main-2", got)
|
||||
}
|
||||
b.trays[2] = &tray{id: 2, name: "notes-main-2"}
|
||||
if got := b.trayName("main", "notes", 3); got != "notes-main-3" {
|
||||
t.Errorf("a third icon of ID main is %q, want notes-main-3", got)
|
||||
}
|
||||
if got := b.trayName("main", "", 3); got != "mygo-main" {
|
||||
t.Errorf("an icon of ID main with no program name is %q, want mygo-main", got)
|
||||
}
|
||||
if got := b.trayName("", "notes", 4); got != "notes-4" {
|
||||
t.Errorf("an icon of no ID is %q, want notes-4", got)
|
||||
}
|
||||
if got := b.trayName("", "", 4); got != "mygo-4" {
|
||||
t.Errorf("an icon of no ID with no program name is %q, want mygo-4", got)
|
||||
}
|
||||
b.trays[3] = &tray{id: 3, name: "notes-5"} // an icon of ID 5
|
||||
if got := b.trayName("", "notes", 5); got != "notes-5-2" {
|
||||
t.Errorf("an icon of no ID whose name an icon of an ID has is %q, want notes-5-2", got)
|
||||
}
|
||||
}
|
||||
+209
@@ -0,0 +1,209 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"sync"
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
// The icons of menu items. A GTK menu item shows its icon in a box with
|
||||
// its label, the image first, as GTK 3 advises in place of the deprecated
|
||||
// GtkImageMenuItem: GTK shows it whatever gtk-menu-images says, and a
|
||||
// check item draws its check before the box. A tray's menu is the panel's
|
||||
// to draw, which libdbusmenu exports: its items get their icon as the
|
||||
// "icon-data" property of the items exported (a PNG), which the parser of
|
||||
// GTK menus would not give a check item.
|
||||
|
||||
// setMenuItemIcon is setItemIcon once LinkMenuIcons links it: the
|
||||
// backend's methods are linked into every app, and only call it.
|
||||
var setMenuItemIcon func(n *nativeItem, ic *platform.MenuIcon)
|
||||
|
||||
// LinkMenuIcons links the code of the icons of menu items, when the app
|
||||
// first gives an item one.
|
||||
func LinkMenuIcons() { setMenuItemIcon = setItemIcon }
|
||||
|
||||
var (
|
||||
menuIconOnce sync.Once
|
||||
|
||||
gtkBinGetChild func(w ptr) ptr
|
||||
gtkImageNew func() ptr
|
||||
gtkImageSetFromSurface func(img, surface ptr)
|
||||
gtkLabelSetLabel func(label ptr, s *byte)
|
||||
gtkMenuItemScale func(w ptr) int32
|
||||
gdkCairoSurfaceCreateFromPixbuf func(pixbuf ptr, scale int32, win ptr) ptr
|
||||
gdkPixbufScaleSimple func(src ptr, w, h int32, interp int32) ptr
|
||||
gdkPixbufGetWidth func(p ptr) int32
|
||||
gdkPixbufGetHeight func(p ptr) int32
|
||||
dbusmenuGtkParseGetCachedItem func(widget ptr) ptr
|
||||
dbusmenuMenuitemPropertySetByteArray func(mi ptr, prop *byte, data unsafe.Pointer, n uintptr) bool
|
||||
dbusmenuMenuitemPropertyRemove func(mi ptr, prop *byte)
|
||||
)
|
||||
|
||||
func loadMenuIcons() {
|
||||
menuIconOnce.Do(func() {
|
||||
mustBind(libGTK, >kBinGetChild, "gtk_bin_get_child")
|
||||
mustBind(libGTK, >kImageNew, "gtk_image_new")
|
||||
mustBind(libGTK, >kImageSetFromSurface, "gtk_image_set_from_surface")
|
||||
mustBind(libGTK, >kLabelSetLabel, "gtk_label_set_label")
|
||||
mustBind(libGTK, >kMenuItemScale, "gtk_widget_get_scale_factor")
|
||||
mustBind(libGDK, &gdkCairoSurfaceCreateFromPixbuf, "gdk_cairo_surface_create_from_pixbuf")
|
||||
mustBind(libPixbuf, &gdkPixbufScaleSimple, "gdk_pixbuf_scale_simple")
|
||||
mustBind(libPixbuf, &gdkPixbufGetWidth, "gdk_pixbuf_get_width")
|
||||
mustBind(libPixbuf, &gdkPixbufGetHeight, "gdk_pixbuf_get_height")
|
||||
// AppIndicator loaded libdbusmenu: these find it.
|
||||
if lib, err := open("libdbusmenu-gtk3.so.4"); err == nil {
|
||||
bind(lib, &dbusmenuGtkParseGetCachedItem, "dbusmenu_gtk_parse_get_cached_item")
|
||||
}
|
||||
if lib, err := open("libdbusmenu-glib.so.4"); err == nil {
|
||||
bind(lib, &dbusmenuMenuitemPropertySetByteArray, "dbusmenu_menuitem_property_set_byte_array")
|
||||
bind(lib, &dbusmenuMenuitemPropertyRemove, "dbusmenu_menuitem_property_remove")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// iconPixbufs is what an icon is decoded to, once (MenuIcon.Native): the
|
||||
// image, its sizes asked for, and the PNG a tray's menu exports.
|
||||
type iconPixbufs struct {
|
||||
image ptr
|
||||
sized map[int32]ptr
|
||||
tray []byte
|
||||
}
|
||||
|
||||
func (p *iconPixbufs) free() {
|
||||
gObjectUnref(p.image)
|
||||
for _, s := range p.sized {
|
||||
if s != 0 {
|
||||
gObjectUnref(s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func iconPixbufsOf(ic *platform.MenuIcon) *iconPixbufs {
|
||||
p, _ := ic.Native(func() any {
|
||||
pix, err := pixbufFromPNG(ic.PNG)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
p := &iconPixbufs{image: pix, sized: map[int32]ptr{}}
|
||||
// The pixbufs' references may be dropped on any thread.
|
||||
runtime.AddCleanup(ic, (*iconPixbufs).free, p)
|
||||
return p
|
||||
}).(*iconPixbufs)
|
||||
return p
|
||||
}
|
||||
|
||||
// iconPixbuf returns an icon's image fit to a box of box pixels, or 0.
|
||||
func iconPixbuf(ic *platform.MenuIcon, box int32) ptr {
|
||||
p := iconPixbufsOf(ic)
|
||||
if p == nil {
|
||||
return 0
|
||||
}
|
||||
if s, ok := p.sized[box]; ok {
|
||||
return s
|
||||
}
|
||||
w, h := platform.FitIcon(int(gdkPixbufGetWidth(p.image)), int(gdkPixbufGetHeight(p.image)), int(box))
|
||||
const interpHyper = 3 // GDK_INTERP_HYPER, the finest when shrinking
|
||||
s := gdkPixbufScaleSimple(p.image, int32(w), int32(h), interpHyper)
|
||||
p.sized[box] = s
|
||||
return s
|
||||
}
|
||||
|
||||
// trayIconPNG returns the PNG a tray's menu exports of an icon: the image,
|
||||
// at most twice the size the panel draws it at.
|
||||
func trayIconPNG(ic *platform.MenuIcon) []byte {
|
||||
p := iconPixbufsOf(ic)
|
||||
if p == nil {
|
||||
return nil
|
||||
}
|
||||
if p.tray == nil {
|
||||
p.tray = ic.PNG
|
||||
const box = 2 * platform.MenuIconSize
|
||||
if gdkPixbufGetWidth(p.image) > box || gdkPixbufGetHeight(p.image) > box {
|
||||
if s := iconPixbuf(ic, box); s != 0 {
|
||||
if png := pngFromPixbuf(s); png != nil {
|
||||
p.tray = png
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return p.tray
|
||||
}
|
||||
|
||||
// menuItemImage returns the image of a GTK menu item, which it gets with a
|
||||
// box holding it and the item's label, and the label.
|
||||
func menuItemImage(n *nativeItem) (image, label ptr) {
|
||||
if n.image != 0 {
|
||||
return n.image, n.label
|
||||
}
|
||||
label = gtkBinGetChild(n.item)
|
||||
if label == 0 {
|
||||
return 0, 0
|
||||
}
|
||||
gObjectRef(label)
|
||||
gtkContainerRemove(n.item, label)
|
||||
box := gtkBoxNew(0, 6) // GTK_ORIENTATION_HORIZONTAL
|
||||
n.image = gtkImageNew()
|
||||
gtkWidgetSetNoShowAll(n.image, true)
|
||||
gtkBoxPackStart(box, n.image, false, false, 0)
|
||||
gtkBoxPackStart(box, label, true, true, 0)
|
||||
gObjectUnref(label)
|
||||
gtkContainerAdd(n.item, box)
|
||||
gtkWidgetShow(box)
|
||||
gtkWidgetShow(label)
|
||||
n.label = label
|
||||
return n.image, n.label
|
||||
}
|
||||
|
||||
// setItemIcon shows an icon in a GTK menu item, nil for none.
|
||||
func setItemIcon(n *nativeItem, ic *platform.MenuIcon) {
|
||||
loadMenuIcons()
|
||||
if n.windowID == 0 {
|
||||
setTrayItemIcon(n.item, ic)
|
||||
return
|
||||
}
|
||||
if ic == nil && n.image == 0 {
|
||||
return
|
||||
}
|
||||
image, _ := menuItemImage(n)
|
||||
if image == 0 {
|
||||
return
|
||||
}
|
||||
var surface ptr
|
||||
if ic != nil {
|
||||
scale := max(gtkMenuItemScale(n.item), 1)
|
||||
if pix := iconPixbuf(ic, platform.MenuIconSize*scale); pix != 0 {
|
||||
surface = gdkCairoSurfaceCreateFromPixbuf(pix, scale, 0)
|
||||
}
|
||||
}
|
||||
gtkImageSetFromSurface(image, surface)
|
||||
gtkWidgetSetVisible(image, surface != 0)
|
||||
if surface != 0 {
|
||||
cairoSurfaceDestroy(surface)
|
||||
}
|
||||
}
|
||||
|
||||
// setTrayItemIcon gives the item a tray's menu exports for a GTK menu item
|
||||
// an icon, nil for none. A tray's items are exported once its menu is set.
|
||||
func setTrayItemIcon(item ptr, ic *platform.MenuIcon) {
|
||||
if dbusmenuGtkParseGetCachedItem == nil || dbusmenuMenuitemPropertySetByteArray == nil || dbusmenuMenuitemPropertyRemove == nil {
|
||||
return
|
||||
}
|
||||
mi := dbusmenuGtkParseGetCachedItem(item)
|
||||
if mi == 0 {
|
||||
return
|
||||
}
|
||||
var png []byte
|
||||
if ic != nil {
|
||||
png = trayIconPNG(ic)
|
||||
}
|
||||
if len(png) == 0 {
|
||||
dbusmenuMenuitemPropertyRemove(mi, cs("icon-data"))
|
||||
return
|
||||
}
|
||||
dbusmenuMenuitemPropertySetByteArray(mi, cs("icon-data"), unsafe.Pointer(&png[0]), uintptr(len(png)))
|
||||
runtime.KeepAlive(png)
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
// GNetworkMonitor is a singleton GLib keeps up to date, so a status is a
|
||||
// plain read and its network-changed signal drives the event.
|
||||
type network struct{ b *Backend }
|
||||
|
||||
func (b *Backend) Network() platform.Network { return network{b} }
|
||||
|
||||
// Status reads the monitor's current view. The first call creates the
|
||||
// singleton, on the main thread.
|
||||
func (network) Status() platform.NetworkStatus {
|
||||
m := gNetworkMonitorGetDefault()
|
||||
if m == 0 {
|
||||
return platform.NetworkStatus{}
|
||||
}
|
||||
// network-available is a default route, of IPv4 or IPv6: a
|
||||
// connectivity other than G_NETWORK_CONNECTIVITY_LOCAL, as macOS's
|
||||
// satisfied path.
|
||||
return platform.NetworkStatus{
|
||||
Online: gNetworkMonitorGetNetworkAvailable(m),
|
||||
Metered: gNetworkMonitorGetNetworkMetered(m),
|
||||
}
|
||||
}
|
||||
|
||||
// Watch connects network-changed. The core calls it once.
|
||||
func (network) Watch() {
|
||||
if m := gNetworkMonitorGetDefault(); m != 0 {
|
||||
connect(m, "network-changed", cbNetworkChanged, 0)
|
||||
}
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
// notificationImageHint is imageHint once LinkNotificationImages links
|
||||
// it: the backend's methods are linked into every app, and only call it.
|
||||
var notificationImageHint func(image []byte) ptr
|
||||
|
||||
// LinkNotificationImages links the code of notifications' images, when
|
||||
// the app first makes a notification with one.
|
||||
func LinkNotificationImages() { notificationImageHint = imageHint }
|
||||
|
||||
var (
|
||||
notifyImageOnce sync.Once
|
||||
|
||||
gVariantNewFixedArray func(typ *byte, elements ptr, n, size uintptr) ptr
|
||||
gdkPixbufGetRowstride func(p ptr) int32
|
||||
gdkPixbufGetHasAlpha func(p ptr) bool
|
||||
gdkPixbufGetBitsPerSample func(p ptr) int32
|
||||
gdkPixbufGetNChannels func(p ptr) int32
|
||||
gdkPixbufGetPixels func(p ptr) ptr
|
||||
)
|
||||
|
||||
func loadNotifyImages() {
|
||||
notifyImageOnce.Do(func() {
|
||||
mustBind(libGLib, &gVariantNewFixedArray, "g_variant_new_fixed_array")
|
||||
// Bound with the icons of menu items too, to the same functions.
|
||||
mustBind(libPixbuf, &gdkPixbufScaleSimple, "gdk_pixbuf_scale_simple")
|
||||
mustBind(libPixbuf, &gdkPixbufGetWidth, "gdk_pixbuf_get_width")
|
||||
mustBind(libPixbuf, &gdkPixbufGetHeight, "gdk_pixbuf_get_height")
|
||||
mustBind(libPixbuf, &gdkPixbufGetRowstride, "gdk_pixbuf_get_rowstride")
|
||||
mustBind(libPixbuf, &gdkPixbufGetHasAlpha, "gdk_pixbuf_get_has_alpha")
|
||||
mustBind(libPixbuf, &gdkPixbufGetBitsPerSample, "gdk_pixbuf_get_bits_per_sample")
|
||||
mustBind(libPixbuf, &gdkPixbufGetNChannels, "gdk_pixbuf_get_n_channels")
|
||||
mustBind(libPixbuf, &gdkPixbufGetPixels, "gdk_pixbuf_get_pixels")
|
||||
})
|
||||
}
|
||||
|
||||
// notifyImageBox is the most pixels across of a notification's image:
|
||||
// servers draw it a few times the size of an icon at most (dunst at 128
|
||||
// pixels, mako at 64), and the bus copies every byte of it.
|
||||
const notifyImageBox = 256
|
||||
|
||||
// imageHint returns the hint "image-data" of an image, which the
|
||||
// notification spec prefers to a file the server would read later: the
|
||||
// pixels GdkPixbuf decodes, fit to notifyImageBox, given as libnotify
|
||||
// gives a pixbuf (width, height, row stride, alpha, bits per sample,
|
||||
// channels, then the bytes, the last row without its padding). It
|
||||
// returns 0 for an image GdkPixbuf cannot decode.
|
||||
func imageHint(image []byte) ptr {
|
||||
loadNotifyImages()
|
||||
pix, err := pixbufFromPNG(image) // any format GdkPixbuf has a loader for
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
defer gObjectUnref(pix)
|
||||
w, h := gdkPixbufGetWidth(pix), gdkPixbufGetHeight(pix)
|
||||
if w > notifyImageBox || h > notifyImageBox {
|
||||
fw, fh := platform.FitIcon(int(w), int(h), notifyImageBox)
|
||||
const interpHyper = 3 // GDK_INTERP_HYPER, the finest when shrinking
|
||||
scaled := gdkPixbufScaleSimple(pix, int32(fw), int32(fh), interpHyper)
|
||||
if scaled == 0 {
|
||||
return 0
|
||||
}
|
||||
defer gObjectUnref(scaled)
|
||||
pix, w, h = scaled, int32(fw), int32(fh)
|
||||
}
|
||||
stride, bits, channels := gdkPixbufGetRowstride(pix), gdkPixbufGetBitsPerSample(pix), gdkPixbufGetNChannels(pix)
|
||||
n := (h-1)*stride + w*((channels*bits+7)/8)
|
||||
data := gVariantNewFixedArray(cs("y"), gdkPixbufGetPixels(pix), uintptr(n), 1)
|
||||
value := tuple(
|
||||
gVariantNewInt32(w),
|
||||
gVariantNewInt32(h),
|
||||
gVariantNewInt32(stride),
|
||||
gVariantNewBoolean(gdkPixbufGetHasAlpha(pix)),
|
||||
gVariantNewInt32(bits),
|
||||
gVariantNewInt32(channels),
|
||||
data,
|
||||
)
|
||||
return gVariantNewDictEntry(gVariantNewString(cs("image-data")), gVariantNewVariant(value))
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestImageHint gives a notification's image to the server as the spec's
|
||||
// "image-data": PNG or JPEG decoded, a large one fit to notifyImageBox,
|
||||
// with as many bytes as libnotify counts; and no hint for bytes that are
|
||||
// no image.
|
||||
func TestImageHint(t *testing.T) {
|
||||
if err := load(); err != nil {
|
||||
t.Skip(err)
|
||||
}
|
||||
var getInt32 func(v ptr) int32
|
||||
mustBind(libGLib, &getInt32, "g_variant_get_int32")
|
||||
|
||||
// The PNGs are translucent, which png.Encode keeps as RGBA: it writes
|
||||
// opaque images as RGB.
|
||||
encode := func(w, h int, jpg bool) []byte {
|
||||
img := image.NewNRGBA(image.Rect(0, 0, w, h))
|
||||
draw.Draw(img, img.Bounds(), image.NewUniform(color.NRGBA{200, 40, 40, 128}), image.Point{}, draw.Src)
|
||||
var b bytes.Buffer
|
||||
var err error
|
||||
if jpg {
|
||||
err = jpeg.Encode(&b, img, nil)
|
||||
} else {
|
||||
err = png.Encode(&b, img)
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b.Bytes()
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
image []byte
|
||||
w, h int32
|
||||
alpha bool
|
||||
channels int32
|
||||
bitsOfSample int32
|
||||
}{
|
||||
{"PNG", encode(64, 48, false), 64, 48, true, 4, 8},
|
||||
{"JPEG", encode(64, 48, true), 64, 48, false, 3, 8},
|
||||
{"large PNG", encode(1024, 512, false), notifyImageBox, notifyImageBox / 2, true, 4, 8},
|
||||
} {
|
||||
hint := imageHint(tc.image)
|
||||
if hint == 0 {
|
||||
t.Errorf("%s: no hint", tc.name)
|
||||
continue
|
||||
}
|
||||
if typ := goStr(gVariantGetTypeString(hint)); typ != "{sv}" {
|
||||
t.Errorf("%s: the hint is %s", tc.name, typ)
|
||||
gVariantUnref(hint)
|
||||
continue
|
||||
}
|
||||
key := gVariantGetChildValue(hint, 0)
|
||||
boxed := gVariantGetChildValue(hint, 1)
|
||||
value := gVariantGetVariant(boxed)
|
||||
if k := goStr(gVariantGetString(key, nil)); k != "image-data" {
|
||||
t.Errorf("%s: the hint is %q", tc.name, k)
|
||||
}
|
||||
if typ := goStr(gVariantGetTypeString(value)); typ != "(iiibiiay)" {
|
||||
t.Errorf("%s: image-data is %s", tc.name, typ)
|
||||
} else {
|
||||
field := func(i uintptr) ptr { return gVariantGetChildValue(value, i) }
|
||||
var ints [6]int32
|
||||
for _, i := range []uintptr{0, 1, 2, 4, 5} {
|
||||
c := field(i)
|
||||
ints[i] = getInt32(c)
|
||||
gVariantUnref(c)
|
||||
}
|
||||
c := field(3)
|
||||
alpha := gVariantGetBoolean(c)
|
||||
gVariantUnref(c)
|
||||
c = field(6)
|
||||
n := gVariantNChildren(c)
|
||||
gVariantUnref(c)
|
||||
w, h, stride, bits, channels := ints[0], ints[1], ints[2], ints[4], ints[5]
|
||||
if w != tc.w || h != tc.h || alpha != tc.alpha || bits != tc.bitsOfSample || channels != tc.channels {
|
||||
t.Errorf("%s: %dx%d, alpha %v, %d bits, %d channels; want %dx%d, alpha %v, %d bits, %d channels",
|
||||
tc.name, w, h, alpha, bits, channels, tc.w, tc.h, tc.alpha, tc.bitsOfSample, tc.channels)
|
||||
}
|
||||
if want := uintptr((h-1)*stride + w*channels*bits/8); n != want {
|
||||
t.Errorf("%s: %d bytes, want %d", tc.name, n, want)
|
||||
}
|
||||
}
|
||||
gVariantUnref(value)
|
||||
gVariantUnref(boxed)
|
||||
gVariantUnref(key)
|
||||
gVariantUnref(hint)
|
||||
}
|
||||
if hint := imageHint([]byte("not an image")); hint != 0 {
|
||||
gVariantUnref(hint)
|
||||
t.Error("bytes that are no image made a hint")
|
||||
}
|
||||
}
|
||||
+416
@@ -0,0 +1,416 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"hash/fnv"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
func (b *Backend) NowPlaying() platform.NowPlaying { return nowPlaying{b} }
|
||||
|
||||
// nowPlaying is an MPRIS player (org.mpris.MediaPlayer2) on the session
|
||||
// bus, which GNOME's and KDE's media controls, their lock screens and
|
||||
// playerctl show and drive, and which the desktops send the media keys
|
||||
// to. The app owns its bus name only while it shows something, so the
|
||||
// player leaves the desktop's controls once it shows nothing. Raise,
|
||||
// which the desktops' controls send as the player is clicked, has the
|
||||
// core bring the app's window forward.
|
||||
type nowPlaying struct{ b *Backend }
|
||||
|
||||
// nowPlayingSet is the code of NowPlaying, which LinkNowPlaying links:
|
||||
// the backend's methods are linked into every app, and only call it.
|
||||
var nowPlayingSet func(b *Backend, info *platform.NowPlayingInfo)
|
||||
|
||||
// LinkNowPlaying links the code of NowPlaying, when the app first shows
|
||||
// what it plays.
|
||||
func LinkNowPlaying() { nowPlayingSet = setNowPlaying }
|
||||
|
||||
func (n nowPlaying) Set(info *platform.NowPlayingInfo) {
|
||||
if nowPlayingSet != nil {
|
||||
nowPlayingSet(n.b, info)
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
mprisPath = "/org/mpris/MediaPlayer2"
|
||||
mprisRoot = "org.mpris.MediaPlayer2"
|
||||
mprisPlayer = "org.mpris.MediaPlayer2.Player"
|
||||
mprisNoTrack = "/org/mpris/MediaPlayer2/TrackList/NoTrack"
|
||||
)
|
||||
|
||||
const mprisXML = `<node>
|
||||
<interface name="org.mpris.MediaPlayer2">
|
||||
<method name="Raise"/>
|
||||
<method name="Quit"/>
|
||||
<property name="CanQuit" type="b" access="read"/>
|
||||
<property name="CanRaise" type="b" access="read"/>
|
||||
<property name="HasTrackList" type="b" access="read"/>
|
||||
<property name="Identity" type="s" access="read"/>
|
||||
<property name="DesktopEntry" type="s" access="read"/>
|
||||
<property name="SupportedUriSchemes" type="as" access="read"/>
|
||||
<property name="SupportedMimeTypes" type="as" access="read"/>
|
||||
</interface>
|
||||
<interface name="org.mpris.MediaPlayer2.Player">
|
||||
<method name="Next"/>
|
||||
<method name="Previous"/>
|
||||
<method name="Pause"/>
|
||||
<method name="PlayPause"/>
|
||||
<method name="Stop"/>
|
||||
<method name="Play"/>
|
||||
<method name="Seek"><arg direction="in" name="Offset" type="x"/></method>
|
||||
<method name="SetPosition"><arg direction="in" name="TrackId" type="o"/><arg direction="in" name="Position" type="x"/></method>
|
||||
<method name="OpenUri"><arg direction="in" name="Uri" type="s"/></method>
|
||||
<signal name="Seeked"><arg name="Position" type="x"/></signal>
|
||||
<property name="PlaybackStatus" type="s" access="read"/>
|
||||
<property name="Rate" type="d" access="read"/>
|
||||
<property name="Metadata" type="a{sv}" access="read"/>
|
||||
<property name="Volume" type="d" access="read"/>
|
||||
<property name="Position" type="x" access="read"/>
|
||||
<property name="MinimumRate" type="d" access="read"/>
|
||||
<property name="MaximumRate" type="d" access="read"/>
|
||||
<property name="CanGoNext" type="b" access="read"/>
|
||||
<property name="CanGoPrevious" type="b" access="read"/>
|
||||
<property name="CanPlay" type="b" access="read"/>
|
||||
<property name="CanPause" type="b" access="read"/>
|
||||
<property name="CanSeek" type="b" access="read"/>
|
||||
<property name="CanControl" type="b" access="read"/>
|
||||
</interface>
|
||||
</node>`
|
||||
|
||||
// The player's state, main thread only.
|
||||
var mpris struct {
|
||||
conn ptr
|
||||
registered bool
|
||||
owner uint32 // the bus name's owner id, 0 while not owned
|
||||
info *platform.NowPlayingInfo
|
||||
at time.Time // when info.Position was
|
||||
track int // counts the tracks, for their ids
|
||||
art string // the artwork's file
|
||||
artHash uint64
|
||||
}
|
||||
|
||||
// GIO's functions of exported objects, bound with the player.
|
||||
var (
|
||||
gDBusNodeInfoNewForXML func(xml *byte, err *ptr) ptr
|
||||
gDBusNodeInfoLookupInterface func(node ptr, name *byte) ptr
|
||||
gDBusConnectionRegisterObject func(conn ptr, path *byte, iface ptr, vtable unsafe.Pointer, data, free ptr, err *ptr) uint32
|
||||
gBusOwnNameOnConnection func(conn ptr, name *byte, flags int32, acquired, lost, data, free ptr) uint32
|
||||
gBusUnownName func(id uint32)
|
||||
gDBusMethodInvocationReturnValue func(inv, params ptr)
|
||||
gDBusMethodInvocationReturnDBusError func(inv ptr, name, msg *byte)
|
||||
gVariantGetInt64 func(v ptr) int64
|
||||
|
||||
// mprisVtable is the GDBusInterfaceVTable of both interfaces: method
|
||||
// calls, property reads, no writes, and GLib's padding.
|
||||
mprisVtable [11]ptr
|
||||
mprisOnce sync.Once
|
||||
// mprisStrings is the GVariantType of strings, of empty arrays.
|
||||
mprisStrings ptr
|
||||
)
|
||||
|
||||
func bindMPRIS() {
|
||||
mprisOnce.Do(func() {
|
||||
i := libGIO
|
||||
mustBind(i, &gDBusNodeInfoNewForXML, "g_dbus_node_info_new_for_xml")
|
||||
mustBind(i, &gDBusNodeInfoLookupInterface, "g_dbus_node_info_lookup_interface")
|
||||
mustBind(i, &gDBusConnectionRegisterObject, "g_dbus_connection_register_object")
|
||||
mustBind(i, &gBusOwnNameOnConnection, "g_bus_own_name_on_connection")
|
||||
mustBind(i, &gBusUnownName, "g_bus_unown_name")
|
||||
mustBind(i, &gDBusMethodInvocationReturnValue, "g_dbus_method_invocation_return_value")
|
||||
mustBind(i, &gDBusMethodInvocationReturnDBusError, "g_dbus_method_invocation_return_dbus_error")
|
||||
mustBind(libGLib, &gVariantGetInt64, "g_variant_get_int64")
|
||||
mprisStrings = gVariantTypeNew(cs("s"))
|
||||
// Created once: the player is registered once per process.
|
||||
mprisVtable[0] = purego.NewCallback(func(conn, sender, path, iface, method, params, inv, data ptr) {
|
||||
mprisCall(goStr(iface), goStr(method), params, inv)
|
||||
})
|
||||
mprisVtable[1] = purego.NewCallback(func(conn, sender, path, iface, prop, gerr, data ptr) ptr {
|
||||
return mprisProperty(goStr(iface), goStr(prop))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
func setNowPlaying(b *Backend, info *platform.NowPlayingInfo) {
|
||||
conn, err := bus()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
bindMPRIS()
|
||||
if !mpris.registered {
|
||||
var gerr ptr
|
||||
node := gDBusNodeInfoNewForXML(cs(mprisXML), &gerr)
|
||||
if node == 0 {
|
||||
_ = gErr(gerr)
|
||||
return
|
||||
}
|
||||
for _, iface := range []string{mprisRoot, mprisPlayer} {
|
||||
if gDBusConnectionRegisterObject(conn, cs(mprisPath), gDBusNodeInfoLookupInterface(node, cs(iface)), unsafe.Pointer(&mprisVtable), 0, 0, &gerr) == 0 {
|
||||
_ = gErr(gerr)
|
||||
return
|
||||
}
|
||||
}
|
||||
mpris.conn, mpris.registered = conn, true
|
||||
}
|
||||
old := mpris.info
|
||||
if info == nil {
|
||||
mpris.info = nil
|
||||
if mpris.owner != 0 {
|
||||
gBusUnownName(mpris.owner)
|
||||
mpris.owner = 0
|
||||
}
|
||||
mprisSetArt(nil)
|
||||
return
|
||||
}
|
||||
expected := mprisPosition()
|
||||
if old == nil || old.Title != info.Title || !slices.Equal(old.Artists, info.Artists) || old.Album != info.Album || old.Duration != info.Duration {
|
||||
mpris.track++
|
||||
}
|
||||
mpris.info, mpris.at = info, time.Now()
|
||||
mprisSetArt(info.Artwork)
|
||||
if mpris.owner == 0 {
|
||||
name := fmt.Sprintf("org.mpris.MediaPlayer2.%s.instance%d", busNameElement(appName()), os.Getpid())
|
||||
mpris.owner = gBusOwnNameOnConnection(conn, cs(name), 0, 0, 0, 0, 0)
|
||||
return
|
||||
}
|
||||
mprisChanged(mprisPlayer, "PlaybackStatus", "Rate", "Metadata", "CanGoNext", "CanGoPrevious", "CanPlay", "CanPause", "CanSeek")
|
||||
// Clients advance the position at the rate, and hear only of jumps.
|
||||
if d := info.Position - expected; old != nil && (d > time.Second/2 || d < -time.Second/2) {
|
||||
var gerr ptr
|
||||
if !gDBusConnectionEmitSignal(conn, nil, cs(mprisPath), cs(mprisPlayer), cs("Seeked"), tuple(gVariantNewInt64(info.Position.Microseconds())), &gerr) {
|
||||
_ = gErr(gerr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// busNameElement makes s an element of a bus name: ASCII letters,
|
||||
// digits, _ and -, not starting with a digit.
|
||||
func busNameElement(s string) string {
|
||||
var b strings.Builder
|
||||
for _, r := range s {
|
||||
switch {
|
||||
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r == '_', r == '-', r >= '0' && r <= '9' && b.Len() > 0:
|
||||
b.WriteRune(r)
|
||||
case r >= '0' && r <= '9':
|
||||
b.WriteString("_")
|
||||
b.WriteRune(r)
|
||||
default:
|
||||
b.WriteRune('_')
|
||||
}
|
||||
}
|
||||
if b.Len() == 0 {
|
||||
return "mygo"
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// mprisSetArt writes the artwork to a file, whose URL the metadata gives,
|
||||
// and removes the one before. Clients read it whenever they like, so the
|
||||
// file stays until the artwork changes.
|
||||
func mprisSetArt(art []byte) {
|
||||
h := fnv.New64a()
|
||||
h.Write(art)
|
||||
sum := h.Sum64()
|
||||
if len(art) > 0 && mpris.art != "" && sum == mpris.artHash {
|
||||
return
|
||||
}
|
||||
if mpris.art != "" {
|
||||
os.Remove(mpris.art)
|
||||
mpris.art = ""
|
||||
}
|
||||
if len(art) == 0 {
|
||||
return
|
||||
}
|
||||
// The user's runtime directory goes away as the session ends.
|
||||
dir := os.Getenv("XDG_RUNTIME_DIR")
|
||||
if dir == "" {
|
||||
dir = os.TempDir()
|
||||
}
|
||||
dir = filepath.Join(dir, busNameElement(appName()))
|
||||
if os.MkdirAll(dir, 0o700) != nil {
|
||||
return
|
||||
}
|
||||
path := filepath.Join(dir, fmt.Sprintf("now-playing-%d-%x", os.Getpid(), sum))
|
||||
if os.WriteFile(path, art, 0o600) == nil {
|
||||
mpris.art, mpris.artHash = path, sum
|
||||
}
|
||||
}
|
||||
|
||||
// mprisPosition is where playback is now.
|
||||
func mprisPosition() time.Duration {
|
||||
info := mpris.info
|
||||
if info == nil {
|
||||
return 0
|
||||
}
|
||||
pos := info.Position
|
||||
if info.State == "playing" {
|
||||
pos += time.Duration(float64(time.Since(mpris.at)) * info.Rate)
|
||||
}
|
||||
if info.Duration > 0 {
|
||||
pos = min(pos, info.Duration)
|
||||
}
|
||||
return max(pos, 0)
|
||||
}
|
||||
|
||||
func mprisTrackID() string {
|
||||
if mpris.info == nil {
|
||||
return mprisNoTrack
|
||||
}
|
||||
return fmt.Sprintf("/org/mygo/track/%d", mpris.track)
|
||||
}
|
||||
|
||||
// mprisCan reports whether the player offers cmd.
|
||||
func mprisCan(cmd platform.MediaCommand) bool {
|
||||
return mpris.info != nil && mpris.info.Commands&cmd != 0
|
||||
}
|
||||
|
||||
// mprisProperty returns a property's value, a new GVariant.
|
||||
func mprisProperty(iface, prop string) ptr {
|
||||
info := mpris.info
|
||||
switch prop {
|
||||
case "CanQuit", "HasTrackList":
|
||||
return gVariantNewBoolean(false)
|
||||
case "CanRaise":
|
||||
return gVariantNewBoolean(true)
|
||||
case "Identity":
|
||||
return gVariantNewString(cs(appName()))
|
||||
case "DesktopEntry":
|
||||
return gVariantNewString(cs(strings.TrimSuffix(desktopEntryID(), ".desktop")))
|
||||
case "SupportedUriSchemes", "SupportedMimeTypes":
|
||||
return gVariantNewArray(mprisStrings, nil, 0)
|
||||
case "PlaybackStatus":
|
||||
status := "Stopped"
|
||||
if info != nil {
|
||||
status = strings.ToUpper(info.State[:1]) + info.State[1:]
|
||||
}
|
||||
return gVariantNewString(cs(status))
|
||||
case "Rate":
|
||||
if info != nil {
|
||||
return gVariantNewDouble(info.Rate)
|
||||
}
|
||||
return gVariantNewDouble(1)
|
||||
case "Volume", "MinimumRate", "MaximumRate":
|
||||
return gVariantNewDouble(1)
|
||||
case "Position":
|
||||
return gVariantNewInt64(mprisPosition().Microseconds())
|
||||
case "Metadata":
|
||||
return mprisMetadata()
|
||||
case "CanGoNext":
|
||||
return gVariantNewBoolean(mprisCan(platform.MediaNext))
|
||||
case "CanGoPrevious":
|
||||
return gVariantNewBoolean(mprisCan(platform.MediaPrevious))
|
||||
case "CanPlay":
|
||||
return gVariantNewBoolean(mprisCan(platform.MediaPlay))
|
||||
case "CanPause":
|
||||
return gVariantNewBoolean(mprisCan(platform.MediaPause))
|
||||
case "CanSeek":
|
||||
return gVariantNewBoolean(mprisCan(platform.MediaSeek) && info.Duration > 0)
|
||||
case "CanControl":
|
||||
return gVariantNewBoolean(true)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func mprisMetadata() ptr {
|
||||
entry := func(key string, v ptr) ptr {
|
||||
return gVariantNewDictEntry(gVariantNewString(cs(key)), gVariantNewVariant(v))
|
||||
}
|
||||
entries := []ptr{entry("mpris:trackid", gVariantNewObjectPath(cs(mprisTrackID())))}
|
||||
if info := mpris.info; info != nil {
|
||||
if info.Title != "" {
|
||||
entries = append(entries, entry("xesam:title", gVariantNewString(cs(info.Title))))
|
||||
}
|
||||
if len(info.Artists) > 0 {
|
||||
artists := make([]ptr, len(info.Artists))
|
||||
for i, a := range info.Artists {
|
||||
artists[i] = gVariantNewString(cs(a))
|
||||
}
|
||||
entries = append(entries, entry("xesam:artist", gVariantNewArray(0, unsafe.Pointer(&artists[0]), uintptr(len(artists)))))
|
||||
}
|
||||
if info.Album != "" {
|
||||
entries = append(entries, entry("xesam:album", gVariantNewString(cs(info.Album))))
|
||||
}
|
||||
if info.Duration > 0 {
|
||||
entries = append(entries, entry("mpris:length", gVariantNewInt64(info.Duration.Microseconds())))
|
||||
}
|
||||
if mpris.art != "" {
|
||||
entries = append(entries, entry("mpris:artUrl", gVariantNewString(cs("file://"+mpris.art))))
|
||||
}
|
||||
}
|
||||
return gVariantNewArray(0, unsafe.Pointer(&entries[0]), uintptr(len(entries)))
|
||||
}
|
||||
|
||||
// mprisChanged emits PropertiesChanged with the values of props.
|
||||
func mprisChanged(iface string, props ...string) {
|
||||
entries := make([]ptr, len(props))
|
||||
for i, p := range props {
|
||||
entries[i] = gVariantNewDictEntry(gVariantNewString(cs(p)), gVariantNewVariant(mprisProperty(iface, p)))
|
||||
}
|
||||
params := tuple(
|
||||
gVariantNewString(cs(iface)),
|
||||
gVariantNewArray(0, unsafe.Pointer(&entries[0]), uintptr(len(entries))),
|
||||
gVariantNewArray(mprisStrings, nil, 0),
|
||||
)
|
||||
var gerr ptr
|
||||
if !gDBusConnectionEmitSignal(mpris.conn, nil, cs(mprisPath), cs("org.freedesktop.DBus.Properties"), cs("PropertiesChanged"), params, &gerr) {
|
||||
_ = gErr(gerr)
|
||||
}
|
||||
}
|
||||
|
||||
// mprisCall answers a method call, reporting the player's commands. GDBus
|
||||
// calls it on the main thread, whose main context registered the player.
|
||||
func mprisCall(iface, method string, params, inv ptr) {
|
||||
var cmd platform.MediaCommand
|
||||
var pos time.Duration
|
||||
switch method {
|
||||
case "Raise":
|
||||
cmd = platform.MediaRaise
|
||||
case "Play":
|
||||
cmd = platform.MediaPlay
|
||||
case "Pause":
|
||||
cmd = platform.MediaPause
|
||||
case "PlayPause":
|
||||
cmd = platform.MediaTogglePlayPause
|
||||
case "Stop":
|
||||
cmd = platform.MediaStop
|
||||
case "Next":
|
||||
cmd = platform.MediaNext
|
||||
case "Previous":
|
||||
cmd = platform.MediaPrevious
|
||||
case "Seek":
|
||||
child := gVariantGetChildValue(params, 0)
|
||||
offset := time.Duration(gVariantGetInt64(child)) * time.Microsecond
|
||||
gVariantUnref(child)
|
||||
cmd, pos = platform.MediaSeek, max(mprisPosition()+offset, 0)
|
||||
case "SetPosition":
|
||||
track := gVariantGetChildValue(params, 0)
|
||||
id := goStr(gVariantGetString(track, nil))
|
||||
gVariantUnref(track)
|
||||
child := gVariantGetChildValue(params, 1)
|
||||
pos = time.Duration(gVariantGetInt64(child)) * time.Microsecond
|
||||
gVariantUnref(child)
|
||||
// The specification ignores positions of other tracks, and out
|
||||
// of the track.
|
||||
if info := mpris.info; id == mprisTrackID() && info != nil && pos >= 0 && (info.Duration == 0 || pos <= info.Duration) {
|
||||
cmd = platform.MediaSeek
|
||||
}
|
||||
case "OpenUri":
|
||||
gDBusMethodInvocationReturnDBusError(inv, cs("org.freedesktop.DBus.Error.NotSupported"), cs("the player opens no URIs"))
|
||||
return
|
||||
}
|
||||
gDBusMethodInvocationReturnValue(inv, 0)
|
||||
if cmd != 0 && mpris.info != nil {
|
||||
theBackend.h.MediaCommand(cmd, pos)
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import "sync"
|
||||
|
||||
var (
|
||||
panelOnce sync.Once
|
||||
gdkWindowSetFunctions func(w ptr, functions uint32)
|
||||
)
|
||||
|
||||
// GdkWMFunction: what the window manager lets the user do to a panel.
|
||||
const (
|
||||
funcResize = 1 << 1
|
||||
funcMove = 1 << 2
|
||||
funcClose = 1 << 5
|
||||
)
|
||||
|
||||
// initPanel makes a new window a panel (WindowOptions.Panel), before it
|
||||
// shows, as launchers make theirs (Albert, Ulauncher): a utility window on
|
||||
// every workspace, out of the pager, which the window manager neither
|
||||
// minimizes nor maximizes (the Motif hints GDK sets). The options keep it
|
||||
// above other windows and out of the taskbar.
|
||||
func (w *window) initPanel() {
|
||||
if w.layer {
|
||||
return // initLayer made it a layer surface
|
||||
}
|
||||
loadFlyouts()
|
||||
panelOnce.Do(func() { mustBind(libGDK, &gdkWindowSetFunctions, "gdk_window_set_functions") })
|
||||
gtkWindowSetTypeHint(w.win, typeHintUtility)
|
||||
gtkWindowSetSkipPagerHint(w.win, true)
|
||||
gtkWindowStick(w.win)
|
||||
gtkWidgetRealize(w.win)
|
||||
gdkWindowSetFunctions(gtkWidgetGetWindow(w.win), funcResize|funcMove|funcClose)
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
func TestEventPhysicalKey(t *testing.T) {
|
||||
// The field order/types from GTK 3's gdk/gdkevents.h, without cgo.
|
||||
// In particular, the deprecated string pointer precedes hardware_keycode.
|
||||
type gdkEventKey struct {
|
||||
kind int32
|
||||
window uintptr
|
||||
sendEvent int8
|
||||
time uint32
|
||||
state uint32
|
||||
keyval uint32
|
||||
length int32
|
||||
text uintptr
|
||||
hardwareKeycode uint16
|
||||
group uint8
|
||||
isModifier uint32
|
||||
}
|
||||
var event gdkEventKey
|
||||
if offset := unsafe.Offsetof(event.hardwareKeycode); offset != 48 {
|
||||
t.Fatalf("hardware_keycode offset = %d, want 48", offset)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
code uint16
|
||||
want platform.Key
|
||||
}{
|
||||
{0, platform.KeyUnknown},
|
||||
{7, platform.KeyUnknown},
|
||||
{31 + 8, platform.KeyS},
|
||||
{41 + 8, platform.KeyBackquote},
|
||||
{53 + 8, platform.KeySlash},
|
||||
{98 + 8, platform.KeyUnknown}, // Keypad slash is not the main slash.
|
||||
} {
|
||||
event.hardwareKeycode = tc.code
|
||||
if got := eventPhysicalKey(ptr(unsafe.Pointer(&event))); got != tc.want {
|
||||
t.Errorf("hardware_keycode=%d: got %v, want %v", tc.code, got, tc.want)
|
||||
}
|
||||
runtime.KeepAlive(&event)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCursorNames(t *testing.T) {
|
||||
// Every cursor has its CSS name, which cursor themes name theirs by.
|
||||
for c := platform.CursorDefault; c <= platform.CursorNoDrop; c++ {
|
||||
if cursorNames[c] == "" {
|
||||
t.Errorf("cursor %d has no name", c)
|
||||
}
|
||||
}
|
||||
}
|
||||
+228
@@ -0,0 +1,228 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// The XDG desktop portal offers what the desktop decides on: settings,
|
||||
// inhibiting sleep, global shortcuts. Methods that may involve the user
|
||||
// return a request object at once and answer later with its Response
|
||||
// signal, which cbPortalSignal routes by the object's path.
|
||||
|
||||
const (
|
||||
portalName = "org.freedesktop.portal.Desktop"
|
||||
portalPath = "/org/freedesktop/portal/desktop"
|
||||
)
|
||||
|
||||
var (
|
||||
cbPortalSignal ptr
|
||||
portalRegistered bool
|
||||
portalListening bool
|
||||
portalRequests = map[string]func(code uint32, results ptr){}
|
||||
portalTokens int
|
||||
vardictType ptr
|
||||
)
|
||||
|
||||
// portalSignal handles the signals of the portal the backend subscribes
|
||||
// to.
|
||||
func portalSignal(conn, sender, path, iface, signal, params, data ptr) {
|
||||
switch goStr(signal) {
|
||||
case "Response":
|
||||
done := portalRequests[goStr(path)]
|
||||
if done == nil {
|
||||
return
|
||||
}
|
||||
delete(portalRequests, goStr(path))
|
||||
code := gVariantGetChildValue(params, 0)
|
||||
results := gVariantGetChildValue(params, 1)
|
||||
done(gVariantGetUint32(code), results)
|
||||
gVariantUnref(code)
|
||||
gVariantUnref(results)
|
||||
case "Activated":
|
||||
theBackend.shortcutActivated(params)
|
||||
case "ShortcutsChanged":
|
||||
if changed := theBackend.portal.changed; changed != nil {
|
||||
changed(params)
|
||||
}
|
||||
case "SettingChanged":
|
||||
// A preference, or the color scheme, changed.
|
||||
ns := gVariantGetChildValue(params, 0)
|
||||
name := goStr(gVariantGetString(ns, nil))
|
||||
gVariantUnref(ns)
|
||||
k := gVariantGetChildValue(params, 1)
|
||||
key := goStr(gVariantGetString(k, nil))
|
||||
gVariantUnref(k)
|
||||
if name != appearanceSettings && name != gnomeInterfaceSettings {
|
||||
return
|
||||
}
|
||||
if name == appearanceSettings && key == "color-scheme" && traysAppearanceChanged != nil {
|
||||
// The panels follow the desktop's scheme, whatever the app's.
|
||||
traysAppearanceChanged()
|
||||
}
|
||||
// GTK tells ThemeChanged itself when its setting changes.
|
||||
if name == appearanceSettings && key == "color-scheme" && followsSystem() && followSystemScheme(gtkSettingsGetDefault()) {
|
||||
return
|
||||
}
|
||||
theBackend.h.ThemeChanged()
|
||||
}
|
||||
}
|
||||
|
||||
// The namespaces of the settings portal that preferences come from.
|
||||
const (
|
||||
appearanceSettings = "org.freedesktop.appearance"
|
||||
gnomeInterfaceSettings = "org.gnome.desktop.interface"
|
||||
)
|
||||
|
||||
// watchPortalSettings follows the changes of the settings the desktop
|
||||
// portal gives.
|
||||
func watchPortalSettings() {
|
||||
if conn, err := bus(); err == nil {
|
||||
gDBusConnectionSignalSubscribe(conn, cs(portalName), cs("org.freedesktop.portal.Settings"), cs("SettingChanged"), cs(portalPath), nil, 0, cbPortalSignal, 0, 0)
|
||||
}
|
||||
}
|
||||
|
||||
// portalSettings reads the settings of namespaces from the desktop portal,
|
||||
// as a{sa{sv}}, which the caller unrefs.
|
||||
func portalSettings(namespaces ...string) (ptr, bool) {
|
||||
names := make([]ptr, len(namespaces))
|
||||
for i, n := range namespaces {
|
||||
names[i] = gVariantNewString(cs(n))
|
||||
}
|
||||
typ := gVariantTypeNew(cs("s"))
|
||||
arr := gVariantNewArray(typ, unsafe.Pointer(&names[0]), uintptr(len(names)))
|
||||
res, err := portalCall(portalPath, "org.freedesktop.portal.Settings", "ReadAll", tuple(arr), "(a{sa{sv}})")
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
all := gVariantGetChildValue(res, 0)
|
||||
gVariantUnref(res)
|
||||
return all, true
|
||||
}
|
||||
|
||||
// portalSetting returns the value of key in namespace of the settings
|
||||
// portalSettings read, if it is of type typ, which the caller unrefs.
|
||||
func portalSetting(all ptr, namespace, key, typ string) ptr {
|
||||
ns := gVariantLookupValue(all, cs(namespace), gVariantTypeNew(cs("a{sv}")))
|
||||
if ns == 0 {
|
||||
return 0
|
||||
}
|
||||
defer gVariantUnref(ns)
|
||||
v := gVariantLookupValue(ns, cs(key), 0)
|
||||
if v == 0 {
|
||||
return 0
|
||||
}
|
||||
if goStr(gVariantGetTypeString(v)) != typ {
|
||||
gVariantUnref(v)
|
||||
return 0
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// portalCall calls a method of the portal, after registering the app with
|
||||
// it, which must come first.
|
||||
func portalCall(path, iface, method string, params ptr, replyType string) (ptr, error) {
|
||||
registerWithPortal()
|
||||
return dbusCall(portalName, path, iface, method, params, replyType)
|
||||
}
|
||||
|
||||
// registerWithPortal tells the portal the app's ID, the name of its
|
||||
// desktop entry: portals know it only for sandboxed apps and apps the
|
||||
// desktop launched, and global shortcuts need it. The portal accepts it
|
||||
// before any other call, when the desktop entry is installed.
|
||||
func registerWithPortal() {
|
||||
if portalRegistered {
|
||||
return
|
||||
}
|
||||
portalRegistered = true
|
||||
id := strings.TrimSuffix(desktopEntryID(), ".desktop")
|
||||
params := tuple(gVariantNewString(cs(id)), vardict())
|
||||
if res, err := dbusCall(portalName, portalPath, "org.freedesktop.host.portal.Registry", "Register", params, ""); err == nil {
|
||||
gVariantUnref(res)
|
||||
}
|
||||
}
|
||||
|
||||
// portalRequest calls a portal method whose last argument is a vardict of
|
||||
// options, and which answers with a Response signal: done then gets the
|
||||
// response code, 0 when the request succeeded, and the results, which it
|
||||
// must not keep.
|
||||
func portalRequest(iface, method string, args []ptr, options []ptr, done func(code uint32, results ptr)) error {
|
||||
conn, err := bus()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !portalListening {
|
||||
portalListening = true
|
||||
gDBusConnectionSignalSubscribe(conn, cs(portalName), cs("org.freedesktop.portal.Request"), cs("Response"), nil, nil, 0, cbPortalSignal, 0, 0)
|
||||
}
|
||||
portalTokens++
|
||||
token := "mygo" + strconv.Itoa(portalTokens)
|
||||
sender := strings.ReplaceAll(strings.TrimPrefix(goStr(gDBusConnectionGetUniqueName(conn)), ":"), ".", "_")
|
||||
path := portalPath + "/request/" + sender + "/" + token
|
||||
portalRequests[path] = done
|
||||
options = append(options, vardictEntry("handle_token", gVariantNewString(cs(token))))
|
||||
res, err := portalCall(portalPath, iface, method, tuple(append(args, vardict(options...))...), "(o)")
|
||||
if err != nil {
|
||||
delete(portalRequests, path)
|
||||
return err
|
||||
}
|
||||
handle := gVariantGetChildValue(res, 0)
|
||||
if p := goStr(gVariantGetString(handle, nil)); p != path {
|
||||
delete(portalRequests, path) // portals before 0.9 pick the path
|
||||
portalRequests[p] = done
|
||||
}
|
||||
gVariantUnref(handle)
|
||||
gVariantUnref(res)
|
||||
return nil
|
||||
}
|
||||
|
||||
// portalVersion returns the version of a portal interface, 0 when the
|
||||
// desktop does not offer it.
|
||||
func portalVersion(iface string) uint32 {
|
||||
res, err := portalCall(portalPath, "org.freedesktop.DBus.Properties", "Get",
|
||||
tuple(gVariantNewString(cs(iface)), gVariantNewString(cs("version"))), "(v)")
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
defer gVariantUnref(res)
|
||||
v := gVariantGetChildValue(res, 0)
|
||||
inner := gVariantGetVariant(v)
|
||||
gVariantUnref(v)
|
||||
defer gVariantUnref(inner)
|
||||
if goStr(gVariantGetTypeString(inner)) != "u" {
|
||||
return 0
|
||||
}
|
||||
return gVariantGetUint32(inner)
|
||||
}
|
||||
|
||||
// vardict builds an a{sv} from entries made by vardictEntry.
|
||||
func vardict(entries ...ptr) ptr {
|
||||
if len(entries) == 0 {
|
||||
if vardictType == 0 {
|
||||
vardictType = gVariantTypeNew(cs("{sv}"))
|
||||
}
|
||||
return gVariantNewArray(vardictType, nil, 0)
|
||||
}
|
||||
return gVariantNewArray(0, unsafe.Pointer(&entries[0]), uintptr(len(entries)))
|
||||
}
|
||||
|
||||
func vardictEntry(key string, v ptr) ptr {
|
||||
return gVariantNewDictEntry(gVariantNewString(cs(key)), gVariantNewVariant(v))
|
||||
}
|
||||
|
||||
// vardictString returns the string (or object path) under key in an
|
||||
// a{sv}, "" when there is none.
|
||||
func vardictString(dict ptr, key string) string {
|
||||
v := gVariantLookupValue(dict, cs(key), 0)
|
||||
if v == 0 {
|
||||
return ""
|
||||
}
|
||||
defer gVariantUnref(v)
|
||||
if t := goStr(gVariantGetTypeString(v)); t != "s" && t != "o" {
|
||||
return ""
|
||||
}
|
||||
return goStr(gVariantGetString(v, nil))
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type power struct{ b *Backend }
|
||||
|
||||
// Watch listens to logind for sleep, on the system bus, and to the screen
|
||||
// savers of GNOME and of the freedesktop specification (KDE and others),
|
||||
// which lock the screen, on the session bus.
|
||||
func (p power) Watch() {
|
||||
var gerr ptr
|
||||
if system := gBusGetSync(1, 0, &gerr); system != 0 { // G_BUS_TYPE_SYSTEM
|
||||
gDBusConnectionSignalSubscribe(system, cs("org.freedesktop.login1"), cs("org.freedesktop.login1.Manager"),
|
||||
cs("PrepareForSleep"), cs("/org/freedesktop/login1"), nil, 0, cbPowerSignal, 0, 0)
|
||||
} else {
|
||||
_ = gErr(gerr)
|
||||
}
|
||||
if session, err := bus(); err == nil {
|
||||
for _, iface := range []string{"org.gnome.ScreenSaver", "org.freedesktop.ScreenSaver"} {
|
||||
gDBusConnectionSignalSubscribe(session, nil, cs(iface), cs("ActiveChanged"), nil, nil, 0, cbPowerSignal, 0, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// KeepRunning does nothing: Linux desktops do not slow down apps whose
|
||||
// windows are out of sight, as macOS's App Nap does.
|
||||
func (p power) KeepRunning(string) func() { return func() {} }
|
||||
|
||||
// KeepAwake asks the XDG desktop portal to inhibit suspending (and, with
|
||||
// display, the session going idle), else the freedesktop screen saver to
|
||||
// inhibit idleness.
|
||||
func (p power) KeepAwake(display bool, reason string) func() {
|
||||
const inhibitSuspend, inhibitIdle = 4, 8
|
||||
flags := uint32(inhibitSuspend)
|
||||
if display {
|
||||
flags |= inhibitIdle
|
||||
}
|
||||
params := tuple(gVariantNewString(cs("")), gVariantNewUint32(flags), vardict(vardictEntry("reason", gVariantNewString(cs(reason)))))
|
||||
if res, err := portalCall(portalPath, "org.freedesktop.portal.Inhibit", "Inhibit", params, "(o)"); err == nil {
|
||||
child := gVariantGetChildValue(res, 0)
|
||||
handle := goStr(gVariantGetString(child, nil))
|
||||
gVariantUnref(child)
|
||||
gVariantUnref(res)
|
||||
return func() {
|
||||
if res, err := portalCall(handle, "org.freedesktop.portal.Request", "Close", 0, ""); err == nil {
|
||||
gVariantUnref(res)
|
||||
}
|
||||
}
|
||||
}
|
||||
res, err := dbusCall("org.freedesktop.ScreenSaver", "/org/freedesktop/ScreenSaver", "org.freedesktop.ScreenSaver", "Inhibit",
|
||||
tuple(gVariantNewString(cs(appName())), gVariantNewString(cs(reason))), "(u)")
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
child := gVariantGetChildValue(res, 0)
|
||||
cookie := gVariantGetUint32(child)
|
||||
gVariantUnref(child)
|
||||
gVariantUnref(res)
|
||||
return func() {
|
||||
if res, err := dbusCall("org.freedesktop.ScreenSaver", "/org/freedesktop/ScreenSaver", "org.freedesktop.ScreenSaver", "UnInhibit",
|
||||
tuple(gVariantNewUint32(cookie)), ""); err == nil {
|
||||
gVariantUnref(res)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// OnBattery reports whether a battery discharges while no power supply is
|
||||
// online, from /sys/class/power_supply.
|
||||
func (p power) OnBattery() bool {
|
||||
read := func(dir, name string) string {
|
||||
b, _ := os.ReadFile(filepath.Join(dir, name))
|
||||
return strings.TrimSpace(string(b))
|
||||
}
|
||||
supplies, _ := filepath.Glob("/sys/class/power_supply/*")
|
||||
discharging := false
|
||||
for _, s := range supplies {
|
||||
switch read(s, "type") {
|
||||
case "Mains", "USB":
|
||||
if read(s, "online") == "1" {
|
||||
return false
|
||||
}
|
||||
case "Battery":
|
||||
if read(s, "scope") != "Device" && read(s, "status") == "Discharging" {
|
||||
discharging = true
|
||||
}
|
||||
}
|
||||
}
|
||||
return discharging
|
||||
}
|
||||
|
||||
// IdleTime asks GNOME's idle monitor, else the freedesktop screen saver
|
||||
// (KDE).
|
||||
func (p power) IdleTime() time.Duration {
|
||||
if res, err := dbusCall("org.gnome.Mutter.IdleMonitor", "/org/gnome/Mutter/IdleMonitor/Core", "org.gnome.Mutter.IdleMonitor", "GetIdletime", 0, "(t)"); err == nil {
|
||||
child := gVariantGetChildValue(res, 0)
|
||||
ms := gVariantGetUint64(child)
|
||||
gVariantUnref(child)
|
||||
gVariantUnref(res)
|
||||
return time.Duration(ms) * time.Millisecond
|
||||
}
|
||||
if res, err := dbusCall("org.freedesktop.ScreenSaver", "/org/freedesktop/ScreenSaver", "org.freedesktop.ScreenSaver", "GetSessionIdleTime", 0, "(u)"); err == nil {
|
||||
child := gVariantGetChildValue(res, 0)
|
||||
s := gVariantGetUint32(child)
|
||||
gVariantUnref(child)
|
||||
gVariantUnref(res)
|
||||
return time.Duration(s) * time.Second
|
||||
}
|
||||
return 0
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// ReplaceFile renames replacement over target, after giving it the
|
||||
// target's permissions and, where the user may, its owner and group, as
|
||||
// GIO's g_file_replace does.
|
||||
func (*Backend) ReplaceFile(target, replacement string) error {
|
||||
if info, err := os.Stat(target); err == nil {
|
||||
if err := os.Chmod(replacement, info.Mode().Perm()|info.Mode()&(os.ModeSetuid|os.ModeSetgid|os.ModeSticky)); err != nil {
|
||||
return err
|
||||
}
|
||||
if st, ok := info.Sys().(*syscall.Stat_t); ok {
|
||||
_ = os.Lchown(replacement, int(st.Uid), int(st.Gid))
|
||||
}
|
||||
}
|
||||
return os.Rename(replacement, target)
|
||||
}
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
var (
|
||||
cbScheme ptr
|
||||
cbHeaderForeach ptr
|
||||
headerSinks = map[ptr]http.Header{}
|
||||
)
|
||||
|
||||
func init() {
|
||||
cbScheme = purego.NewCallback(func(req, data ptr) { theBackend.serveScheme(req) })
|
||||
cbHeaderForeach = purego.NewCallback(func(name, value, data ptr) {
|
||||
if h := headerSinks[data]; h != nil {
|
||||
h.Add(goStr(name), goStr(value))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// registerScheme registers scheme on the web context ctx, unless
|
||||
// registered, the schemes registered on it, has it.
|
||||
func (b *Backend) registerScheme(ctx ptr, registered map[string]bool, scheme string) {
|
||||
if registered[scheme] {
|
||||
return
|
||||
}
|
||||
registered[scheme] = true
|
||||
webkitWebContextRegisterURIScheme(ctx, cs(scheme), cbScheme, 0, 0)
|
||||
sec := webkitWebContextGetSecurityManager(ctx)
|
||||
webkitSecurityManagerRegisterSecure(sec, cs(scheme))
|
||||
webkitSecurityManagerRegisterCORS(sec, cs(scheme))
|
||||
}
|
||||
|
||||
func (b *Backend) serveScheme(req ptr) {
|
||||
gObjectRef(req)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t := &schemeTask{req: req, cancel: cancel, fd: -1}
|
||||
w := b.byWebView[webkitURISchemeRequestGetWebView(req)]
|
||||
if w == nil || w.closed {
|
||||
t.Fail(context.Canceled)
|
||||
return
|
||||
}
|
||||
r := &platform.SchemeRequest{
|
||||
Context: ctx,
|
||||
Method: http.MethodGet,
|
||||
URL: goStr(webkitURISchemeRequestGetURI(req)),
|
||||
Header: http.Header{},
|
||||
Responder: t,
|
||||
}
|
||||
if webkitURISchemeRequestGetHTTPMethod != nil {
|
||||
if m := goStr(webkitURISchemeRequestGetHTTPMethod(req)); m != "" {
|
||||
r.Method = m
|
||||
}
|
||||
}
|
||||
if webkitURISchemeRequestGetHTTPHeaders != nil {
|
||||
if hdrs := webkitURISchemeRequestGetHTTPHeaders(req); hdrs != 0 {
|
||||
key := ptr(len(headerSinks) + 1)
|
||||
headerSinks[key] = r.Header
|
||||
soupMessageHeadersForeach(hdrs, cbHeaderForeach, key)
|
||||
delete(headerSinks, key)
|
||||
}
|
||||
}
|
||||
if webkitURISchemeRequestGetHTTPBody != nil {
|
||||
if stream := webkitURISchemeRequestGetHTTPBody(req); stream != 0 {
|
||||
r.Body = io.NopCloser(bytes.NewReader(readStream(stream)))
|
||||
gObjectUnref(stream)
|
||||
}
|
||||
}
|
||||
w.h.SchemeRequest(r)
|
||||
}
|
||||
|
||||
func readStream(stream ptr) []byte {
|
||||
var out []byte
|
||||
buf := make([]byte, 64<<10)
|
||||
for {
|
||||
var n uintptr
|
||||
var gerr ptr
|
||||
ok := gInputStreamReadAll(stream, unsafe.Pointer(&buf[0]), uintptr(len(buf)), &n, 0, &gerr)
|
||||
out = append(out, buf[:n]...)
|
||||
if gerr != 0 {
|
||||
gErrorFree(gerr)
|
||||
}
|
||||
if !ok || n < uintptr(len(buf)) {
|
||||
return out
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// schemeTask streams a response to WebKit through a pipe, which WebKit
|
||||
// reads on the main loop. The goroutine serving the request writes the
|
||||
// body into it (WriteBody), waiting while it is full, so the main loop
|
||||
// never blocks and a response WebKit reads slowly does not pile up in
|
||||
// memory. The other methods run on the main thread.
|
||||
type schemeTask struct {
|
||||
req ptr
|
||||
cancel context.CancelFunc
|
||||
responded bool
|
||||
done bool
|
||||
// fd is the write end of the pipe, -1 before Respond and once closed.
|
||||
fd int
|
||||
}
|
||||
|
||||
var errNoResponse = errors.New("mygo: the response was not started")
|
||||
|
||||
func (t *schemeTask) Respond(status int, h map[string][]string) {
|
||||
header := http.Header(h)
|
||||
if t.done || t.responded {
|
||||
return
|
||||
}
|
||||
var fds [2]int
|
||||
if err := syscall.Pipe2(fds[:], syscall.O_CLOEXEC); err != nil {
|
||||
t.Fail(err)
|
||||
return
|
||||
}
|
||||
t.responded = true
|
||||
stream := gUnixInputStreamNew(int32(fds[0]), true)
|
||||
length := int64(-1)
|
||||
if cl, err := strconv.ParseInt(header.Get("Content-Length"), 10, 64); err == nil {
|
||||
length = cl
|
||||
}
|
||||
if webkitURISchemeRequestFinishWithResponse != nil {
|
||||
resp := webkitURISchemeResponseNew(stream, length)
|
||||
webkitURISchemeResponseSetStatus(resp, uint32(status), nil)
|
||||
if ct := header.Get("Content-Type"); ct != "" {
|
||||
webkitURISchemeResponseSetContentType(resp, cs(ct))
|
||||
}
|
||||
hdrs := soupMessageHeadersNew(1) // SOUP_MESSAGE_HEADERS_RESPONSE
|
||||
for k, vs := range header {
|
||||
for _, v := range vs {
|
||||
soupMessageHeadersAppend(hdrs, cs(k), cs(v))
|
||||
}
|
||||
}
|
||||
webkitURISchemeResponseSetHTTPHeaders(resp, hdrs)
|
||||
webkitURISchemeRequestFinishWithResponse(t.req, resp)
|
||||
gObjectUnref(resp)
|
||||
} else {
|
||||
// WebKitGTK before 2.36 cannot send status codes or headers.
|
||||
webkitURISchemeRequestFinish(t.req, stream, length, optCS(header.Get("Content-Type")))
|
||||
}
|
||||
gObjectUnref(stream)
|
||||
t.release()
|
||||
t.fd = fds[1]
|
||||
}
|
||||
|
||||
// WriteBody writes to the pipe, blocking while it is full.
|
||||
func (t *schemeTask) WriteBody(p []byte) error {
|
||||
if t.fd < 0 {
|
||||
return errNoResponse
|
||||
}
|
||||
for len(p) > 0 {
|
||||
n, err := syscall.Write(t.fd, p)
|
||||
if err == syscall.EINTR {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
// The page no longer wants the response.
|
||||
t.cancel()
|
||||
return err
|
||||
}
|
||||
p = p[n:]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Write is not used: the body goes through WriteBody.
|
||||
func (t *schemeTask) Write([]byte) {}
|
||||
|
||||
func (t *schemeTask) Finish() {
|
||||
if t.done {
|
||||
return
|
||||
}
|
||||
if !t.responded {
|
||||
t.Respond(http.StatusOK, http.Header{})
|
||||
}
|
||||
t.done = true
|
||||
if t.fd >= 0 {
|
||||
syscall.Close(t.fd) // the end of the body
|
||||
t.fd = -1
|
||||
}
|
||||
}
|
||||
|
||||
func (t *schemeTask) Fail(err error) {
|
||||
if t.done {
|
||||
return
|
||||
}
|
||||
if !t.responded {
|
||||
t.responded = true
|
||||
gerr := gErrorNewLiteral(gQuarkFromString(cs("mygo")), 1, cs(err.Error()))
|
||||
webkitURISchemeRequestFinishError(t.req, gerr)
|
||||
gErrorFree(gerr)
|
||||
t.release()
|
||||
}
|
||||
t.Finish()
|
||||
}
|
||||
|
||||
func (t *schemeTask) release() {
|
||||
if t.req != 0 {
|
||||
gObjectUnref(t.req)
|
||||
t.req = 0
|
||||
}
|
||||
}
|
||||
+247
@@ -0,0 +1,247 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"sync"
|
||||
"unsafe"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
// secrets keeps secrets in the Secret Service (GNOME Keyring, KWallet,
|
||||
// KeePassXC…) through libsecret, with keytar's schema: the generic one,
|
||||
// whose attributes are the service and account. libsecret loads with the
|
||||
// first secret, independently of GTK, so secrets work before Init and
|
||||
// from any thread: its synchronous calls run their own main context.
|
||||
//
|
||||
// Without a store, the errors are platform.ErrUnsupported: no libsecret
|
||||
// (or one too old), no session bus, or no Secret Service on it, which
|
||||
// D-Bus reports as an unknown service or a name without an owner.
|
||||
type secrets struct{}
|
||||
|
||||
// libsecret's functions, loaded once.
|
||||
type secretAPI struct {
|
||||
err error
|
||||
|
||||
hashTableNewFull func(hash, equal, keyDestroy, valueDestroy ptr) ptr
|
||||
hashTableInsert func(table, key, value ptr) bool
|
||||
hashTableUnref func(table ptr)
|
||||
strdup func(s *byte) ptr
|
||||
free func(p ptr)
|
||||
errorFree func(e ptr)
|
||||
strHash, strEqual ptr
|
||||
freeFn ptr
|
||||
|
||||
schemaNewv func(name *byte, flags int32, attributes ptr) ptr
|
||||
schemaUnref func(schema ptr)
|
||||
valueNew func(secret unsafe.Pointer, length int, contentType *byte) ptr
|
||||
valueGet func(value ptr, length *uint) ptr
|
||||
valueUnref func(value ptr)
|
||||
storeBinary func(schema, attributes ptr, collection, label *byte, value, cancellable ptr, gerr *ptr) bool
|
||||
lookupBinary func(schema, attributes, cancellable ptr, gerr *ptr) ptr
|
||||
clear func(schema, attributes, cancellable ptr, gerr *ptr) bool
|
||||
|
||||
// GIO's, to tell that there is no Secret Service: the session bus, and
|
||||
// the domain of D-Bus's errors.
|
||||
busGetSync func(busType int32, cancellable ptr, gerr *ptr) ptr
|
||||
dbusErrorQuark uint32
|
||||
busMu sync.Mutex
|
||||
bus ptr // the session bus, once connected (a reference kept)
|
||||
|
||||
// schema is keytar's: org.freedesktop.Secret.Generic with the string
|
||||
// attributes service and account.
|
||||
schema ptr
|
||||
}
|
||||
|
||||
// noStoreError is having no credential store, for the reason it wraps:
|
||||
// platform.ErrUnsupported.
|
||||
type noStoreError struct{ err error }
|
||||
|
||||
func (e noStoreError) Error() string { return "no credential store: " + e.err.Error() }
|
||||
func (e noStoreError) Unwrap() []error { return []error{platform.ErrUnsupported, e.err} }
|
||||
|
||||
func noStore(err error) error { return noStoreError{err} }
|
||||
|
||||
var libsecret = sync.OnceValue(func() *secretAPI {
|
||||
s := &secretAPI{}
|
||||
glib, err := open("libglib-2.0.so.0")
|
||||
if err != nil {
|
||||
s.err = noStore(err)
|
||||
return s
|
||||
}
|
||||
gio, err := open("libgio-2.0.so.0")
|
||||
if err != nil {
|
||||
s.err = noStore(err)
|
||||
return s
|
||||
}
|
||||
lib, err := open("libsecret-1.so.0")
|
||||
if err != nil {
|
||||
s.err = noStore(fmt.Errorf("%w (install libsecret: libsecret-1-0 on Debian/Ubuntu, libsecret on Fedora)", err))
|
||||
return s
|
||||
}
|
||||
var dbusErrorQuark func() uint32
|
||||
mustBind(gio, &s.busGetSync, "g_bus_get_sync")
|
||||
mustBind(gio, &dbusErrorQuark, "g_dbus_error_quark")
|
||||
s.dbusErrorQuark = dbusErrorQuark()
|
||||
mustBind(glib, &s.hashTableNewFull, "g_hash_table_new_full")
|
||||
mustBind(glib, &s.hashTableInsert, "g_hash_table_insert")
|
||||
mustBind(glib, &s.hashTableUnref, "g_hash_table_unref")
|
||||
mustBind(glib, &s.strdup, "g_strdup")
|
||||
mustBind(glib, &s.free, "g_free")
|
||||
mustBind(glib, &s.errorFree, "g_error_free")
|
||||
for _, sym := range []struct {
|
||||
p *ptr
|
||||
name string
|
||||
}{{&s.strHash, "g_str_hash"}, {&s.strEqual, "g_str_equal"}, {&s.freeFn, "g_free"}} {
|
||||
if *sym.p, err = purego.Dlsym(glib, sym.name); err != nil {
|
||||
s.err = noStore(err)
|
||||
return s
|
||||
}
|
||||
}
|
||||
ok := bind(lib, &s.schemaNewv, "secret_schema_newv") &&
|
||||
bind(lib, &s.schemaUnref, "secret_schema_unref") &&
|
||||
bind(lib, &s.valueNew, "secret_value_new") &&
|
||||
bind(lib, &s.valueGet, "secret_value_get") &&
|
||||
bind(lib, &s.valueUnref, "secret_value_unref") &&
|
||||
bind(lib, &s.storeBinary, "secret_password_storev_binary_sync") &&
|
||||
bind(lib, &s.lookupBinary, "secret_password_lookupv_binary_sync") &&
|
||||
bind(lib, &s.clear, "secret_password_clearv_sync")
|
||||
if !ok {
|
||||
s.err = noStore(errors.New("libsecret is too old: secrets need libsecret 0.19 or later"))
|
||||
return s
|
||||
}
|
||||
types := s.hashTableNewFull(s.strHash, s.strEqual, s.freeFn, 0)
|
||||
s.hashTableInsert(types, s.strdup(cs("service")), 0) // SECRET_SCHEMA_ATTRIBUTE_STRING
|
||||
s.hashTableInsert(types, s.strdup(cs("account")), 0)
|
||||
s.schema = s.schemaNewv(cs("org.freedesktop.Secret.Generic"), 0, types) // SECRET_SCHEMA_NONE
|
||||
s.hashTableUnref(types)
|
||||
return s
|
||||
})
|
||||
|
||||
// attributes returns a new hash table with the attributes of the secret of
|
||||
// service and account, which the caller unrefs.
|
||||
func (s *secretAPI) attributes(service, account string) ptr {
|
||||
t := s.hashTableNewFull(s.strHash, s.strEqual, s.freeFn, s.freeFn)
|
||||
s.hashTableInsert(t, s.strdup(cs("service")), s.strdup(cs(service)))
|
||||
s.hashTableInsert(t, s.strdup(cs("account")), s.strdup(cs(account)))
|
||||
return t
|
||||
}
|
||||
|
||||
// ready returns the API once there is a session bus to reach the Secret
|
||||
// Service on, which libsecret connects to as well: GIO shares the
|
||||
// connection, which this keeps.
|
||||
func (s *secretAPI) ready() (*secretAPI, error) {
|
||||
if s.err != nil {
|
||||
return nil, s.err
|
||||
}
|
||||
s.busMu.Lock()
|
||||
defer s.busMu.Unlock()
|
||||
if s.bus == 0 {
|
||||
var gerr ptr
|
||||
if s.bus = s.busGetSync(2, 0, &gerr); s.bus == 0 { // G_BUS_TYPE_SESSION
|
||||
err := s.gErr(gerr)
|
||||
if err == nil {
|
||||
err = errors.New("no session bus")
|
||||
}
|
||||
return nil, noStore(fmt.Errorf("no session bus: %w", err))
|
||||
}
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// D-Bus's errors (GDBusError) of a bus without the Secret Service.
|
||||
const (
|
||||
dbusErrorServiceUnknown = 2
|
||||
dbusErrorNameHasNoOwner = 3
|
||||
dbusErrorNoServer = 11
|
||||
)
|
||||
|
||||
// gErr converts and frees a GError (GQuark domain, gint code, gchar
|
||||
// *message) without needing GTK's bindings.
|
||||
func (s *secretAPI) gErr(e ptr) error {
|
||||
if e == 0 {
|
||||
return nil
|
||||
}
|
||||
base := *(*unsafe.Pointer)(unsafe.Pointer(&e))
|
||||
domain, code := *(*uint32)(base), *(*int32)(unsafe.Add(base, 4))
|
||||
msg := goStr(*(*ptr)(unsafe.Add(base, 8)))
|
||||
s.errorFree(e)
|
||||
err := fmt.Errorf("secret service: %s", msg)
|
||||
if domain == s.dbusErrorQuark {
|
||||
switch code {
|
||||
case dbusErrorServiceUnknown, dbusErrorNameHasNoOwner, dbusErrorNoServer:
|
||||
return noStore(err)
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (secrets) SetSecret(service, account string, secret []byte) error {
|
||||
s, err := libsecret().ready()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
attrs := s.attributes(service, account)
|
||||
defer s.hashTableUnref(attrs)
|
||||
data := secret
|
||||
if len(data) == 0 {
|
||||
data = []byte{0} // a valid pointer for an empty secret
|
||||
}
|
||||
value := s.valueNew(unsafe.Pointer(&data[0]), len(secret), cs("application/octet-stream"))
|
||||
runtime.KeepAlive(data)
|
||||
defer s.valueUnref(value)
|
||||
var gerr ptr
|
||||
if !s.storeBinary(s.schema, attrs, nil, cs(service+"/"+account), value, 0, &gerr) {
|
||||
if err := s.gErr(gerr); err != nil {
|
||||
return err
|
||||
}
|
||||
return fmt.Errorf("secret service: cannot store the secret")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (secrets) Secret(service, account string) ([]byte, error) {
|
||||
s, err := libsecret().ready()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
attrs := s.attributes(service, account)
|
||||
defer s.hashTableUnref(attrs)
|
||||
var gerr ptr
|
||||
value := s.lookupBinary(s.schema, attrs, 0, &gerr)
|
||||
if err := s.gErr(gerr); err != nil {
|
||||
if value != 0 {
|
||||
s.valueUnref(value)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if value == 0 {
|
||||
return nil, platform.ErrSecretNotFound
|
||||
}
|
||||
defer s.valueUnref(value)
|
||||
var n uint
|
||||
p := s.valueGet(value, &n)
|
||||
if p == 0 || n == 0 {
|
||||
return []byte{}, nil
|
||||
}
|
||||
base := *(*unsafe.Pointer)(unsafe.Pointer(&p))
|
||||
return append([]byte(nil), unsafe.Slice((*byte)(base), n)...), nil
|
||||
}
|
||||
|
||||
func (secrets) DeleteSecret(service, account string) error {
|
||||
s, err := libsecret().ready()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
attrs := s.attributes(service, account)
|
||||
defer s.hashTableUnref(attrs)
|
||||
var gerr ptr
|
||||
s.clear(s.schema, attrs, 0, &gerr) // false without an error: nothing to delete
|
||||
return s.gErr(gerr)
|
||||
}
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"sync"
|
||||
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
// Sessions (mygo.Session): a store is a WebKitWebContext of its own, with
|
||||
// a WebKitWebsiteDataManager whose data and caches are in the store's
|
||||
// directories, or kept in memory for an ephemeral one. Its web views are
|
||||
// made with the context; custom schemes, the languages and downloads are
|
||||
// set up on it as on the default context.
|
||||
|
||||
var (
|
||||
sessionsOnce sync.Once
|
||||
webkitWebsiteDataManagerNew func(k1, v1, k2, v2 *byte, end ptr) ptr
|
||||
webkitWebsiteDataManagerNewEphemeral func() ptr
|
||||
webkitWebContextNewWithWebsiteDataManager func(manager ptr) ptr
|
||||
webkitWebViewGetType func() uintptr
|
||||
gObjectNewWebView func(t uintptr, k1 *byte, v1 ptr, k2 *byte, v2 ptr, end ptr) ptr
|
||||
)
|
||||
|
||||
func bindSessions() {
|
||||
bind(libWebKit, &webkitWebsiteDataManagerNew, "webkit_website_data_manager_new")
|
||||
bind(libWebKit, &webkitWebsiteDataManagerNewEphemeral, "webkit_website_data_manager_new_ephemeral")
|
||||
bind(libWebKit, &webkitWebContextNewWithWebsiteDataManager, "webkit_web_context_new_with_website_data_manager")
|
||||
bind(libWebKit, &webkitWebViewGetType, "webkit_web_view_get_type")
|
||||
bind(libGObject, &gObjectNewWebView, "g_object_new")
|
||||
}
|
||||
|
||||
// dataStore is a store of the pages of a session: a web context, and the
|
||||
// custom schemes registered on it.
|
||||
type dataStore struct {
|
||||
b *Backend
|
||||
ctx ptr
|
||||
schemes map[string]bool
|
||||
closed bool
|
||||
}
|
||||
|
||||
// NewDataStore makes a web context with a website data manager of its
|
||||
// own: WebKitGTK 2.16 or newer.
|
||||
func (a appController) NewDataStore(opts platform.DataStoreOptions) (platform.DataStore, error) {
|
||||
if err := webKit(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sessionsOnce.Do(bindSessions)
|
||||
if webkitWebsiteDataManagerNew == nil || webkitWebsiteDataManagerNewEphemeral == nil || webkitWebContextNewWithWebsiteDataManager == nil || webkitWebViewGetType == nil || gObjectNewWebView == nil {
|
||||
return nil, fmt.Errorf("sessions need WebKitGTK 2.16 or newer: %w", platform.ErrUnsupported)
|
||||
}
|
||||
var manager ptr
|
||||
if opts.Ephemeral {
|
||||
manager = webkitWebsiteDataManagerNewEphemeral()
|
||||
} else {
|
||||
if opts.DataDir == "" || opts.CacheDir == "" {
|
||||
return nil, fmt.Errorf("no directory for the session's data")
|
||||
}
|
||||
if err := os.MkdirAll(opts.DataDir, 0o700); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
manager = webkitWebsiteDataManagerNew(cs("base-data-directory"), cs(opts.DataDir), cs("base-cache-directory"), cs(opts.CacheDir), 0)
|
||||
}
|
||||
if manager == 0 {
|
||||
return nil, fmt.Errorf("WebKitGTK made no website data manager")
|
||||
}
|
||||
ctx := webkitWebContextNewWithWebsiteDataManager(manager)
|
||||
gObjectUnref(manager) // the context holds it
|
||||
s := &dataStore{b: a.b, ctx: ctx, schemes: map[string]bool{}}
|
||||
a.b.stores = append(a.b.stores, s)
|
||||
a.b.applyWebLanguages()
|
||||
connect(ctx, "download-started", cbDownloadStarted, 0)
|
||||
if !opts.Ephemeral && cookieManager != nil && cookieSetPersistentStorage != nil {
|
||||
// As the default context's (persistCookies): WebKitGTK keeps
|
||||
// cookies in memory unless told where to store them.
|
||||
const sqlite = 1 // WEBKIT_COOKIE_PERSISTENT_STORAGE_SQLITE
|
||||
cookieSetPersistentStorage(cookieManager(ctx), cs(filepath.Join(opts.DataDir, "cookies.sqlite")), sqlite)
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// Close drops the backend's reference to the context, which its web
|
||||
// views keep while they live: an ephemeral one's data goes with the last.
|
||||
func (s *dataStore) Close() {
|
||||
if s.closed {
|
||||
return
|
||||
}
|
||||
s.closed = true
|
||||
s.b.stores = slices.DeleteFunc(s.b.stores, func(x *dataStore) bool { return x == s })
|
||||
gObjectUnref(s.ctx)
|
||||
}
|
||||
|
||||
// webContext returns the web context of store, the default one for nil.
|
||||
func webContext(store platform.DataStore) ptr {
|
||||
if s, ok := store.(*dataStore); ok {
|
||||
return s.ctx
|
||||
}
|
||||
return webkitWebContextGetDefault()
|
||||
}
|
||||
|
||||
// newWebView makes the web view of w, with the web context of its store.
|
||||
func (w *window) newWebView() ptr {
|
||||
s, ok := w.opts.DataStore.(*dataStore)
|
||||
if !ok {
|
||||
for _, scheme := range w.opts.Schemes {
|
||||
w.b.registerScheme(webkitWebContextGetDefault(), w.b.schemes, scheme)
|
||||
}
|
||||
return webkitWebViewNewWithUserContentManager(w.ucm)
|
||||
}
|
||||
for _, scheme := range w.opts.Schemes {
|
||||
w.b.registerScheme(s.ctx, s.schemes, scheme)
|
||||
}
|
||||
return gObjectNewWebView(webkitWebViewGetType(), cs("web-context"), s.ctx, cs("user-content-manager"), w.ucm, 0)
|
||||
}
|
||||
|
||||
// websiteDataTypes returns the WebKitWebsiteDataTypes of types.
|
||||
func websiteDataTypes(types platform.SiteData) uint32 {
|
||||
if types.All() {
|
||||
return 1<<14 - 1 // WEBKIT_WEBSITE_DATA_ALL
|
||||
}
|
||||
var out uint32
|
||||
if types&platform.SiteDataCookies != 0 {
|
||||
out |= 1 << 8 // COOKIES
|
||||
}
|
||||
if types&platform.SiteDataLocalStorage != 0 {
|
||||
out |= 1<<3 | 1<<4 // SESSION_STORAGE, LOCAL_STORAGE
|
||||
}
|
||||
if types&platform.SiteDataIndexedDB != 0 {
|
||||
out |= 1<<5 | 1<<6 // WEBSQL_DATABASES, INDEXEDDB_DATABASES
|
||||
}
|
||||
if types&platform.SiteDataCaches != 0 {
|
||||
out |= 1<<0 | 1<<1 | 1<<2 | 1<<13 // MEMORY_CACHE, DISK_CACHE, OFFLINE_APPLICATION_CACHE, DOM_CACHE
|
||||
}
|
||||
if types&platform.SiteDataServiceWorkers != 0 {
|
||||
out |= 1 << 12 // SERVICE_WORKER_REGISTRATIONS
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// WebKitGTK's session state (2.12+), bound the first time a page's is
|
||||
// saved or restored.
|
||||
var (
|
||||
webkitWebViewGetSessionState func(wv ptr) ptr
|
||||
webkitWebViewRestoreSessionState func(wv, state ptr)
|
||||
webkitWebViewSessionStateNew func(bytes ptr) ptr
|
||||
webkitWebViewSessionStateSerialize func(state ptr) ptr
|
||||
webkitWebViewSessionStateUnref func(state ptr)
|
||||
webkitWebViewGetBackForwardList func(wv ptr) ptr
|
||||
webkitBackForwardListGetCurrentItem func(list ptr) ptr
|
||||
webkitWebViewGoToBackForwardListItem func(wv, item ptr)
|
||||
gBytesGetData func(bytes ptr, size *uintptr) unsafe.Pointer
|
||||
sessionStateOnce sync.Once
|
||||
sessionStateBound bool
|
||||
)
|
||||
|
||||
func bindSessionState() bool {
|
||||
sessionStateOnce.Do(func() {
|
||||
w := libWebKit
|
||||
sessionStateBound = bind(w, &webkitWebViewGetSessionState, "webkit_web_view_get_session_state") &&
|
||||
bind(w, &webkitWebViewRestoreSessionState, "webkit_web_view_restore_session_state") &&
|
||||
bind(w, &webkitWebViewSessionStateNew, "webkit_web_view_session_state_new") &&
|
||||
bind(w, &webkitWebViewSessionStateSerialize, "webkit_web_view_session_state_serialize") &&
|
||||
bind(w, &webkitWebViewSessionStateUnref, "webkit_web_view_session_state_unref") &&
|
||||
bind(w, &webkitWebViewGetBackForwardList, "webkit_web_view_get_back_forward_list") &&
|
||||
bind(w, &webkitBackForwardListGetCurrentItem, "webkit_back_forward_list_get_current_item") &&
|
||||
bind(w, &webkitWebViewGoToBackForwardListItem, "webkit_web_view_go_to_back_forward_list_item") &&
|
||||
bind(libGLib, &gBytesNew, "g_bytes_new") && bind(libGLib, &gBytesUnref, "g_bytes_unref") &&
|
||||
bind(libGLib, &gBytesGetData, "g_bytes_get_data")
|
||||
})
|
||||
return sessionStateBound
|
||||
}
|
||||
|
||||
// SessionState serializes webkit_web_view_get_session_state: the
|
||||
// back/forward list, in WebKitGTK's own versioned encoding.
|
||||
func (w *window) SessionState() []byte {
|
||||
if !bindSessionState() {
|
||||
return nil
|
||||
}
|
||||
state := webkitWebViewGetSessionState(w.web)
|
||||
data := webkitWebViewSessionStateSerialize(state)
|
||||
webkitWebViewSessionStateUnref(state)
|
||||
var n uintptr
|
||||
p := gBytesGetData(data, &n)
|
||||
b := append([]byte{}, unsafe.Slice((*byte)(p), n)...)
|
||||
gBytesUnref(data)
|
||||
return b
|
||||
}
|
||||
|
||||
// RestoreSessionState puts back the back/forward list, which
|
||||
// webkit_web_view_restore_session_state does without loading anything,
|
||||
// then goes to its current item, as Epiphany does. A state WebKitGTK
|
||||
// can't read makes no session state.
|
||||
func (w *window) RestoreSessionState(b []byte) bool {
|
||||
if len(b) == 0 || !bindSessionState() {
|
||||
return false
|
||||
}
|
||||
data := gBytesNew(&b[0], uintptr(len(b)))
|
||||
state := webkitWebViewSessionStateNew(data)
|
||||
gBytesUnref(data)
|
||||
if state == 0 {
|
||||
return false
|
||||
}
|
||||
webkitWebViewRestoreSessionState(w.web, state)
|
||||
webkitWebViewSessionStateUnref(state)
|
||||
item := webkitBackForwardListGetCurrentItem(webkitWebViewGetBackForwardList(w.web))
|
||||
if item == 0 {
|
||||
return false
|
||||
}
|
||||
webkitWebViewGoToBackForwardListItem(w.web, item)
|
||||
return true
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import "testing"
|
||||
|
||||
// A Signal before Init is done, as from a goroutine posting while the app
|
||||
// starts, adds no idle source and leaves the backend unsignaled, so that
|
||||
// the Signal at the end of Init and those after it dispatch (#1770).
|
||||
func TestSignalBeforeInit(t *testing.T) {
|
||||
saved := gIdleAddFull
|
||||
defer func() { gIdleAddFull = saved }()
|
||||
var added []ptr
|
||||
gIdleAddFull = func(_ int32, fn, _, _ ptr) uint32 {
|
||||
added = append(added, fn)
|
||||
return 1
|
||||
}
|
||||
|
||||
b := &Backend{}
|
||||
b.Signal()
|
||||
if len(added) != 0 || b.signaled.Load() {
|
||||
t.Fatalf("before Init: added %v, signaled %v", added, b.signaled.Load())
|
||||
}
|
||||
|
||||
// As Init ends.
|
||||
b.signalable.Store(true)
|
||||
b.Signal()
|
||||
if len(added) != 1 || !b.signaled.Load() {
|
||||
t.Fatalf("after Init: added %v, signaled %v", added, b.signaled.Load())
|
||||
}
|
||||
b.Signal()
|
||||
if len(added) != 1 {
|
||||
t.Fatalf("signaled twice before dispatching: added %v", added)
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// The app's style sheet (Theme.SetGTKCSS) is a provider of its own, for
|
||||
// the default screen, at GTK_STYLE_PROVIDER_PRIORITY_USER: above the
|
||||
// theme's and MyGo's own (titlebar.go), and above the user's gtk.css, which
|
||||
// has that priority too but was added first. Only apps that set a sheet
|
||||
// reach this file: the core calls it through platform.StyleBackend.
|
||||
|
||||
const priorityUser = 800 // GTK_STYLE_PROVIDER_PRIORITY_USER
|
||||
|
||||
var (
|
||||
styleOnce sync.Once
|
||||
gdkScreenGetDefault func() ptr
|
||||
gtkStyleContextRemoveProviderForScreen func(screen, provider ptr)
|
||||
|
||||
// styleProvider holds the sheet loaded last, 0 for none. Main thread
|
||||
// only.
|
||||
styleProvider ptr
|
||||
)
|
||||
|
||||
// SetStyleSheet loads css into a new provider and puts it in place of the
|
||||
// one before, which stays when css does not parse: GTK resets a provider
|
||||
// before it parses, and keeps the rules before an error.
|
||||
func (b *Backend) SetStyleSheet(css string) error {
|
||||
styleOnce.Do(func() {
|
||||
mustBind(libGDK, &gdkScreenGetDefault, "gdk_screen_get_default")
|
||||
mustBind(libGTK, >kStyleContextRemoveProviderForScreen, "gtk_style_context_remove_provider_for_screen")
|
||||
})
|
||||
screen := gdkScreenGetDefault()
|
||||
var provider ptr
|
||||
if css != "" {
|
||||
provider = gtkCssProviderNew()
|
||||
// With an error to fill, GTK reports the first parse error there
|
||||
// rather than as a warning, and returns false.
|
||||
var gerr ptr
|
||||
if !gtkCssProviderLoadFromData(provider, cs(css), len(css), &gerr) || gerr != 0 {
|
||||
gObjectUnref(provider)
|
||||
if gerr == 0 {
|
||||
return errors.New("GTK did not load the style sheet")
|
||||
}
|
||||
return gErr(gerr)
|
||||
}
|
||||
gtkStyleContextAddProviderForScreen(screen, provider, priorityUser)
|
||||
}
|
||||
if styleProvider != 0 {
|
||||
gtkStyleContextRemoveProviderForScreen(screen, styleProvider)
|
||||
gObjectUnref(styleProvider)
|
||||
}
|
||||
styleProvider = provider
|
||||
return nil
|
||||
}
|
||||
+1441
File diff suppressed because it is too large.
Load diff
+1598
File diff suppressed because it is too large.
Load diff
+399
@@ -0,0 +1,399 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"image"
|
||||
"image/png"
|
||||
"slices"
|
||||
"unsafe"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
"github.com/egoist/mygo/transfer"
|
||||
)
|
||||
|
||||
// Selection data arrives asynchronously. Only accepted formats are read
|
||||
// after drop, before acknowledging the negotiated effect.
|
||||
var (
|
||||
gtkDragDestSet func(ptr, int32, unsafe.Pointer, int32, int32)
|
||||
gtkDragGetData func(ptr, ptr, ptr, uint32)
|
||||
gtkDragFinish func(ptr, bool, bool, uint32)
|
||||
gdkDragStatus func(ptr, int32, uint32)
|
||||
gtkTargetListNew func(unsafe.Pointer, uint32) ptr
|
||||
gtkTargetListUnref func(ptr)
|
||||
gtkDragBeginCoordinates func(ptr, ptr, int32, int32, ptr, int32, int32) ptr
|
||||
gtkDragCancel func(ptr)
|
||||
gtkDragSetIconPixbuf func(ptr, ptr, int32, int32)
|
||||
gtkDragGetSourceWidget func(ptr) ptr
|
||||
gdkDragContextTargets func(ptr) ptr
|
||||
gdkDragContextActions func(ptr) int32
|
||||
gdkDragContextSuggested func(ptr) int32
|
||||
gdkDragContextSelected func(ptr) int32
|
||||
gtkSelectionDataSet func(ptr, ptr, int32, *byte, int32)
|
||||
gtkSelectionDataTarget func(ptr) ptr
|
||||
cbSurfaceDragMotion, cbSurfaceDragLeave, cbSurfaceDragDrop, cbSurfaceDragData ptr
|
||||
cbSurfaceDragGet, cbSurfaceDragEnd, cbSurfaceDragFailed, cbSurfaceDragDelete ptr
|
||||
gtkDataSources = map[ptr]*surface{}
|
||||
)
|
||||
|
||||
const (
|
||||
gdkActionCopy = 1 << 1
|
||||
gdkActionMove = 1 << 2
|
||||
)
|
||||
|
||||
type gtkTargetEntry struct {
|
||||
target *byte
|
||||
flags, info uint32
|
||||
}
|
||||
type gtkDataDrop struct {
|
||||
context ptr
|
||||
event *platform.DataDragEvent
|
||||
x, y float64
|
||||
time uint32
|
||||
pending map[ptr][]transfer.Format
|
||||
reps []transfer.Representation
|
||||
failed bool
|
||||
}
|
||||
|
||||
func loadDrops() {
|
||||
mustBind(libGTK, >kDragDestSet, "gtk_drag_dest_set")
|
||||
mustBind(libGTK, >kDragGetData, "gtk_drag_get_data")
|
||||
mustBind(libGTK, >kDragFinish, "gtk_drag_finish")
|
||||
mustBind(libGDK, &gdkDragStatus, "gdk_drag_status")
|
||||
mustBind(libGTK, >kTargetListNew, "gtk_target_list_new")
|
||||
mustBind(libGTK, >kTargetListUnref, "gtk_target_list_unref")
|
||||
mustBind(libGTK, >kDragBeginCoordinates, "gtk_drag_begin_with_coordinates")
|
||||
mustBind(libGTK, >kDragCancel, "gtk_drag_cancel")
|
||||
mustBind(libGTK, >kDragSetIconPixbuf, "gtk_drag_set_icon_pixbuf")
|
||||
mustBind(libGTK, >kDragGetSourceWidget, "gtk_drag_get_source_widget")
|
||||
mustBind(libGDK, &gdkDragContextTargets, "gdk_drag_context_list_targets")
|
||||
mustBind(libGDK, &gdkDragContextActions, "gdk_drag_context_get_actions")
|
||||
mustBind(libGDK, &gdkDragContextSuggested, "gdk_drag_context_get_suggested_action")
|
||||
mustBind(libGDK, &gdkDragContextSelected, "gdk_drag_context_get_selected_action")
|
||||
mustBind(libGTK, >kSelectionDataSet, "gtk_selection_data_set")
|
||||
mustBind(libGTK, >kSelectionDataTarget, "gtk_selection_data_get_target")
|
||||
b := func() *Backend { return theBackend }
|
||||
cbSurfaceDragMotion = purego.NewCallback(func(widget, context ptr, x, y int32, time uint32, data ptr) bool {
|
||||
s := b().surfaceOf(data)
|
||||
if s == nil {
|
||||
return false
|
||||
}
|
||||
d, _ := gtkOffer(context)
|
||||
taken := s.send(platform.SurfaceEvent{Kind: platform.DataDragOver, X: float64(x), Y: float64(y), Drag: d})
|
||||
gdkDragStatus(context, gtkOperations(d.Operation), time)
|
||||
return taken
|
||||
})
|
||||
cbSurfaceDragLeave = purego.NewCallback(func(widget, context ptr, time uint32, data ptr) {
|
||||
if s := b().surfaceOf(data); s != nil {
|
||||
s.send(platform.SurfaceEvent{Kind: platform.DataDragLeave, Drag: &platform.DataDragEvent{}})
|
||||
}
|
||||
})
|
||||
cbSurfaceDragDrop = purego.NewCallback(func(widget, context ptr, x, y int32, time uint32, data ptr) bool {
|
||||
s := b().surfaceOf(data)
|
||||
if s == nil {
|
||||
return false
|
||||
}
|
||||
d, targets := gtkOffer(context)
|
||||
if !s.send(platform.SurfaceEvent{Kind: platform.DataDragOver, X: float64(x), Y: float64(y), Drag: d}) {
|
||||
return false
|
||||
}
|
||||
if len(d.Data.Formats()) > 0 {
|
||||
// A recognized local source preserves item boundaries and typed values.
|
||||
taken := s.send(platform.SurfaceEvent{Kind: platform.DataDrop, X: float64(x), Y: float64(y), Drag: d})
|
||||
gtkDragFinish(context, taken, taken && d.Operation == transfer.Move, time)
|
||||
return true
|
||||
}
|
||||
s.cancelPendingDrop()
|
||||
drop := >kDataDrop{context: gObjectRef(context), event: d, x: float64(x), y: float64(y), time: time, pending: map[ptr][]transfer.Format{}}
|
||||
for _, f := range d.Formats {
|
||||
if atom := targets[f]; atom != 0 {
|
||||
drop.pending[atom] = append(drop.pending[atom], f)
|
||||
}
|
||||
}
|
||||
if len(drop.pending) == 0 {
|
||||
gtkDragFinish(context, false, false, time)
|
||||
gObjectUnref(drop.context)
|
||||
return true
|
||||
}
|
||||
s.dataDrop = drop
|
||||
for atom := range drop.pending {
|
||||
gtkDragGetData(widget, context, atom, time)
|
||||
}
|
||||
return true
|
||||
})
|
||||
cbSurfaceDragData = purego.NewCallback(func(widget, context ptr, x, y int32, sel ptr, info, time uint32, data ptr) {
|
||||
s := b().surfaceOf(data)
|
||||
if s == nil || s.dataDrop == nil || s.dataDrop.context != context {
|
||||
return
|
||||
}
|
||||
drop := s.dataDrop
|
||||
atom := gtkSelectionDataTarget(sel)
|
||||
formats, exists := drop.pending[atom]
|
||||
if !exists {
|
||||
return
|
||||
}
|
||||
delete(drop.pending, atom)
|
||||
n, p := gtkSelectionDataGetLength(sel), gtkSelectionDataGetData(sel)
|
||||
if n < 0 || n > 64<<20 || (n > 0 && p == 0) {
|
||||
drop.failed = true
|
||||
} else {
|
||||
var buf []byte
|
||||
if n > 0 {
|
||||
buf = bytes.Clone(unsafe.Slice(*(**byte)(unsafe.Pointer(&p)), n))
|
||||
}
|
||||
for _, f := range formats {
|
||||
if f == transfer.FileList {
|
||||
files, _ := transfer.New(transfer.NewItem(transfer.Bytes(transfer.URIList, buf))).Files()
|
||||
if len(files) == 0 {
|
||||
continue
|
||||
}
|
||||
}
|
||||
drop.reps = append(drop.reps, transfer.Bytes(f, buf))
|
||||
}
|
||||
}
|
||||
if len(drop.pending) != 0 {
|
||||
return
|
||||
}
|
||||
s.dataDrop = nil
|
||||
taken := false
|
||||
if !drop.failed {
|
||||
drop.event.Data = transfer.New(transfer.NewItem(drop.reps...))
|
||||
taken = s.send(platform.SurfaceEvent{Kind: platform.DataDrop, X: drop.x, Y: drop.y, Drag: drop.event})
|
||||
}
|
||||
gtkDragFinish(context, taken, taken && drop.event.Operation == transfer.Move, drop.time)
|
||||
gObjectUnref(drop.context)
|
||||
})
|
||||
cbSurfaceDragGet = purego.NewCallback(func(widget, context, sel ptr, info, time uint32, data ptr) {
|
||||
s := b().surfaceOf(data)
|
||||
if s == nil || s.dragRequest == nil {
|
||||
return
|
||||
}
|
||||
r, atom := s.dragRequest, gtkSelectionDataTarget(sel)
|
||||
f := gtkFormat(takeStr(gdkAtomName(atom)))
|
||||
var buf []byte
|
||||
var err error
|
||||
if f == platform.DragSessionFormat {
|
||||
buf = []byte(r.Session)
|
||||
} else {
|
||||
buf, err = r.Data.Read(f)
|
||||
}
|
||||
if err != nil {
|
||||
s.dragError = err
|
||||
return
|
||||
}
|
||||
if len(buf) == 0 {
|
||||
buf = []byte{0}
|
||||
gtkSelectionDataSet(sel, atom, 8, &buf[0], 0)
|
||||
} else {
|
||||
gtkSelectionDataSet(sel, atom, 8, &buf[0], int32(len(buf)))
|
||||
}
|
||||
})
|
||||
cbSurfaceDragFailed = purego.NewCallback(func(widget, context ptr, result int32, data ptr) bool {
|
||||
s := b().surfaceOf(data)
|
||||
if s == nil {
|
||||
s = gtkDataSources[widget]
|
||||
}
|
||||
if s != nil && s.dragRequest != nil {
|
||||
// GTK_NO_TARGET=1 and USER_CANCELLED=2 are normal no-drop
|
||||
// results. gtk_drag_cancel can also abort with a generic error;
|
||||
// our explicit cancellation must remain a cancellation. Only
|
||||
// USER_CANCELLED (Escape) and ours are Escaped.
|
||||
explicit := s.dragCanceled
|
||||
canceled := explicit || result == 1 || result == 2
|
||||
s.dragCanceled = true
|
||||
s.dragEscaped = s.dragEscaped || result == 2
|
||||
if !canceled && result > 2 {
|
||||
s.dragError = errors.New("mygo: GTK drag failed")
|
||||
}
|
||||
// An explicit cancel (including destruction) must release the
|
||||
// tracker immediately, without a snap-back animation holding
|
||||
// the input grab after the app reports cancellation.
|
||||
return explicit
|
||||
}
|
||||
return false
|
||||
})
|
||||
cbSurfaceDragEnd = purego.NewCallback(func(widget, context, data ptr) {
|
||||
s := b().surfaceOf(data)
|
||||
if s == nil {
|
||||
s = gtkDataSources[widget]
|
||||
}
|
||||
if s == nil || s.dragRequest == nil {
|
||||
return
|
||||
}
|
||||
r := s.dragRequest
|
||||
op := goGTKOperations(gdkDragContextSelected(context))
|
||||
if s.dragCanceled || s.dragError != nil {
|
||||
op = transfer.None
|
||||
}
|
||||
delete(gtkDataSources, widget)
|
||||
s.dragRequest, s.dragContext = nil, 0
|
||||
if s.lastPointer != 0 {
|
||||
gdkEventFree(s.lastPointer)
|
||||
s.lastPointer = 0
|
||||
}
|
||||
p := screen{}.CursorPoint()
|
||||
canceled := op == transfer.None && s.dragError == nil
|
||||
r.Done(transfer.Result{Operation: op, Canceled: canceled, Escaped: canceled && s.dragEscaped, Point: image.Point{X: p.X, Y: p.Y}, Err: s.dragError})
|
||||
})
|
||||
// The app's Done callback owns removal after a successful move.
|
||||
cbSurfaceDragDelete = purego.NewCallback(func(widget, context, data ptr) {})
|
||||
}
|
||||
func gtkOperations(o transfer.Operation) int32 {
|
||||
var n int32
|
||||
if o&transfer.Copy != 0 {
|
||||
n |= gdkActionCopy
|
||||
}
|
||||
if o&transfer.Move != 0 {
|
||||
n |= gdkActionMove
|
||||
}
|
||||
return n
|
||||
}
|
||||
func goGTKOperations(n int32) transfer.Operation {
|
||||
var o transfer.Operation
|
||||
if n&gdkActionCopy != 0 {
|
||||
o |= transfer.Copy
|
||||
}
|
||||
if n&gdkActionMove != 0 {
|
||||
o |= transfer.Move
|
||||
}
|
||||
return o
|
||||
}
|
||||
func gtkFormat(t string) transfer.Format {
|
||||
if t == "UTF8_STRING" || t == "text/plain;charset=utf-8" {
|
||||
return transfer.Text
|
||||
}
|
||||
return transfer.Format(t)
|
||||
}
|
||||
func gtkOffer(context ptr) (*platform.DataDragEvent, map[transfer.Format]ptr) {
|
||||
d := &platform.DataDragEvent{Offer: transfer.Offer{Operations: goGTKOperations(gdkDragContextActions(context)), Suggested: goGTKOperations(gdkDragContextSuggested(context))}}
|
||||
targets := map[transfer.Format]ptr{}
|
||||
for l := gdkDragContextTargets(context); l != 0; l = field[ptr](l, 8) {
|
||||
atom := field[ptr](l, 0)
|
||||
f := gtkFormat(takeStr(gdkAtomName(atom)))
|
||||
if f == platform.DragSessionFormat {
|
||||
continue
|
||||
}
|
||||
if !slices.Contains(d.Offer.Formats, f) {
|
||||
d.Offer.Formats = append(d.Offer.Formats, f)
|
||||
}
|
||||
targets[f] = atom
|
||||
if f == transfer.URIList {
|
||||
d.HasFiles = true // Existing GTK file drops also advertise URI lists.
|
||||
if !slices.Contains(d.Offer.Formats, transfer.FileList) {
|
||||
d.Offer.Formats = append(d.Offer.Formats, transfer.FileList)
|
||||
}
|
||||
targets[transfer.FileList] = atom
|
||||
}
|
||||
}
|
||||
if src := gtkDataSources[gtkDragGetSourceWidget(context)]; src != nil && src.dragRequest != nil {
|
||||
d.Session = src.dragRequest.Session
|
||||
}
|
||||
return d, targets
|
||||
}
|
||||
func gtkTargets(formats []transfer.Format) []gtkTargetEntry {
|
||||
var names []string
|
||||
for _, f := range formats {
|
||||
name := string(f)
|
||||
if f == transfer.FileList {
|
||||
name = string(transfer.URIList)
|
||||
}
|
||||
if !slices.Contains(names, name) {
|
||||
names = append(names, name)
|
||||
}
|
||||
if f == transfer.Text {
|
||||
names = append(names, "UTF8_STRING", "text/plain;charset=utf-8")
|
||||
}
|
||||
}
|
||||
targets := make([]gtkTargetEntry, len(names))
|
||||
for n, name := range names {
|
||||
targets[n] = gtkTargetEntry{target: cs(name), info: uint32(n)}
|
||||
}
|
||||
return targets
|
||||
}
|
||||
func (s *surface) SetDropFormats(formats []transfer.Format) {
|
||||
targets := gtkTargets(formats)
|
||||
if len(targets) != 0 {
|
||||
gtkDragDestSet(s.area, 0, unsafe.Pointer(&targets[0]), int32(len(targets)), gdkActionCopy|gdkActionMove)
|
||||
}
|
||||
}
|
||||
func (s *surface) acceptFileDrops(data ptr) {
|
||||
s.SetDropFormats([]transfer.Format{transfer.URIList})
|
||||
connect(s.area, "drag-motion", cbSurfaceDragMotion, data)
|
||||
connect(s.area, "drag-leave", cbSurfaceDragLeave, data)
|
||||
connect(s.area, "drag-drop", cbSurfaceDragDrop, data)
|
||||
connect(s.area, "drag-data-received", cbSurfaceDragData, data)
|
||||
connect(s.area, "drag-data-get", cbSurfaceDragGet, data)
|
||||
connect(s.area, "drag-end", cbSurfaceDragEnd, data)
|
||||
connect(s.area, "drag-failed", cbSurfaceDragFailed, data)
|
||||
connect(s.area, "drag-data-delete", cbSurfaceDragDelete, data)
|
||||
}
|
||||
func (s *surface) StartDataDrag(r platform.DragRequest) {
|
||||
if s.dragRequest != nil || s.lastPointer == 0 {
|
||||
r.Done(transfer.Result{Err: errors.New("mygo: GTK drag needs a pointer gesture")})
|
||||
return
|
||||
}
|
||||
targets := gtkTargets(append(r.Data.Formats(), platform.DragSessionFormat))
|
||||
list := gtkTargetListNew(unsafe.Pointer(&targets[0]), uint32(len(targets)))
|
||||
defer gtkTargetListUnref(list)
|
||||
s.dragRequest, s.dragError, s.dragCanceled, s.dragEscaped = &r, nil, false, false
|
||||
gtkDataSources[s.area] = s
|
||||
s.dragContext = gtkDragBeginCoordinates(s.area, list, gtkOperations(r.Operations), 1, s.lastPointer, int32(r.X), int32(r.Y))
|
||||
if s.dragContext == 0 {
|
||||
delete(gtkDataSources, s.area)
|
||||
s.dragRequest = nil
|
||||
r.Done(transfer.Result{Err: errors.New("mygo: GTK failed to start drag")})
|
||||
return
|
||||
}
|
||||
if len(r.Preview) > 0 {
|
||||
pix := bytes.Clone(r.Preview)
|
||||
for i := 0; i < len(pix); i += 4 {
|
||||
pix[i], pix[i+2] = pix[i+2], pix[i]
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
png.Encode(&buf, &image.RGBA{Pix: pix, Stride: r.Width * 4, Rect: image.Rect(0, 0, r.Width, r.Height)})
|
||||
if pb, err := pixbufFromPNG(buf.Bytes()); err == nil {
|
||||
gtkDragSetIconPixbuf(s.dragContext, pb, int32(r.HotX), int32(r.HotY))
|
||||
gObjectUnref(pb)
|
||||
}
|
||||
}
|
||||
}
|
||||
func (s *surface) CancelDataDrag() {
|
||||
if s.dragContext != 0 {
|
||||
s.dragCanceled, s.dragEscaped = true, true
|
||||
gtkDragCancel(s.dragContext)
|
||||
}
|
||||
}
|
||||
func (s *surface) cancelPendingDrop() {
|
||||
if d := s.dataDrop; d != nil {
|
||||
s.dataDrop = nil
|
||||
gtkDragFinish(d.context, false, false, d.time)
|
||||
gObjectUnref(d.context)
|
||||
}
|
||||
}
|
||||
func (s *surface) fileDragOver(x, y float64) bool {
|
||||
return s.send(platform.SurfaceEvent{Kind: platform.FileDragOver, X: x, Y: y})
|
||||
}
|
||||
func (s *surface) dropFiles(x, y float64, paths []string) bool {
|
||||
return s.send(platform.SurfaceEvent{Kind: platform.FileDrop, X: x, Y: y, Files: paths})
|
||||
}
|
||||
func selectionPaths(sel ptr) []string {
|
||||
uris := gtkSelectionDataGetUris(sel)
|
||||
if uris == 0 {
|
||||
return nil
|
||||
}
|
||||
defer gStrfreev(uris)
|
||||
var paths []string
|
||||
for i := uintptr(0); ; i++ {
|
||||
uri := field[ptr](uris, i*8)
|
||||
if uri == 0 {
|
||||
break
|
||||
}
|
||||
if p := takeStr(gFilenameFromURI(goStr(uri), 0, 0)); p != "" {
|
||||
paths = append(paths, p)
|
||||
}
|
||||
}
|
||||
return paths
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
// Input methods ask for the text around the caret, and delete some of it
|
||||
// before they commit what replaces it, as Hangul and other input methods
|
||||
// that edit what was typed do.
|
||||
|
||||
var (
|
||||
systemOnce sync.Once
|
||||
gtkIMContextSetSurrounding func(im ptr, text *byte, length, cursor int32)
|
||||
gtkIMContextGetSurrounding func(im ptr, text *ptr, cursor *int32) bool
|
||||
gtkIMContextDeleteSurrounding func(im ptr, offset, n int32) bool
|
||||
|
||||
cbIMRetrieveSurrounding, cbIMDeleteSurrounding, cbSurfaceAreaDestroy ptr
|
||||
|
||||
// surfaceAreas finds surfaces by their widget.
|
||||
surfaceAreas = map[ptr]*surface{}
|
||||
)
|
||||
|
||||
// connectSystem connects the surface to the system's input methods, drag
|
||||
// and drop, and assistive technology.
|
||||
func (s *surface) connectSystem(data ptr) {
|
||||
systemOnce.Do(initSystemSurface)
|
||||
surfaceAreas[s.area] = s
|
||||
connect(s.area, "destroy", cbSurfaceAreaDestroy, data)
|
||||
connect(s.im, "retrieve-surrounding", cbIMRetrieveSurrounding, data)
|
||||
connect(s.im, "delete-surrounding", cbIMDeleteSurrounding, data)
|
||||
s.acceptFileDrops(data)
|
||||
}
|
||||
|
||||
func initSystemSurface() {
|
||||
t := libGTK
|
||||
mustBind(t, >kIMContextSetSurrounding, "gtk_im_context_set_surrounding")
|
||||
mustBind(t, >kIMContextGetSurrounding, "gtk_im_context_get_surrounding")
|
||||
mustBind(t, >kIMContextDeleteSurrounding, "gtk_im_context_delete_surrounding")
|
||||
loadDrops()
|
||||
b := func() *Backend { return theBackend }
|
||||
cbIMRetrieveSurrounding = purego.NewCallback(func(im, data ptr) bool {
|
||||
s := b().surfaceOf(data)
|
||||
if s == nil || !s.input.Active {
|
||||
return false
|
||||
}
|
||||
text, cursor := s.surrounding()
|
||||
gtkIMContextSetSurrounding(im, cs(text), int32(len(text)), int32(cursor))
|
||||
return true
|
||||
})
|
||||
cbIMDeleteSurrounding = purego.NewCallback(func(im ptr, offset, n int32, data ptr) bool {
|
||||
s := b().surfaceOf(data)
|
||||
if s == nil || !s.input.Active || n < 0 {
|
||||
return false
|
||||
}
|
||||
if client := s.input.Client; client != nil {
|
||||
r := platform.ClientDeleteRange(client, int(offset), int(n))
|
||||
client.ReplaceText(&r, "")
|
||||
return true
|
||||
}
|
||||
from := s.input.End + int(offset)
|
||||
s.send(platform.SurfaceEvent{Kind: platform.TextInput, Replace: true, From: from, To: from + int(n)})
|
||||
return true
|
||||
})
|
||||
cbSurfaceAreaDestroy = purego.NewCallback(func(widget, data ptr) {
|
||||
if s := surfaceAreas[widget]; s != nil {
|
||||
delete(surfaceAreas, widget)
|
||||
s.destroyAccess()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// surrounding returns the text around the caret that input methods see,
|
||||
// and the caret's byte offset in it: the end of the selection.
|
||||
func (s *surface) surrounding() (string, int) {
|
||||
if c := s.input.Client; c != nil {
|
||||
context := platform.ClientTextContext(c)
|
||||
return context.Text, platform.UTF16ByteOffset(context.Text, context.Caret)
|
||||
}
|
||||
text, cursor := s.input.Text, 0
|
||||
for i := range text {
|
||||
if cursor == s.input.End {
|
||||
return text, i
|
||||
}
|
||||
cursor++
|
||||
}
|
||||
return text, len(text)
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// The frame clock spaces frames by the interval of the monitor's rate in
|
||||
// millihertz, as GDK computes it from a Wayland output's: 165.001 Hz is
|
||||
// 6060 µs, not the 16667 of 60 Hz, which only an unknown rate keeps.
|
||||
func TestRefreshInterval(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
mhz int32
|
||||
want int64
|
||||
}{{165001, 6060}, {144000, 6944}, {60000, 16666}, {59940, 16683}, {0, 0}, {-1, 0}} {
|
||||
if got := refreshInterval(c.mhz); got != c.want {
|
||||
t.Errorf("refreshInterval(%d) = %d µs, want %d", c.mhz, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// setRefreshInterval finds refresh_interval in GdkFrameTimings of either
|
||||
// layout of GTK 3.24 through its getter, and leaves the other fields as
|
||||
// they were.
|
||||
func TestSetRefreshInterval(t *testing.T) {
|
||||
defer func(at int) { refreshIntervalAt = at }(refreshIntervalAt)
|
||||
// ref_count, frame_counter, cookie, frame_time, smoothed_frame_time
|
||||
// (3.24.24 on), drawn_time, presentation_time, refresh_interval,
|
||||
// predicted_presentation_time.
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
interval int // index of refresh_interval in int64s
|
||||
fields map[int]int64
|
||||
}{
|
||||
{"GTK 3.24.24", 7, map[int]int64{0: 1, 1: 42, 3: 1000, 4: 1000, 8: 26000}},
|
||||
{"GTK 3.24.24 frozen", 7, map[int]int64{0: 1, 1: 42, 3: 1000, 4: 1000}},
|
||||
{"GTK 3.22", 6, map[int]int64{0: 1, 1: 42, 3: 1000, 7: 26000}},
|
||||
{"GTK 3.22 frozen", 6, map[int]int64{0: 1, 1: 42, 3: 1000}},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
refreshIntervalAt = 0
|
||||
timings := new([12]int64)
|
||||
for i, v := range c.fields {
|
||||
timings[i] = v
|
||||
}
|
||||
p := ptr(unsafe.Pointer(timings))
|
||||
get := func(q ptr) int64 {
|
||||
if q != p {
|
||||
t.Fatal("got the interval of other timings")
|
||||
}
|
||||
return timings[c.interval]
|
||||
}
|
||||
for frame := range 2 {
|
||||
timings[c.interval] = 0
|
||||
if !setRefreshInterval(p, 6060, get) {
|
||||
t.Fatalf("frame %d: refresh interval not set", frame)
|
||||
}
|
||||
for i, v := range timings {
|
||||
want := c.fields[i]
|
||||
if i == c.interval {
|
||||
want = 6060
|
||||
}
|
||||
if v != want {
|
||||
t.Fatalf("frame %d: timings[%d] = %d, want %d", frame, i, v, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
if refreshIntervalAt != c.interval*8 {
|
||||
t.Errorf("found the interval at %d, want %d", refreshIntervalAt, c.interval*8)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Timings where neither offset holds it are left alone, and not
|
||||
// probed again.
|
||||
refreshIntervalAt = 0
|
||||
timings := new([12]int64)
|
||||
if setRefreshInterval(ptr(unsafe.Pointer(timings)), 6060, func(ptr) int64 { return 0 }) {
|
||||
t.Fatal("set an interval its getter does not read")
|
||||
}
|
||||
if *timings != ([12]int64{}) || refreshIntervalAt != -1 {
|
||||
t.Fatalf("timings %v, offset %d", *timings, refreshIntervalAt)
|
||||
}
|
||||
}
|
||||
+778
@@ -0,0 +1,778 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash/fnv"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
"github.com/egoist/mygo/transfer"
|
||||
)
|
||||
|
||||
var (
|
||||
cbThemeChanged ptr
|
||||
cbMonitorsChanged ptr
|
||||
cbNotification ptr
|
||||
cbPowerSignal ptr
|
||||
cbNetworkChanged ptr
|
||||
)
|
||||
|
||||
func initSystemCallbacks() {
|
||||
cbThemeChanged = purego.NewCallback(func(a, b, data ptr) { theBackend.h.ThemeChanged() })
|
||||
cbMonitorsChanged = purego.NewCallback(func(display, monitor, data ptr) { theBackend.h.DisplaysChanged() })
|
||||
cbPortalSignal = purego.NewCallback(portalSignal)
|
||||
cbPowerSignal = purego.NewCallback(func(conn, sender, path, iface, signal, params, data ptr) {
|
||||
child := gVariantGetChildValue(params, 0)
|
||||
on := gVariantGetBoolean(child)
|
||||
gVariantUnref(child)
|
||||
event := map[bool]string{true: "lock-screen", false: "unlock-screen"}[on]
|
||||
if goStr(signal) == "PrepareForSleep" {
|
||||
event = map[bool]string{true: "suspend", false: "resume"}[on]
|
||||
}
|
||||
theBackend.h.PowerEvent(event)
|
||||
})
|
||||
cbNotification = purego.NewCallback(func(conn, sender, path, iface, signal, params, data ptr) {
|
||||
if goStr(signal) != "ActionInvoked" {
|
||||
return
|
||||
}
|
||||
child := gVariantGetChildValue(params, 0)
|
||||
dbusID := gVariantGetUint32(child)
|
||||
gVariantUnref(child)
|
||||
if id, ok := notifications[dbusID]; ok {
|
||||
theBackend.h.NotificationClicked(id)
|
||||
}
|
||||
})
|
||||
// The network-changed signal of GNetworkMonitor (network.go).
|
||||
cbNetworkChanged = purego.NewCallback(func(monitor, available, data ptr) {
|
||||
theBackend.h.NetworkChanged(theBackend.Network().Status())
|
||||
})
|
||||
|
||||
settings := gtkSettingsGetDefault()
|
||||
connect(settings, "notify::gtk-theme-name", cbThemeChanged, 0)
|
||||
connect(settings, "notify::gtk-font-name", cbThemeChanged, 0) // Theme.UIFont
|
||||
connect(settings, "notify::gtk-decoration-layout", cbDecorationLayout, 0)
|
||||
connect(settings, "notify::gtk-application-prefer-dark-theme", cbThemeChanged, 0)
|
||||
connect(settings, "notify::gtk-enable-animations", cbThemeChanged, 0) // Theme.Preferences
|
||||
watchPortalSettings()
|
||||
if d := gdkDisplayGetDefault(); d != 0 {
|
||||
connect(d, "monitor-added", cbMonitorsChanged, 0)
|
||||
connect(d, "monitor-removed", cbMonitorsChanged, 0)
|
||||
// The pointing devices (Theme.Preferences).
|
||||
if seat := gdkDisplayGetDefaultSeat(d); seat != 0 {
|
||||
connect(seat, "device-added", cbThemeChanged, 0)
|
||||
connect(seat, "device-removed", cbThemeChanged, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Pixbuf helpers.
|
||||
|
||||
func pixbufFromPNG(png []byte) (ptr, error) {
|
||||
if len(png) == 0 {
|
||||
return 0, errors.New("mygo: empty image")
|
||||
}
|
||||
loader := gdkPixbufLoaderNew()
|
||||
defer gObjectUnref(loader)
|
||||
var gerr ptr
|
||||
if !gdkPixbufLoaderWrite(loader, unsafe.Pointer(&png[0]), uintptr(len(png)), &gerr) {
|
||||
gdkPixbufLoaderClose(loader, nil)
|
||||
return 0, gErr(gerr)
|
||||
}
|
||||
if !gdkPixbufLoaderClose(loader, &gerr) {
|
||||
return 0, gErr(gerr)
|
||||
}
|
||||
pix := gdkPixbufLoaderGetPixbuf(loader)
|
||||
if pix == 0 {
|
||||
return 0, errors.New("mygo: invalid image")
|
||||
}
|
||||
return gObjectRef(pix), nil
|
||||
}
|
||||
|
||||
func pngFromPixbuf(pix ptr) []byte {
|
||||
var buf ptr
|
||||
var size uintptr
|
||||
if !gdkPixbufSaveToBufferv(pix, &buf, &size, cs("png"), 0, 0, nil) {
|
||||
return nil
|
||||
}
|
||||
out := append([]byte(nil), unsafe.Slice(*(**byte)(unsafe.Pointer(&buf)), size)...)
|
||||
gFree(buf)
|
||||
return out
|
||||
}
|
||||
|
||||
// Clipboard.
|
||||
|
||||
type clipboard struct{}
|
||||
|
||||
func clip() ptr {
|
||||
cb := gtkClipboardGet(gdkAtomIntern(cs("CLIPBOARD"), false))
|
||||
if !clipboardConnected {
|
||||
connect(cb, "owner-change", cbClipboardOwner, 0)
|
||||
clipboardConnected = true
|
||||
}
|
||||
return cb
|
||||
}
|
||||
|
||||
func (clipboard) ReadText() string { return takeStr(gtkClipboardWaitForText(clip())) }
|
||||
func (c clipboard) WriteText(text string) { _ = c.WriteData(transfer.TextData(text), false, nil) }
|
||||
|
||||
func (clipboard) ReadHTML() string {
|
||||
sd := gtkClipboardWaitForContents(clip(), gdkAtomIntern(cs("text/html"), false))
|
||||
if sd == 0 {
|
||||
return ""
|
||||
}
|
||||
defer gtkSelectionDataFree(sd)
|
||||
n := gtkSelectionDataGetLength(sd)
|
||||
data := gtkSelectionDataGetData(sd)
|
||||
if n <= 0 || data == 0 {
|
||||
return ""
|
||||
}
|
||||
return string(unsafe.Slice(*(**byte)(unsafe.Pointer(&data)), n))
|
||||
}
|
||||
|
||||
func (c clipboard) WriteHTML(markup string) {
|
||||
_ = c.WriteData(transfer.New(transfer.NewItem(transfer.Bytes(transfer.HTML, []byte(markup)), transfer.Bytes(transfer.Text, []byte(markup)))), false, nil)
|
||||
}
|
||||
|
||||
func (clipboard) ReadImage() []byte {
|
||||
pix := gtkClipboardWaitForImage(clip())
|
||||
if pix == 0 {
|
||||
return nil
|
||||
}
|
||||
defer gObjectUnref(pix)
|
||||
return pngFromPixbuf(pix)
|
||||
}
|
||||
|
||||
func (c clipboard) WriteImage(png []byte) error {
|
||||
pix, err := pixbufFromPNG(png)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer gObjectUnref(pix)
|
||||
return c.WriteData(transfer.New(transfer.NewItem(transfer.Bytes(transfer.PNG, png))), false, nil)
|
||||
}
|
||||
|
||||
func (clipboard) Clear() { gtkClipboardClear(clip()) }
|
||||
|
||||
func (clipboard) AvailableFormats() []string {
|
||||
var atoms ptr
|
||||
var n int32
|
||||
if !gtkClipboardWaitForTargets(clip(), &atoms, &n) || atoms == 0 {
|
||||
return nil
|
||||
}
|
||||
defer gFree(atoms)
|
||||
out := make([]string, 0, n)
|
||||
for i := range int(n) {
|
||||
out = append(out, takeStr(gdkAtomName(field[ptr](atoms, uintptr(i)*8))))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Shell.
|
||||
|
||||
type shell struct{}
|
||||
|
||||
// launch opens uri in its default application, with the display's launch
|
||||
// context, which gives it startup notification or the activation token that
|
||||
// lets it take the focus: GNOME shows an app that has none behind, and
|
||||
// tells in a notification that it is ready.
|
||||
func launch(uri string) error {
|
||||
loadLaunch()
|
||||
ctx := gdkDisplayGetAppLaunchContext(gdkDisplayGetDefault())
|
||||
defer gObjectUnref(ctx)
|
||||
var gerr ptr
|
||||
if !gAppInfoLaunchDefaultForURI(cs(uri), ctx, &gerr) {
|
||||
return gErr(gerr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func fileURI(path string) string {
|
||||
f := gFileNewForPath(cs(path))
|
||||
defer gObjectUnref(f)
|
||||
return takeStr(gFileGetURI(f))
|
||||
}
|
||||
|
||||
func (shell) OpenExternal(url string) error { return launch(url) }
|
||||
func (shell) OpenPath(path string) error { return launch(fileURI(path)) }
|
||||
|
||||
func (s shell) ShowItemInFolder(path string) {
|
||||
uri := fileURI(path)
|
||||
uris := gVariantNewArray(gVariantTypeNew(cs("s")), unsafe.Pointer(&[]ptr{gVariantNewString(cs(uri))}[0]), 1)
|
||||
ctx, id := folderStartup()
|
||||
defer gObjectUnref(ctx)
|
||||
params := tuple(uris, gVariantNewString(cs(id)))
|
||||
if _, err := dbusCall("org.freedesktop.FileManager1", "/org/freedesktop/FileManager1", "org.freedesktop.FileManager1", "ShowItems", params, ""); err != nil {
|
||||
if id != "" {
|
||||
gAppLaunchContextLaunchFailed(ctx, cs(id))
|
||||
}
|
||||
_ = s.OpenPath(filepath.Dir(path))
|
||||
}
|
||||
}
|
||||
|
||||
// folderStartup returns a launch context of the display and the startup ID
|
||||
// it gives the application that opens folders, which the file manager takes
|
||||
// to show its window in front, as an X11 startup notification or a Wayland
|
||||
// activation token; "" where no application opens folders.
|
||||
func folderStartup() (ctx ptr, id string) {
|
||||
loadLaunch()
|
||||
ctx = gdkDisplayGetAppLaunchContext(gdkDisplayGetDefault())
|
||||
if info := gAppInfoGetDefaultForType(cs("inode/directory"), false); info != 0 {
|
||||
id = takeStr(gAppLaunchContextGetStartupID(ctx, info, 0))
|
||||
gObjectUnref(info)
|
||||
}
|
||||
return ctx, id
|
||||
}
|
||||
|
||||
func (shell) TrashItem(path string) error {
|
||||
f := gFileNewForPath(cs(path))
|
||||
defer gObjectUnref(f)
|
||||
var gerr ptr
|
||||
if !gFileTrash(f, 0, &gerr) {
|
||||
return gErr(gerr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (shell) TrashItemResult(string) (string, error) { return "", platform.ErrUnsupported }
|
||||
|
||||
func (shell) PreviewItem(string) error { return platform.ErrUnsupported }
|
||||
|
||||
func (shell) Beep() { gdkDisplayBeep(gdkDisplayGetDefault()) }
|
||||
|
||||
// Screen.
|
||||
|
||||
type screen struct{}
|
||||
|
||||
func (screen) Displays() []platform.Display {
|
||||
d := gdkDisplayGetDefault()
|
||||
if d == 0 {
|
||||
return nil
|
||||
}
|
||||
primary := gdkDisplayGetPrimaryMonitor(d)
|
||||
n := int(gdkDisplayGetNMonitors(d))
|
||||
out := make([]platform.Display, 0, n)
|
||||
for i := range n {
|
||||
m := gdkDisplayGetMonitor(d, int32(i))
|
||||
var geo, work gdkRectangle
|
||||
gdkMonitorGetGeometry(m, &geo)
|
||||
gdkMonitorGetWorkarea(m, &work)
|
||||
out = append(out, platform.Display{
|
||||
ID: int64(i),
|
||||
Label: goStr(gdkMonitorGetModel(m)),
|
||||
Bounds: platform.Rect{X: int(geo.X), Y: int(geo.Y), Width: int(geo.Width), Height: int(geo.Height)},
|
||||
WorkArea: platform.Rect{X: int(work.X), Y: int(work.Y), Width: int(work.Width), Height: int(work.Height)},
|
||||
ScaleFactor: float64(gdkMonitorGetScaleFactor(m)),
|
||||
Primary: m == primary || (primary == 0 && i == 0),
|
||||
})
|
||||
}
|
||||
// Primary first, like on other platforms.
|
||||
for i, disp := range out {
|
||||
if disp.Primary && i > 0 {
|
||||
out[0], out[i] = out[i], out[0]
|
||||
break
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (screen) CursorPoint() platform.Point {
|
||||
d := gdkDisplayGetDefault()
|
||||
if d == 0 {
|
||||
return platform.Point{}
|
||||
}
|
||||
var x, y int32
|
||||
gdkDeviceGetPosition(gdkSeatGetPointer(gdkDisplayGetDefaultSeat(d)), nil, &x, &y)
|
||||
return platform.Point{X: int(x), Y: int(y)}
|
||||
}
|
||||
|
||||
// Theme.
|
||||
|
||||
type theme struct{ b *Backend }
|
||||
|
||||
// FontRendering returns GTK's gtk-xft settings, which the desktop's
|
||||
// settings daemon gives (XSETTINGS) or GDK's defaults, as GTK makes them
|
||||
// the screen's font options: no hinting where hinting is off, and subpixel
|
||||
// antialiasing where the screen's subpixels have an order.
|
||||
func (theme) FontRendering() platform.FontRendering {
|
||||
settings := gtkSettingsGetDefault()
|
||||
if settings == 0 {
|
||||
return platform.FontRendering{}
|
||||
}
|
||||
var antialias, hinting int32
|
||||
var style, rgba ptr
|
||||
gObjectGetPtr(settings, cs("gtk-xft-antialias"), unsafe.Pointer(&antialias), 0)
|
||||
gObjectGetPtr(settings, cs("gtk-xft-hinting"), unsafe.Pointer(&hinting), 0)
|
||||
gObjectGetPtr(settings, cs("gtk-xft-hintstyle"), unsafe.Pointer(&style), 0)
|
||||
gObjectGetPtr(settings, cs("gtk-xft-rgba"), unsafe.Pointer(&rgba), 0)
|
||||
var r platform.FontRendering
|
||||
switch hintStyle := takeStr(style); {
|
||||
case hinting == 0:
|
||||
r.Hinting = "none"
|
||||
case hinting == 1 && strings.HasPrefix(hintStyle, "hint"):
|
||||
switch h := strings.TrimPrefix(hintStyle, "hint"); h {
|
||||
case "none", "slight", "medium", "full":
|
||||
r.Hinting = h
|
||||
}
|
||||
}
|
||||
switch order := takeStr(rgba); order {
|
||||
case "rgb", "bgr", "vrgb", "vbgr":
|
||||
r.Subpixels = order
|
||||
}
|
||||
switch {
|
||||
case antialias == 0:
|
||||
r.Antialias = "none"
|
||||
case antialias == 1 && r.Subpixels != "":
|
||||
r.Antialias = "subpixel"
|
||||
case antialias == 1:
|
||||
r.Antialias = "gray"
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// UIFont returns the family of the font GTK apps show their interface
|
||||
// in, gtk-font-name, such as "Cantarell 11" on GNOME, which the desktop's
|
||||
// settings daemon or settings.ini gives; fontconfig knows only a default
|
||||
// sans-serif.
|
||||
func (theme) UIFont() string {
|
||||
var name ptr
|
||||
gObjectGetPtr(gtkSettingsGetDefault(), cs("gtk-font-name"), unsafe.Pointer(&name), 0)
|
||||
spec := takeStr(name)
|
||||
if spec == "" {
|
||||
return ""
|
||||
}
|
||||
var (
|
||||
fromString func(s *byte) ptr
|
||||
getFamily func(d ptr) ptr
|
||||
free func(d ptr)
|
||||
)
|
||||
pango, err := open("libpango-1.0.so.0")
|
||||
if err != nil || !bind(pango, &fromString, "pango_font_description_from_string") ||
|
||||
!bind(pango, &getFamily, "pango_font_description_get_family") || !bind(pango, &free, "pango_font_description_free") {
|
||||
return ""
|
||||
}
|
||||
desc := fromString(cs(spec))
|
||||
defer free(desc)
|
||||
return goStr(getFamily(desc))
|
||||
}
|
||||
|
||||
// portalColorScheme reads the desktop wide preference (1 = dark, 2 =
|
||||
// light, 0 = no preference) from the settings portal.
|
||||
func portalColorScheme() (uint32, bool) {
|
||||
params := tuple(gVariantNewString(cs("org.freedesktop.appearance")), gVariantNewString(cs("color-scheme")))
|
||||
res, err := portalCall(portalPath, "org.freedesktop.portal.Settings", "Read", params, "(v)")
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
defer gVariantUnref(res)
|
||||
v := gVariantGetChildValue(res, 0) // v
|
||||
inner := gVariantGetVariant(v) // v (the portal wraps twice)
|
||||
gVariantUnref(v)
|
||||
for strings.HasPrefix(goStr(gVariantGetTypeString(inner)), "v") {
|
||||
next := gVariantGetVariant(inner)
|
||||
gVariantUnref(inner)
|
||||
inner = next
|
||||
}
|
||||
defer gVariantUnref(inner)
|
||||
if goStr(gVariantGetTypeString(inner)) != "u" {
|
||||
return 0, false
|
||||
}
|
||||
return gVariantGetUint32(inner), true
|
||||
}
|
||||
|
||||
// doubleClick reads the double click as GTK's settings have it from the
|
||||
// desktop.
|
||||
func doubleClick() platform.DoubleClick {
|
||||
ms, distance := int32(400), int32(5) // GTK's defaults
|
||||
if settings := gtkSettingsGetDefault(); settings != 0 {
|
||||
gObjectGetPtr(settings, cs("gtk-double-click-time"), unsafe.Pointer(&ms), 0)
|
||||
gObjectGetPtr(settings, cs("gtk-double-click-distance"), unsafe.Pointer(&distance), 0)
|
||||
}
|
||||
return platform.DoubleClick{Time: time.Duration(ms) * time.Millisecond, DX: float64(distance), DY: float64(distance)}
|
||||
}
|
||||
|
||||
// Preferences reads GTK's animations setting, the accent, contrast and
|
||||
// text size the desktop portal gives, as GNOME's and KDE's do, and the
|
||||
// seat's pointing devices.
|
||||
func (t theme) Preferences() platform.Preferences {
|
||||
var p platform.Preferences
|
||||
p.Pointer, p.AnyPointer, p.NoHover, p.NoAnyHover = pointingDevices()
|
||||
settings := gtkSettingsGetDefault()
|
||||
animations := int32(1)
|
||||
gObjectGetPtr(settings, cs("gtk-enable-animations"), unsafe.Pointer(&animations), 0)
|
||||
p.ReduceMotion = animations == 0
|
||||
var name ptr
|
||||
gObjectGetPtr(settings, cs("gtk-theme-name"), unsafe.Pointer(&name), 0)
|
||||
p.HighContrast = strings.Contains(strings.ToLower(takeStr(name)), "highcontrast")
|
||||
all, ok := portalSettings(appearanceSettings, gnomeInterfaceSettings)
|
||||
if !ok {
|
||||
return p
|
||||
}
|
||||
defer gVariantUnref(all)
|
||||
// The accent: red, green and blue between 0 and 1, others for none.
|
||||
if v := portalSetting(all, appearanceSettings, "accent-color", "(ddd)"); v != 0 {
|
||||
var rgb [3]float64
|
||||
in := true
|
||||
for i := range rgb {
|
||||
c := gVariantGetChildValue(v, uintptr(i))
|
||||
rgb[i] = gVariantGetDouble(c)
|
||||
gVariantUnref(c)
|
||||
in = in && rgb[i] >= 0 && rgb[i] <= 1
|
||||
}
|
||||
gVariantUnref(v)
|
||||
if in {
|
||||
b := func(f float64) uint8 { return uint8(f*255 + 0.5) }
|
||||
p.Accent = platform.Color{R: b(rgb[0]), G: b(rgb[1]), B: b(rgb[2]), A: 255}
|
||||
}
|
||||
}
|
||||
if v := portalSetting(all, appearanceSettings, "contrast", "u"); v != 0 {
|
||||
p.HighContrast = p.HighContrast || gVariantGetUint32(v) == 1
|
||||
gVariantUnref(v)
|
||||
}
|
||||
if v := portalSetting(all, gnomeInterfaceSettings, "text-scaling-factor", "d"); v != 0 {
|
||||
if s := gVariantGetDouble(v); s >= 0.5 && s <= 5 {
|
||||
p.TextScale = s
|
||||
}
|
||||
gVariantUnref(v)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// GdkInputSource's sources of pointing devices, and GdkSeatCapabilities'
|
||||
// of pointing.
|
||||
const (
|
||||
sourceMouse = 0
|
||||
sourcePen = 1
|
||||
sourceEraser = 2
|
||||
sourceCursor = 3
|
||||
sourceTouchscreen = 5
|
||||
sourceTouchpad = 6
|
||||
sourceTrackpoint = 7
|
||||
seatAllPointing = 7 // GDK_SEAT_CAPABILITY_ALL_POINTING
|
||||
)
|
||||
|
||||
// pointingDevices returns how accurate the primary pointing device is and
|
||||
// the most accurate of all, and whether they cannot hover, from the
|
||||
// seat's devices as Chromium tells them: mice, touchpads, trackpoints and
|
||||
// pens point finely and hover, touch screens coarsely, without hovering;
|
||||
// the primary device is the finest. A seat that lists none, as a display
|
||||
// GDK does not know, has a mouse's.
|
||||
func pointingDevices() (primary, finest platform.PointerAccuracy, noHover, noneHover bool) {
|
||||
d := gdkDisplayGetDefault()
|
||||
if d == 0 {
|
||||
return
|
||||
}
|
||||
seat := gdkDisplayGetDefaultSeat(d)
|
||||
if seat == 0 {
|
||||
return
|
||||
}
|
||||
list := gdkSeatGetSlaves(seat, seatAllPointing)
|
||||
if list == 0 {
|
||||
return
|
||||
}
|
||||
defer gListFree(list)
|
||||
fine, touch := false, false
|
||||
for node := list; node != 0; node = field[ptr](node, 8) {
|
||||
switch gdkDeviceGetSource(field[ptr](node, 0)) {
|
||||
case sourceMouse, sourcePen, sourceEraser, sourceCursor, sourceTouchpad, sourceTrackpoint:
|
||||
fine = true
|
||||
case sourceTouchscreen:
|
||||
touch = true
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case fine:
|
||||
return platform.PointerFine, platform.PointerFine, false, false
|
||||
case touch:
|
||||
return platform.PointerCoarse, platform.PointerCoarse, true, true
|
||||
}
|
||||
return platform.PointerNone, platform.PointerNone, true, true
|
||||
}
|
||||
|
||||
func (t theme) IsDark() bool {
|
||||
switch themeSource {
|
||||
case "light":
|
||||
return false
|
||||
case "dark":
|
||||
return true
|
||||
}
|
||||
settings := gtkSettingsGetDefault()
|
||||
var prefer int32
|
||||
gObjectGetPtr(settings, cs("gtk-application-prefer-dark-theme"), unsafe.Pointer(&prefer), 0)
|
||||
if prefer != 0 {
|
||||
return true
|
||||
}
|
||||
if scheme, ok := portalColorScheme(); ok && scheme != 0 {
|
||||
return scheme == 1
|
||||
}
|
||||
return strings.Contains(strings.ToLower(gtkThemeName(settings)), "dark")
|
||||
}
|
||||
|
||||
var (
|
||||
// themeSource is the appearance SetSource was given last.
|
||||
themeSource string
|
||||
// lightTheme is true while SetSource("light") has put the light
|
||||
// variant in place of the desktop's dark theme.
|
||||
lightTheme bool
|
||||
// preferDarkSet is true while MyGo has put its own value in
|
||||
// gtk-application-prefer-dark-theme in place of the desktop's.
|
||||
preferDarkSet bool
|
||||
)
|
||||
|
||||
func (t theme) SetSource(source string) {
|
||||
themeSource = source
|
||||
settings := gtkSettingsGetDefault()
|
||||
// A theme named for its dark variant, as Ubuntu's Yaru-dark in dark
|
||||
// mode, keeps GTK and WebKitGTK's prefers-color-scheme dark whatever
|
||||
// gtk-application-prefer-dark-theme says: the light appearance takes
|
||||
// the theme of the name without the suffix (Yaru, or GTK's Adwaita
|
||||
// where there is none), and the others the desktop's theme again.
|
||||
if source != "light" && lightTheme {
|
||||
lightTheme = false
|
||||
gtkSettingsResetProperty(settings, cs("gtk-theme-name"))
|
||||
}
|
||||
if name := gtkThemeName(settings); source == "light" && !lightTheme && len(name) > 5 && strings.EqualFold(name[len(name)-5:], "-dark") {
|
||||
lightTheme = true
|
||||
gObjectSetStr(settings, cs("gtk-theme-name"), cs(name[:len(name)-5]), 0)
|
||||
}
|
||||
if source == "light" || source == "dark" {
|
||||
setPreferDark(settings, source == "dark")
|
||||
} else {
|
||||
followSystemScheme(settings)
|
||||
}
|
||||
}
|
||||
|
||||
// followsSystem reports whether the app has not chosen an appearance, and
|
||||
// so follows the desktop's.
|
||||
func followsSystem() bool { return themeSource == "" || themeSource == "system" }
|
||||
|
||||
// followSystemScheme brings the desktop's color scheme to GTK: GTK 3 does
|
||||
// not read the settings portal's, where GNOME and KDE keep their dark
|
||||
// style, but gtk-application-prefer-dark-theme, from which WebKitGTK takes
|
||||
// pages' prefers-color-scheme too (#1120). Where the portal prefers dark,
|
||||
// so does GTK; elsewhere GTK keeps the desktop's own settings, which may
|
||||
// prefer dark or name a dark theme, as without the portal. It reports
|
||||
// whether it changed GTK's setting, which then tells ThemeChanged.
|
||||
func followSystemScheme(settings ptr) bool {
|
||||
if scheme, ok := portalColorScheme(); ok && scheme == 1 {
|
||||
return setPreferDark(settings, true)
|
||||
}
|
||||
if !preferDarkSet {
|
||||
return false
|
||||
}
|
||||
preferDarkSet = false
|
||||
gtkSettingsResetProperty(settings, cs("gtk-application-prefer-dark-theme"))
|
||||
return true
|
||||
}
|
||||
|
||||
// setPreferDark sets gtk-application-prefer-dark-theme, only when it
|
||||
// changes: GTK tells ThemeChanged at every write, and apps may set the
|
||||
// source again from Theme.OnUpdated. It reports whether it wrote.
|
||||
func setPreferDark(settings ptr, dark bool) bool {
|
||||
var prefer int32
|
||||
gObjectGetPtr(settings, cs("gtk-application-prefer-dark-theme"), unsafe.Pointer(&prefer), 0)
|
||||
if (prefer != 0) == dark {
|
||||
return false
|
||||
}
|
||||
preferDarkSet = true
|
||||
gObjectSetBool(settings, cs("gtk-application-prefer-dark-theme"), dark, 0)
|
||||
return true
|
||||
}
|
||||
|
||||
// gtkThemeName returns the name of GTK's theme.
|
||||
func gtkThemeName(settings ptr) string {
|
||||
var name ptr
|
||||
gObjectGetPtr(settings, cs("gtk-theme-name"), unsafe.Pointer(&name), 0)
|
||||
return takeStr(name)
|
||||
}
|
||||
|
||||
// D-Bus helpers.
|
||||
|
||||
var sessionBus ptr
|
||||
|
||||
func bus() (ptr, error) {
|
||||
if sessionBus != 0 {
|
||||
return sessionBus, nil
|
||||
}
|
||||
var gerr ptr
|
||||
conn := gBusGetSync(2, 0, &gerr) // G_BUS_TYPE_SESSION
|
||||
if conn == 0 {
|
||||
return 0, gErr(gerr)
|
||||
}
|
||||
sessionBus = conn
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
func tuple(children ...ptr) ptr {
|
||||
return gVariantNewTuple(unsafe.Pointer(&children[0]), uintptr(len(children)))
|
||||
}
|
||||
|
||||
func dbusCall(name, path, iface, method string, params ptr, replyType string) (ptr, error) {
|
||||
conn, err := bus()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var rt ptr
|
||||
if replyType != "" {
|
||||
rt = gVariantTypeNew(cs(replyType))
|
||||
}
|
||||
var gerr ptr
|
||||
res := gDBusConnectionCallSync(conn, cs(name), cs(path), cs(iface), cs(method), params, rt, 0, 3000, 0, &gerr)
|
||||
if res == 0 {
|
||||
return 0, gErr(gerr)
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// updateLauncherEntry shows the progress and badge count on the app's
|
||||
// launcher entry with the Unity launcher API, which the docks of KDE Plasma
|
||||
// and Ubuntu, Dash to Dock and Plank implement. They find the app by its
|
||||
// desktop entry.
|
||||
func (b *Backend) updateLauncherEntry() {
|
||||
conn, err := bus()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
l := &b.launcher
|
||||
count, _ := strconv.Atoi(l.badge)
|
||||
entry := func(key string, v ptr) ptr {
|
||||
return gVariantNewDictEntry(gVariantNewString(cs(key)), gVariantNewVariant(v))
|
||||
}
|
||||
props := []ptr{
|
||||
entry("progress", gVariantNewDouble(l.progress)),
|
||||
entry("progress-visible", gVariantNewBoolean(l.showing)),
|
||||
entry("count", gVariantNewInt64(int64(count))),
|
||||
entry("count-visible", gVariantNewBoolean(count > 0)),
|
||||
}
|
||||
id := desktopEntryID()
|
||||
params := tuple(gVariantNewString(cs("application://"+id)), gVariantNewArray(0, unsafe.Pointer(&props[0]), uintptr(len(props))))
|
||||
h := fnv.New32a()
|
||||
h.Write([]byte(id))
|
||||
path := fmt.Sprintf("/com/canonical/unity/launcherentry/%d", h.Sum32())
|
||||
var gerr ptr
|
||||
if !gDBusConnectionEmitSignal(conn, nil, cs(path), cs("com.canonical.Unity.LauncherEntry"), cs("Update"), params, &gerr) {
|
||||
_ = gErr(gerr)
|
||||
}
|
||||
}
|
||||
|
||||
// desktopEntryID is the file name of the app's desktop entry: the one it
|
||||
// was launched from, else the one `mygo build` writes, named after the
|
||||
// executable.
|
||||
func desktopEntryID() string {
|
||||
for _, env := range []string{"GIO_LAUNCHED_DESKTOP_FILE", "BAMF_DESKTOP_FILE_HINT"} {
|
||||
if p := os.Getenv(env); p != "" {
|
||||
return filepath.Base(p)
|
||||
}
|
||||
}
|
||||
exe, _ := os.Executable()
|
||||
return filepath.Base(exe) + ".desktop"
|
||||
}
|
||||
|
||||
// Notifications (org.freedesktop.Notifications).
|
||||
|
||||
var (
|
||||
notifications = map[uint32]string{}
|
||||
notifyDBusIDs = map[string]uint32{}
|
||||
notifySubscribed bool
|
||||
)
|
||||
|
||||
func (b *Backend) NotificationsSupported() bool {
|
||||
_, err := bus()
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// WebViewAvailable reports whether a window showing a web page can have
|
||||
// one: WebKitGTK, JavaScriptCore and libsoup, which it needs. Windows
|
||||
// showing native UI need GTK alone, so an app whose windows all do runs
|
||||
// without them. Loading the libraries is as much as can be known before a
|
||||
// page loads.
|
||||
func (b *Backend) WebViewAvailable() bool { return webKit() == nil }
|
||||
|
||||
func (b *Backend) ShowNotification(n *platform.Notification, done func(error)) {
|
||||
done(b.showNotification(n))
|
||||
}
|
||||
|
||||
func (b *Backend) showNotification(n *platform.Notification) error {
|
||||
conn, err := bus()
|
||||
if err != nil {
|
||||
return fmt.Errorf("mygo: notifications need a D-Bus session: %w", err)
|
||||
}
|
||||
if !notifySubscribed {
|
||||
notifySubscribed = true
|
||||
gDBusConnectionSignalSubscribe(conn, cs("org.freedesktop.Notifications"), cs("org.freedesktop.Notifications"),
|
||||
cs("ActionInvoked"), cs("/org/freedesktop/Notifications"), nil, 0, cbNotification, 0, 0)
|
||||
}
|
||||
actions := []ptr{gVariantNewString(cs("default")), gVariantNewString(cs("Open"))}
|
||||
var hints []ptr
|
||||
if n.Silent {
|
||||
hints = append(hints, gVariantNewDictEntry(gVariantNewString(cs("suppress-sound")), gVariantNewVariant(gVariantNewBoolean(true))))
|
||||
}
|
||||
if len(n.Image) > 0 && notificationImageHint != nil {
|
||||
if hint := notificationImageHint(n.Image); hint != 0 {
|
||||
hints = append(hints, hint)
|
||||
}
|
||||
}
|
||||
hintArray := gVariantNewArray(gVariantTypeNew(cs("{sv}")), nil, 0)
|
||||
if len(hints) > 0 {
|
||||
hintArray = gVariantNewArray(0, unsafe.Pointer(&hints[0]), uintptr(len(hints)))
|
||||
}
|
||||
body := n.Body
|
||||
if n.Subtitle != "" {
|
||||
body = n.Subtitle + "\n" + body
|
||||
}
|
||||
params := tuple(
|
||||
gVariantNewString(cs(appName())),
|
||||
gVariantNewUint32(notifyDBusIDs[n.ID]),
|
||||
gVariantNewString(cs("")),
|
||||
gVariantNewString(cs(n.Title)),
|
||||
gVariantNewString(cs(body)),
|
||||
gVariantNewArray(0, unsafe.Pointer(&actions[0]), uintptr(len(actions))),
|
||||
hintArray,
|
||||
gVariantNewInt32(-1),
|
||||
)
|
||||
res, err := dbusCall("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "org.freedesktop.Notifications", "Notify", params, "(u)")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
child := gVariantGetChildValue(res, 0)
|
||||
dbusID := gVariantGetUint32(child)
|
||||
gVariantUnref(child)
|
||||
gVariantUnref(res)
|
||||
notifications[dbusID] = n.ID
|
||||
notifyDBusIDs[n.ID] = dbusID
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *Backend) RemoveNotification(id string) {
|
||||
dbusID, ok := notifyDBusIDs[id]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
delete(notifyDBusIDs, id)
|
||||
delete(notifications, dbusID)
|
||||
if res, err := dbusCall("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "org.freedesktop.Notifications", "CloseNotification", tuple(gVariantNewUint32(dbusID)), ""); err == nil {
|
||||
gVariantUnref(res)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Backend) RemoveAllNotifications() {
|
||||
for id := range notifyDBusIDs {
|
||||
b.RemoveNotification(id)
|
||||
}
|
||||
}
|
||||
|
||||
func appName() string {
|
||||
if theBackend.name != "" {
|
||||
return theBackend.name
|
||||
}
|
||||
return "MyGo"
|
||||
}
|
||||
+1073
File diff suppressed because it is too large.
Load diff
+133
@@ -0,0 +1,133 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"image"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gl"
|
||||
)
|
||||
|
||||
// TestSurfaceGL tells how the native UI of a window draws: "opengl" when
|
||||
// its renderer draws in the GtkGLArea, "memory" when the GtkGLArea shows
|
||||
// frames drawn on the CPU, "cairo" when a drawing area, or a GtkGLArea
|
||||
// without a context, paints them with cairo, and "" before the first frame.
|
||||
// For a GtkGLArea it returns its framebuffer's pixels too, premultiplied
|
||||
// BGRA rows from the top, and their size.
|
||||
func TestSurfaceGL(handle uintptr) (how string, pix []byte, width, height int) {
|
||||
s := surfaceByHandle(handle)
|
||||
switch {
|
||||
case s == nil:
|
||||
return "", nil, 0, 0
|
||||
case !s.gl || gtkGLAreaGetError(s.area) != 0:
|
||||
return "cairo", nil, 0, 0
|
||||
case !s.rendered:
|
||||
return "", nil, 0, 0
|
||||
}
|
||||
how = "opengl"
|
||||
if s.inMemory {
|
||||
how = "memory"
|
||||
}
|
||||
var makeCurrent, attachBuffers func(area ptr)
|
||||
if !bind(libGTK, &makeCurrent, "gtk_gl_area_make_current") || !bind(libGTK, &attachBuffers, "gtk_gl_area_attach_buffers") {
|
||||
return how, nil, 0, 0
|
||||
}
|
||||
// The area's framebuffer keeps the last frame it rendered.
|
||||
makeCurrent(s.area)
|
||||
attachBuffers(s.area)
|
||||
scale := int(max(gtkWidgetGetScaleFactor(s.area), 1))
|
||||
width, height = int(gtkWidgetGetAllocatedWidth(s.area))*scale, int(gtkWidgetGetAllocatedHeight(s.area))*scale
|
||||
pix, err := gl.ReadFramebuffer(width, height)
|
||||
if err != nil {
|
||||
return how, nil, 0, 0
|
||||
}
|
||||
return how, pix, width, height
|
||||
}
|
||||
|
||||
// TestSurfaceOnScreen returns, as a PNG, what the display shows of the
|
||||
// surface of a window: GTK repaints only what frames drawn in memory
|
||||
// changed, and keeps the rest.
|
||||
func TestSurfaceOnScreen(handle uintptr) []byte {
|
||||
s := surfaceByHandle(handle)
|
||||
var getFromWindow func(win ptr, x, y, width, height int32) ptr
|
||||
if s == nil || !bind(libGDK, &getFromWindow, "gdk_pixbuf_get_from_window") {
|
||||
return nil
|
||||
}
|
||||
// The area's GdkWindow is its parent's when it has none of its own.
|
||||
var at gdkRectangle
|
||||
if !gtkWidgetGetHasWindow(s.area) {
|
||||
gtkWidgetGetAllocation(s.area, &at)
|
||||
}
|
||||
pix := getFromWindow(gtkWidgetGetWindow(s.area), at.X, at.Y, gtkWidgetGetAllocatedWidth(s.area), gtkWidgetGetAllocatedHeight(s.area))
|
||||
if pix == 0 {
|
||||
return nil
|
||||
}
|
||||
defer gObjectUnref(pix)
|
||||
return pngFromPixbuf(pix)
|
||||
}
|
||||
|
||||
// TestProbeGL probes OpenGL as the first window of native UI does, and
|
||||
// returns what it found and a function that reports whether GDK freed the
|
||||
// probe's window; nil where GDK keeps it: GTK 3 on Wayland never drops a
|
||||
// reference of its own.
|
||||
func TestProbeGL() (renderer, failure string, freed func() bool) {
|
||||
var malloc0 func(n uintptr) ptr
|
||||
var addWeakPointer func(obj, location ptr)
|
||||
if !theBackend.onX11 || !bind(libGLib, &malloc0, "g_malloc0") || !bind(libGObject, &addWeakPointer, "g_object_add_weak_pointer") {
|
||||
return "", "", nil
|
||||
}
|
||||
// GObject clears the location as it finalizes the window. It stays
|
||||
// allocated: a window GDK still had when the test ended may go later.
|
||||
var location ptr
|
||||
renderer, failure = probeGLWith(func(win ptr) {
|
||||
location = malloc0(8)
|
||||
*slot(location, 0) = win
|
||||
addWeakPointer(win, location)
|
||||
})
|
||||
if location == 0 {
|
||||
return renderer, failure, nil
|
||||
}
|
||||
return renderer, failure, func() bool { return *slot(location, 0) == 0 }
|
||||
}
|
||||
|
||||
// TestGLDamage returns what the paints of a window of native UI drawing
|
||||
// with OpenGL told a Wayland compositor they changed since the last call,
|
||||
// beside GTK's own damage (damageGLPaint), in the window's coordinates;
|
||||
// where its GtkGLArea is in them; and the window's scale. The first call
|
||||
// starts recording. It returns ok false but on Wayland, for a GtkGLArea.
|
||||
func TestGLDamage(handle uintptr) (damage []image.Rectangle, area image.Point, scale int, ok bool) {
|
||||
w := windowByHandle(handle)
|
||||
if w == nil || w.surface == nil || !w.surface.gl || w.b.waylandSurface == nil {
|
||||
return nil, image.Point{}, 0, false
|
||||
}
|
||||
if testGLDamage == nil {
|
||||
testGLDamaged = map[*window][]image.Rectangle{}
|
||||
testGLDamage = func(w *window, r image.Rectangle) { testGLDamaged[w] = append(testGLDamaged[w], r) }
|
||||
}
|
||||
damage, testGLDamaged[w] = testGLDamaged[w], nil
|
||||
// The area has no GdkWindow of its own: its allocation is in the
|
||||
// window's.
|
||||
var at gdkRectangle
|
||||
gtkWidgetGetAllocation(w.surface.area, &at)
|
||||
return damage, image.Pt(int(at.X), int(at.Y)), int(gtkWidgetGetScaleFactor(w.win)), true
|
||||
}
|
||||
|
||||
// testGLDamaged holds what TestGLDamage recorded, by window.
|
||||
var testGLDamaged map[*window][]image.Rectangle
|
||||
|
||||
// TestFrameClockInterval returns the refresh interval, in microseconds, in
|
||||
// the timings of the last frame of the frame clock of a window showing
|
||||
// native UI, which the clock waits after it for the next (paceFrameClock),
|
||||
// and the refresh rate of the monitor showing the window in millihertz.
|
||||
func TestFrameClockInterval(handle uintptr) (interval int64, mhz int32) {
|
||||
s := surfaceByHandle(handle)
|
||||
if s == nil {
|
||||
return 0, 0
|
||||
}
|
||||
if clock := gtkWidgetGetFrameClock(s.area); clock != 0 {
|
||||
if t := gdkFrameClockCurrentTimings(clock); t != 0 {
|
||||
interval = gdkFrameTimingsRefresh(t)
|
||||
}
|
||||
}
|
||||
return interval, s.refreshMilliHz()
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"sync"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
"github.com/egoist/mygo/transfer"
|
||||
)
|
||||
|
||||
// Hooks for tests of native UI with input methods, file drops and
|
||||
// assistive technology.
|
||||
|
||||
var (
|
||||
accessTestsOnce sync.Once
|
||||
gSignalEmitString func(obj ptr, signal *byte, s *byte)
|
||||
gtkIMMulticontextGetContextID func(im ptr) ptr
|
||||
gtkIMMulticontextSetContextID func(im ptr, id *byte)
|
||||
atkObjectGetNAccessibleChild func(obj ptr) int32
|
||||
atkObjectRefAccessibleChild func(obj ptr, i int32) ptr
|
||||
atkObjectGetRole func(obj ptr) int32
|
||||
atkRoleGetName func(role int32) ptr
|
||||
atkObjectGetName func(obj ptr) ptr
|
||||
atkObjectGetDescription func(obj ptr) ptr
|
||||
atkObjectRefStateSet func(obj ptr) ptr
|
||||
atkStateSetContainsState func(set ptr, state int32) bool
|
||||
atkActionGetNActions func(obj ptr) int32
|
||||
atkActionDoAction func(obj ptr, i int32) bool
|
||||
atkTextGetText func(obj ptr, start, end int32) ptr
|
||||
atkValueGetValueAndText func(obj ptr, value *float64, text ptr)
|
||||
atkValueSetValue func(obj ptr, value float64)
|
||||
atkEditableTextSetTextContent func(obj ptr, text *byte)
|
||||
atkComponentGrabFocus func(obj ptr) bool
|
||||
atkObjectGetAttributes func(obj ptr) ptr
|
||||
atkAttributeSetFree func(set ptr)
|
||||
)
|
||||
|
||||
func surfaceByHandle(handle uintptr) *surface {
|
||||
if w := windowByHandle(handle); w != nil {
|
||||
return w.surface
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestSurrounding returns the text around the caret that input methods get
|
||||
// from a window showing native UI, and the caret's offset in runes. GTK's
|
||||
// own input method reads it back: others, as fcitx5's, keep it to
|
||||
// themselves, so the window's input switches to GTK's.
|
||||
func TestSurrounding(handle uintptr) (text string, caret int, ok bool) {
|
||||
s := surfaceByHandle(handle)
|
||||
if s == nil {
|
||||
return "", 0, false
|
||||
}
|
||||
if gtkIMMulticontextSetContextID == nil {
|
||||
mustBind(libGTK, >kIMMulticontextGetContextID, "gtk_im_multicontext_get_context_id")
|
||||
mustBind(libGTK, >kIMMulticontextSetContextID, "gtk_im_multicontext_set_context_id")
|
||||
}
|
||||
const simple = "gtk-im-context-simple"
|
||||
if goStr(gtkIMMulticontextGetContextID(s.im)) != simple {
|
||||
gtkIMMulticontextSetContextID(s.im, cs(simple))
|
||||
}
|
||||
var p ptr
|
||||
var cursor int32
|
||||
if !gtkIMContextGetSurrounding(s.im, &p, &cursor) {
|
||||
return "", 0, true
|
||||
}
|
||||
text = takeStr(p)
|
||||
return text, utf8.RuneCountInString(text[:max(0, min(int(cursor), len(text)))]), true
|
||||
}
|
||||
|
||||
// TestComposeOver does what an input method that edits typed text does:
|
||||
// it deletes length runes from offset from of the text around the caret
|
||||
// unless from is -1, then composes text with the caret at caret, or
|
||||
// commits it.
|
||||
func TestComposeOver(handle uintptr, text string, caret int, commit bool, from, length int) bool {
|
||||
s := surfaceByHandle(handle)
|
||||
if s == nil {
|
||||
return false
|
||||
}
|
||||
if from >= 0 {
|
||||
_, cursor, _ := TestSurrounding(handle)
|
||||
gtkIMContextDeleteSurrounding(s.im, int32(from-cursor), int32(length))
|
||||
}
|
||||
if commit {
|
||||
if gSignalEmitString == nil {
|
||||
mustBind(libGObject, &gSignalEmitString, "g_signal_emit_by_name")
|
||||
}
|
||||
gSignalEmitString(s.im, cs("commit"), cs(text))
|
||||
} else {
|
||||
// Input methods compose in contexts out of the test's reach: send
|
||||
// what the preedit-changed signal would.
|
||||
s.send(platform.SurfaceEvent{Kind: platform.TextComposition, Text: text, Caret: caret})
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// TestDropFiles drags files to (x, y) of a window showing native UI and
|
||||
// drops them there, as GTK tells it, and reports whether the content took
|
||||
// them over there and when dropped.
|
||||
func TestDropFiles(handle uintptr, x, y float64, paths []string) (over, dropped bool) {
|
||||
s := surfaceByHandle(handle)
|
||||
if s == nil {
|
||||
return false, false
|
||||
}
|
||||
over = s.fileDragOver(x, y)
|
||||
s.send(platform.SurfaceEvent{Kind: platform.FileDragLeave})
|
||||
return over, s.dropFiles(x, y, paths)
|
||||
}
|
||||
|
||||
// TestMoveSurfacePointer sends real XTEST motion to the surface, including
|
||||
// during GTK's native drag tracker. It is unavailable outside X11.
|
||||
func TestMoveSurfacePointer(handle uintptr, x, y float64) bool {
|
||||
s := surfaceByHandle(handle)
|
||||
if s == nil {
|
||||
return false
|
||||
}
|
||||
var origin func(ptr, *int32, *int32) int32
|
||||
if !bind(libGDK, &origin, "gdk_window_get_origin") {
|
||||
return false
|
||||
}
|
||||
var ox, oy int32
|
||||
origin(s.eventWindow(), &ox, &oy)
|
||||
scale := float64(gtkWidgetGetScaleFactor(s.area))
|
||||
return TestMovePointer(int((float64(ox)+x)*scale), int((float64(oy)+y)*scale))
|
||||
}
|
||||
|
||||
func TestDataDragReady(handle uintptr) bool {
|
||||
s := surfaceByHandle(handle)
|
||||
return s != nil && s.lastPointer != 0
|
||||
}
|
||||
|
||||
// TestStartSerializedDrag simulates another application: the source uses
|
||||
// GTK's production providers with no token in MyGo's local registry.
|
||||
func TestStartSerializedDrag(handle uintptr, d transfer.Data, ops transfer.Operation, done func(transfer.Result)) bool {
|
||||
s := surfaceByHandle(handle)
|
||||
if s == nil || s.lastPointer == 0 {
|
||||
return false
|
||||
}
|
||||
s.StartDataDrag(platform.DragRequest{Data: d.Snapshot(), Operations: ops, X: 30, Y: 30, Done: done})
|
||||
return true
|
||||
}
|
||||
func TestCancelDataDrag(handle uintptr) {
|
||||
if s := surfaceByHandle(handle); s != nil {
|
||||
s.CancelDataDrag()
|
||||
}
|
||||
}
|
||||
|
||||
func TestDataDragResources() int { return len(gtkDataSources) }
|
||||
|
||||
// TestAccessNode is an element of native UI as assistive technology reads
|
||||
// it through ATK: the name of its role, its name, its value, and its
|
||||
// description.
|
||||
type TestAccessNode struct {
|
||||
Role, Label, Value, Description string
|
||||
// Busy, Active, Selectable, Selected, Multiselectable, Focused and
|
||||
// SupportsAutocompletion are its ATK states of those names,
|
||||
// Attributes its object attributes, and Selection whether it
|
||||
// implements AtkSelection.
|
||||
Busy, Active, Selectable, Selected, Multiselectable, Focused bool
|
||||
SupportsAutocompletion, Selection bool
|
||||
Attributes map[string]string
|
||||
obj ptr
|
||||
}
|
||||
|
||||
func loadAccessTests() {
|
||||
libATK, _ := open("libatk-1.0.so.0")
|
||||
a := libATK
|
||||
mustBind(a, &atkObjectGetNAccessibleChild, "atk_object_get_n_accessible_children")
|
||||
mustBind(a, &atkObjectRefAccessibleChild, "atk_object_ref_accessible_child")
|
||||
mustBind(a, &atkObjectGetRole, "atk_object_get_role")
|
||||
mustBind(a, &atkRoleGetName, "atk_role_get_name")
|
||||
mustBind(a, &atkObjectGetName, "atk_object_get_name")
|
||||
mustBind(a, &atkObjectGetDescription, "atk_object_get_description")
|
||||
mustBind(a, &atkObjectRefStateSet, "atk_object_ref_state_set")
|
||||
mustBind(a, &atkStateSetContainsState, "atk_state_set_contains_state")
|
||||
mustBind(a, &atkActionGetNActions, "atk_action_get_n_actions")
|
||||
mustBind(a, &atkActionDoAction, "atk_action_do_action")
|
||||
mustBind(a, &atkTextGetText, "atk_text_get_text")
|
||||
mustBind(a, &atkValueGetValueAndText, "atk_value_get_value_and_text")
|
||||
mustBind(a, &atkValueSetValue, "atk_value_set_value")
|
||||
mustBind(a, &atkEditableTextSetTextContent, "atk_editable_text_set_text_contents")
|
||||
mustBind(a, &atkComponentGrabFocus, "atk_component_grab_focus")
|
||||
mustBind(a, &atkObjectGetAttributes, "atk_object_get_attributes")
|
||||
mustBind(a, &atkAttributeSetFree, "atk_attribute_set_free")
|
||||
}
|
||||
|
||||
// TestAccessibility reads the elements of a window showing native UI as
|
||||
// assistive technology does, in order, and reports false when it cannot.
|
||||
func TestAccessibility(handle uintptr) ([]TestAccessNode, bool) {
|
||||
s := surfaceByHandle(handle)
|
||||
if s == nil || areaType == 0 {
|
||||
return nil, false
|
||||
}
|
||||
accessTestsOnce.Do(loadAccessTests)
|
||||
var nodes []TestAccessNode
|
||||
var walk func(obj ptr)
|
||||
walk = func(obj ptr) {
|
||||
for i := range atkObjectGetNAccessibleChild(obj) {
|
||||
child := atkObjectRefAccessibleChild(obj, i)
|
||||
if child == 0 {
|
||||
continue
|
||||
}
|
||||
n := TestAccessNode{Role: goStr(atkRoleGetName(atkObjectGetRole(child))), Label: goStr(atkObjectGetName(child)),
|
||||
Description: goStr(atkObjectGetDescription(child)), obj: child}
|
||||
if n.Role == "push button" {
|
||||
n.Role = "button" // as older versions of ATK name it
|
||||
}
|
||||
states := atkObjectRefStateSet(child)
|
||||
switch {
|
||||
case gTypeCheckInstanceIsA(child, atkTextGetType()):
|
||||
n.Value = takeStr(atkTextGetText(child, 0, -1))
|
||||
case gTypeCheckInstanceIsA(child, atkValueGetType()):
|
||||
var v float64
|
||||
atkValueGetValueAndText(child, &v, 0)
|
||||
n.Value = strconv.FormatFloat(v, 'g', -1, 64)
|
||||
case n.Role == "check box" || n.Role == "radio button":
|
||||
n.Value = "0"
|
||||
if atkStateSetContainsState(states, atkStates.checked) {
|
||||
n.Value = "1"
|
||||
}
|
||||
}
|
||||
n.Busy = atkStateSetContainsState(states, atkStates.busy)
|
||||
n.Active = atkStateSetContainsState(states, atkStates.active)
|
||||
n.Selectable = atkStateSetContainsState(states, atkStates.selectable)
|
||||
n.Selected = atkStateSetContainsState(states, atkStates.selected)
|
||||
n.Multiselectable = atkStateSetContainsState(states, atkStates.multiselectable)
|
||||
n.Selection = gTypeCheckInstanceIsA(child, atkSelectionGetType())
|
||||
n.Focused = atkStateSetContainsState(states, atkStates.focused)
|
||||
n.SupportsAutocompletion = atkStateSetContainsState(states, atkStates.supportsAutocompletion)
|
||||
gObjectUnref(states)
|
||||
if set := atkObjectGetAttributes(child); set != 0 {
|
||||
// A GSList of AtkAttribute: name and value.
|
||||
n.Attributes = map[string]string{}
|
||||
for l := set; l != 0; l = *slot(l, 8) {
|
||||
attr := *slot(l, 0)
|
||||
n.Attributes[goStr(*slot(attr, 0))] = goStr(*slot(attr, 8))
|
||||
}
|
||||
atkAttributeSetFree(set)
|
||||
}
|
||||
nodes = append(nodes, n)
|
||||
walk(child)
|
||||
gObjectUnref(child) // the tree holds the node
|
||||
}
|
||||
}
|
||||
walk(gtkWidgetGetAccessible(s.area))
|
||||
return nodes, true
|
||||
}
|
||||
|
||||
// TestAccessibilityPerform acts on the element labeled label as assistive
|
||||
// technology does: "press", "increment", "decrement", "focus", or "value"
|
||||
// to set its text to value. It reports whether the element can.
|
||||
func TestAccessibilityPerform(handle uintptr, label, action, value string) bool {
|
||||
nodes, _ := TestAccessibility(handle)
|
||||
for _, n := range nodes {
|
||||
if n.Label != label {
|
||||
continue
|
||||
}
|
||||
switch action {
|
||||
case "press":
|
||||
return gTypeCheckInstanceIsA(n.obj, atkActionGetType()) && atkActionGetNActions(n.obj) > 0 && atkActionDoAction(n.obj, 0)
|
||||
case "increment", "decrement":
|
||||
if !gTypeCheckInstanceIsA(n.obj, atkValueGetType()) {
|
||||
return false
|
||||
}
|
||||
var v float64
|
||||
atkValueGetValueAndText(n.obj, &v, 0)
|
||||
step := 1.0
|
||||
if action == "decrement" {
|
||||
step = -1
|
||||
}
|
||||
atkValueSetValue(n.obj, v+step)
|
||||
return true
|
||||
case "focus":
|
||||
return atkComponentGrabFocus(n.obj)
|
||||
case "value":
|
||||
if !gTypeCheckInstanceIsA(n.obj, atkEditableTextGetType()) {
|
||||
return false
|
||||
}
|
||||
atkEditableTextSetTextContent(n.obj, cs(value))
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// TestAccessibilityEnabled reports whether the element labeled label is
|
||||
// enabled and focusable for assistive technology, as ATK's enabled and
|
||||
// focusable states say, and ok false without one.
|
||||
func TestAccessibilityEnabled(handle uintptr, label string) (enabled, focusable, ok bool) {
|
||||
nodes, _ := TestAccessibility(handle)
|
||||
for _, n := range nodes {
|
||||
if n.Label == label {
|
||||
states := atkObjectRefStateSet(n.obj)
|
||||
defer gObjectUnref(states)
|
||||
return atkStateSetContainsState(states, atkStates.enabled), atkStateSetContainsState(states, atkStates.focusable), true
|
||||
}
|
||||
}
|
||||
return false, false, false
|
||||
}
|
||||
|
||||
// What tests read of ATK's states by name and of relations.
|
||||
var (
|
||||
accessStateTestsOnce sync.Once
|
||||
atkStateTypeGetName func(state int32) ptr
|
||||
atkObjectRefRelationSet func(obj ptr) ptr
|
||||
atkRelationSetGetNRelations func(set ptr) int32
|
||||
atkRelationSetGetRelation func(set ptr, i int32) ptr
|
||||
atkRelationGetRelationType func(relation ptr) int32
|
||||
atkRelationTypeGetName func(relation int32) ptr
|
||||
atkRelationGetTarget func(relation ptr) ptr
|
||||
atkStateLastDefined = int32(64) // more than ATK has
|
||||
)
|
||||
|
||||
func loadAccessStateTests() {
|
||||
a, _ := open("libatk-1.0.so.0")
|
||||
mustBind(a, &atkStateTypeGetName, "atk_state_type_get_name")
|
||||
mustBind(a, &atkObjectRefRelationSet, "atk_object_ref_relation_set")
|
||||
mustBind(a, &atkRelationSetGetNRelations, "atk_relation_set_get_n_relations")
|
||||
mustBind(a, &atkRelationSetGetRelation, "atk_relation_set_get_relation")
|
||||
mustBind(a, &atkRelationGetRelationType, "atk_relation_get_relation_type")
|
||||
mustBind(a, &atkRelationTypeGetName, "atk_relation_type_get_name")
|
||||
mustBind(a, &atkRelationGetTarget, "atk_relation_get_target")
|
||||
}
|
||||
|
||||
// TestAccessStatesAndRelations reads the element labeled label of a
|
||||
// window showing native UI as assistive technology does: the names of its
|
||||
// ATK states, and the labels of the elements each of its relations points
|
||||
// to, by the relation's name. ok is false without such an element.
|
||||
func TestAccessStatesAndRelations(handle uintptr, label string) (states []string, relations map[string][]string, ok bool) {
|
||||
nodes, _ := TestAccessibility(handle)
|
||||
accessStateTestsOnce.Do(loadAccessStateTests)
|
||||
for _, n := range nodes {
|
||||
if n.Label != label {
|
||||
continue
|
||||
}
|
||||
set := atkObjectRefStateSet(n.obj)
|
||||
for s := int32(1); s < atkStateLastDefined; s++ {
|
||||
if name := goStr(atkStateTypeGetName(s)); name != "" && atkStateSetContainsState(set, s) {
|
||||
states = append(states, name)
|
||||
}
|
||||
}
|
||||
gObjectUnref(set)
|
||||
relations = map[string][]string{}
|
||||
rs := atkObjectRefRelationSet(n.obj)
|
||||
for i := range atkRelationSetGetNRelations(rs) {
|
||||
r := atkRelationSetGetRelation(rs, i)
|
||||
name := goStr(atkRelationTypeGetName(atkRelationGetRelationType(r)))
|
||||
// A GPtrArray: its pointers, and how many.
|
||||
targets := atkRelationGetTarget(r)
|
||||
pdata, count := *slot(targets, 0), uint32(*slot(targets, 8))
|
||||
for j := range uintptr(count) {
|
||||
relations[name] = append(relations[name], goStr(atkObjectGetName(*slot(pdata, j*8))))
|
||||
}
|
||||
}
|
||||
gObjectUnref(rs)
|
||||
return states, relations, true
|
||||
}
|
||||
return nil, nil, false
|
||||
}
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/bridge"
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
// A window with a hidden title bar has no decorations, as a frameless one,
|
||||
// and the outer pixels of its page resize it. GTK's own title buttons go
|
||||
// over the page, in an overlay: a header bar for each side of the desktop's
|
||||
// button layout (gtk-decoration-layout) that has buttons, with its
|
||||
// background cleared. They look and act as the buttons of the desktop's
|
||||
// header bars do, and only those the layout names show: GNOME, KDE and Xfce
|
||||
// keep it in step with their window managers, and users of tiling window
|
||||
// managers empty it to have none.
|
||||
//
|
||||
// A Wayland compositor that decorates windows itself gets no buttons at all.
|
||||
// KWin, Hyprland and Sway say so with the default mode of
|
||||
// org_kde_kwin_server_decoration_manager, and GTK then asks them to decorate
|
||||
// a window without decorations too. The compositor's title bar has the
|
||||
// buttons, and a tiling compositor, which draws none, wants none, whatever
|
||||
// the button layout says: GTK reads it from GNOME's settings on Wayland, and
|
||||
// their default shows close.
|
||||
|
||||
// controlsCSS clears the bars around the buttons. With TitleBarHeight, the
|
||||
// bars take that height instead of the theme's.
|
||||
const controlsCSS = `headerbar.mygo-window-controls { background: none; border: none; box-shadow: none; }
|
||||
headerbar.mygo-window-controls.mygo-sized { min-height: 0; }`
|
||||
|
||||
// windowControls are the title buttons of a window with a hidden title bar.
|
||||
type windowControls struct {
|
||||
overlay ptr // GtkOverlay of the web view and the bars
|
||||
bars [2]ptr // the header bars at the start and the end, or 0
|
||||
room platform.TitleBar
|
||||
}
|
||||
|
||||
var controlsStyled bool
|
||||
|
||||
// newControls puts an overlay, whose bars hold the title buttons, where the
|
||||
// web view goes. It comes before the web view, whose first page is told the
|
||||
// room the buttons take.
|
||||
func (w *window) newControls() {
|
||||
if !controlsStyled {
|
||||
provider := gtkCssProviderNew()
|
||||
gtkCssProviderLoadFromData(provider, cs(controlsCSS), len(controlsCSS), nil)
|
||||
gtkStyleContextAddProviderForScreen(gtkWidgetGetScreen(w.win), provider, 600) // GTK_STYLE_PROVIDER_PRIORITY_APPLICATION
|
||||
gObjectUnref(provider)
|
||||
controlsStyled = true
|
||||
}
|
||||
w.controls = &windowControls{overlay: gtkOverlayNew()}
|
||||
// In the window before the bars: a header bar shows window buttons
|
||||
// only inside one.
|
||||
gtkBoxPackStart(w.box, w.controls.overlay, true, true, 0)
|
||||
w.layoutControls()
|
||||
}
|
||||
|
||||
// layoutControls gives the bars the buttons of the desktop's layout: GTK
|
||||
// shows each only when the window can do it (maximize when it is
|
||||
// resizable, close when it is deletable).
|
||||
func (w *window) layoutControls() {
|
||||
c := w.controls
|
||||
start, end := buttonLayout()
|
||||
if w.b.compositorDecorates {
|
||||
start, end = "", ""
|
||||
}
|
||||
for side, buttons := range [2]string{start, end} {
|
||||
bar := c.bars[side]
|
||||
if buttons == "" {
|
||||
if bar != 0 {
|
||||
gtkWidgetDestroy(bar)
|
||||
c.bars[side] = 0
|
||||
}
|
||||
continue
|
||||
}
|
||||
if bar == 0 {
|
||||
bar = w.newControlsBar(side)
|
||||
c.bars[side] = bar
|
||||
}
|
||||
layout := buttons + ":"
|
||||
if side == 1 {
|
||||
layout = ":" + buttons
|
||||
}
|
||||
// Also rebuilds the buttons for the window's state.
|
||||
gtkHeaderBarSetDecorationLayout(bar, cs(layout))
|
||||
gtkWidgetShowAll(bar)
|
||||
gtkWidgetSetVisible(bar, w.state&stateFullscreen == 0)
|
||||
}
|
||||
w.measureControls()
|
||||
}
|
||||
|
||||
func (w *window) newControlsBar(side int) ptr {
|
||||
bar := gtkHeaderBarNew()
|
||||
gtkHeaderBarSetShowCloseButton(bar, true) // the window buttons
|
||||
gtkHeaderBarSetHasSubtitle(bar, false)
|
||||
style := gtkWidgetGetStyleContext(bar)
|
||||
gtkStyleContextAddClass(style, cs("mygo-window-controls"))
|
||||
if h := w.opts.TitleBarHeight; h > 0 {
|
||||
gtkStyleContextAddClass(style, cs("mygo-sized"))
|
||||
gtkWidgetSetSizeRequest(bar, -1, int32(h))
|
||||
}
|
||||
const alignStart, alignEnd = 1, 2
|
||||
align := int32(alignEnd)
|
||||
if side == 0 {
|
||||
align = alignStart
|
||||
}
|
||||
gtkWidgetSetHalign(bar, align)
|
||||
gtkWidgetSetValign(bar, alignStart)
|
||||
gtkOverlayAddOverlay(w.controls.overlay, bar)
|
||||
connect(bar, "size-allocate", cbControlsAllocated, ptr(w.id))
|
||||
return bar
|
||||
}
|
||||
|
||||
// measureControls takes note of the room the bars take, from their
|
||||
// allocations once GTK laid them out and from their natural sizes before,
|
||||
// and tells the core when it changed.
|
||||
func (w *window) measureControls() {
|
||||
c := w.controls
|
||||
room := platform.TitleBar{Height: w.opts.TitleBarHeight}
|
||||
for side, bar := range c.bars {
|
||||
if bar == 0 {
|
||||
continue
|
||||
}
|
||||
var a gdkRectangle
|
||||
gtkWidgetGetAllocation(bar, &a)
|
||||
width, height := a.Width, a.Height
|
||||
if width <= 1 { // not allocated yet
|
||||
var minimum int32
|
||||
gtkWidgetGetPreferredWidth(bar, &minimum, &width)
|
||||
gtkWidgetGetPreferredHeight(bar, &minimum, &height)
|
||||
}
|
||||
if side == 0 {
|
||||
room.Left = int(width)
|
||||
} else {
|
||||
room.Right = int(width)
|
||||
}
|
||||
if w.opts.TitleBarHeight == 0 {
|
||||
room.Height = max(room.Height, int(height))
|
||||
}
|
||||
}
|
||||
// The bars, which hold the buttons, take the title bar's height.
|
||||
if room.Left > 0 || room.Right > 0 {
|
||||
room.Bottom = room.Height
|
||||
}
|
||||
if room != c.room {
|
||||
c.room = room
|
||||
w.h.TitleBarChanged()
|
||||
}
|
||||
}
|
||||
|
||||
// fullScreenChanged hides the buttons in full screen, and shows them after.
|
||||
func (w *window) fullScreenChanged() {
|
||||
for _, bar := range w.controls.bars {
|
||||
if bar != 0 {
|
||||
gtkWidgetSetVisible(bar, w.state&stateFullscreen == 0)
|
||||
}
|
||||
}
|
||||
w.h.TitleBarChanged()
|
||||
}
|
||||
|
||||
func (w *window) TitleBar() platform.TitleBar {
|
||||
if w.controls == nil || w.state&stateFullscreen != 0 {
|
||||
return platform.TitleBar{}
|
||||
}
|
||||
return w.controls.room
|
||||
}
|
||||
|
||||
// titleBarScript tells the first page the room of the title buttons, at
|
||||
// document start.
|
||||
func (w *window) titleBarScript() string { return bridge.TitleBarScript(w.TitleBar(), w.opts.Zoom) }
|
||||
|
||||
// buttonLayout returns the window buttons that gtk-decoration-layout puts at
|
||||
// the start and at the end of a title bar, such as "close,minimize" and
|
||||
// "minimize,maximize,close", without the icon and menu it may name.
|
||||
func buttonLayout() (start, end string) {
|
||||
var p ptr
|
||||
gObjectGetPtr(gtkSettingsGetDefault(), cs("gtk-decoration-layout"), unsafe.Pointer(&p), 0)
|
||||
before, after, _ := strings.Cut(takeStr(p), ":")
|
||||
return windowButtons(before), windowButtons(after)
|
||||
}
|
||||
|
||||
// WindowButtons returns the buttons of the desktop's layout, none where the
|
||||
// compositor decorates windows itself (platform.WindowButtonsBackend).
|
||||
func (b *Backend) WindowButtons() (start, end []string) {
|
||||
if b.compositorDecorates {
|
||||
return nil, nil
|
||||
}
|
||||
s, e := buttonLayout()
|
||||
split := func(side string) []string {
|
||||
if side == "" {
|
||||
return nil
|
||||
}
|
||||
return strings.Split(side, ",")
|
||||
}
|
||||
return split(s), split(e)
|
||||
}
|
||||
|
||||
func windowButtons(side string) string {
|
||||
var kept []string
|
||||
for b := range strings.SplitSeq(side, ",") {
|
||||
switch b = strings.TrimSpace(b); b {
|
||||
case "minimize", "maximize", "close":
|
||||
kept = append(kept, b)
|
||||
}
|
||||
}
|
||||
return strings.Join(kept, ",")
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"slices"
|
||||
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
// The fingers' taps, scrolls and pinches are platform.TouchGesture's
|
||||
// (surface.go gives it GTK's touches).
|
||||
|
||||
// touchPoints numbers the fingers on a surface for the views that follow
|
||||
// each (platform.TouchDown): GDK's sequences, which it frees and gives the
|
||||
// fingers after, become IDs counted from 1.
|
||||
type touchPoints struct {
|
||||
down []touchPoint
|
||||
last uint64
|
||||
}
|
||||
|
||||
type touchPoint struct {
|
||||
seq uintptr
|
||||
id uint64
|
||||
}
|
||||
|
||||
// event returns the kind and the finger's ID of the touch event of a
|
||||
// GdkEventTouch of type typ (GDK_TOUCH_BEGIN 37, UPDATE 38, END 39, CANCEL
|
||||
// 40) of seq, and false for a sequence that did not begin here.
|
||||
func (p *touchPoints) event(typ int32, seq uintptr) (kind platform.SurfaceEventKind, id uint64, ok bool) {
|
||||
i := slices.IndexFunc(p.down, func(t touchPoint) bool { return t.seq == seq })
|
||||
switch {
|
||||
case typ == 37 && i < 0:
|
||||
p.last++
|
||||
p.down = append(p.down, touchPoint{seq, p.last})
|
||||
return platform.TouchDown, p.last, true
|
||||
case i < 0, typ == 37:
|
||||
return 0, 0, false
|
||||
case typ == 38:
|
||||
return platform.TouchMove, p.down[i].id, true
|
||||
}
|
||||
id = p.down[i].id
|
||||
p.down = slices.Delete(p.down, i, i+1)
|
||||
if typ == 40 {
|
||||
return platform.TouchCancel, id, true
|
||||
}
|
||||
return platform.TouchUp, id, true
|
||||
}
|
||||
|
||||
// reset forgets the fingers down, whose ends went unseen, returning their
|
||||
// IDs, which the surface cancels.
|
||||
func (p *touchPoints) reset() []uint64 {
|
||||
var ids []uint64
|
||||
for _, t := range p.down {
|
||||
ids = append(ids, t.id)
|
||||
}
|
||||
p.down = p.down[:0]
|
||||
return ids
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
// TestTouchPoints checks that GDK's touch sequences become IDs that
|
||||
// stay with a finger from its begin to its end or cancel, and that a
|
||||
// sequence GDK frees and gives the next finger gets another (#1879).
|
||||
func TestTouchPoints(t *testing.T) {
|
||||
type touch struct {
|
||||
typ int32 // 37 begin, 38 update, 39 end, 40 cancel, 0 reset
|
||||
seq uintptr
|
||||
}
|
||||
type finger struct {
|
||||
kind platform.SurfaceEventKind
|
||||
id uint64
|
||||
}
|
||||
const (
|
||||
down = platform.TouchDown
|
||||
move = platform.TouchMove
|
||||
up = platform.TouchUp
|
||||
cancel = platform.TouchCancel
|
||||
)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
touches []touch
|
||||
want []finger
|
||||
}{
|
||||
{"one finger", []touch{{37, 0xa0}, {38, 0xa0}, {39, 0xa0}}, []finger{{down, 1}, {move, 1}, {up, 1}}},
|
||||
{"four fingers swiping", []touch{
|
||||
{37, 0xa0}, {37, 0xb0}, {37, 0xc0}, {37, 0xd0},
|
||||
{38, 0xc0}, {38, 0xa0}, {38, 0xd0}, {38, 0xb0},
|
||||
{39, 0xb0}, {39, 0xa0}, {39, 0xd0}, {39, 0xc0},
|
||||
}, []finger{
|
||||
{down, 1}, {down, 2}, {down, 3}, {down, 4},
|
||||
{move, 3}, {move, 1}, {move, 4}, {move, 2},
|
||||
{up, 2}, {up, 1}, {up, 4}, {up, 3},
|
||||
}},
|
||||
{"canceled", []touch{{37, 0xa0}, {37, 0xb0}, {40, 0xa0}, {38, 0xb0}, {38, 0xa0}},
|
||||
[]finger{{down, 1}, {down, 2}, {cancel, 1}, {move, 2}}},
|
||||
// GDK frees a sequence as its finger lifts, and may give the next
|
||||
// finger the same.
|
||||
{"sequence used again", []touch{{37, 0xa0}, {39, 0xa0}, {37, 0xa0}, {39, 0xa0}},
|
||||
[]finger{{down, 1}, {up, 1}, {down, 2}, {up, 2}}},
|
||||
// Fingers whose ends went unseen, as under a grab, are canceled
|
||||
// as new touches begin.
|
||||
{"reset", []touch{{37, 0xa0}, {37, 0xb0}, {0, 0}, {37, 0xa0}, {38, 0xb0}},
|
||||
[]finger{{down, 1}, {down, 2}, {cancel, 1}, {cancel, 2}, {down, 3}}},
|
||||
{"unknown sequences", []touch{{38, 0xe0}, {39, 0xe0}, {40, 0xe0}}, nil},
|
||||
{"begun twice", []touch{{37, 0xa0}, {37, 0xa0}}, []finger{{down, 1}}},
|
||||
} {
|
||||
var p touchPoints
|
||||
var got []finger
|
||||
for _, tt := range tc.touches {
|
||||
if tt.typ == 0 {
|
||||
for _, id := range p.reset() {
|
||||
got = append(got, finger{cancel, id})
|
||||
}
|
||||
continue
|
||||
}
|
||||
if kind, id, ok := p.event(tt.typ, tt.seq); ok {
|
||||
got = append(got, finger{kind, id})
|
||||
}
|
||||
}
|
||||
if !reflect.DeepEqual(got, tc.want) {
|
||||
t.Errorf("%s:\n got %v\nwant %v", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import "github.com/ebitengine/purego"
|
||||
|
||||
// Tray icons reach the panel through the StatusNotifierWatcher, which the
|
||||
// shell owns on KDE, quickshell and others. While it is away, as when the
|
||||
// shell restarts under the app, libayatana-appindicator falls back to a
|
||||
// GtkStatusIcon, and a tray call then could kill the app inside the
|
||||
// library (#1784). A tray holds its calls from when a watcher it saw
|
||||
// goes away until one returns, then gives the indicator what the app set
|
||||
// in the meantime. Where no watcher was ever seen, as on GNOME without the
|
||||
// AppIndicator extension or a plain X11 window manager, the fallback icon
|
||||
// is the only one, and the calls go through as before.
|
||||
|
||||
const statusNotifierWatcher = "org.kde.StatusNotifierWatcher"
|
||||
|
||||
// trayWatcher is what the backend knows of the watcher: whether it
|
||||
// listens to its owner, whether one owned it since, and whether that
|
||||
// owner is gone with none in its place.
|
||||
var trayWatcher struct{ subscribed, seen, away bool }
|
||||
|
||||
// watchTrayWatcher follows the watcher's owner, from the first tray on: a
|
||||
// subscription to NameOwnerChanged, then one NameHasOwner for the owner
|
||||
// now. Without a bus the trays call the indicator as before. Its callback
|
||||
// is made here, once per process, so that apps that never reach NewTray
|
||||
// link none of this.
|
||||
func watchTrayWatcher() {
|
||||
if trayWatcher.subscribed {
|
||||
return
|
||||
}
|
||||
trayWatcher.subscribed = true
|
||||
conn, err := bus()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
gDBusConnectionSignalSubscribe(conn, cs("org.freedesktop.DBus"), cs("org.freedesktop.DBus"), cs("NameOwnerChanged"),
|
||||
cs("/org/freedesktop/DBus"), cs(statusNotifierWatcher), 0, purego.NewCallback(watcherOwnerChanged), 0, 0)
|
||||
res, err := dbusCall("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "NameHasOwner",
|
||||
tuple(gVariantNewString(cs(statusNotifierWatcher))), "(b)")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
v := gVariantGetChildValue(res, 0)
|
||||
if gVariantGetBoolean(v) {
|
||||
trayWatcher.seen = true
|
||||
}
|
||||
gVariantUnref(v)
|
||||
gVariantUnref(res)
|
||||
}
|
||||
|
||||
// watcherOwnerChanged handles NameOwnerChanged (name, old owner, new
|
||||
// owner) for the watcher, on the GLib main loop.
|
||||
func watcherOwnerChanged(conn, sender, path, iface, signal, params, data ptr) {
|
||||
v := gVariantGetChildValue(params, 2)
|
||||
owned := goStr(gVariantGetString(v, nil)) != ""
|
||||
gVariantUnref(v)
|
||||
theBackend.watcherChanged(owned)
|
||||
}
|
||||
|
||||
// watcherChanged notes that the watcher has an owner or lost it. When one
|
||||
// appears, the trays drop libayatana's fallback tooltips and those that
|
||||
// held calls give the indicator their state again.
|
||||
func (b *Backend) watcherChanged(owned bool) {
|
||||
if !owned {
|
||||
trayWatcher.away = trayWatcher.seen
|
||||
return
|
||||
}
|
||||
trayWatcher.seen, trayWatcher.away = true, false
|
||||
for _, t := range b.trays {
|
||||
if t.ind != 0 {
|
||||
dropFallbackTooltips(t.ind)
|
||||
}
|
||||
t.resume()
|
||||
}
|
||||
}
|
||||
|
||||
// held reports whether the tray's calls wait for the watcher, and marks
|
||||
// the tray to give the indicator its state when the watcher returns.
|
||||
func (t *tray) held() bool {
|
||||
if trayWatcher.away {
|
||||
t.pending = true
|
||||
}
|
||||
return trayWatcher.away
|
||||
}
|
||||
|
||||
// resume gives the indicator what the app set while the watcher was away,
|
||||
// once: the image under a new file name, which makes the host load it
|
||||
// again, the title and tooltip, even empty, and the menu.
|
||||
func (t *tray) resume() {
|
||||
if !t.pending || t.ind == 0 {
|
||||
return
|
||||
}
|
||||
t.pending = false
|
||||
if t.image != nil {
|
||||
_ = t.SetImage(t.image, t.template)
|
||||
}
|
||||
t.SetTitle(t.title)
|
||||
t.SetToolTip(t.tip)
|
||||
t.SetMenu(t.spec)
|
||||
}
|
||||
|
||||
// dropFallbackTooltips disconnects the handlers of an indicator's
|
||||
// new-tooltip signal. libayatana connects one to its fallback
|
||||
// GtkStatusIcon and leaves it connected when it frees that icon for a
|
||||
// watcher that appeared, so the next tooltip would go to freed memory. A
|
||||
// watcher appearing is when it is about to free it; MyGo connects no
|
||||
// handler there. Releases without the signal need nothing.
|
||||
var dropFallbackTooltips = func(ind ptr) {
|
||||
// Older GLib, 2.56 among them, has g_signal_handlers_disconnect_matched
|
||||
// ignore a match by ID alone; g_signal_handler_find takes it.
|
||||
var find func(instance ptr, mask int32, signal, detail uint32, closure, fn, data ptr) uint64
|
||||
signal := indicatorSignal("new-tooltip")
|
||||
if signal == 0 || !bind(libGObject, &find, "g_signal_handler_find") {
|
||||
return
|
||||
}
|
||||
for id := find(ind, 1, signal, 0, 0, 0, 0); id != 0; id = find(ind, 1, signal, 0, 0, 0, 0) { // G_SIGNAL_MATCH_ID
|
||||
gSignalHandlerDisconnect(ind, id)
|
||||
}
|
||||
}
|
||||
|
||||
// indicatorSignal returns the ID of the AppIndicator's signal, 0 where
|
||||
// the library lacks it. It is asked once an indicator exists, which
|
||||
// registers the type.
|
||||
func indicatorSignal(name string) uint32 {
|
||||
var lookup func(name *byte, typ uintptr) uint32
|
||||
var typeFromName func(name *byte) uintptr
|
||||
if !bind(libGObject, &lookup, "g_signal_lookup") || !bind(libGObject, &typeFromName, "g_type_from_name") {
|
||||
return 0
|
||||
}
|
||||
typ := typeFromName(cs("AppIndicator"))
|
||||
if typ == 0 {
|
||||
return 0
|
||||
}
|
||||
return lookup(cs(name), typ)
|
||||
}
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"image"
|
||||
"image/png"
|
||||
"slices"
|
||||
"testing"
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
// indicatorCalls stands in for libayatana and GTK's menus, recording the
|
||||
// calls a tray makes, and gives the tests a fresh watcher state.
|
||||
func indicatorCalls(t *testing.T) *[]string {
|
||||
t.Helper()
|
||||
var calls []string
|
||||
str := func(p *byte) string { return goStr(ptr(unsafe.Pointer(p))) }
|
||||
oldIcon, oldLabel, oldTitle, oldTip, oldMenu := appIndicatorSetIconFull, appIndicatorSetLabel, appIndicatorSetTitle, appIndicatorSetTooltipFull, appIndicatorSetMenu
|
||||
oldMenuNew, oldShowAll, oldDrop, oldWatcher := gtkMenuNew, gtkWidgetShowAll, dropFallbackTooltips, trayWatcher
|
||||
t.Cleanup(func() {
|
||||
appIndicatorSetIconFull, appIndicatorSetLabel, appIndicatorSetTitle, appIndicatorSetTooltipFull, appIndicatorSetMenu = oldIcon, oldLabel, oldTitle, oldTip, oldMenu
|
||||
gtkMenuNew, gtkWidgetShowAll, dropFallbackTooltips, trayWatcher = oldMenuNew, oldShowAll, oldDrop, oldWatcher
|
||||
})
|
||||
appIndicatorSetIconFull = func(_ ptr, file, _ *byte) { calls = append(calls, "icon "+str(file)) }
|
||||
appIndicatorSetLabel = func(_ ptr, label, _ *byte) { calls = append(calls, "label "+str(label)) }
|
||||
appIndicatorSetTitle = func(_ ptr, title *byte) { calls = append(calls, "title "+str(title)) }
|
||||
appIndicatorSetTooltipFull = func(_ ptr, _, title, _ *byte) { calls = append(calls, "tooltip "+str(title)) }
|
||||
appIndicatorSetMenu = func(_, _ ptr) { calls = append(calls, "menu") }
|
||||
gtkMenuNew = func() ptr { return 1 }
|
||||
gtkWidgetShowAll = func(ptr) {}
|
||||
dropFallbackTooltips = func(ptr) { calls = append(calls, "drop tooltips") }
|
||||
trayWatcher = struct{ subscribed, seen, away bool }{subscribed: true}
|
||||
return &calls
|
||||
}
|
||||
|
||||
func testTray(t *testing.T) (*Backend, *tray) {
|
||||
b := &Backend{trays: map[int]*tray{}}
|
||||
tr := &tray{b: b, id: 1, ind: 1, iconDir: t.TempDir()}
|
||||
b.trays[tr.id] = tr
|
||||
return b, tr
|
||||
}
|
||||
|
||||
func pngImage(t *testing.T) []byte {
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, image.NewNRGBA(image.Rect(0, 0, 1, 1))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
// TestTrayWithoutWatcher checks that a session where no watcher was ever
|
||||
// seen, whose only icon is libayatana's fallback, calls the indicator
|
||||
// as before, even when told the watcher has no owner.
|
||||
func TestTrayWithoutWatcher(t *testing.T) {
|
||||
calls := indicatorCalls(t)
|
||||
b, tr := testTray(t)
|
||||
b.watcherChanged(false)
|
||||
tr.SetToolTip("tip")
|
||||
tr.SetTitle("title")
|
||||
if want := []string{"title tip", "tooltip tip", "label title"}; !slices.Equal(*calls, want) || tr.pending {
|
||||
t.Errorf("calls %q, pending %v; want %q, not pending", *calls, tr.pending, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTrayHoldsWhileWatcherAway checks that once a watcher seen goes
|
||||
// away, the tray keeps what the app sets, empty strings too, without
|
||||
// calling the indicator, and gives it all once when a watcher returns,
|
||||
// the image under a new file name.
|
||||
func TestTrayHoldsWhileWatcherAway(t *testing.T) {
|
||||
calls := indicatorCalls(t)
|
||||
b, tr := testTray(t)
|
||||
b.watcherChanged(true)
|
||||
img := pngImage(t)
|
||||
if err := tr.SetImage(img, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tr.SetTitle("before")
|
||||
*calls = nil
|
||||
|
||||
b.watcherChanged(false)
|
||||
menu := &platform.Menu{}
|
||||
if err := tr.SetImage(img, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tr.SetTitle("")
|
||||
tr.SetToolTip("away")
|
||||
tr.SetMenu(menu)
|
||||
if len(*calls) != 0 {
|
||||
t.Fatalf("called the indicator while the watcher was away: %q", *calls)
|
||||
}
|
||||
if !tr.pending || !bytes.Equal(tr.image, img) || tr.title != "" || tr.tip != "away" || tr.spec != menu {
|
||||
t.Fatalf("state not kept: pending %v, title %q, tip %q, menu kept %v", tr.pending, tr.title, tr.tip, tr.spec == menu)
|
||||
}
|
||||
|
||||
b.watcherChanged(true)
|
||||
want := []string{"drop tooltips", "icon " + tr.iconDir + "/icon-2.png", "label ", "title away", "tooltip away", "menu"}
|
||||
if !slices.Equal(*calls, want) || tr.pending {
|
||||
t.Errorf("on return: calls %q, pending %v; want %q, not pending", *calls, tr.pending, want)
|
||||
}
|
||||
*calls = nil
|
||||
b.watcherChanged(true)
|
||||
if want := []string{"drop tooltips"}; !slices.Equal(*calls, want) {
|
||||
t.Errorf("a second owner reapplied the state: calls %q, want %q", *calls, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTrayDestroyedWhileHeld checks that a tray destroyed while it held
|
||||
// calls gives the indicator nothing when the watcher returns.
|
||||
func TestTrayDestroyedWhileHeld(t *testing.T) {
|
||||
calls := indicatorCalls(t)
|
||||
b, tr := testTray(t)
|
||||
b.watcherChanged(true)
|
||||
b.watcherChanged(false)
|
||||
tr.SetToolTip("away")
|
||||
oldStatus, oldUnref := appIndicatorSetStatus, gObjectUnref
|
||||
t.Cleanup(func() { appIndicatorSetStatus, gObjectUnref = oldStatus, oldUnref })
|
||||
appIndicatorSetStatus = func(ptr, int32) {}
|
||||
gObjectUnref = func(ptr) {}
|
||||
tr.Destroy()
|
||||
*calls = nil
|
||||
b.watcherChanged(true)
|
||||
tr.resume()
|
||||
if len(*calls) != 0 {
|
||||
t.Errorf("a destroyed tray called the indicator: %q", *calls)
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"github.com/egoist/mygo/internal/inotify"
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
func (*Backend) NewFileWatch(notify func(platform.FileWatchNotice)) (platform.FileWatch, error) {
|
||||
return inotify.New(notify)
|
||||
}
|
||||
+549
@@ -0,0 +1,549 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"math"
|
||||
"slices"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
// A web view in a window of native UI (platform.Surface.NewWebView) is a
|
||||
// window of this package without a GtkWindow of its own: win is its
|
||||
// host's, and its WebKitWebView is a child of a GtkLayout under the
|
||||
// surface's area, in a GtkOverlay that the first web view puts where the
|
||||
// area was (the area is then an overlay of it, which GTK realizes again,
|
||||
// with a new GL context). The area keeps an alpha channel from then on:
|
||||
// its frames are transparent where the content shows a web view (holes),
|
||||
// so that what the content paints after it shows over the page, and an
|
||||
// input shape lets the pointer through to the page there. A drawing area
|
||||
// (frames drawn in memory) has a GdkWindow of its own, which X11 shows
|
||||
// over the page whatever its frames leave transparent: the same region
|
||||
// shapes it, so that the page shows in the holes. Its signals find it by
|
||||
// its id in Backend.webViews, apart from the windows.
|
||||
//
|
||||
// GTK 3 has no transforms of widgets: a page the content shows scaled has
|
||||
// its view at the size it shows, and WebKit zooms the page by the scale
|
||||
// (pageScale), so that it lays out in as many CSS pixels and only looks
|
||||
// smaller or larger. The view draws cut to the corners of the content's
|
||||
// hole, on whole pixels, as GTK draws WebKit's frames with OpenGL within
|
||||
// the rectangles of a clip alone, and the region shaping the area
|
||||
// follows them.
|
||||
|
||||
var (
|
||||
gtkLayoutNew func(h, v ptr) ptr
|
||||
gtkLayoutPut func(l, child ptr, x, y int32)
|
||||
gtkLayoutMove func(l, child ptr, x, y int32)
|
||||
gtkWidgetGetParent func(w ptr) ptr
|
||||
gtkWidgetGetParentWindow func(w ptr) ptr
|
||||
gdkWindowInputShapeCombineRegion func(w, region ptr, x, y int32)
|
||||
gdkWindowShapeCombineRegion func(w, region ptr, x, y int32)
|
||||
cairoRegionCreateRectangle func(r *gdkRectangle) ptr
|
||||
cairoRegionSubtractRectangle func(region ptr, r *gdkRectangle) int32
|
||||
cairoRegionUnion func(region, other ptr) int32
|
||||
cairoRegionDestroy func(region ptr)
|
||||
cairoRegionUnionRectangle func(region ptr, r *gdkRectangle) int32
|
||||
gdkCairoRegion func(cr, region ptr)
|
||||
cairoClip func(cr ptr)
|
||||
gtkWidgetEvent func(w, event ptr) bool
|
||||
gtkContainerGetFocusChild func(c ptr) ptr
|
||||
webViewsLoaded bool
|
||||
|
||||
// cbWebViewFocus handles a web view's focus signal, cbWebViewScroll
|
||||
// the scroll-event of one that scrolls its container, and
|
||||
// cbWebViewDraw its draw signal, and cbWebViewKey the key-press-events
|
||||
// its page leaves unhandled.
|
||||
cbWebViewFocus, cbWebViewScroll, cbWebViewDraw, cbWebViewKey ptr
|
||||
)
|
||||
|
||||
// widgetClassDraw is the offset of draw in GtkWidgetClass: a GObjectClass,
|
||||
// activate_signal and 19 functions.
|
||||
const widgetClassDraw = 288
|
||||
|
||||
func loadWebViews() {
|
||||
if webViewsLoaded {
|
||||
return
|
||||
}
|
||||
webViewsLoaded = true
|
||||
mustBind(libGTK, >kLayoutNew, "gtk_layout_new")
|
||||
mustBind(libGTK, >kLayoutPut, "gtk_layout_put")
|
||||
mustBind(libGTK, >kLayoutMove, "gtk_layout_move")
|
||||
mustBind(libGTK, >kWidgetGetParent, "gtk_widget_get_parent")
|
||||
mustBind(libGTK, >kWidgetGetParentWindow, "gtk_widget_get_parent_window")
|
||||
mustBind(libGDK, &gdkWindowInputShapeCombineRegion, "gdk_window_input_shape_combine_region")
|
||||
mustBind(libGDK, &gdkWindowShapeCombineRegion, "gdk_window_shape_combine_region")
|
||||
mustBind(libCairo, &cairoRegionCreateRectangle, "cairo_region_create_rectangle")
|
||||
mustBind(libCairo, &cairoRegionSubtractRectangle, "cairo_region_subtract_rectangle")
|
||||
mustBind(libCairo, &cairoRegionUnion, "cairo_region_union")
|
||||
mustBind(libCairo, &cairoRegionDestroy, "cairo_region_destroy")
|
||||
mustBind(libCairo, &cairoRegionUnionRectangle, "cairo_region_union_rectangle")
|
||||
mustBind(libGDK, &gdkCairoRegion, "gdk_cairo_region")
|
||||
mustBind(libCairo, &cairoClip, "cairo_clip")
|
||||
mustBind(libGTK, >kWidgetEvent, "gtk_widget_event")
|
||||
mustBind(libGTK, >kContainerGetFocusChild, "gtk_container_get_focus_child")
|
||||
// GTK moves the keyboard with Tab through focus signals, which
|
||||
// WebKit's Tab past the page's ends starts: the content takes the
|
||||
// keyboard back, and GTK moving it into a page by itself, as a window
|
||||
// shows, leaves it with the content.
|
||||
cbWebViewFocus = purego.NewCallback(func(widget ptr, direction int32, data ptr) bool {
|
||||
w := theBackend.window(data)
|
||||
if w == nil || w.host == nil {
|
||||
return false
|
||||
}
|
||||
const tabForward, tabBackward = 0, 1 // GtkDirectionType
|
||||
switch {
|
||||
case gtkWidgetHasFocus(w.web):
|
||||
if direction == tabForward || direction == tabBackward {
|
||||
w.tabOut(direction == tabBackward)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
case gtkContainerGetFocusChild(w.web) != 0:
|
||||
return false // a dialog of WebKit's in the view has the keyboard
|
||||
}
|
||||
if s := w.host.surface; s != nil {
|
||||
gtkWidgetGrabFocus(s.area)
|
||||
}
|
||||
return true
|
||||
})
|
||||
// The wheel and the touchpad over a web view with ScrollToContainer
|
||||
// scroll the content around it, as over the content itself, and never
|
||||
// reach WebKit, whose handler of the signal runs last.
|
||||
cbWebViewScroll = purego.NewCallback(func(widget, event, data ptr) bool {
|
||||
w := theBackend.window(data)
|
||||
if w == nil || w.host == nil || w.host.closed || w.host.surface == nil {
|
||||
return false
|
||||
}
|
||||
// The event is in the web view's window, at its allocation in the
|
||||
// layout, which is where the area is.
|
||||
var a gdkRectangle
|
||||
gtkWidgetGetAllocation(w.web, &a)
|
||||
w.host.surface.send(scrollEvent(event, float64(a.X), float64(a.Y)))
|
||||
return true
|
||||
})
|
||||
// A rounded page draws inside its corners: WebKit's handler, which
|
||||
// GTK would run with the clip of none before it, draws clipped here.
|
||||
cbWebViewDraw = purego.NewCallback(func(widget, cr, data ptr) bool {
|
||||
w := theBackend.window(data)
|
||||
if w == nil || w.corners == [4]float64{} {
|
||||
return false
|
||||
}
|
||||
region := cairoRegionCreateRectangle(&gdkRectangle{Width: gtkWidgetGetAllocatedWidth(widget), Height: gtkWidgetGetAllocatedHeight(widget)})
|
||||
box := platform.RectF{W: float64(gtkWidgetGetAllocatedWidth(widget)), H: float64(gtkWidgetGetAllocatedHeight(widget))}
|
||||
for _, r := range cornerPixels(box, w.corners, w.corners) {
|
||||
cairoRegionSubtractRectangle(region, &r)
|
||||
}
|
||||
gdkCairoRegion(cr, region)
|
||||
cairoRegionDestroy(region)
|
||||
cairoClip(cr)
|
||||
// The instance's class, then its draw.
|
||||
draw := *slot(*slot(widget, 0), widgetClassDraw)
|
||||
purego.SyscallN(uintptr(draw), uintptr(widget), uintptr(cr))
|
||||
return true
|
||||
})
|
||||
// A key the page leaves unhandled, which WebKit sends again once its
|
||||
// web process said so, and which its class handler then passes on:
|
||||
// this handler runs after it, for those keys alone. The content takes
|
||||
// it as if the web view's element had the focus. Tab moves the
|
||||
// keyboard (cbWebViewFocus), a modifier key on its own is no key of
|
||||
// the content's, and the shortcut of a menu item with a role, as Edit
|
||||
// › Copy's, goes on to the menu (cbMenuKey). GdkEventKey: state 24,
|
||||
// keyval 28.
|
||||
cbWebViewKey = purego.NewCallback(func(widget, event, data ptr) bool {
|
||||
w := theBackend.window(data)
|
||||
if w == nil || w.host == nil || w.host.closed || w.host.surface == nil {
|
||||
return false
|
||||
}
|
||||
keyval := field[uint32](event, 28)
|
||||
if roleKeys[w.host.accel][[2]uint32{gdkKeyvalToLower(keyval), field[uint32](event, 24) & modifierMask}] {
|
||||
return false
|
||||
}
|
||||
k, physical, mods := keyvalKey(keyval), eventPhysicalKey(event), gdkMods(field[uint32](event, 24))
|
||||
if k == platform.KeyTab || modifierKeyval(keyval) != 0 || k == platform.KeyUnknown && !platform.KeyByPosition(k, physical, mods) {
|
||||
return false
|
||||
}
|
||||
w.host.surface.send(platform.SurfaceEvent{Kind: platform.WebViewKey, Key: k, PhysicalKey: physical, Mods: mods, WebView: w})
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
func (s *surface) NewWebView(o *platform.WindowOptions, h platform.WindowHandler) (platform.WebView, error) {
|
||||
if err := webKit(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
loadWebViews()
|
||||
host := s.w
|
||||
b := host.b
|
||||
if s.layers == 0 {
|
||||
s.makeLayers()
|
||||
}
|
||||
b.nextID++
|
||||
v := &window{b: b, id: b.nextID, h: h, opts: o, win: host.win, host: host}
|
||||
b.webViews[v.id] = v
|
||||
v.createWebView()
|
||||
connect(v.web, "focus", cbWebViewFocus, ptr(v.id))
|
||||
connect(v.web, "draw", cbWebViewDraw, ptr(v.id))
|
||||
connectAfter(v.web, "key-press-event", cbWebViewKey, ptr(v.id))
|
||||
if o.ScrollToContainer {
|
||||
connect(v.web, "scroll-event", cbWebViewScroll, ptr(v.id))
|
||||
}
|
||||
gtkWidgetSetNoShowAll(v.web, true) // hidden until placed
|
||||
gtkLayoutPut(s.web, v.web, 0, 0)
|
||||
b.byWebView[v.web] = v
|
||||
host.webViews = append(host.webViews, v)
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// makeLayers puts the surface's area over a layout holding the web views,
|
||||
// in an overlay where the area was.
|
||||
func (s *surface) makeLayers() {
|
||||
area := s.area
|
||||
parent := gtkWidgetGetParent(area)
|
||||
focused := gtkWidgetHasFocus(area)
|
||||
s.layers = newOverlay()
|
||||
s.web = gtkLayoutNew(0, 0)
|
||||
gtkContainerAdd(s.layers, s.web)
|
||||
gObjectRef(area)
|
||||
if parent != 0 {
|
||||
gtkContainerRemove(parent, area)
|
||||
}
|
||||
if s.gl {
|
||||
// Holes show the web views through the frames.
|
||||
gtkGLAreaSetHasAlpha(area, true)
|
||||
}
|
||||
gtkOverlayAddOverlay(s.layers, area)
|
||||
gObjectUnref(area)
|
||||
switch {
|
||||
case parent == 0:
|
||||
case parent == s.w.box:
|
||||
gtkBoxPackStart(parent, s.layers, true, true, 0)
|
||||
if s.w.menubar != 0 {
|
||||
gtkBoxReorderChild(parent, s.layers, 1) // under the menu bar
|
||||
}
|
||||
default: // the overlay of a hidden title bar's controls
|
||||
gtkContainerAdd(parent, s.layers)
|
||||
}
|
||||
gtkWidgetShowAll(s.layers)
|
||||
if focused {
|
||||
gtkWidgetGrabFocus(area)
|
||||
}
|
||||
}
|
||||
|
||||
// PlaceWebViews shows the window's web views where the content shows
|
||||
// them, in its paint order under the surface, and hides the others; the
|
||||
// area's shapes show them and let the pointer through to them.
|
||||
func (s *surface) PlaceWebViews(views []platform.WebViewPlacement) {
|
||||
host := s.w
|
||||
if host.closed || s.layers == 0 {
|
||||
return
|
||||
}
|
||||
s.placed = append(s.placed[:0], views...)
|
||||
shown := make([]*window, 0, len(views))
|
||||
for _, p := range views {
|
||||
v, ok := p.WebView.(*window)
|
||||
if !ok || v.host != host || v.closed {
|
||||
continue
|
||||
}
|
||||
f := p.Frame
|
||||
x, y := int32(math.Round(f.X)), int32(math.Round(f.Y))
|
||||
width, height := int32(math.Round(f.X+f.W))-x, int32(math.Round(f.Y+f.H))-y
|
||||
gtkLayoutMove(s.web, v.web, x, y)
|
||||
gtkWidgetSetSizeRequest(v.web, width, height)
|
||||
// The placement's opacity fades the page itself, over what is
|
||||
// behind the window too, as a flyout over a parent left live.
|
||||
gtkWidgetSetOpacity(v.web, p.Opacity)
|
||||
v.present(&p, width)
|
||||
if !gtkWidgetGetVisible(v.web) {
|
||||
gtkWidgetShow(v.web)
|
||||
}
|
||||
shown = append(shown, v)
|
||||
}
|
||||
for _, v := range host.webViews {
|
||||
if !slices.Contains(shown, v) && gtkWidgetGetVisible(v.web) {
|
||||
if gtkWidgetHasFocus(v.web) {
|
||||
// A hidden view keeps no keyboard: it goes back to the
|
||||
// content.
|
||||
gtkWidgetGrabFocus(s.area)
|
||||
}
|
||||
gtkWidgetHide(v.web)
|
||||
}
|
||||
}
|
||||
s.shape()
|
||||
}
|
||||
|
||||
// present zooms the page of the web view w by the scale its placement p
|
||||
// shows it at, width wide, and cuts its drawing to p's corners.
|
||||
func (w *window) present(p *platform.WebViewPlacement, width int32) {
|
||||
scale := 1.0
|
||||
if sx, _ := p.Scale(); math.Abs(sx-1) > 1e-6 && width > 0 {
|
||||
// WebKit lays the page out at the view's width over its zoom: at
|
||||
// the page's own, whatever whole pixels the view has.
|
||||
pw, _ := p.Size()
|
||||
scale = float64(width) / pw
|
||||
}
|
||||
if old := cmp.Or(w.pageScale, 1); scale != old {
|
||||
webkitWebViewSetZoomLevel(w.web, webkitWebViewGetZoomLevel(w.web)/old*scale)
|
||||
w.pageScale = scale
|
||||
}
|
||||
var corners [4]float64
|
||||
for i, r := range p.Radii {
|
||||
corners[i] = r * scale
|
||||
}
|
||||
if corners != w.corners {
|
||||
w.corners = corners
|
||||
gtkWidgetQueueDraw(w.web)
|
||||
}
|
||||
}
|
||||
|
||||
// shape lets the pointer through the area where the web views take it:
|
||||
// in their clips but where the content painted over them. A drawing area
|
||||
// (frames drawn in memory) is shaped by the same region, as only its
|
||||
// shape lets the pages show through its own GdkWindow (#693). A GtkGLArea
|
||||
// has no window of its own: it draws in its parent's, with an alpha
|
||||
// channel whose holes show the pages, and is left unshaped. The shapes
|
||||
// follow the area's size (cbSurfaceSize) and new windows
|
||||
// (cbSurfaceRealize), and go once no web view is placed.
|
||||
func (s *surface) shape() {
|
||||
var all gdkRectangle
|
||||
gtkWidgetGetAllocation(s.area, &all)
|
||||
region := shapeRegion(all.Width, all.Height, s.placed) // none: no shape
|
||||
// The overlay's window of the area.
|
||||
if win := gtkWidgetGetParentWindow(s.area); win != 0 && win != gtkWidgetGetWindow(s.w.win) {
|
||||
gdkWindowInputShapeCombineRegion(win, region, 0, 0)
|
||||
}
|
||||
if gtkWidgetGetHasWindow(s.area) {
|
||||
if win := gtkWidgetGetWindow(s.area); win != 0 {
|
||||
gdkWindowShapeCombineRegion(win, region, 0, 0)
|
||||
}
|
||||
}
|
||||
if region != 0 {
|
||||
cairoRegionDestroy(region)
|
||||
}
|
||||
}
|
||||
|
||||
// shapeRegion returns the region, in an area width by height, that shows
|
||||
// the content and takes the pointer with web views placed there: all of
|
||||
// it but their clips, save what the content painted over them; 0 without
|
||||
// web views. Clips leave out the pixels they cover only in part, covers
|
||||
// put back those they cover in part.
|
||||
func shapeRegion(width, height int32, placed []platform.WebViewPlacement) ptr {
|
||||
if len(placed) == 0 {
|
||||
return 0
|
||||
}
|
||||
region := cairoRegionCreateRectangle(&gdkRectangle{Width: width, Height: height})
|
||||
for _, p := range placed {
|
||||
clip := gdkRect(p.Clip)
|
||||
cairoRegionSubtractRectangle(region, clip)
|
||||
// Save what its corners cut off.
|
||||
for _, r := range cornerRows(&p) {
|
||||
if r = intersectRect(r, *clip); r.Width > 0 && r.Height > 0 {
|
||||
cairoRegionUnionRectangle(region, &r)
|
||||
}
|
||||
}
|
||||
// Unless what the content painted over it: put back by a second
|
||||
// region, as cairo has no union of a difference.
|
||||
for _, c := range p.Covers {
|
||||
cover := cairoRegionCreateRectangle(gdkRectOut(c))
|
||||
cairoRegionUnion(region, cover)
|
||||
cairoRegionDestroy(cover)
|
||||
}
|
||||
}
|
||||
return region
|
||||
}
|
||||
|
||||
// cornerRows returns, by rows, the pixels of the surface that the corners
|
||||
// of a placed page cut off at all, in DIPs.
|
||||
func cornerRows(p *platform.WebViewPlacement) []gdkRectangle {
|
||||
if !p.Rounded() {
|
||||
return nil
|
||||
}
|
||||
sx, sy := p.Scale()
|
||||
var rx, ry [4]float64
|
||||
for i, r := range p.Radii {
|
||||
rx[i], ry[i] = r*sx, r*sy
|
||||
}
|
||||
return cornerPixels(p.Frame, rx, ry)
|
||||
}
|
||||
|
||||
// cornerPixels returns, by rows, the pixels that corners of radii rx, ry
|
||||
// (from the top-left clockwise) cut off at all from f.
|
||||
func cornerPixels(f platform.RectF, rx, ry [4]float64) []gdkRectangle {
|
||||
var out []gdkRectangle
|
||||
for i := range 4 {
|
||||
rx, ry := rx[i], ry[i]
|
||||
if rx <= 0 || ry <= 0 {
|
||||
continue
|
||||
}
|
||||
right, bottom := i == 1 || i == 2, i >= 2
|
||||
cx, cy := f.X+rx, f.Y+ry // the center of the corner's curve
|
||||
if right {
|
||||
cx = f.X + f.W - rx
|
||||
}
|
||||
if bottom {
|
||||
cy = f.Y + f.H - ry
|
||||
}
|
||||
top := f.Y
|
||||
if bottom {
|
||||
top = cy
|
||||
}
|
||||
for y := math.Floor(top); y < top+ry; y++ {
|
||||
// The curve is nearest the side at the row's edge furthest
|
||||
// from its center.
|
||||
dy := cy - max(y, top)
|
||||
if bottom {
|
||||
dy = min(y+1, top+ry) - cy
|
||||
}
|
||||
half := rx * math.Sqrt(max(1-dy*dy/(ry*ry), 0))
|
||||
x0, x1 := math.Floor(f.X), math.Ceil(cx-half)
|
||||
if right {
|
||||
x0, x1 = math.Floor(cx+half), math.Ceil(f.X+f.W)
|
||||
}
|
||||
if x1 > x0 {
|
||||
out = append(out, gdkRectangle{X: int32(x0), Y: int32(y), Width: int32(x1 - x0), Height: 1})
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// intersectRect returns the pixels a and b both have.
|
||||
func intersectRect(a, b gdkRectangle) gdkRectangle {
|
||||
x0, y0 := max(a.X, b.X), max(a.Y, b.Y)
|
||||
x1, y1 := min(a.X+a.Width, b.X+b.Width), min(a.Y+a.Height, b.Y+b.Height)
|
||||
return gdkRectangle{X: x0, Y: y0, Width: max(x1-x0, 0), Height: max(y1-y0, 0)}
|
||||
}
|
||||
|
||||
// gdkRect returns the pixels of r, in DIPs, that it covers wholly.
|
||||
func gdkRect(r platform.RectF) *gdkRectangle {
|
||||
x, y := int32(math.Ceil(r.X)), int32(math.Ceil(r.Y))
|
||||
return &gdkRectangle{X: x, Y: y, Width: max(int32(math.Floor(r.X+r.W))-x, 0), Height: max(int32(math.Floor(r.Y+r.H))-y, 0)}
|
||||
}
|
||||
|
||||
// gdkRectOut returns the pixels of r, in DIPs, that it covers at all.
|
||||
func gdkRectOut(r platform.RectF) *gdkRectangle {
|
||||
x, y := int32(math.Floor(r.X)), int32(math.Floor(r.Y))
|
||||
return &gdkRectangle{X: x, Y: y, Width: max(int32(math.Ceil(r.X+r.W))-x, 0), Height: max(int32(math.Ceil(r.Y+r.H))-y, 0)}
|
||||
}
|
||||
|
||||
// webViewAt returns the web view that takes the pointer at x, y in the
|
||||
// surface.
|
||||
func (s *surface) webViewAt(x, y float64) *window {
|
||||
for i := len(s.placed) - 1; i >= 0; i-- {
|
||||
if p := &s.placed[i]; p.At(x, y) {
|
||||
if v, ok := p.WebView.(*window); ok && !v.closed {
|
||||
return v
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// top returns the window that shows w: its host for a web view.
|
||||
func (w *window) top() *window {
|
||||
if w.host != nil {
|
||||
return w.host
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
// webViewPressed tells the content of the window that a button went down
|
||||
// on the web view w, at x, y in its window, which takes the press.
|
||||
func (w *window) webViewPressed(x, y float64, button uint32, mods platform.Modifiers) {
|
||||
s := w.host.surface
|
||||
if s == nil || w.host.closed {
|
||||
return
|
||||
}
|
||||
var a gdkRectangle
|
||||
gtkWidgetGetAllocation(w.web, &a)
|
||||
b, ok := map[uint32]int{1: 0, 2: 2, 3: 1}[button]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
s.send(platform.SurfaceEvent{Kind: platform.WebViewPress, X: float64(a.X) + x, Y: float64(a.Y) + y, Button: b, Mods: mods})
|
||||
}
|
||||
|
||||
// focusedWebView returns the web view of w that has the keyboard, if one
|
||||
// does.
|
||||
func (w *window) focusedWebView() *window {
|
||||
for _, v := range w.webViews {
|
||||
if !v.closed && gtkWidgetHasFocus(v.web) {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// TabInto gives the web view the keyboard. WebKitGTK focuses no element
|
||||
// of the page as the view takes it: once the page let go of the one it
|
||||
// had, the Tab moving the focus here, passed on, focuses its first, or
|
||||
// its last going back.
|
||||
func (w *window) TabInto(back bool) {
|
||||
s := w.host.surface
|
||||
if w.closed || s == nil {
|
||||
return
|
||||
}
|
||||
w.Eval("document.activeElement && document.activeElement.blur()")
|
||||
gtkWidgetGrabFocus(w.web)
|
||||
if ev := s.pressing; ev != 0 {
|
||||
switch field[uint32](ev, 28) {
|
||||
case 0xff09, 0xfe20, 0xff89: // GDK_KEY_Tab, ISO_Left_Tab, KP_Tab
|
||||
gtkWidgetEvent(w.web, ev)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// tabOut gives the content the keyboard back as Tab leaves the page of the
|
||||
// web view w past its last element, or Shift+Tab past its first.
|
||||
func (w *window) tabOut(back bool) {
|
||||
s := w.host.surface
|
||||
if s == nil || w.host.closed {
|
||||
return
|
||||
}
|
||||
gtkWidgetGrabFocus(s.area)
|
||||
ev := platform.SurfaceEvent{Kind: platform.WebViewTabOut, Key: platform.KeyTab, WebView: w}
|
||||
if back {
|
||||
ev.Mods = platform.ModShift
|
||||
}
|
||||
s.send(ev)
|
||||
}
|
||||
|
||||
// closeWebView closes a web view: by Close, or as its window closes.
|
||||
func (w *window) closeWebView() {
|
||||
if w.closed {
|
||||
return
|
||||
}
|
||||
w.closed = true
|
||||
b := w.b
|
||||
delete(b.webViews, w.id)
|
||||
delete(b.byWebView, w.web)
|
||||
if gtkWidgetHasFocus(w.web) && w.host.surface != nil {
|
||||
gtkWidgetGrabFocus(w.host.surface.area)
|
||||
}
|
||||
webkitUserContentManagerUnregisterHandler(w.ucm, cs("mygo"))
|
||||
webkitUserContentManagerRemoveAllScripts(w.ucm)
|
||||
gtkWidgetDestroy(w.web)
|
||||
gObjectUnref(w.ucm)
|
||||
if w.press.event != 0 {
|
||||
gdkEventFree(w.press.event)
|
||||
w.press.event = 0
|
||||
}
|
||||
h := w.host
|
||||
h.webViews = slices.DeleteFunc(h.webViews, func(v *window) bool { return v == w })
|
||||
if s := h.surface; s != nil {
|
||||
s.placed = slices.DeleteFunc(s.placed, func(p platform.WebViewPlacement) bool { return p.WebView == platform.WebView(w) })
|
||||
if !h.closed {
|
||||
s.shape()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// closeWebViews closes the web views of a window that closes.
|
||||
func (w *window) closeWebViews() {
|
||||
for len(w.webViews) > 0 {
|
||||
w.webViews[len(w.webViews)-1].closeWebView()
|
||||
}
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package linux
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
// TestShapeRegion checks the region that shapes a surface's area with
|
||||
// web views placed: the area but their clips, save the covers.
|
||||
func TestShapeRegion(t *testing.T) {
|
||||
lib, err := open("libcairo.so.2")
|
||||
if err != nil {
|
||||
t.Skip("no cairo:", err)
|
||||
}
|
||||
var contains func(region ptr, x, y int32) bool
|
||||
for _, b := range []struct {
|
||||
fn any
|
||||
name string
|
||||
}{
|
||||
{&cairoRegionCreateRectangle, "cairo_region_create_rectangle"},
|
||||
{&cairoRegionSubtractRectangle, "cairo_region_subtract_rectangle"},
|
||||
{&cairoRegionUnion, "cairo_region_union"},
|
||||
{&cairoRegionDestroy, "cairo_region_destroy"},
|
||||
{&cairoRegionUnionRectangle, "cairo_region_union_rectangle"},
|
||||
{&contains, "cairo_region_contains_point"},
|
||||
} {
|
||||
if !bind(lib, b.fn, b.name) {
|
||||
t.Skip("no " + b.name)
|
||||
}
|
||||
}
|
||||
if r := shapeRegion(100, 80, nil); r != 0 {
|
||||
cairoRegionDestroy(r)
|
||||
t.Fatal("shapeRegion without web views = a region, want none (no shape)")
|
||||
}
|
||||
placed := []platform.WebViewPlacement{{
|
||||
Frame: platform.RectF{X: 10, Y: 20, W: 60, H: 40},
|
||||
// Partly scrolled out: the clip is what shows of the frame.
|
||||
Clip: platform.RectF{X: 10.5, Y: 20, W: 59.5, H: 40},
|
||||
Covers: []platform.RectF{{X: 30.5, Y: 30, W: 10, H: 5}},
|
||||
}}
|
||||
r := shapeRegion(100, 80, placed)
|
||||
if r == 0 {
|
||||
t.Fatal("shapeRegion with a web view = none")
|
||||
}
|
||||
defer cairoRegionDestroy(r)
|
||||
for _, c := range []struct {
|
||||
x, y int32
|
||||
want bool
|
||||
}{
|
||||
{0, 0, true}, // the content around the page
|
||||
{99, 79, true}, // the area's last pixel
|
||||
{100, 40, false}, // past the area
|
||||
{9, 30, true}, // left of the page
|
||||
{10, 30, true}, // the clip covers it in part: the content's
|
||||
{11, 30, false}, // the page
|
||||
{69, 59, false}, // the page's last pixel
|
||||
{70, 59, true}, // right of the page
|
||||
{30, 30, true}, // a cover over it in part
|
||||
{35, 34, true}, // a cover over it
|
||||
{41, 34, false}, // past the cover
|
||||
{35, 35, false}, // below the cover
|
||||
} {
|
||||
if got := contains(r, c.x, c.y); got != c.want {
|
||||
t.Errorf("region contains %d, %d = %v, want %v", c.x, c.y, got, c.want)
|
||||
}
|
||||
}
|
||||
|
||||
// A page 120 by 80 shown at half its size, its corners rounded by 20
|
||||
// of its DIPs but the bottom-left one: the area keeps what they cut
|
||||
// off.
|
||||
placed = []platform.WebViewPlacement{{
|
||||
Frame: platform.RectF{X: 10, Y: 20, W: 60, H: 40}, Clip: platform.RectF{X: 10, Y: 20, W: 60, H: 40},
|
||||
Width: 120, Height: 80, Radii: [4]float64{20, 20, 20, 0},
|
||||
}}
|
||||
rounded := shapeRegion(100, 80, placed)
|
||||
defer cairoRegionDestroy(rounded)
|
||||
for _, c := range []struct {
|
||||
x, y int32
|
||||
want bool
|
||||
}{
|
||||
{10, 20, true}, // cut off by the top-left corner
|
||||
{12, 22, true}, // still outside its curve, 10 wide
|
||||
{14, 24, false}, // inside it
|
||||
{19, 20, true}, // the corner's last pixel on the top edge, in part
|
||||
{20, 20, false}, // past the corner, on the top edge
|
||||
{10, 30, false}, // past the corner, on the left edge
|
||||
{69, 20, true}, // cut off by the top-right corner
|
||||
{69, 59, true}, // the bottom-right
|
||||
{10, 59, false}, // the bottom-left is square
|
||||
{40, 40, false}, // the page
|
||||
} {
|
||||
if got := contains(rounded, c.x, c.y); got != c.want {
|
||||
t.Errorf("rounded: region contains %d, %d = %v, want %v", c.x, c.y, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
+2161
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user