Wake GTK helpers for events instead of polling every millisecond

This commit is contained in:
Storm Dragon committed 2026-11-19 04:27:39 -05:00
1 parent eb9dddbc2b
commit 938847e6ae
12 files changed
+328 -80

No files matched your search

+8
View File
@@ -63,6 +63,14 @@ void clipboard_watch_enable(int enabled, unsigned long long epoch) {
void clipboard_watch_iterate(void) { void clipboard_watch_iterate(void) {
while (gtk_events_pending()) gtk_main_iteration_do(FALSE); while (gtk_events_pending()) gtk_main_iteration_do(FALSE);
} }
// Milliseconds until the oldest unfinished change expires, or -1 if none.
int clipboard_watch_timeout(void) {
ClipboardChange *change = g_queue_peek_head(&changes);
if (!change || change->done) return -1;
gint64 remaining = change->deadline - g_get_monotonic_time();
return remaining <= 0 ? 0 : (int)MIN(remaining / 1000 + 1, G_MAXINT);
}
ClipboardChange *clipboard_watch_next(void) { ClipboardChange *clipboard_watch_next(void) {
ClipboardChange *change = g_queue_peek_head(&changes); ClipboardChange *change = g_queue_peek_head(&changes);
if (!change || (!change->done && g_get_monotonic_time() < change->deadline)) return NULL; if (!change || (!change->done && g_get_monotonic_time() < change->deadline)) return NULL;
+41 -24
View File
@@ -17,6 +17,8 @@ import (
"io" "io"
"runtime" "runtime"
"time" "time"
"git.stormux.org/storm/cthulhu/internal/glibwake"
) )
type WatchSettings struct { type WatchSettings struct {
@@ -39,9 +41,15 @@ func WatchText(ctx context.Context, input io.Reader, output io.Writer) error {
defer runtime.UnlockOSThread() defer runtime.UnlockOSThread()
ctx, cancel := context.WithCancel(ctx) ctx, cancel := context.WithCancel(ctx)
defer cancel() defer cancel()
loop, err := glibwake.New(ctx)
if err != nil {
return err
}
defer loop.Close()
settings := make(chan WatchSettings, 1) settings := make(chan WatchSettings, 1)
inputDone := make(chan error, 1) inputDone := make(chan error, 1)
go func() { go func() {
defer loop.Wake()
scanner := bufio.NewScanner(input) scanner := bufio.NewScanner(input)
scanner.Buffer(make([]byte, 1024), 4096) scanner.Buffer(make([]byte, 1024), 4096)
for scanner.Scan() { for scanner.Scan() {
@@ -52,6 +60,7 @@ func WatchText(ctx context.Context, input io.Reader, output io.Writer) error {
} }
select { select {
case settings <- request: case settings <- request:
loop.Wake()
case <-ctx.Done(): case <-ctx.Done():
return return
} }
@@ -65,35 +74,43 @@ func WatchText(ctx context.Context, input io.Reader, output io.Writer) error {
if err := encoder.Encode(TextChange{Ready: true}); err != nil { if err := encoder.Encode(TextChange{Ready: true}); err != nil {
return err return err
} }
ticker := time.NewTicker(time.Millisecond)
defer ticker.Stop()
for { for {
select { for drained := false; !drained; {
case <-ctx.Done(): select {
return ctx.Err() case <-ctx.Done():
case err := <-inputDone: return ctx.Err()
return err case err := <-inputDone:
case request := <-settings:
enabled := C.int(0)
if request.Enabled {
enabled = 1
}
C.clipboard_watch_enable(enabled, C.ulonglong(request.Epoch))
if err := encoder.Encode(TextChange{Ready: true, Epoch: request.Epoch}); err != nil {
return err return err
} case request := <-settings:
case <-ticker.C: enabled := C.int(0)
C.clipboard_watch_iterate() if request.Enabled {
for { enabled = 1
change := C.clipboard_watch_next()
if change == nil {
break
} }
value := TextChange{Text: C.GoString(change.text), Epoch: uint64(change.epoch), Timestamp: uint32(change.timestamp)} C.clipboard_watch_enable(enabled, C.ulonglong(request.Epoch))
C.clipboard_watch_free(change) if err := encoder.Encode(TextChange{Ready: true, Epoch: request.Epoch}); err != nil {
if err := encoder.Encode(value); err != nil {
return err return err
} }
default:
drained = true
}
}
timeout := time.Duration(-1)
if milliseconds := C.clipboard_watch_timeout(); milliseconds >= 0 {
timeout = time.Duration(milliseconds) * time.Millisecond
}
if err := loop.Wait(timeout); err != nil {
return err
}
C.clipboard_watch_iterate()
for {
change := C.clipboard_watch_next()
if change == nil {
break
}
value := TextChange{Text: C.GoString(change.text), Epoch: uint64(change.epoch), Timestamp: uint32(change.timestamp)}
C.clipboard_watch_free(change)
if err := encoder.Encode(value); err != nil {
return err
} }
} }
} }
+1
View File
@@ -13,5 +13,6 @@ typedef struct {
int clipboard_watch_init(void); int clipboard_watch_init(void);
void clipboard_watch_enable(int enabled, unsigned long long epoch); void clipboard_watch_enable(int enabled, unsigned long long epoch);
void clipboard_watch_iterate(void); void clipboard_watch_iterate(void);
int clipboard_watch_timeout(void);
ClipboardChange *clipboard_watch_next(void); ClipboardChange *clipboard_watch_next(void);
void clipboard_watch_free(ClipboardChange *change); void clipboard_watch_free(ClipboardChange *change);
+37
View File
@@ -0,0 +1,37 @@
// Copyright (c) 2026 Storm Dragon
// Authors: Storm Dragon, Angus Kola
// SPDX-License-Identifier: GPL-3.0-or-later
#include <glib.h>
#include <unistd.h>
#include "wait.h"
// One iteration of the default main context that also returns when wakeFd is
// readable. GLib's own timeout is honored; timeoutMs, when not negative,
// shortens it. Readiness on wakeFd is consumed. Returns -1 if another thread
// owns the context.
int glibwake_wait(int wakeFd, int timeoutMs) {
GMainContext *context = g_main_context_default();
if (!g_main_context_acquire(context)) return -1;
gint priority = 0;
g_main_context_prepare(context, &priority);
gint capacity = 16, count = 0, timeout = -1;
GPollFD *fds = NULL;
for (;;) {
fds = g_renew(GPollFD, fds, capacity + 1);
count = g_main_context_query(context, priority, &timeout, fds, capacity);
if (count <= capacity) break;
capacity = count;
}
if (timeoutMs >= 0) timeout = timeout < 0 ? timeoutMs : MIN(timeout, timeoutMs);
fds[count] = (GPollFD){.fd = wakeFd, .events = G_IO_IN | G_IO_HUP | G_IO_ERR};
g_poll(fds, count + 1, timeout);
if (fds[count].revents != 0) {
char buffer[64];
while (read(wakeFd, buffer, sizeof buffer) > 0) {}
}
g_main_context_check(context, priority, fds, count);
g_main_context_dispatch(context);
g_main_context_release(context);
g_free(fds);
return 0;
}
+7
View File
@@ -0,0 +1,7 @@
// Copyright (c) 2026 Storm Dragon
// Authors: Storm Dragon, Angus Kola
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef CTHULHU_GLIBWAKE_WAIT_H
#define CTHULHU_GLIBWAKE_WAIT_H
int glibwake_wait(int wakeFd, int timeoutMs);
#endif
+71
View File
@@ -0,0 +1,71 @@
// Copyright (c) 2026 Storm Dragon
// Authors: Storm Dragon, Angus Kola
// SPDX-License-Identifier: GPL-3.0-or-later
// Package glibwake lets a Go loop that owns the default GLib main context
// sleep until GLib has work or another goroutine has news for it, instead of
// polling on a short ticker.
package glibwake
/*
#cgo pkg-config: glib-2.0
#include "wait.h"
*/
import "C"
import (
"context"
"errors"
"os"
"syscall"
"time"
)
var ErrContextBusy = errors.New("GLib main context is owned by another thread")
// Loop must be waited on from the OS thread that owns the GTK/GLib context.
// Wake may be called from any goroutine, including after Close.
type Loop struct {
read int
write *os.File
stopWake func() bool
}
// New returns a Loop that also wakes when ctx ends.
func New(ctx context.Context) (*Loop, error) {
var pipe [2]int
if err := syscall.Pipe2(pipe[:], syscall.O_NONBLOCK|syscall.O_CLOEXEC); err != nil {
return nil, err
}
// Goroutines blocked on input can outlive the loop. A closed os.File
// rejects their late writes instead of reaching a reused descriptor.
loop := &Loop{read: pipe[0], write: os.NewFile(uintptr(pipe[1]), "glib-wake")}
loop.stopWake = context.AfterFunc(ctx, loop.Wake)
return loop, nil
}
// Wake ends the current or next Wait. Call it after publishing the news,
// such as after a channel send, so the woken loop can observe it.
func (loop *Loop) Wake() {
_, _ = loop.write.Write([]byte{0})
}
// Wait dispatches one GLib iteration, sleeping until a source is ready, Wake
// is called, or timeout passes. A negative timeout waits without a limit of
// its own.
func (loop *Loop) Wait(timeout time.Duration) error {
milliseconds := -1
if timeout >= 0 {
milliseconds = int(min((timeout+time.Millisecond-1)/time.Millisecond, 1<<30))
}
if C.glibwake_wait(C.int(loop.read), C.int(milliseconds)) != 0 {
return ErrContextBusy
}
return nil
}
func (loop *Loop) Close() {
loop.stopWake()
_ = loop.write.Close()
_ = syscall.Close(loop.read)
}
+71
View File
@@ -0,0 +1,71 @@
// Copyright (c) 2026 Storm Dragon
// Authors: Storm Dragon, Angus Kola
// SPDX-License-Identifier: GPL-3.0-or-later
package glibwake
import (
"context"
"runtime"
"testing"
"time"
)
func TestWaitEndsOnWakeTimeoutAndCancellation(t *testing.T) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
loop, err := New(ctx)
if err != nil {
t.Fatal(err)
}
defer loop.Close()
start := time.Now()
if err := loop.Wait(20 * time.Millisecond); err != nil {
t.Fatal(err)
}
if elapsed := time.Since(start); elapsed < 15*time.Millisecond {
t.Fatalf("timeout ended after %v", elapsed)
}
go func() {
time.Sleep(10 * time.Millisecond)
loop.Wake()
}()
if err := waitWithin(t, loop, 5*time.Second); err != nil {
t.Fatal(err)
}
// Earlier wakes are consumed, so an idle wait now blocks until cancel.
go func() {
time.Sleep(10 * time.Millisecond)
cancel()
}()
if err := waitWithin(t, loop, 5*time.Second); err != nil {
t.Fatal(err)
}
}
func TestWakeAfterCloseIsHarmless(t *testing.T) {
loop, err := New(t.Context())
if err != nil {
t.Fatal(err)
}
loop.Close()
loop.Wake()
}
// waitWithin waits without a timeout of its own and fails if nothing woke it.
func waitWithin(t *testing.T, loop *Loop, limit time.Duration) error {
t.Helper()
guard := time.AfterFunc(limit, loop.Wake)
defer guard.Stop()
start := time.Now()
err := loop.Wait(-1)
if time.Since(start) >= limit {
t.Fatal("wait was not woken")
}
return err
}
+9 -4
View File
@@ -23,6 +23,7 @@ import (
"time" "time"
"unsafe" "unsafe"
"git.stormux.org/storm/cthulhu/internal/glibwake"
"git.stormux.org/storm/cthulhu/internal/platform/xorg" "git.stormux.org/storm/cthulhu/internal/platform/xorg"
) )
@@ -83,7 +84,7 @@ func runningApplications() []string {
// The chooser shares the preferences child and bounded pipe protocol. Cancel // The chooser shares the preferences child and bounded pipe protocol. Cancel
// emits no request, so it cannot open a profile or submit settings. // emits no request, so it cannot open a profile or submit settings.
func chooseApplication(ctx context.Context, updates <-chan Response, errorsIn <-chan error, output io.Writer) (Response, bool, error) { func chooseApplication(ctx context.Context, loop *glibwake.Loop, updates <-chan Response, errorsIn <-chan error, output io.Writer) (Response, bool, error) {
choices := runningApplications() choices := runningApplications()
if C.prefs_application_chooser_init() == 0 { if C.prefs_application_chooser_init() == 0 {
return Response{}, false, errors.New("cannot open application chooser on this display") return Response{}, false, errors.New("cannot open application chooser on this display")
@@ -95,8 +96,7 @@ func chooseApplication(ctx context.Context, updates <-chan Response, errorsIn <-
C.free(unsafe.Pointer(name)) C.free(unsafe.Pointer(name))
} }
C.prefs_application_chooser_present() C.prefs_application_chooser_present()
ticker := time.NewTicker(time.Millisecond) waitTimeout := time.Duration(-1)
defer ticker.Stop()
selected := false selected := false
for { for {
select { select {
@@ -105,12 +105,17 @@ func chooseApplication(ctx context.Context, updates <-chan Response, errorsIn <-
case err := <-errorsIn: case err := <-errorsIn:
return Response{}, false, err return Response{}, false, err
case response := <-updates: case response := <-updates:
waitTimeout = 0
if response.Present { if response.Present {
C.prefs_application_chooser_present() C.prefs_application_chooser_present()
} else if selected { } else if selected {
return response, true, nil return response, true, nil
} }
case <-ticker.C: default:
if err := loop.Wait(waitTimeout); err != nil {
return Response{}, false, err
}
waitTimeout = -1
C.prefs_application_chooser_iterate() C.prefs_application_chooser_iterate()
switch C.prefs_application_chooser_action() { switch C.prefs_application_chooser_action() {
case 2: case 2:
+4 -1
View File
@@ -83,7 +83,9 @@ func EncodeInitial(encoder *json.Encoder, response Response) error {
// readResponses owns catalog assembly for the lifetime of the helper pipe. // readResponses owns catalog assembly for the lifetime of the helper pipe.
// Only complete responses reach GTK, including after application selection. // Only complete responses reach GTK, including after application selection.
func readResponses(ctx context.Context, input io.Reader, updates chan<- Response, errorsIn chan<- error) { // notify runs after each delivered response or error, waking the GTK loop.
func readResponses(ctx context.Context, input io.Reader, updates chan<- Response, errorsIn chan<- error, notify func()) {
defer notify()
scanner := bufio.NewScanner(input) scanner := bufio.NewScanner(input)
scanner.Buffer(make([]byte, 4096), 1024*1024) scanner.Buffer(make([]byte, 4096), 1024*1024)
var initial *Response var initial *Response
@@ -112,6 +114,7 @@ func readResponses(ctx context.Context, input io.Reader, updates chan<- Response
} }
select { select {
case updates <- response: case updates <- response:
notify()
case <-ctx.Done(): case <-ctx.Done():
return return
} }
@@ -51,7 +51,7 @@ func TestInitialCatalogRoundTrip(t *testing.T) {
} }
updates := make(chan Response, 3) updates := make(chan Response, 3)
errorsIn := make(chan error, 1) errorsIn := make(chan error, 1)
readResponses(t.Context(), &wire, updates, errorsIn) readResponses(t.Context(), &wire, updates, errorsIn, func() {})
if err := <-errorsIn; err != nil { if err := <-errorsIn; err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -82,13 +82,13 @@ func TestInitialCatalogRejectsOversizedEntry(t *testing.T) {
func TestInitialCatalogIncompleteAndCancellation(t *testing.T) { func TestInitialCatalogIncompleteAndCancellation(t *testing.T) {
updates := make(chan Response, 1) updates := make(chan Response, 1)
errorsIn := make(chan error, 1) errorsIn := make(chan error, 1)
readResponses(t.Context(), strings.NewReader(`{"CatalogPending":true}`+"\n"), updates, errorsIn) readResponses(t.Context(), strings.NewReader(`{"CatalogPending":true}`+"\n"), updates, errorsIn, func() {})
if err := <-errorsIn; !errors.Is(err, io.ErrUnexpectedEOF) || len(updates) != 0 { if err := <-errorsIn; !errors.Is(err, io.ErrUnexpectedEOF) || len(updates) != 0 {
t.Fatalf("incomplete catalog reached the UI: %v", err) t.Fatalf("incomplete catalog reached the UI: %v", err)
} }
ctx, cancel := context.WithCancel(t.Context()) ctx, cancel := context.WithCancel(t.Context())
cancel() cancel()
readResponses(ctx, strings.NewReader("{}\n"), make(chan Response), errorsIn) readResponses(ctx, strings.NewReader("{}\n"), make(chan Response), errorsIn, func() {})
} }
func TestDefaultVoicesFiltersESpeakAndDefaultAlias(t *testing.T) { func TestDefaultVoicesFiltersESpeakAndDefaultAlias(t *testing.T) {
+18 -7
View File
@@ -22,6 +22,7 @@ import (
"unsafe" "unsafe"
"git.stormux.org/storm/cthulhu/internal/config" "git.stormux.org/storm/cthulhu/internal/config"
"git.stormux.org/storm/cthulhu/internal/glibwake"
"git.stormux.org/storm/cthulhu/internal/tentacle" "git.stormux.org/storm/cthulhu/internal/tentacle"
) )
@@ -35,9 +36,14 @@ func Run(ctx context.Context, input io.Reader, output io.Writer) error {
defer runtime.UnlockOSThread() defer runtime.UnlockOSThread()
ctx, cancel := context.WithCancel(ctx) ctx, cancel := context.WithCancel(ctx)
defer cancel() defer cancel()
loop, err := glibwake.New(ctx)
if err != nil {
return err
}
defer loop.Close()
updates := make(chan Response, 1) updates := make(chan Response, 1)
errorsIn := make(chan error, 1) errorsIn := make(chan error, 1)
go readResponses(ctx, input, updates, errorsIn) go readResponses(ctx, input, updates, errorsIn, loop.Wake)
var initial Response var initial Response
select { select {
case initial = <-updates: case initial = <-updates:
@@ -47,7 +53,7 @@ func Run(ctx context.Context, input io.Reader, output io.Writer) error {
return ctx.Err() return ctx.Err()
} }
if initial.ChooseApplication { if initial.ChooseApplication {
response, chosen, err := chooseApplication(ctx, updates, errorsIn, output) response, chosen, err := chooseApplication(ctx, loop, updates, errorsIn, output)
if err != nil || !chosen { if err != nil || !chosen {
return err return err
} }
@@ -84,10 +90,10 @@ func Run(ctx context.Context, input io.Reader, output io.Writer) error {
C.prefs_busy(0, boolean(canSave)) C.prefs_busy(0, boolean(canSave))
encoder := json.NewEncoder(output) encoder := json.NewEncoder(output)
// AT-SPI calls into this GTK process are served by the same event pump. // AT-SPI calls into this GTK process are served by the same event pump.
// Focus snapshots make several synchronous calls, so a 10 ms poll adds // Focus snapshots make several synchronous calls, so the loop sleeps in
// noticeable delay to every Tab stop in the dialog. // GLib's poll and answers each one as soon as it arrives. After a
ticker := time.NewTicker(time.Millisecond) // response, one non-blocking iteration observes any state it changed.
defer ticker.Stop() waitTimeout := time.Duration(-1)
for { for {
select { select {
case <-ctx.Done(): case <-ctx.Done():
@@ -95,6 +101,7 @@ func Run(ctx context.Context, input io.Reader, output io.Writer) error {
case err := <-errorsIn: case err := <-errorsIn:
return err return err
case response := <-updates: case response := <-updates:
waitTimeout = 0
if response.ExtensionsOnly { if response.ExtensionsOnly {
if err := session.setExtensionPages(response.ExtensionPages); err != nil { if err := session.setExtensionPages(response.ExtensionPages); err != nil {
return err return err
@@ -149,7 +156,11 @@ func Run(ctx context.Context, input io.Reader, output io.Writer) error {
} }
C.prefs_busy(0, boolean(canSave)) C.prefs_busy(0, boolean(canSave))
status(response.Message, !response.Accepted) status(response.Message, !response.Accepted)
case <-ticker.C: default:
if err := loop.Wait(waitTimeout); err != nil {
return err
}
waitTimeout = -1
C.prefs_iterate() C.prefs_iterate()
profileActive := session.profileTick() profileActive := session.profileTick()
if session.profilePreview != nil && !previewPending && !busy { if session.profilePreview != nil && !previewPending && !busy {
+58 -41
View File
@@ -20,6 +20,8 @@ import (
"runtime" "runtime"
"time" "time"
"unsafe" "unsafe"
"git.stormux.org/storm/cthulhu/internal/glibwake"
) )
type Message struct { type Message struct {
@@ -43,9 +45,15 @@ func Run(ctx context.Context, input io.Reader, output io.Writer) error {
defer runtime.UnlockOSThread() defer runtime.UnlockOSThread()
ctx, cancel := context.WithCancel(ctx) ctx, cancel := context.WithCancel(ctx)
defer cancel() defer cancel()
loop, err := glibwake.New(ctx)
if err != nil {
return err
}
defer loop.Close()
updates := make(chan Message, 16) updates := make(chan Message, 16)
readErrors := make(chan error, 1) readErrors := make(chan error, 1)
go func() { go func() {
defer loop.Wake()
scanner := bufio.NewScanner(input) scanner := bufio.NewScanner(input)
scanner.Buffer(make([]byte, 4096), 1024*1024) scanner.Buffer(make([]byte, 4096), 1024*1024)
for scanner.Scan() { for scanner.Scan() {
@@ -56,6 +64,7 @@ func Run(ctx context.Context, input io.Reader, output io.Writer) error {
} }
select { select {
case updates <- update: case updates <- update:
loop.Wake()
case <-ctx.Done(): case <-ctx.Done():
return return
} }
@@ -83,52 +92,60 @@ func Run(ctx context.Context, input io.Reader, output io.Writer) error {
setItems(initial.Items, initial.Selected) setItems(initial.Items, initial.Selected)
} }
encoder := json.NewEncoder(output) encoder := json.NewEncoder(output)
// AT-SPI requests are served by GTK's main context. A longer polling // AT-SPI requests are served by GTK's main context, so this loop sleeps
// interval is paid once for every synchronous accessibility query, so a // in GLib's poll rather than on a ticker: each synchronous accessibility
// single arrow key can accumulate hundreds of milliseconds of delay. // query is answered as soon as it arrives.
ticker := time.NewTicker(time.Millisecond)
defer ticker.Stop()
for { for {
select { // After an update, run one non-blocking iteration so state it
case <-ctx.Done(): // changed is observed below even if it queued no GLib work.
return ctx.Err() timeout := time.Duration(-1)
case err := <-readErrors: for drained := false; !drained; {
select {
case <-ctx.Done():
return ctx.Err()
case err := <-readErrors:
return err
case update := <-updates:
timeout = 0
if update.Close {
return nil
}
if update.Present {
C.history_present()
}
if update.Items != nil {
setItems(update.Items, update.Selected)
}
if update.Append != "" {
value := C.CString(update.Append)
C.history_append(value)
C.free(unsafe.Pointer(value))
}
default:
drained = true
}
}
if err := loop.Wait(timeout); err != nil {
return err return err
case update := <-updates: }
if update.Close { C.history_iterate()
return nil switch C.history_action() {
} case 1:
if update.Present { if C.history_copy() != 0 {
C.history_present() if err := encoder.Encode(Request{Action: "copy"}); err != nil {
}
if update.Items != nil {
setItems(update.Items, update.Selected)
}
if update.Append != "" {
value := C.CString(update.Append)
C.history_append(value)
C.free(unsafe.Pointer(value))
}
case <-ticker.C:
C.history_iterate()
switch C.history_action() {
case 1:
if C.history_copy() != 0 {
if err := encoder.Encode(Request{Action: "copy"}); err != nil {
return err
}
} else if err := encoder.Encode(Request{Action: "empty"}); err != nil {
return err return err
} }
case 2: } else if err := encoder.Encode(Request{Action: "empty"}); err != nil {
if err := encoder.Encode(Request{Action: "remove", Selection: C.GoString(C.history_selected()), Row: int(C.history_selected_row())}); err != nil { return err
return err
}
case 3:
return nil
case 4:
C.history_clear()
} }
case 2:
if err := encoder.Encode(Request{Action: "remove", Selection: C.GoString(C.history_selected()), Row: int(C.history_selected_row())}); err != nil {
return err
}
case 3:
return nil
case 4:
C.history_clear()
} }
} }
} }