Keep notification history on single lines with responsive navigation

This commit is contained in:
ak47 committed 2026-11-16 22:54:28 -05:00
1 parent 5dfa038706
commit 5fd5a26120
8 files changed
+398 -68

No files matched your search

@@ -0,0 +1,106 @@
// Copyright (c) 2026 Storm Dragon
// Authors: Storm Dragon, Angus Kola
// SPDX-License-Identifier: GPL-3.0-or-later
package app
import (
"context"
"encoding/json"
"io"
"log/slog"
"os"
"os/exec"
"strings"
"testing"
"time"
"git.stormux.org/storm/cthulhu/internal/atspi"
"git.stormux.org/storm/cthulhu/internal/braille"
"git.stormux.org/storm/cthulhu/internal/notificationui"
)
func TestNativeNotificationListOutput(t *testing.T) {
if os.Getenv("CTHULHU_NATIVE_NOTIFICATIONS") != "1" {
t.Skip("requires private notification UI session")
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
adapter := atspi.New()
if err := adapter.Start(ctx); err != nil {
t.Fatal(err)
}
defer adapter.Stop(context.Background())
queue := &autocompleteRequestQueue{requests: make(chan speechRequest, 256)}
frames := make(chan braille.Frame, 256)
done := make(chan struct{})
go func() {
defer close(done)
processEventsWithInput(ctx, slog.New(slog.DiscardHandler),
outputQueue{speech: queue, braille: frameRecorder{frames: frames}},
adapter, nil, nil, 0, nil, nil, nil, nil)
}()
defer func() { cancel(); <-done }()
command := exec.CommandContext(ctx, os.Getenv("CTHULHU_BINARY"), "--notification-list-ui")
in, err := command.StdinPipe()
if err != nil {
t.Fatal(err)
}
defer in.Close()
command.Stdout = io.Discard
command.Stderr = os.Stderr
if err := command.Start(); err != nil {
t.Fatal(err)
}
defer func() { _ = command.Process.Kill(); _ = command.Wait() }()
if err := json.NewEncoder(in).Encode(notificationui.Response{
Title: "Notification output test", Selected: "newest",
Entries: []notificationui.Entry{
{ID: "newest", Message: "Newest message", Received: "0 seconds ago"},
{ID: "middle", Message: "Middle\n\nmessage\tbody", Received: "1 minute ago"},
{ID: "oldest", Message: "Oldest message", Received: "2 minutes ago"},
},
}); err != nil {
t.Fatal(err)
}
wait := func(want string) {
t.Helper()
spoken, displayed := false, false
timer := time.NewTimer(4 * time.Second)
defer timer.Stop()
for !spoken || !displayed {
select {
case request := <-queue.requests:
t.Logf("speech: %q", request.Text)
spoken = spoken || strings.Contains(request.Text, want)
case frame := <-frames:
t.Logf("braille: %q", frame.Text)
displayed = displayed || strings.Contains(frame.Text, want)
case <-timer.C:
t.Fatalf("missing %q: speech=%v braille=%v", want, spoken, displayed)
case <-ctx.Done():
t.Fatal(ctx.Err())
}
}
}
wait("Newest message, 0 seconds ago")
for _, step := range []struct{ key, want string }{
{"Down", "Middle message body, 1 minute ago"},
{"Down", "Oldest message, 2 minutes ago"},
{"Up", "Middle message body, 1 minute ago"},
{"Home", "Newest message, 0 seconds ago"},
{"End", "Oldest message, 2 minutes ago"},
} {
if output, err := exec.CommandContext(ctx, "xdotool", "key", "--clearmodifiers", step.key).CombinedOutput(); err != nil {
t.Fatalf("%s: %v: %s", step.key, err, output)
}
wait(step.want)
}
if output, err := exec.CommandContext(ctx, "xdotool", "key", "--clearmodifiers", "Escape").CombinedOutput(); err != nil {
t.Fatalf("Escape: %v: %s", err, output)
}
if err := command.Wait(); err != nil {
t.Fatalf("closing notification list: %v", err)
}
}
+45 -24
View File
@@ -11,6 +11,7 @@ enum { ACTION_NONE, ACTION_COPY, ACTION_DISMISS, ACTION_CLEAR, ACTION_CLOSE,
static GtkWidget *dialog;
static GtkListStore *model;
static GtkWidget *tree;
static GtkTreeSelection *selection;
static GtkWidget *dismiss_button;
static GtkWidget *actions_box;
@@ -24,13 +25,25 @@ static void set_action(int code) {
if (!action_code) action_code = code;
}
static void dialog_destroyed(GtkWidget *widget, gpointer data) {
(void)widget;
(void)data;
dialog = NULL;
tree = NULL;
selection = NULL;
dismiss_button = NULL;
actions_box = NULL;
actions_status = NULL;
action_code = ACTION_CLOSE;
}
static void response(GtkDialog *widget, int response_id, gpointer data) {
(void)widget;
(void)data;
if (response_id == ACTION_COPY) set_action(ACTION_COPY);
else if (response_id == ACTION_DISMISS) set_action(ACTION_DISMISS);
else if (response_id == ACTION_CLEAR) set_action(ACTION_CLEAR);
else if (response_id == ACTION_CLOSE) set_action(ACTION_CLOSE);
else if (response_id == ACTION_CLOSE || response_id == GTK_RESPONSE_DELETE_EVENT) set_action(ACTION_CLOSE);
}
static void selection_changed(GtkTreeSelection *widget, gpointer data) {
@@ -67,10 +80,11 @@ static void set_actions(char **keys, char **labels, int count) {
gtk_widget_show_all(actions_box);
}
int notification_list_init(const char *title, const char *message_header,
const char *received_header) {
int notification_list_init(const char *title, const char *message_header) {
if (!gtk_init_check(NULL, NULL)) return 0;
g_set_application_name("Cthulhu Notifications");
action_code = ACTION_NONE;
if (g_strcmp0(g_get_application_name(), "Cthulhu Notifications"))
g_set_application_name("Cthulhu Notifications");
dialog = gtk_dialog_new();
gtk_window_set_title(GTK_WINDOW(dialog), title ? title : "Notifications");
gtk_window_set_default_size(GTK_WINDOW(dialog), 600, 400);
@@ -81,6 +95,7 @@ int notification_list_init(const char *title, const char *message_header,
gtk_dialog_add_button(GTK_DIALOG(dialog), "Close", ACTION_CLOSE);
gtk_dialog_set_default_response(GTK_DIALOG(dialog), ACTION_CLOSE);
g_signal_connect(dialog, "response", G_CALLBACK(response), NULL);
g_signal_connect(dialog, "destroy", G_CALLBACK(dialog_destroyed), NULL);
GtkWidget *content = gtk_dialog_get_content_area(GTK_DIALOG(dialog));
GtkWidget *grid = gtk_grid_new();
@@ -91,20 +106,20 @@ int notification_list_init(const char *title, const char *message_header,
gtk_widget_set_vexpand(scrolled, TRUE);
gtk_container_add(GTK_CONTAINER(grid), scrolled);
model = gtk_list_store_new(3, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING);
GtkWidget *tree = gtk_tree_view_new_with_model(GTK_TREE_MODEL(model));
model = gtk_list_store_new(4, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING);
tree = gtk_tree_view_new_with_model(GTK_TREE_MODEL(model));
gtk_widget_set_hexpand(tree, TRUE);
gtk_widget_set_vexpand(tree, TRUE);
AtkObject *tree_accessible = gtk_widget_get_accessible(tree);
if (tree_accessible) atk_object_set_name(tree_accessible, title ? title : "Notifications");
for (int column = 0; column < 2; column++) {
const char *header = column == 0 ? message_header : received_header;
GtkCellRenderer *renderer = gtk_cell_renderer_text_new();
GtkTreeViewColumn *view = gtk_tree_view_column_new_with_attributes(header, renderer,
"text", column, NULL);
if (header && header[0]) gtk_tree_view_column_set_sort_column_id(view, column);
gtk_tree_view_append_column(GTK_TREE_VIEW(tree), view);
}
// A single accessible cell contains both the message and received time.
// Keep history order fixed, with the newest notification first.
GtkCellRenderer *renderer = gtk_cell_renderer_text_new();
g_object_set(renderer, "single-paragraph-mode", TRUE, NULL);
GtkTreeViewColumn *view = gtk_tree_view_column_new_with_attributes(message_header,
renderer, "text", 3, NULL);
gtk_tree_view_append_column(GTK_TREE_VIEW(tree), view);
gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(tree), FALSE);
selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(tree));
gtk_tree_selection_set_mode(selection, GTK_SELECTION_SINGLE);
g_signal_connect(selection, "changed", G_CALLBACK(selection_changed), NULL);
@@ -129,11 +144,9 @@ int notification_list_init(const char *title, const char *message_header,
return 1;
}
void notification_list_set_entries(char **messages, char **received, int count,
char **ids, const char *selected, int can_control,
char **action_keys, char **action_labels,
int action_count) {
if (!model) return;
void notification_list_set_entries(char **lines, char **messages, char **received, int count,
char **ids, const char *selected) {
if (!dialog || !model) return;
suppress_selection = 1;
gtk_list_store_clear(model);
for (int index = 0; index < count; index++) {
@@ -141,7 +154,7 @@ void notification_list_set_entries(char **messages, char **received, int count,
gtk_list_store_append(model, &iterator);
gtk_list_store_set(model, &iterator, 0, messages && messages[index] ? messages[index] : "",
1, received && received[index] ? received[index] : "",
2, ids && ids[index] ? ids[index] : "", -1);
2, ids && ids[index] ? ids[index] : "", 3, lines && lines[index] ? lines[index] : "", -1);
}
GtkTreeIter iterator;
gboolean found = FALSE;
@@ -153,13 +166,20 @@ void notification_list_set_entries(char **messages, char **received, int count,
g_free(value);
if (found) {
GtkTreePath *path = gtk_tree_model_get_path(GTK_TREE_MODEL(model), &iterator);
gtk_tree_selection_select_path(selection, path);
gtk_tree_view_set_cursor(GTK_TREE_VIEW(tree), path, NULL, FALSE);
gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW(tree), path, NULL, FALSE, 0, 0);
gtk_tree_path_free(path);
break;
}
} while (gtk_tree_model_iter_next(GTK_TREE_MODEL(model), &iterator));
}
if (!found) gtk_tree_selection_unselect_all(selection);
suppress_selection = 0;
}
void notification_list_set_actions(int can_control, char **action_keys,
char **action_labels, int action_count) {
if (!dialog) return;
gtk_widget_set_sensitive(dismiss_button, can_control != 0);
if (!can_control) {
clear_action_buttons();
@@ -174,13 +194,13 @@ void notification_list_set_entries(char **messages, char **received, int count,
gtk_label_set_text(GTK_LABEL(actions_status), "");
gtk_widget_hide(actions_status);
}
suppress_selection = 0;
}
void notification_list_show(void) {
if (!dialog) return;
gtk_widget_show_all(dialog);
gtk_window_present(GTK_WINDOW(dialog));
gtk_widget_grab_focus(tree);
}
void notification_list_present(void) {
@@ -248,10 +268,11 @@ int notification_list_copy(void) {
}
void notification_list_close(void) {
if (!dialog) return;
gtk_widget_destroy(dialog);
if (dialog) gtk_widget_destroy(dialog);
dialog = NULL;
if (model) g_object_unref(model);
model = NULL;
tree = NULL;
selection = NULL;
dismiss_button = NULL;
actions_box = NULL;
+5 -6
View File
@@ -1,12 +1,11 @@
#ifndef CTHULHU_NOTIFICATION_UI_NATIVE_H
#define CTHULHU_NOTIFICATION_UI_NATIVE_H
int notification_list_init(const char *title, const char *message_header,
const char *received_header);
void notification_list_set_entries(char **messages, char **received, int count,
char **ids, const char *selected, int can_control,
char **action_keys, char **action_labels,
int action_count);
int notification_list_init(const char *title, const char *message_header);
void notification_list_set_entries(char **lines, char **messages, char **received, int count,
char **ids, const char *selected);
void notification_list_set_actions(int can_control, char **action_keys,
char **action_labels, int action_count);
void notification_list_show(void);
void notification_list_present(void);
void notification_list_iterate(void);
+63 -27
View File
@@ -18,6 +18,7 @@ import (
"errors"
"io"
"runtime"
"strings"
"time"
"unsafe"
)
@@ -60,19 +61,12 @@ func Run(ctx context.Context, input io.Reader, output io.Writer) error {
case <-ctx.Done():
return ctx.Err()
}
title := C.CString(initial.Title)
defer C.free(unsafe.Pointer(title))
messageHeader := C.CString("Notifications")
defer C.free(unsafe.Pointer(messageHeader))
receivedHeader := C.CString("Received")
defer C.free(unsafe.Pointer(receivedHeader))
if C.notification_list_init(title, messageHeader, receivedHeader) == 0 {
return errors.New("cannot open the notification list on this display")
if err := initialize(initial); err != nil {
return err
}
defer C.notification_list_close()
apply(initial)
C.notification_list_show()
defer closeWindow()
current := initial
encoder := json.NewEncoder(output)
ticker := time.NewTicker(10 * time.Millisecond)
defer ticker.Stop()
@@ -93,13 +87,14 @@ func Run(ctx context.Context, input io.Reader, output io.Writer) error {
C.notification_list_present()
continue
}
current = response
apply(response)
case <-ticker.C:
C.notification_list_iterate()
switch C.notification_list_action() {
case 1:
if C.notification_list_copy() != 0 {
if err := encoder.Encode(Request{Copy: true}); err != nil {
if err := encoder.Encode(Request{Copy: true, Selection: C.GoString(C.notification_list_selected_id())}); err != nil {
return err
}
}
@@ -117,10 +112,9 @@ func Run(ctx context.Context, input io.Reader, output io.Writer) error {
return nil
case 5:
selection := C.GoString(C.notification_list_selected_id())
row := int(C.notification_list_selected_row())
if err := encoder.Encode(Request{Selection: selection, Row: &row}); err != nil {
return err
}
// Navigation is local: keep the GTK rows and cursor intact and
// avoid a daemon refresh and pipe round trip for every arrow.
updateSelection(current, selection)
case 6:
action := C.GoString(C.notification_list_selected_action())
selection := C.GoString(C.notification_list_selected_id())
@@ -133,16 +127,48 @@ func Run(ctx context.Context, input io.Reader, output io.Writer) error {
}
}
func initialize(initial Response) error {
title := C.CString(initial.Title)
defer C.free(unsafe.Pointer(title))
messageHeader := C.CString("Notifications")
defer C.free(unsafe.Pointer(messageHeader))
if C.notification_list_init(title, messageHeader) == 0 {
return errors.New("cannot open the notification list on this display")
}
apply(initial)
C.notification_list_show()
return nil
}
func closeWindow() { C.notification_list_close() }
func updateSelection(response Response, selected string) {
var selectedEntry Entry
for _, entry := range response.Entries {
if entry.ID == selected {
selectedEntry = entry
break
}
}
applyActions(selectedEntry)
}
func apply(response Response) {
lines := make([]*C.char, len(response.Entries))
messages := make([]*C.char, len(response.Entries))
received := make([]*C.char, len(response.Entries))
identifiers := make([]*C.char, len(response.Entries))
for index, entry := range response.Entries {
identifiers[index] = C.CString(entry.ID)
lines[index] = C.CString(entryLine(entry))
messages[index] = C.CString(entry.Message)
received[index] = C.CString(entry.Received)
}
defer func() {
for _, value := range lines {
C.free(unsafe.Pointer(value))
}
for _, value := range messages {
C.free(unsafe.Pointer(value))
}
@@ -156,13 +182,26 @@ func apply(response Response) {
selectedID := C.CString(response.Selected)
defer C.free(unsafe.Pointer(selectedID))
var selectedEntry Entry
for _, entry := range response.Entries {
if entry.ID == response.Selected {
selectedEntry = entry
break
}
C.notification_list_set_entries(
cStringArray(lines), cStringArray(messages), cStringArray(received), C.int(len(response.Entries)),
cStringArray(identifiers), selectedID,
)
updateSelection(response, response.Selected)
}
func entryLine(entry Entry) string {
message := strings.Join(strings.Fields(entry.Message), " ")
received := strings.Join(strings.Fields(entry.Received), " ")
if message == "" {
return received
}
if received == "" {
return message
}
return message + ", " + received
}
func applyActions(selectedEntry Entry) {
actionKeys := make([]*C.char, len(selectedEntry.Actions))
actionLabels := make([]*C.char, len(selectedEntry.Actions))
for index, action := range selectedEntry.Actions {
@@ -178,11 +217,8 @@ func apply(response Response) {
}
}()
C.notification_list_set_entries(
cStringArray(messages), cStringArray(received), C.int(len(response.Entries)),
cStringArray(identifiers), selectedID, cBoolean(selectedEntry.CanControl),
cStringArray(actionKeys), cStringArray(actionLabels), C.int(len(selectedEntry.Actions)),
)
C.notification_list_set_actions(cBoolean(selectedEntry.CanControl),
cStringArray(actionKeys), cStringArray(actionLabels), C.int(len(selectedEntry.Actions)))
}
func cStringArray(values []*C.char) **C.char {
+61
View File
@@ -0,0 +1,61 @@
// Copyright (c) 2026 Storm Dragon
// Authors: Storm Dragon, Angus Kola
// SPDX-License-Identifier: GPL-3.0-or-later
package notificationui
import (
"fmt"
"os"
"runtime"
"testing"
)
func TestNotificationSingleLine(t *testing.T) {
for _, test := range []struct{ text, want string }{
{"Mail\n\nNew message\r\nFrom a friend\t ", "Mail New message From a friend"},
{"Alpha\u2028Beta\u2029Gamma", "Alpha Beta Gamma"},
{"One notification", "One notification"},
{"", ""},
} {
if got := entryLine(Entry{Message: test.text}); got != test.want {
t.Errorf("entryLine(%q) = %q, want %q", test.text, got, test.want)
}
}
for _, entry := range []Entry{
{Message: "Mail", Received: "1 minute ago"},
{Message: "Mail\n", Received: "1\tminute ago"},
} {
if got := entryLine(entry); got != "Mail, 1 minute ago" {
t.Errorf("entryLine(%+v) = %q", entry, got)
}
}
if got := entryLine(Entry{Received: "1 minute ago"}); got != "1 minute ago" {
t.Errorf("time-only entry = %q", got)
}
}
// This measures GTK work for a full history, excluding daemon and pipe latency.
// Run only on a private display and accessibility bus.
func BenchmarkNotificationSelection(b *testing.B) {
if os.Getenv("CTHULHU_NATIVE_NOTIFICATIONS") != "1" {
b.Skip("requires private notification UI session")
}
runtime.LockOSThread()
defer runtime.UnlockOSThread()
response := Response{Title: "Notifications", Selected: "0"}
for index := range 55 {
response.Entries = append(response.Entries, Entry{
ID: fmt.Sprint(index), Message: fmt.Sprintf("Notification %d", index), Received: "1 minute ago",
})
}
if err := initialize(response); err != nil {
b.Fatal(err)
}
defer closeWindow()
b.ReportAllocs()
b.ResetTimer()
for index := 0; index < b.N; index++ {
updateSelection(response, response.Entries[index%len(response.Entries)].ID)
}
}