diff --git a/.gitignore b/.gitignore index 0584260..90a2d24 100644 --- a/.gitignore +++ b/.gitignore @@ -11,3 +11,4 @@ .relay/ .relay-archive/ dist/ +docs/desktop-tests/gnome-r1-*.png diff --git a/CLAUDE.md b/CLAUDE.md index 82d2350..ff15f83 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,8 +1,8 @@ # Menew for Linux: Project Rules for Agents -Native Linux productivity utility built in Rust (GTK4 + Libadwaita). Separate repository from the macOS version (`../menew`). Licensed under **GPL-3.0-only**, the same as the Mac app. The name "Menew", the icon and the website are not covered by the license: see `TRADEMARK.md`. +Native Linux productivity utility built in Rust (GTK4 + Libadwaita). Separate repository from the macOS version (`../menew`; on some machines the folder is `../MeuMenu`). Licensed under **GPL-3.0-only**, the same as the Mac app. The name "Menew", the icon and the website are not covered by the license: see `TRADEMARK.md`. -**Parity with the Mac app is the goal.** Before planning or reviewing any feature, check `../menew` itself (README, `LICENSE`, `TRADEMARK.md`, `Sources/`), not only this repo, and keep `docs/parity.md` up to date. +**Parity with the Mac app is the goal.** Before planning or reviewing any feature, check the Mac repo itself (`../menew` or `../MeuMenu`) (README, `LICENSE`, `TRADEMARK.md`, `Sources/`), not only this repo, and keep `docs/parity.md` up to date. ## Core Principles (Strict - Never Violate) @@ -12,7 +12,7 @@ Native Linux productivity utility built in Rust (GTK4 + Libadwaita). Separate re 4. **Localization (i18n)**: Every single UI string must be translatable across 5 languages: English (`en`), Portuguese (`pt`), German (`de`), Spanish (`es`), and Chinese (`zh`). 5. **English Commits**: Conventional Commits in English (e.g., `feat(palette): ...`, `fix(clipboard): ...`). 6. **No Em-Dash**: Never use the em-dash character in documentation or code comments. Always use the regular hyphen (`-`). -7. **Isolation from Mac repo**: Do not touch `../menew`. The Linux version has its own lifecycle. +7. **Isolation from Mac repo**: Do not touch the Mac repo (`../menew` or `../MeuMenu`). The Linux version has its own lifecycle. ## Technical Architecture & Decisions @@ -34,10 +34,11 @@ Native Linux productivity utility built in Rust (GTK4 + Libadwaita). Separate re ## Workspace Structure - `crates/menew-core`: Pure Rust core logic, desktop entry scanner, inline math evaluator, SQLite storage, i18n dictionary. -- `crates/menew-ui`: Command palette window and widgets using GTK4 and Libadwaita. +- `crates/menew-ui`: GTK4 / Libadwaita windows: palette, Menew window (notes, performance, settings), tray popover, screenshot editor, welcome tour. - `crates/menew-tray`: System tray implementation with `ksni`. - `crates/menew-shortcuts`: Global shortcut listener with `ashpd`. - `crates/menew-clipboard`: Clipboard service and data-control/D-Bus listeners. +- `crates/menew-desktop`: Screenshot and color picker portals, window snapping (KWin scripting, GNOME extension `org.menew.Shell`). - `crates/menew`: Main coordinator daemon and entry point. - `gnome-extension`: GNOME Shell extension for clipboard bridging on GNOME Wayland. - `docs/`: Technical findings and architecture specifications. @@ -50,3 +51,7 @@ cargo check cargo test cargo clippy ``` + +From macOS or Windows, run them (and the headless GNOME/KDE tests) in the Linux dev image: +`docker build -t menew-dev scripts/dev`, then `bash scripts/dev/run.sh "cargo test --workspace"` and +`bash scripts/dev/run.sh "bash scripts/dev/desktop-tests.sh"`. diff --git a/crates/menew-core/src/focus.rs b/crates/menew-core/src/focus.rs index 91afe1f..2e5f299 100644 --- a/crates/menew-core/src/focus.rs +++ b/crates/menew-core/src/focus.rs @@ -2,9 +2,9 @@ //! +5 minutes, stop, and a 5 minute break at the end. Pure state: the daemon ticks it and shows the //! time left in the tray and the notification at the end. //! -//! The Mac app can also mute the microphone, keep the computer awake and pause the clipboard while -//! a focus runs. Those options depend on the quick actions (Phase 9) and the clipboard pause -//! (Phase 5), so they are left as the [`FocusHooks`] trait: the daemon passes [`NoHooks`] today. +//! Like the Mac, a focus can also mute the microphone, keep the computer awake and pause the +//! clipboard while it runs: the daemon does those through the [`FocusHooks`] trait +//! (`crates/menew/src/focus_hooks.rs`), following the Settings. use crate::i18n::Language; use crate::strings::tr; @@ -31,7 +31,7 @@ pub trait FocusHooks { fn ended(&mut self); } -/// Does nothing: the options that need them are not on Linux yet (see `docs/parity.md`). +/// Does nothing (tests, and before the daemon sets its own hooks). pub struct NoHooks; impl FocusHooks for NoHooks { diff --git a/crates/menew-core/src/strings_r1.rs b/crates/menew-core/src/strings_r1.rs index 6c1c2b6..fe80473 100644 --- a/crates/menew-core/src/strings_r1.rs +++ b/crates/menew-core/src/strings_r1.rs @@ -128,4 +128,176 @@ pub(crate) static TABLE: &[(&str, [&str; 5])] = &[ ("sc_clipboard", ["Clipboard history", "Histórico do clipboard", "Zwischenablage-Verlauf", "Historial del portapapeles", "剪贴板历史"]), ("sc_paste_next", ["Paste the next item", "Colar o próximo item", "Nächsten Eintrag einfügen", "Pegar el siguiente elemento", "粘贴下一项"]), ("sc_capture_text", ["Copy text from the screen", "Copiar texto da tela", "Text vom Bildschirm kopieren", "Copiar texto de la pantalla", "复制屏幕上的文字"]), + // Legacy release-1 keys kept while the unconnected UI modules are evaluated. + ("mon_ram", ["RAM", "RAM", "RAM", "RAM", "内存"]), + ("mon_gpu", ["GPU", "GPU", "GPU", "GPU", "GPU"]), + ("mon_uptime", ["Uptime", "Ligado há", "Laufzeit", "Tiempo encendido", "运行时间"]), + ("mon_load", ["Load", "Carga", "Last", "Carga", "负载"]), + ("mon_used_of", ["{} of {}", "{} de {}", "{} von {}", "{} de {}", "{} / {}"]), + ("mon_read_write", ["Read {} · Write {}", "Leitura {} · Escrita {}", "Lesen {} · Schreiben {}", "Lectura {} · Escritura {}", "读取 {} · 写入 {}"]), + ("mon_health", ["Health {}%", "Saúde {}%", "Zustand {} %", "Salud {}%", "健康度 {}%"]), + ("mon_cycles", ["{} cycles", "{} ciclos", "{} Zyklen", "{} ciclos", "{} 次循环"]), + ("mon_watts", ["{} W", "{} W", "{} W", "{} W", "{} W"]), + ("mon_top_memory", ["Using the most memory", "Usando mais memória", "Meister Speicher", "Usando más memoria", "内存占用最高"]), + ("mon_quit_process", ["Quit", "Fechar", "Beenden", "Cerrar", "退出"]), + ("mon_all_good", ["All good", "Tudo certo", "Alles gut", "Todo bien", "一切正常"]), + ("mon_warn_memory", ["Memory is {}% full", "Memória {}% cheia", "Speicher zu {} % voll", "Memoria al {}%", "内存已用 {}%"]), + ("mon_warn_disk", ["Only {} free on the disk", "Só {} livres no disco", "Nur {} frei auf der Festplatte", "Solo {} libres en el disco", "磁盘仅剩 {}"]), + ("mon_warn_battery", ["Battery at {}%", "Bateria em {}%", "Akku bei {} %", "Batería al {}%", "电量 {}%"]), + ("mon_warn_cpu", ["CPU at {}%", "CPU em {}%", "CPU bei {} %", "CPU al {}%", "CPU {}%"]), + ("mon_tray_metrics", ["Metrics in the tray", "Métricas na bandeja", "Werte in der Statusleiste", "Métricas en la bandeja", "托盘中的指标"]), + ("mon_tray_metrics_sub", ["KDE shows the text next to the icon; GNOME shows it in the tooltip", "O KDE mostra o texto ao lado do ícone; o GNOME mostra na dica", "KDE zeigt den Text neben dem Symbol, GNOME im Tooltip", "KDE muestra el texto junto al icono; GNOME en la descripción", "KDE 在图标旁显示文字;GNOME 在提示中显示"]), + ("mon_open", ["Performance", "Desempenho", "Leistung", "Rendimiento", "性能"]), + ("mon_open_sub", ["CPU, memory, disk, battery and top processes", "CPU, memória, disco, bateria e processos", "CPU, Speicher, Festplatte, Akku und Prozesse", "CPU, memoria, disco, batería y procesos", "CPU、内存、磁盘、电池与进程"]), + ("sc_capture", ["Capture an area of the screen", "Capturar uma área da tela", "Bildschirmbereich aufnehmen", "Capturar un área de la pantalla", "截取屏幕区域"]), + ("sc_screen_text", ["Copy text from the screen", "Copiar texto da tela", "Text vom Bildschirm kopieren", "Copiar texto de la pantalla", "从屏幕复制文字"]), + ("note_field_user", ["User", "Usuário", "Benutzer", "Usuario", "用户名"]), + ("note_field_password", ["Password", "Senha", "Passwort", "Contraseña", "密码"]), + ("note_new", ["New note", "Nova nota", "Neue Notiz", "Nueva nota", "新建笔记"]), + ("note_new_passwords", ["New password note", "Nova nota de senhas", "Neue Passwortnotiz", "Nueva nota de contraseñas", "新建密码笔记"]), + ("note_open_all", ["Notes", "Notas", "Notizen", "Notas", "笔记"]), + ("note_search", ["Search notes", "Buscar notas", "Notizen durchsuchen", "Buscar notas", "搜索笔记"]), + ("note_all_tags", ["All", "Todas", "Alle", "Todas", "全部"]), + ("note_empty", ["No notes yet", "Nenhuma nota ainda", "Noch keine Notizen", "Aún no hay notas", "还没有笔记"]), + ("note_empty_sub", ["Write anything: Markdown, #tags and - [ ] checklists work.", "Escreva qualquer coisa: Markdown, #tags e listas - [ ] funcionam.", "Schreib, was du willst: Markdown, #Tags und - [ ] Listen funktionieren.", "Escribe lo que quieras: Markdown, #etiquetas y listas - [ ] funcionan.", "随便写:支持 Markdown、#标签 和 - [ ] 清单。"]), + ("note_delete", ["Delete note", "Apagar nota", "Notiz löschen", "Borrar nota", "删除笔记"]), + ("note_delete_ask", ["Delete this note?", "Apagar esta nota?", "Diese Notiz löschen?", "¿Borrar esta nota?", "删除这条笔记?"]), + ("note_delete_body", ["It can't be undone.", "Não dá para desfazer.", "Das lässt sich nicht rückgängig machen.", "No se puede deshacer.", "此操作无法撤销。"]), + ("delete", ["Delete", "Apagar", "Löschen", "Borrar", "删除"]), + ("note_protect", ["Protect", "Proteger", "Schützen", "Proteger", "保护"]), + ("note_unprotect", ["Remove protection", "Tirar proteção", "Schutz entfernen", "Quitar protección", "取消保护"]), + ("note_protect_help", ["Keeps the text in the system keyring and asks for your password to open it", "Guarda o texto no chaveiro do sistema e pede sua senha para abrir", "Speichert den Text im Schlüsselbund und fragt beim Öffnen nach deinem Passwort", "Guarda el texto en el llavero del sistema y pide tu contraseña para abrirlo", "将文本保存在系统钥匙环中,打开时需要密码"]), + ("note_locked", ["This note is protected", "Esta nota está protegida", "Diese Notiz ist geschützt", "Esta nota está protegida", "此笔记受保护"]), + ("note_unlock", ["Unlock", "Desbloquear", "Entsperren", "Desbloquear", "解锁"]), + ("note_unlock_fail", ["Couldn't open the protected note", "Não deu para abrir a nota protegida", "Geschützte Notiz konnte nicht geöffnet werden", "No se pudo abrir la nota protegida", "无法打开受保护的笔记"]), + ("note_vault_missing", ["Protected notes need secret-tool (libsecret-tools) and a keyring", "Notas protegidas precisam do secret-tool (libsecret-tools) e de um chaveiro", "Geschützte Notizen brauchen secret-tool (libsecret-tools) und einen Schlüsselbund", "Las notas protegidas necesitan secret-tool (libsecret-tools) y un llavero", "受保护的笔记需要 secret-tool(libsecret-tools)和钥匙环"]), + ("note_kind_text", ["Text", "Texto", "Text", "Texto", "文本"]), + ("note_kind_passwords", ["Passwords", "Senhas", "Passwörter", "Contraseñas", "密码"]), + ("note_add_field", ["Add field", "Adicionar campo", "Feld hinzufügen", "Añadir campo", "添加字段"]), + ("note_field_name", ["Name", "Nome", "Name", "Nombre", "名称"]), + ("note_field_value", ["Value", "Valor", "Wert", "Valor", "值"]), + ("note_title_placeholder", ["Title", "Título", "Titel", "Título", "标题"]), + ("note_show", ["Show", "Mostrar", "Anzeigen", "Mostrar", "显示"]), + ("note_hide", ["Hide", "Esconder", "Verbergen", "Ocultar", "隐藏"]), + ("note_copy", ["Copy", "Copiar", "Kopieren", "Copiar", "复制"]), + ("note_secret_copied", ["Copied · cleared in 30 s", "Copiado · some em 30 s", "Kopiert · wird in 30 s gelöscht", "Copiado · se borra en 30 s", "已复制 · 30 秒后清除"]), + ("note_lock_all", ["Lock protected notes", "Trancar notas protegidas", "Geschützte Notizen sperren", "Bloquear notas protegidas", "锁定受保护的笔记"]), + ("note_updated", ["Edited {}", "Editada {}", "Bearbeitet {}", "Editada {}", "编辑于 {}"]), + ("cap_area", ["Capture screen", "Capturar tela", "Bildschirm aufnehmen", "Capturar pantalla", "截取屏幕"]), + ("cap_area_sub", ["Area or window, with annotations", "Área ou janela, com anotações", "Bereich oder Fenster, mit Anmerkungen", "Área o ventana, con anotaciones", "区域或窗口,可标注"]), + ("cap_full", ["Capture the whole screen", "Capturar a tela inteira", "Ganzen Bildschirm aufnehmen", "Capturar toda la pantalla", "截取整个屏幕"]), + ("cap_ocr", ["Copy text from the screen", "Copiar texto da tela", "Text vom Bildschirm kopieren", "Copiar texto de la pantalla", "从屏幕复制文字"]), + ("cap_ocr_done", ["Text copied", "Texto copiado", "Text kopiert", "Texto copiado", "文字已复制"]), + ("cap_ocr_none", ["No text found", "Nenhum texto encontrado", "Kein Text gefunden", "No se encontró texto", "未找到文字"]), + ("cap_ocr_missing", ["Install tesseract-ocr to read text from the screen", "Instale o tesseract-ocr para ler texto da tela", "Installiere tesseract-ocr, um Text vom Bildschirm zu lesen", "Instala tesseract-ocr para leer texto de la pantalla", "安装 tesseract-ocr 以读取屏幕文字"]), + ("cap_failed", ["The screenshot was cancelled or is not available", "A captura foi cancelada ou não está disponível", "Die Aufnahme wurde abgebrochen oder ist nicht verfügbar", "La captura se canceló o no está disponible", "截图已取消或不可用"]), + ("cap_qr_read", ["Read a QR code from the screen", "Ler um QR code da tela", "QR-Code vom Bildschirm lesen", "Leer un código QR de la pantalla", "读取屏幕上的二维码"]), + ("cap_qr_none", ["No QR code found", "Nenhum QR code encontrado", "Kein QR-Code gefunden", "No se encontró ningún código QR", "未找到二维码"]), + ("cap_qr_missing", ["Install zbar-tools to read QR codes", "Instale o zbar-tools para ler QR codes", "Installiere zbar-tools, um QR-Codes zu lesen", "Instala zbar-tools para leer códigos QR", "安装 zbar-tools 以读取二维码"]), + ("cap_qr_make_missing", ["Install qrencode to show QR codes", "Instale o qrencode para mostrar QR codes", "Installiere qrencode, um QR-Codes anzuzeigen", "Instala qrencode para mostrar códigos QR", "安装 qrencode 以显示二维码"]), + ("cap_qr_show", ["Show the copied text as a QR code", "Mostrar o texto copiado como QR code", "Kopierten Text als QR-Code zeigen", "Mostrar el texto copiado como código QR", "将复制的文字显示为二维码"]), + ("cap_qr_for", ["QR code for “{}”", "QR code de “{}”", "QR-Code für „{}“", "Código QR de «{}»", "“{}” 的二维码"]), + ("cap_qr_wifi", ["Share Wi-Fi as a QR code", "Compartilhar Wi-Fi por QR code", "WLAN als QR-Code teilen", "Compartir Wi-Fi con código QR", "用二维码分享 Wi-Fi"]), + ("cap_qr_wifi_none", ["Not connected to a Wi-Fi network", "Sem conexão a uma rede Wi-Fi", "Mit keinem WLAN verbunden", "Sin conexión a una red Wi-Fi", "未连接 Wi-Fi"]), + ("cap_qr_title", ["QR code", "QR code", "QR-Code", "Código QR", "二维码"]), + ("cap_qr_scan_hint", ["Point the phone camera at the code", "Aponte a câmera do celular para o código", "Richte die Handykamera auf den Code", "Apunta la cámara del móvil al código", "用手机相机扫描此码"]), + ("cap_qr_found", ["QR code: {}", "QR code: {}", "QR-Code: {}", "Código QR: {}", "二维码:{}"]), + ("ann_title", ["Screenshot", "Captura", "Bildschirmfoto", "Captura", "截图"]), + ("ann_pen", ["Pen", "Caneta", "Stift", "Lápiz", "画笔"]), + ("ann_arrow", ["Arrow", "Seta", "Pfeil", "Flecha", "箭头"]), + ("ann_rect", ["Rectangle", "Retângulo", "Rechteck", "Rectángulo", "矩形"]), + ("ann_text", ["Text", "Texto", "Text", "Texto", "文字"]), + ("ann_blur", ["Blur", "Desfocar", "Verpixeln", "Desenfocar", "模糊"]), + ("ann_undo", ["Undo", "Desfazer", "Rückgängig", "Deshacer", "撤销"]), + ("ann_copy", ["Copy", "Copiar", "Kopieren", "Copiar", "复制"]), + ("ann_save", ["Save…", "Salvar…", "Speichern…", "Guardar…", "保存…"]), + ("ann_copied", ["Screenshot copied", "Captura copiada", "Bildschirmfoto kopiert", "Captura copiada", "截图已复制"]), + ("ann_saved", ["Saved to {}", "Salvo em {}", "Gespeichert in {}", "Guardado en {}", "已保存到 {}"]), + ("ann_text_ask", ["Text to add", "Texto para colocar", "Text einfügen", "Texto para añadir", "要添加的文字"]), + ("ann_add", ["Add", "Colocar", "Hinzufügen", "Añadir", "添加"]), + ("ann_drag_hint", ["Drag the image into any app", "Arraste a imagem para qualquer app", "Zieh das Bild in eine App", "Arrastra la imagen a cualquier app", "将图片拖到任意应用"]), + ("ann_copy_text", ["Copy text", "Copiar texto", "Text kopieren", "Copiar texto", "复制文字"]), + ("tray_open_window", ["Open Menew", "Abrir o Menew", "Menew öffnen", "Abrir Menew", "打开 Menew"]), + ("pop_now", ["Now", "Agora", "Jetzt", "Ahora", "现在"]), + ("pop_actions", ["Actions", "Ações", "Aktionen", "Acciones", "操作"]), + ("pop_search", ["Search or calculate…", "Buscar ou calcular…", "Suchen oder rechnen…", "Buscar o calcular…", "搜索或计算…"]), + ("pop_favorites", ["Favorites", "Favoritos", "Favoriten", "Favoritos", "收藏"]), + ("pop_edit", ["Edit", "Editar", "Bearbeiten", "Editar", "编辑"]), + ("pop_done", ["Done", "Pronto", "Fertig", "Listo", "完成"]), + ("pop_edit_hint", ["Tap a favorite to remove it, or an action below to add it.", "Toque num favorito para tirar, ou numa ação abaixo para pôr.", "Tippe auf einen Favoriten, um ihn zu entfernen, oder auf eine Aktion unten, um sie hinzuzufügen.", "Toca un favorito para quitarlo o una acción de abajo para añadirla.", "点按收藏可移除,点按下方操作可添加。"]), + ("pop_remove_fav", ["Remove {} from favorites", "Tirar {} dos favoritos", "{} aus Favoriten entfernen", "Quitar {} de favoritos", "从收藏中移除 {}"]), + ("pop_clocks", ["Clocks", "Relógios", "Uhren", "Relojes", "时钟"]), + ("pop_awake_until", ["Keeping awake until {}", "Acordado até {}", "Wach bis {}", "Despierto hasta {}", "保持唤醒至 {}"]), + ("pop_awake_on", ["Keeping awake", "Mantendo acordado", "Bleibt wach", "Manteniendo despierto", "保持唤醒中"]), + ("grp_screen", ["Screen and capture", "Tela e captura", "Bildschirm und Aufnahme", "Pantalla y captura", "屏幕与截图"]), + ("grp_windows", ["Windows and displays", "Janelas e telas", "Fenster und Bildschirme", "Ventanas y pantallas", "窗口与显示器"]), + ("grp_sound", ["Sound and focus", "Som e foco", "Ton und Fokus", "Sonido y concentración", "声音与专注"]), + ("grp_system", ["System and cleanup", "Sistema e limpeza", "System und Aufräumen", "Sistema y limpieza", "系统与清理"]), + ("grp_menew", ["Menew", "Menew", "Menew", "Menew", "Menew"]), + ("set_title", ["Settings", "Ajustes", "Einstellungen", "Ajustes", "设置"]), + ("set_general", ["General", "Geral", "Allgemein", "General", "通用"]), + ("set_language", ["Language", "Idioma", "Sprache", "Idioma", "语言"]), + ("set_lang_system", ["Same as the system", "Igual ao sistema", "Wie das System", "Igual que el sistema", "跟随系统"]), + ("set_lang_restart", ["Restart Menew to use the new language everywhere", "Reinicie o Menew para usar o novo idioma em tudo", "Starte Menew neu, um die neue Sprache überall zu nutzen", "Reinicia Menew para usar el nuevo idioma en todo", "重启 Menew 以全面使用新语言"]), + ("set_restart", ["Restart", "Reiniciar", "Neu starten", "Reiniciar", "重启"]), + ("set_later", ["Later", "Depois", "Später", "Más tarde", "稍后"]), + ("tray_start_at_login_r1", ["Start at login", "Abrir ao iniciar a sessão", "Beim Anmelden starten", "Abrir al iniciar sesión", "登录时启动"]), + ("set_updates", ["Check for updates", "Procurar atualizações", "Nach Updates suchen", "Buscar actualizaciones", "检查更新"]), + ("set_updates_sub", ["Once a day, only the GitHub releases page of Menew", "Uma vez por dia, só a página de versões do Menew no GitHub", "Einmal am Tag, nur die GitHub-Releases von Menew", "Una vez al día, solo la página de versiones de Menew en GitHub", "每天一次,仅访问 Menew 的 GitHub 发布页"]), + ("set_check_now", ["Check now", "Verificar agora", "Jetzt prüfen", "Comprobar ahora", "立即检查"]), + ("set_up_to_date", ["Menew is up to date ({})", "O Menew está atualizado ({})", "Menew ist aktuell ({})", "Menew está actualizado ({})", "Menew 已是最新版({})"]), + ("set_update_available", ["Menew {} is available", "O Menew {} está disponível", "Menew {} ist verfügbar", "Menew {} está disponible", "Menew {} 可用"]), + ("set_update_how", ["Update it with your package manager or download the new AppImage", "Atualize pelo gerenciador de pacotes ou baixe o novo AppImage", "Aktualisiere über die Paketverwaltung oder lade das neue AppImage", "Actualiza con tu gestor de paquetes o descarga el nuevo AppImage", "请通过软件包管理器更新或下载新的 AppImage"]), + ("set_update_fail", ["Couldn't check for updates", "Não deu para procurar atualizações", "Updates konnten nicht geprüft werden", "No se pudieron buscar actualizaciones", "无法检查更新"]), + ("set_welcome", ["Show the welcome tour", "Mostrar o tour de boas-vindas", "Willkommenstour zeigen", "Mostrar el recorrido de bienvenida", "显示欢迎导览"]), + ("set_modules", ["Features", "Recursos", "Funktionen", "Funciones", "功能"]), + ("set_modules_sub", ["Turned off, a feature disappears completely", "Desligado, o recurso some por completo", "Ausgeschaltet verschwindet eine Funktion ganz", "Desactivada, la función desaparece por completo", "关闭后,该功能会完全消失"]), + ("set_mod_clipboard", ["Clipboard history", "Histórico do clipboard", "Verlauf der Zwischenablage", "Historial del portapapeles", "剪贴板历史"]), + ("set_mod_clipboard_sub", ["Off: Menew doesn't even read the clipboard", "Desligado: o Menew nem lê o clipboard", "Aus: Menew liest die Zwischenablage gar nicht", "Desactivado: Menew ni siquiera lee el portapapeles", "关闭后 Menew 完全不读取剪贴板"]), + ("set_mod_actions", ["Quick actions", "Ações rápidas", "Schnellaktionen", "Acciones rápidas", "快捷操作"]), + ("set_mod_actions_sub", ["Sound, dark mode, keep awake, windows, screenshots…", "Som, modo escuro, manter acordado, janelas, capturas…", "Ton, Dunkelmodus, Wachhalten, Fenster, Bildschirmfotos…", "Sonido, modo oscuro, mantener despierto, ventanas, capturas…", "声音、深色模式、保持唤醒、窗口、截图…"]), + ("set_mod_notes", ["Notes", "Notas", "Notizen", "Notas", "笔记"]), + ("set_mod_notes_sub", ["Notes, protected notes and passwords", "Notas, notas protegidas e senhas", "Notizen, geschützte Notizen und Passwörter", "Notas, notas protegidas y contraseñas", "笔记、受保护的笔记与密码"]), + ("set_paste_auto", ["Paste after picking", "Colar ao escolher", "Nach dem Auswählen einfügen", "Pegar al elegir", "选择后自动粘贴"]), + ("set_paste_auto_sub", ["Needs write access to /dev/uinput; otherwise Menew copies and you press Ctrl+V", "Precisa de acesso a /dev/uinput; senão o Menew copia e você aperta Ctrl+V", "Braucht Schreibzugriff auf /dev/uinput, sonst kopiert Menew und du drückst Strg+V", "Necesita acceso a /dev/uinput; si no, Menew copia y tú pulsas Ctrl+V", "需要 /dev/uinput 写权限,否则 Menew 只复制,由你按 Ctrl+V"]), + ("set_clip_ocr", ["Read the text in copied images", "Ler o texto das imagens copiadas", "Text in kopierten Bildern lesen", "Leer el texto de las imágenes copiadas", "识别复制图片中的文字"]), + ("set_clip_ocr_sub", ["With tesseract, on this computer", "Com o tesseract, neste computador", "Mit tesseract, auf diesem Computer", "Con tesseract, en este ordenador", "使用 tesseract,在本机完成"]), + ("set_clip_max", ["Items kept", "Itens guardados", "Gespeicherte Einträge", "Elementos guardados", "保留条目数"]), + ("set_clip_days", ["Delete after (days)", "Apagar depois de (dias)", "Löschen nach (Tagen)", "Borrar después de (días)", "多少天后删除"]), + ("set_clip_days_sub", ["0 keeps them; pinned items are never deleted", "0 guarda para sempre; fixados nunca são apagados", "0 behält sie; angeheftete werden nie gelöscht", "0 los conserva; los fijados nunca se borran", "0 表示永久保留;置顶项不会被删除"]), + ("set_clip_ignored", ["Apps whose copies are not kept", "Apps cujas cópias não são guardadas", "Apps, deren Kopien nicht gespeichert werden", "Apps cuyas copias no se guardan", "不保存其复制内容的应用"]), + ("set_clip_ignored_sub", ["Application ids, separated by commas (GNOME only: KDE doesn't say which app copied)", "Ids dos apps, separados por vírgula (só no GNOME: o KDE não diz qual app copiou)", "App-IDs, durch Kommas getrennt (nur GNOME: KDE verrät nicht, welche App kopiert hat)", "Ids de apps separados por comas (solo GNOME: KDE no dice qué app copió)", "应用 ID,用逗号分隔(仅 GNOME:KDE 不提供复制来源)"]), + ("set_gnome_ext", ["Menew GNOME extension", "Extensão do Menew no GNOME", "Menew-GNOME-Erweiterung", "Extensión de Menew para GNOME", "Menew GNOME 扩展"]), + ("set_gnome_ext_on", ["Running: clipboard history and window snapping work", "Funcionando: histórico do clipboard e encaixe de janelas", "Läuft: Verlauf und Fensteranordnung funktionieren", "Activa: historial y ajuste de ventanas funcionan", "运行中:剪贴板历史和窗口贴靠可用"]), + ("set_gnome_ext_off", ["Not running: turn on “Menew Integration” in the Extensions app", "Desligada: ligue “Menew Integration” no app Extensões", "Nicht aktiv: Schalte „Menew Integration“ in der App Erweiterungen ein", "Inactiva: activa «Menew Integration» en la app Extensiones", "未运行:请在“扩展”应用中开启“Menew Integration”"]), + ("set_clocks", ["World clocks", "Relógios", "Weltuhren", "Relojes mundiales", "世界时钟"]), + ("set_clocks_sub", ["Shown on the Now tab and with “clocks” in the palette", "Aparecem na aba Agora e com “relógios” na paleta", "Im Tab Jetzt und mit „uhren“ in der Palette", "Aparecen en la pestaña Ahora y con «relojes» en la paleta", "显示在“现在”标签页,也可在面板中输入“时钟”"]), + ("set_clock_add", ["Add a city (Lisbon, Tokyo, America/New_York)", "Adicionar cidade (Lisboa, Tóquio, America/New_York)", "Stadt hinzufügen (Lissabon, Tokio, America/New_York)", "Añadir ciudad (Lisboa, Tokio, America/New_York)", "添加城市(里斯本、东京、America/New_York)"]), + ("set_focus_actions", ["Focus and actions", "Foco e ações", "Fokus und Aktionen", "Concentración y acciones", "专注与操作"]), + ("set_focus_breaks", ["A 5 minute break after each focus session", "Pausa de 5 minutos depois de cada foco", "5 Minuten Pause nach jeder Fokussitzung", "Descanso de 5 minutos tras cada sesión", "每次专注后休息 5 分钟"]), + ("set_never_quit", ["Never quit these apps (ids, commas)", "Nunca fechar estes apps (ids, vírgulas)", "Diese Apps nie beenden (IDs, Kommas)", "Nunca cerrar estas apps (ids, comas)", "永不退出这些应用(ID,逗号分隔)"]), + ("set_shortcuts", ["Shortcuts", "Atalhos", "Tastenkürzel", "Atajos", "快捷键"]), + ("set_shortcuts_sub", ["Change them in the system settings. Where the desktop has no shortcut portal, add a custom shortcut with the command shown.", "Mude nos ajustes do sistema. Onde o desktop não tem o portal de atalhos, crie um atalho personalizado com o comando mostrado.", "Ändere sie in den Systemeinstellungen. Ohne Kürzel-Portal leg ein eigenes Kürzel mit dem gezeigten Befehl an.", "Cámbialos en los ajustes del sistema. Si el escritorio no tiene el portal de atajos, crea uno personalizado con el comando indicado.", "在系统设置中修改。若桌面不支持快捷键门户,请用所示命令添加自定义快捷键。"]), + ("set_privacy", ["Privacy", "Privacidade", "Datenschutz", "Privacidad", "隐私"]), + ("set_privacy_body", ["No telemetry, no account. Everything stays on this computer. The only network requests are the currency rate when you press ↩ and the update check, if you turn it on.", "Sem telemetria, sem conta. Tudo fica neste computador. Os únicos acessos à rede são a cotação quando você aperta ↩ e a busca de atualizações, se você ligar.", "Keine Telemetrie, kein Konto. Alles bleibt auf diesem Computer. Ins Netz geht nur der Wechselkurs, wenn du ↩ drückst, und die Update-Prüfung, wenn du sie einschaltest.", "Sin telemetría ni cuenta. Todo queda en este ordenador. Solo se usa la red para el cambio de divisa al pulsar ↩ y para buscar actualizaciones, si lo activas.", "无遥测,无需账户。所有数据留在本机。仅在你按 ↩ 查询汇率或开启更新检查时联网。"]), + ("set_config_file", ["Settings file", "Arquivo de ajustes", "Einstellungsdatei", "Archivo de ajustes", "设置文件"]), + ("set_open", ["Settings", "Ajustes", "Einstellungen", "Ajustes", "设置"]), + ("set_open_kw", ["settings ajustes preferências preferences config einstellungen ajustes 设置", "settings ajustes preferências preferences config einstellungen ajustes 设置", "settings ajustes preferências preferences config einstellungen ajustes 设置", "settings ajustes preferências preferences config einstellungen ajustes 设置", "settings ajustes preferências preferences config einstellungen ajustes 设置"]), + ("ovw_title", ["Overview", "Visão geral", "Übersicht", "Resumen", "概览"]), + ("wel_title", ["Welcome to Menew", "Boas-vindas ao Menew", "Willkommen bei Menew", "Te damos la bienvenida a Menew", "欢迎使用 Menew"]), + ("wel_body", ["A command palette, clipboard history, notes, screenshots, quick actions and system health. Private and native.", "Paleta de comandos, histórico do clipboard, notas, capturas, ações rápidas e saúde do sistema. Privado e nativo.", "Befehlspalette, Verlauf der Zwischenablage, Notizen, Bildschirmfotos, Schnellaktionen und Systemzustand. Privat und nativ.", "Paleta de comandos, historial del portapapeles, notas, capturas, acciones rápidas y estado del sistema. Privado y nativo.", "命令面板、剪贴板历史、笔记、截图、快捷操作与系统状态。私密、原生。"]), + ("wel_shortcut", ["Ctrl+Alt+Space opens the palette", "Ctrl+Alt+Espaço abre a paleta", "Strg+Alt+Leertaste öffnet die Palette", "Ctrl+Alt+Espacio abre la paleta", "Ctrl+Alt+空格 打开命令面板"]), + ("wel_shortcut_body", ["Search apps, calculate, convert, start timers, snap windows. Ctrl+Alt+V opens the clipboard. The desktop asks once to allow the shortcuts.", "Busque apps, calcule, converta, inicie timers, encaixe janelas. Ctrl+Alt+V abre o clipboard. O desktop pede uma vez para permitir os atalhos.", "Apps suchen, rechnen, umrechnen, Timer starten, Fenster anordnen. Strg+Alt+V öffnet die Zwischenablage. Der Desktop fragt einmal nach den Kürzeln.", "Busca apps, calcula, convierte, inicia temporizadores, ajusta ventanas. Ctrl+Alt+V abre el portapapeles. El escritorio pide una vez permitir los atajos.", "搜索应用、计算、换算、计时、排列窗口。Ctrl+Alt+V 打开剪贴板。桌面会询问一次是否允许快捷键。"]), + ("wel_clip", ["Clipboard history", "Histórico do clipboard", "Verlauf der Zwischenablage", "Historial del portapapeles", "剪贴板历史"]), + ("wel_clip_gnome", ["On GNOME, turn on “Menew Integration” in the Extensions app. It also lets Menew snap windows.", "No GNOME, ligue “Menew Integration” no app Extensões. Ela também deixa o Menew encaixar janelas.", "Unter GNOME schalte „Menew Integration“ in der App Erweiterungen ein. Damit kann Menew auch Fenster anordnen.", "En GNOME, activa «Menew Integration» en la app Extensiones. También permite ajustar ventanas.", "在 GNOME 上,请在“扩展”应用中开启“Menew Integration”,它也让 Menew 能排列窗口。"]), + ("wel_clip_kde", ["On KDE Plasma it works right away (wl-clipboard).", "No KDE Plasma funciona na hora (wl-clipboard).", "Unter KDE Plasma klappt es sofort (wl-clipboard).", "En KDE Plasma funciona al momento (wl-clipboard).", "在 KDE Plasma 上开箱即用(wl-clipboard)。"]), + ("wel_clip_other", ["Needs a compositor with the data-control protocol (wl-clipboard).", "Precisa de um compositor com o protocolo data-control (wl-clipboard).", "Braucht einen Compositor mit dem data-control-Protokoll (wl-clipboard).", "Necesita un compositor con el protocolo data-control (wl-clipboard).", "需要支持 data-control 协议的合成器(wl-clipboard)。"]), + ("wel_choose", ["Choose what to keep", "Escolha o que manter", "Wähle, was du behalten willst", "Elige qué mantener", "选择要保留的功能"]), + ("wel_privacy", ["Nothing leaves this computer. You can change all of this later in Settings.", "Nada sai deste computador. Dá para mudar tudo depois nos Ajustes.", "Nichts verlässt diesen Computer. Alles lässt sich später in den Einstellungen ändern.", "Nada sale de este ordenador. Puedes cambiarlo todo luego en Ajustes.", "数据不会离开本机。以后可在设置中修改。"]), + ("wel_start", ["Start using Menew", "Começar a usar", "Loslegen", "Empezar", "开始使用"]), + ("wel_next", ["Next", "Próximo", "Weiter", "Siguiente", "下一步"]), + ("shortcut_palette_r1", ["Open the command palette", "Abrir a paleta de comandos", "Befehlspalette öffnen", "Abrir la paleta de comandos", "打开命令面板"]), + ("set_focus_mute", ["Mute the microphone while focusing", "Mutar o microfone durante o foco", "Mikrofon während des Fokus stummschalten", "Silenciar el micrófono durante la concentración", "专注时将麦克风静音"]), + ("set_focus_awake", ["Keep the computer awake while focusing", "Manter o computador acordado durante o foco", "Computer während des Fokus wach halten", "Mantener el ordenador despierto durante la concentración", "专注时保持电脑唤醒"]), + ("set_focus_pause", ["Pause the clipboard while focusing", "Pausar o clipboard durante o foco", "Zwischenablage während des Fokus pausieren", "Pausar el portapapeles durante la concentración", "专注时暂停剪贴板"]), ]; diff --git a/crates/menew-core/src/sysmon.rs b/crates/menew-core/src/sysmon.rs new file mode 100644 index 0000000..928fb91 --- /dev/null +++ b/crates/menew-core/src/sysmon.rs @@ -0,0 +1,549 @@ +//! System monitor (port of `SystemMonitor.swift`): CPU, GPU, memory, swap, disk space and speed, +//! battery, network and the top processes, read from `/proc` and `/sys` once a second. Nothing is +//! sent anywhere and nothing is kept on disk. +//! +//! The parsers are pure and tested with real samples; [`Monitor`] keeps the previous sample to turn +//! counters into rates. + +use crate::i18n::Language; +use crate::strings::tr; +use std::collections::HashMap; +use std::path::Path; + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct CpuTimes { + pub busy: u64, + pub total: u64, +} + +/// The first `cpu` line of `/proc/stat` (user nice system idle iowait irq softirq steal). +pub fn parse_cpu(stat: &str) -> Option { + let line = stat.lines().find(|l| l.starts_with("cpu "))?; + let v: Vec = line.split_whitespace().skip(1).filter_map(|x| x.parse().ok()).collect(); + if v.len() < 4 { + return None; + } + // guest and guest_nice are already counted in user and nice + let total: u64 = v.iter().take(8).sum(); + let idle = v[3] + v.get(4).copied().unwrap_or(0); + Some(CpuTimes { busy: total - idle, total }) +} + +/// Number of `cpuN` lines. +pub fn parse_cpu_count(stat: &str) -> usize { + stat.lines().filter(|l| l.starts_with("cpu") && l.as_bytes().get(3).is_some_and(|b| b.is_ascii_digit())).count().max(1) +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Memory { + pub total: u64, + pub available: u64, + pub swap_total: u64, + pub swap_free: u64, +} + +impl Memory { + pub fn used(&self) -> u64 { + self.total.saturating_sub(self.available) + } + pub fn used_percent(&self) -> f64 { + if self.total == 0 { + 0.0 + } else { + self.used() as f64 * 100.0 / self.total as f64 + } + } + pub fn swap_used(&self) -> u64 { + self.swap_total.saturating_sub(self.swap_free) + } +} + +/// `/proc/meminfo` (values in kB, returned in bytes). +pub fn parse_meminfo(text: &str) -> Memory { + let mut m = Memory::default(); + for line in text.lines() { + let mut it = line.split_whitespace(); + let (Some(k), Some(v)) = (it.next(), it.next()) else { continue }; + let bytes = v.parse::().unwrap_or(0) * 1024; + match k { + "MemTotal:" => m.total = bytes, + "MemAvailable:" => m.available = bytes, + "SwapTotal:" => m.swap_total = bytes, + "SwapFree:" => m.swap_free = bytes, + _ => {} + } + } + m +} + +/// Bytes received and sent by every interface but loopback (`/proc/net/dev`). +pub fn parse_net_dev(text: &str) -> (u64, u64) { + let mut rx = 0; + let mut tx = 0; + for line in text.lines().skip(2) { + let Some((name, rest)) = line.split_once(':') else { continue }; + let name = name.trim(); + if name == "lo" || name.starts_with("veth") || name.starts_with("docker") || name.starts_with("br-") || name.starts_with("virbr") { + continue; + } + let v: Vec = rest.split_whitespace().filter_map(|x| x.parse().ok()).collect(); + if v.len() >= 9 { + rx += v[0]; + tx += v[8]; + } + } + (rx, tx) +} + +/// Whole disks (not partitions) of `/proc/diskstats`: sectors read and written, in bytes. +pub fn parse_diskstats(text: &str) -> (u64, u64) { + let mut r = 0; + let mut w = 0; + for line in text.lines() { + let f: Vec<&str> = line.split_whitespace().collect(); + if f.len() < 10 { + continue; + } + let name = f[2]; + let whole = (name.starts_with("sd") || name.starts_with("vd") || name.starts_with("xvd")) && !name.ends_with(|c: char| c.is_ascii_digit()) + || (name.starts_with("nvme") && !name.contains('p')) + || (name.starts_with("mmcblk") && !name.contains('p')); + if whole { + r += f[5].parse::().unwrap_or(0) * 512; + w += f[9].parse::().unwrap_or(0) * 512; + } + } + (r, w) +} + +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Battery { + pub percent: u32, + /// `Charging`, `Discharging`, `Full`, `Not charging`. + pub status: String, + /// Full charge now against the design, in percent. + pub health: Option, + pub cycles: Option, + /// Watts drawn or charged. + pub power: Option, +} + +impl Battery { + pub fn charging(&self) -> bool { + self.status == "Charging" || self.status == "Full" + } +} + +pub fn read_battery_in(dir: &Path) -> Option { + let mut names: Vec<_> = std::fs::read_dir(dir).ok()?.filter_map(Result::ok).collect(); + names.sort_by_key(|e| e.file_name()); + let bat = names.into_iter().find(|e| { + std::fs::read_to_string(e.path().join("type")).map(|t| t.trim() == "Battery").unwrap_or(false) + && std::fs::read_to_string(e.path().join("scope")).map(|s| s.trim() != "Device").unwrap_or(true) + })?; + let p = bat.path(); + let read = |f: &str| std::fs::read_to_string(p.join(f)).ok().map(|s| s.trim().to_string()); + let num = |f: &str| read(f).and_then(|s| s.parse::().ok()); + let percent = num("capacity")? as u32; + let full = num("energy_full").or_else(|| num("charge_full")); + let design = num("energy_full_design").or_else(|| num("charge_full_design")); + let health = match (full, design) { + (Some(f), Some(d)) if d > 0.0 => Some(((f / d) * 100.0).round().min(100.0) as u32), + _ => None, + }; + let power = num("power_now").map(|uw| uw / 1_000_000.0).or_else(|| match (num("current_now"), num("voltage_now")) { + (Some(c), Some(v)) => Some(c * v / 1e12), + _ => None, + }); + Some(Battery { + percent: percent.min(100), + status: read("status").unwrap_or_default(), + health, + cycles: num("cycle_count").map(|c| c as u32).filter(|c| *c > 0), + power: power.filter(|w| *w > 0.0), + }) +} + +/// GPU use in percent: amdgpu (and Intel Xe) expose `gpu_busy_percent`. +pub fn read_gpu_in(drm: &Path) -> Option { + let mut best: Option = None; + for e in std::fs::read_dir(drm).ok()?.filter_map(Result::ok) { + let name = e.file_name().to_string_lossy().into_owned(); + if !name.starts_with("card") || name.contains('-') { + continue; + } + if let Some(v) = std::fs::read_to_string(e.path().join("device/gpu_busy_percent")).ok().and_then(|s| s.trim().parse::().ok()) { + best = Some(best.map_or(v, |b| b.max(v))); + } + } + best +} + +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Disk { + pub total: u64, + pub free: u64, +} + +impl Disk { + pub fn used_percent(&self) -> f64 { + if self.total == 0 { + 0.0 + } else { + (self.total - self.free) as f64 * 100.0 / self.total as f64 + } + } +} + +pub fn disk_space(path: &str) -> Option { + #[cfg(target_os = "linux")] + { + let c = std::ffi::CString::new(path).ok()?; + // SAFETY: statvfs writes into the zeroed struct we own + let mut st: libc::statvfs = unsafe { std::mem::zeroed() }; + if unsafe { libc::statvfs(c.as_ptr(), &mut st) } != 0 { + return None; + } + let bs = st.f_frsize as u64; + Some(Disk { total: st.f_blocks as u64 * bs, free: st.f_bavail as u64 * bs }) + } + #[cfg(not(target_os = "linux"))] + { + let _ = path; + None + } +} + +/// One process line: `(pid, name, cpu ticks, rss bytes)` from `/proc/PID/stat`. +pub fn parse_proc_stat(text: &str, page: u64) -> Option<(String, u64, u64)> { + let open = text.find('(')?; + let close = text.rfind(')')?; + let name = text[open + 1..close].to_string(); + let rest: Vec<&str> = text[close + 1..].split_whitespace().collect(); + // after the name: state(0) ppid(1) ... utime(11) stime(12) ... rss(21) + let utime: u64 = rest.get(11)?.parse().ok()?; + let stime: u64 = rest.get(12)?.parse().ok()?; + let rss: u64 = rest.get(21)?.parse().ok()?; + Some((name, utime + stime, rss * page)) +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Process { + pub pid: u32, + pub name: String, + /// Percent of one core, like `top`. + pub cpu: f64, + pub memory: u64, +} + +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Snapshot { + pub cpu: f64, + pub cores: usize, + pub gpu: Option, + pub memory: Memory, + pub disk: Option, + pub disk_read: f64, + pub disk_write: f64, + pub net_down: f64, + pub net_up: f64, + pub battery: Option, + pub uptime: f64, + pub load: Option<(f64, f64, f64)>, + pub top_cpu: Vec, + pub top_memory: Vec, +} + +/// Keeps the counters of the last sample. +#[derive(Default)] +pub struct Monitor { + cpu: Option, + net: Option<(u64, u64, f64)>, + disk: Option<(u64, u64, f64)>, + procs: HashMap, + procs_at: f64, +} + +fn read(p: &str) -> String { + std::fs::read_to_string(p).unwrap_or_default() +} + +fn clock_ticks() -> f64 { + #[cfg(target_os = "linux")] + { + // SAFETY: sysconf has no side effects + let t = unsafe { libc::sysconf(libc::_SC_CLK_TCK) }; + if t > 0 { + return t as f64; + } + } + 100.0 +} + +fn page_size() -> u64 { + #[cfg(target_os = "linux")] + { + // SAFETY: sysconf has no side effects + let p = unsafe { libc::sysconf(libc::_SC_PAGESIZE) }; + if p > 0 { + return p as u64; + } + } + 4096 +} + +pub fn rate(prev: Option<(u64, u64, f64)>, now: (u64, u64), t: f64) -> (f64, f64) { + match prev { + Some((a, b, t0)) if t > t0 => (now.0.saturating_sub(a) as f64 / (t - t0), now.1.saturating_sub(b) as f64 / (t - t0)), + _ => (0.0, 0.0), + } +} + +impl Monitor { + /// Read everything once. `now` is in seconds (any monotonic clock). + pub fn sample(&mut self, now: f64, with_processes: bool) -> Snapshot { + let stat = read("/proc/stat"); + let cpu_now = parse_cpu(&stat); + let cpu = match (self.cpu, cpu_now) { + (Some(a), Some(b)) if b.total > a.total => (b.busy - a.busy.min(b.busy)) as f64 * 100.0 / (b.total - a.total) as f64, + _ => 0.0, + }; + self.cpu = cpu_now; + let net = parse_net_dev(&read("/proc/net/dev")); + let (down, up) = rate(self.net, net, now); + self.net = Some((net.0, net.1, now)); + let disk = parse_diskstats(&read("/proc/diskstats")); + let (dr, dw) = rate(self.disk, disk, now); + self.disk = Some((disk.0, disk.1, now)); + let load = { + let l: Vec = read("/proc/loadavg").split_whitespace().take(3).filter_map(|x| x.parse().ok()).collect(); + (l.len() == 3).then(|| (l[0], l[1], l[2])) + }; + let (top_cpu, top_memory) = if with_processes { self.processes(now) } else { (vec![], vec![]) }; + Snapshot { + cpu: cpu.clamp(0.0, 100.0), + cores: parse_cpu_count(&stat), + gpu: read_gpu_in(Path::new("/sys/class/drm")), + memory: parse_meminfo(&read("/proc/meminfo")), + disk: disk_space("/"), + disk_read: dr, + disk_write: dw, + net_down: down, + net_up: up, + battery: read_battery_in(Path::new("/sys/class/power_supply")), + uptime: read("/proc/uptime").split_whitespace().next().and_then(|x| x.parse().ok()).unwrap_or(0.0), + load, + top_cpu, + top_memory, + } + } + + fn processes(&mut self, now: f64) -> (Vec, Vec) { + let uid = crate::quick_actions::current_uid(); + let page = page_size(); + let hz = clock_ticks(); + let elapsed = now - self.procs_at; + let mut seen: HashMap = HashMap::new(); + let mut list: Vec = vec![]; + let Ok(rd) = std::fs::read_dir("/proc") else { return (vec![], vec![]) }; + for e in rd.filter_map(Result::ok) { + let Some(pid) = e.file_name().to_str().and_then(|n| n.parse::().ok()) else { continue }; + let Some((name, ticks, rss)) = parse_proc_stat(&read(&format!("/proc/{pid}/stat")), page) else { continue }; + seen.insert(pid, ticks); + let owner = read(&format!("/proc/{pid}/status")).lines().find_map(|l| l.strip_prefix("Uid:")).and_then(|u| u.split_whitespace().next()?.parse::().ok()); + if owner != Some(uid) || rss == 0 { + continue; + } + let cpu = match self.procs.get(&pid) { + Some(prev) if elapsed > 0.0 => ticks.saturating_sub(*prev) as f64 / hz / elapsed * 100.0, + _ => 0.0, + }; + list.push(Process { pid, name, cpu, memory: rss }); + } + self.procs = seen; + self.procs_at = now; + let mut by_cpu = list.clone(); + by_cpu.sort_by(|a, b| b.cpu.partial_cmp(&a.cpu).unwrap_or(std::cmp::Ordering::Equal)); + by_cpu.truncate(5); + list.sort_by_key(|p| std::cmp::Reverse(p.memory)); + list.truncate(5); + (by_cpu, list) + } +} + +/// "1.2 GB", "340 MB" (decimal units, like the Mac's `ByteCountFormatter`). +pub fn bytes(n: u64, lang: Language) -> String { + let n = n as f64; + let (v, unit) = if n >= 1e12 { + (n / 1e12, "TB") + } else if n >= 1e9 { + (n / 1e9, "GB") + } else if n >= 1e6 { + (n / 1e6, "MB") + } else if n >= 1e3 { + (n / 1e3, "KB") + } else { + return format!("{} B", n as u64); + }; + let digits = if v < 10.0 { 1 } else { 0 }; + format!("{} {unit}", crate::format::format_number(v, digits, lang)) +} + +/// "1.2 MB/s" +pub fn speed(bps: f64, lang: Language) -> String { + format!("{}/s", bytes(bps.max(0.0) as u64, lang)) +} + +/// "3 d 4 h", "5 h 12 min" +pub fn uptime_text(secs: f64) -> String { + let m = (secs / 60.0) as u64; + let (d, h, min) = (m / 1440, (m / 60) % 24, m % 60); + if d > 0 { + format!("{d} d {h} h") + } else if h > 0 { + format!("{h} h {min} min") + } else { + format!("{min} min") + } +} + +/// The metrics people can put in the tray. +pub const TRAY_METRICS: [&str; 6] = ["cpu", "memory", "gpu", "disk", "network", "battery"]; + +/// The tray text for the chosen metrics: "CPU 12% · RAM 45%". +pub fn tray_text(s: &Snapshot, metrics: &[String], lang: Language) -> String { + let mut parts = vec![]; + for m in metrics { + match m.as_str() { + "cpu" => parts.push(format!("CPU {:.0}%", s.cpu)), + "memory" => parts.push(format!("{} {:.0}%", tr("mon_ram", lang, &[]), s.memory.used_percent())), + "gpu" => { + if let Some(g) = s.gpu { + parts.push(format!("GPU {g}%")) + } + } + "disk" => { + if let Some(d) = &s.disk { + parts.push(format!("{} {}", tr("mon_disk", lang, &[]), bytes(d.free, lang))) + } + } + "network" => parts.push(format!("↓{} ↑{}", speed(s.net_down, lang), speed(s.net_up, lang))), + "battery" => { + if let Some(b) = &s.battery { + parts.push(format!("{}{}%", if b.charging() { "⚡" } else { "" }, b.percent)) + } + } + _ => {} + } + } + parts.join(" · ") +} + +/// "All good", or what needs attention (the Mac's status line on the Now tab). +pub fn attention(s: &Snapshot, lang: Language) -> Vec { + let mut out = vec![]; + if s.memory.used_percent() > 90.0 { + out.push(tr("mon_warn_memory", lang, &[&format!("{:.0}", s.memory.used_percent())])); + } + if let Some(d) = &s.disk { + if d.free < 5_000_000_000 || d.used_percent() > 95.0 { + out.push(tr("mon_warn_disk", lang, &[&bytes(d.free, lang)])); + } + } + if let Some(b) = &s.battery { + if !b.charging() && b.percent <= 10 { + out.push(tr("mon_warn_battery", lang, &[&b.percent.to_string()])); + } + } + if s.cpu > 90.0 { + out.push(tr("mon_warn_cpu", lang, &[&format!("{:.0}", s.cpu)])); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cpu_from_proc_stat() { + let a = parse_cpu("cpu 100 0 50 800 50 0 0 0 0 0\ncpu0 1 2 3 4\ncpu1 1 2 3 4\n").unwrap(); + assert_eq!(a, CpuTimes { busy: 150, total: 1000 }); + assert_eq!(parse_cpu_count("cpu 1 2 3 4\ncpu0 1 2 3 4\ncpu1 1 2 3 4\nintr 5\n"), 2); + assert_eq!(parse_cpu("nothing"), None); + } + + #[test] + fn memory_from_meminfo() { + let m = parse_meminfo("MemTotal: 16000000 kB\nMemFree: 100 kB\nMemAvailable: 4000000 kB\nSwapTotal: 2000 kB\nSwapFree: 500 kB\n"); + assert_eq!(m.total, 16_000_000 * 1024); + assert_eq!(m.used_percent().round(), 75.0); + assert_eq!(m.swap_used(), 1500 * 1024); + } + + #[test] + fn network_skips_loopback_and_bridges() { + let t = "Inter-| Receive | Transmit\n face |bytes packets errs drop fifo frame compressed multicast|bytes packets\n lo: 999 1 0 0 0 0 0 0 999 1 0 0 0 0 0 0\n eth0: 1000 10 0 0 0 0 0 0 500 5 0 0 0 0 0 0\ndocker0: 77 1 0 0 0 0 0 0 77 1 0 0 0 0 0 0\n wlan0: 24 1 0 0 0 0 0 0 6 1 0 0 0 0 0 0\n"; + assert_eq!(parse_net_dev(t), (1024, 506)); + } + + #[test] + fn disk_io_counts_whole_disks_only() { + let t = " 8 0 sda 100 0 2 0 50 0 4 0 0 0 0\n 8 1 sda1 100 0 2000 0 50 0 4000 0 0 0 0\n 259 0 nvme0n1 1 0 10 0 1 0 20 0 0 0 0\n 259 1 nvme0n1p1 1 0 10 0 1 0 20 0 0 0 0\n"; + assert_eq!(parse_diskstats(t), (12 * 512, 24 * 512)); + } + + #[test] + fn process_line_with_spaces_and_parens_in_the_name() { + let line = "1234 (Web Content (x)) S 1 2 3 4 5 6 7 8 9 10 300 200 0 0 20 0 1 0 100 1000 250 18446744073709551615"; + let (name, ticks, rss) = parse_proc_stat(line, 4096).unwrap(); + assert_eq!(name, "Web Content (x)"); + assert_eq!(ticks, 500); + assert_eq!(rss, 250 * 4096); + } + + #[test] + fn battery_from_sysfs() { + let dir = tempfile::tempdir().unwrap(); + let ac = dir.path().join("AC"); + std::fs::create_dir(&ac).unwrap(); + std::fs::write(ac.join("type"), "Mains\n").unwrap(); + let mouse = dir.path().join("hidpp_battery_0"); + std::fs::create_dir(&mouse).unwrap(); + std::fs::write(mouse.join("type"), "Battery\n").unwrap(); + std::fs::write(mouse.join("scope"), "Device\n").unwrap(); + std::fs::write(mouse.join("capacity"), "5\n").unwrap(); + let b = dir.path().join("BAT0"); + std::fs::create_dir(&b).unwrap(); + for (f, v) in [("type", "Battery"), ("capacity", "81"), ("status", "Discharging"), ("energy_full", "45000000"), ("energy_full_design", "50000000"), ("cycle_count", "312"), ("power_now", "7500000")] { + std::fs::write(b.join(f), format!("{v}\n")).unwrap(); + } + let bat = read_battery_in(dir.path()).unwrap(); + assert_eq!(bat.percent, 81); + assert_eq!(bat.health, Some(90)); + assert_eq!(bat.cycles, Some(312)); + assert_eq!(bat.power, Some(7.5)); + assert!(!bat.charging()); + } + + #[test] + fn rates_need_two_samples() { + assert_eq!(rate(None, (10, 10), 1.0), (0.0, 0.0)); + assert_eq!(rate(Some((0, 0, 0.0)), (2000, 1000), 2.0), (1000.0, 500.0)); + } + + #[test] + fn texts() { + assert_eq!(bytes(1_234_000_000, Language::En), "1.2 GB"); + assert_eq!(bytes(1_234_000_000, Language::Pt), "1,2 GB"); + assert_eq!(bytes(340_000_000, Language::En), "340 MB"); + assert_eq!(bytes(12, Language::En), "12 B"); + assert_eq!(uptime_text(3.0 * 86400.0 + 4.0 * 3600.0), "3 d 4 h"); + assert_eq!(uptime_text(5.0 * 3600.0 + 12.0 * 60.0), "5 h 12 min"); + let s = Snapshot { cpu: 12.4, memory: Memory { total: 100, available: 55, ..Memory::default() }, battery: Some(Battery { percent: 80, status: "Charging".into(), ..Battery::default() }), ..Snapshot::default() }; + assert_eq!(tray_text(&s, &["cpu".into(), "memory".into(), "battery".into(), "gpu".into()], Language::En), "CPU 12% · RAM 45% · ⚡80%"); + assert!(attention(&s, Language::En).is_empty()); + let full = Snapshot { memory: Memory { total: 100, available: 5, ..Memory::default() }, ..Snapshot::default() }; + assert_eq!(attention(&full, Language::En).len(), 1); + } +} diff --git a/crates/menew-ui/src/annotate.rs b/crates/menew-ui/src/annotate.rs new file mode 100644 index 0000000..d5fad7b --- /dev/null +++ b/crates/menew-ui/src/annotate.rs @@ -0,0 +1,403 @@ +//! The screenshot editor (port of the annotation window of `Capture.swift`): pen, arrows, +//! rectangles, text and blur over the capture, then copy, save or drag it out. Also the window that +//! shows a QR code. + +use crate::dialogs; +use gtk4::gdk; +use gtk4::gdk_pixbuf::{InterpType, Pixbuf}; +use gtk4::gio; +use gtk4::glib; +use gtk4::prelude::*; +use libadwaita as adw; +use libadwaita::prelude::*; +use menew_core::current_language; +use menew_core::strings::tr; +use std::cell::{Cell, RefCell}; +use std::path::{Path, PathBuf}; +use std::rc::Rc; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Tool { + Pen, + Arrow, + Rect, + Text, + Blur, +} + +#[derive(Debug, Clone)] +enum Shape { + Pen(Vec<(f64, f64)>, (f64, f64, f64)), + Arrow((f64, f64), (f64, f64), (f64, f64, f64)), + Rect((f64, f64), (f64, f64), (f64, f64, f64)), + Text((f64, f64), String, (f64, f64, f64)), + Blur((f64, f64), (f64, f64)), +} + +const COLORS: [(f64, f64, f64); 5] = [(0.92, 0.2, 0.2), (1.0, 0.75, 0.0), (0.2, 0.7, 0.3), (0.2, 0.5, 0.95), (0.1, 0.1, 0.1)]; + +struct Editor { + image: Pixbuf, + shapes: RefCell>, + current: RefCell>, + tool: Cell, + color: Cell<(f64, f64, f64)>, + area: gtk4::DrawingArea, + window: adw::ApplicationWindow, + /// Scale from image pixels to widget pixels and the offset of the image in the widget. + view: Cell<(f64, f64, f64)>, +} + +/// Pixelate one rectangle of the image (in image coordinates) and paint it. +fn paint_blur(cr: >k4::cairo::Context, image: &Pixbuf, a: (f64, f64), b: (f64, f64)) { + let x = a.0.min(b.0).max(0.0) as i32; + let y = a.1.min(b.1).max(0.0) as i32; + let w = ((a.0 - b.0).abs() as i32).min(image.width() - x); + let h = ((a.1 - b.1).abs() as i32).min(image.height() - y); + if w < 2 || h < 2 { + return; + } + let sub = image.new_subpixbuf(x, y, w, h); + let block = 12; + let Some(small) = sub.scale_simple((w / block).max(1), (h / block).max(1), InterpType::Bilinear) else { return }; + let Some(big) = small.scale_simple(w, h, InterpType::Nearest) else { return }; + cr.save().ok(); + cr.set_source_pixbuf(&big, x as f64, y as f64); + cr.rectangle(x as f64, y as f64, w as f64, h as f64); + let _ = cr.fill(); + cr.restore().ok(); +} + +/// Draw the shapes in image coordinates (the caller sets the scale). +fn paint(cr: >k4::cairo::Context, image: &Pixbuf, shapes: &[Shape]) { + cr.set_source_pixbuf(image, 0.0, 0.0); + let _ = cr.paint(); + let line = (image.width().max(image.height()) as f64 / 300.0).clamp(3.0, 10.0); + cr.set_line_cap(gtk4::cairo::LineCap::Round); + cr.set_line_join(gtk4::cairo::LineJoin::Round); + for s in shapes { + match s { + Shape::Blur(a, b) => paint_blur(cr, image, *a, *b), + Shape::Pen(pts, c) => { + cr.set_source_rgb(c.0, c.1, c.2); + cr.set_line_width(line); + if let Some(first) = pts.first() { + cr.move_to(first.0, first.1); + for p in pts.iter().skip(1) { + cr.line_to(p.0, p.1); + } + let _ = cr.stroke(); + } + } + Shape::Rect(a, b, c) => { + cr.set_source_rgb(c.0, c.1, c.2); + cr.set_line_width(line); + cr.rectangle(a.0.min(b.0), a.1.min(b.1), (a.0 - b.0).abs(), (a.1 - b.1).abs()); + let _ = cr.stroke(); + } + Shape::Arrow(a, b, c) => { + cr.set_source_rgb(c.0, c.1, c.2); + cr.set_line_width(line); + cr.move_to(a.0, a.1); + cr.line_to(b.0, b.1); + let _ = cr.stroke(); + let ang = (b.1 - a.1).atan2(b.0 - a.0); + let head = line * 4.5; + cr.move_to(b.0, b.1); + cr.line_to(b.0 - head * (ang - 0.45).cos(), b.1 - head * (ang - 0.45).sin()); + cr.line_to(b.0 - head * (ang + 0.45).cos(), b.1 - head * (ang + 0.45).sin()); + cr.close_path(); + let _ = cr.fill(); + } + Shape::Text(p, t, c) => { + let size = line * 7.0; + cr.select_font_face("Sans", gtk4::cairo::FontSlant::Normal, gtk4::cairo::FontWeight::Bold); + cr.set_font_size(size); + // a light outline keeps the text readable on any background + cr.move_to(p.0, p.1); + cr.text_path(t); + cr.set_source_rgb(1.0, 1.0, 1.0); + cr.set_line_width(line); + let _ = cr.stroke_preserve(); + cr.set_source_rgb(c.0, c.1, c.2); + let _ = cr.fill(); + } + } + } +} + +impl Editor { + fn to_image(&self, x: f64, y: f64) -> (f64, f64) { + let (s, ox, oy) = self.view.get(); + ((x - ox) / s, (y - oy) / s) + } + + /// The image with the annotations, at full size. + fn texture(&self) -> Option { + let (w, h) = (self.image.width(), self.image.height()); + let mut surface = gtk4::cairo::ImageSurface::create(gtk4::cairo::Format::ARgb32, w, h).ok()?; + { + let cr = gtk4::cairo::Context::new(&surface).ok()?; + paint(&cr, &self.image, &self.shapes.borrow()); + } + surface.flush(); + let stride = surface.stride() as usize; + let data = surface.data().ok()?.to_vec(); + // cairo's ARGB32 is native-endian premultiplied: BGRA in memory on little-endian machines + let format = if cfg!(target_endian = "little") { gdk::MemoryFormat::B8g8r8a8Premultiplied } else { gdk::MemoryFormat::A8r8g8b8Premultiplied }; + Some(gdk::MemoryTexture::new(w, h, format, &glib::Bytes::from_owned(data), stride).upcast()) + } + + fn png_bytes(&self) -> Option> { + Some(self.texture()?.save_to_png_bytes().to_vec()) + } +} + +fn notify(text: &str) { + if let Some(app) = gio::Application::default() { + app.send_notification(Some("menew-capture"), &gio::Notification::new(text)); + } +} + +/// Open the editor on a capture. `ocr` reads the text of the image (for the "Copy text" button). +pub fn open_editor(app: &adw::Application, path: &Path, ocr: Rc) { + let lang = current_language(); + let Ok(image) = Pixbuf::from_file(path) else { + notify(&tr("cap_failed", lang, &[])); + return; + }; + let window = adw::ApplicationWindow::builder().application(app).title(tr("ann_title", lang, &[])).default_width((image.width() + 40).clamp(480, 1400)).default_height((image.height() + 120).clamp(360, 900)).build(); + let area = gtk4::DrawingArea::builder().hexpand(true).vexpand(true).build(); + let ed = Rc::new(Editor { + image, + shapes: RefCell::new(vec![]), + current: RefCell::new(None), + tool: Cell::new(Tool::Arrow), + color: Cell::new(COLORS[0]), + area: area.clone(), + window: window.clone(), + view: Cell::new((1.0, 0.0, 0.0)), + }); + + let e = Rc::clone(&ed); + area.set_draw_func(move |_, cr, w, h| { + let (iw, ih) = (e.image.width() as f64, e.image.height() as f64); + let s = (w as f64 / iw).min(h as f64 / ih).min(1.0); + let (ox, oy) = ((w as f64 - iw * s) / 2.0, (h as f64 - ih * s) / 2.0); + e.view.set((s, ox, oy)); + cr.translate(ox, oy); + cr.scale(s, s); + let mut all = e.shapes.borrow().clone(); + if let Some(c) = e.current.borrow().clone() { + all.push(c); + } + paint(cr, &e.image, &all); + }); + + let drag = gtk4::GestureDrag::new(); + let e = Rc::clone(&ed); + drag.connect_drag_begin(move |_, x, y| { + let p = e.to_image(x, y); + let c = e.color.get(); + let shape = match e.tool.get() { + Tool::Pen => Some(Shape::Pen(vec![p], c)), + Tool::Arrow => Some(Shape::Arrow(p, p, c)), + Tool::Rect => Some(Shape::Rect(p, p, c)), + Tool::Blur => Some(Shape::Blur(p, p)), + Tool::Text => None, + }; + *e.current.borrow_mut() = shape; + }); + let e = Rc::clone(&ed); + drag.connect_drag_update(move |g, dx, dy| { + let Some((sx, sy)) = g.start_point() else { return }; + let p = e.to_image(sx + dx, sy + dy); + if let Some(s) = e.current.borrow_mut().as_mut() { + match s { + Shape::Pen(pts, _) => pts.push(p), + Shape::Arrow(_, b, _) | Shape::Rect(_, b, _) | Shape::Blur(_, b) => *b = p, + Shape::Text(..) => {} + } + } + e.area.queue_draw(); + }); + let e = Rc::clone(&ed); + drag.connect_drag_end(move |g, dx, dy| { + if let Some(s) = e.current.borrow_mut().take() { + e.shapes.borrow_mut().push(s); + } else if e.tool.get() == Tool::Text && dx.abs() < 4.0 && dy.abs() < 4.0 { + let Some((sx, sy)) = g.start_point() else { return }; + let p = e.to_image(sx, sy); + let c = e.color.get(); + let e2 = Rc::clone(&e); + let lang = current_language(); + dialogs::ask_text(Some(e.window.upcast_ref()), &tr("ann_text_ask", lang, &[]), "", &tr("ann_add", lang, &[]), &tr("cancel", lang, &[]), move |t| { + if !t.trim().is_empty() { + e2.shapes.borrow_mut().push(Shape::Text(p, t, c)); + e2.area.queue_draw(); + } + }); + } + e.area.queue_draw(); + }); + area.add_controller(drag); + + // ---- toolbar ---- + let header = adw::HeaderBar::new(); + let tools = gtk4::Box::builder().css_classes(["linked"]).build(); + let mut first: Option = None; + for (tool, icon, key) in [ + (Tool::Arrow, "go-next-symbolic", "ann_arrow"), + (Tool::Rect, "checkbox-symbolic", "ann_rect"), + (Tool::Pen, "document-edit-symbolic", "ann_pen"), + (Tool::Text, "insert-text-symbolic", "ann_text"), + (Tool::Blur, "view-conceal-symbolic", "ann_blur"), + ] { + let b = gtk4::ToggleButton::builder().icon_name(icon).tooltip_text(tr(key, lang, &[])).build(); + if let Some(f) = &first { + b.set_group(Some(f)); + } else { + b.set_active(true); + first = Some(b.clone()); + } + let e = Rc::clone(&ed); + b.connect_toggled(move |b| { + if b.is_active() { + e.tool.set(tool); + } + }); + tools.append(&b); + } + header.pack_start(&tools); + let colors = gtk4::Box::builder().css_classes(["linked"]).margin_start(6).build(); + let mut first_c: Option = None; + for c in COLORS { + let sw = gtk4::DrawingArea::builder().content_width(14).content_height(14).build(); + sw.set_draw_func(move |_, cr, w, h| { + cr.set_source_rgb(c.0, c.1, c.2); + cr.arc(w as f64 / 2.0, h as f64 / 2.0, w.min(h) as f64 / 2.0, 0.0, std::f64::consts::TAU); + let _ = cr.fill(); + }); + let b = gtk4::ToggleButton::builder().child(&sw).build(); + if let Some(f) = &first_c { + b.set_group(Some(f)); + } else { + b.set_active(true); + first_c = Some(b.clone()); + } + let e = Rc::clone(&ed); + b.connect_toggled(move |b| { + if b.is_active() { + e.color.set(c); + } + }); + colors.append(&b); + } + header.pack_start(&colors); + let undo = gtk4::Button::builder().icon_name("edit-undo-symbolic").tooltip_text(tr("ann_undo", lang, &[])).build(); + let e = Rc::clone(&ed); + undo.connect_clicked(move |_| { + e.shapes.borrow_mut().pop(); + e.area.queue_draw(); + }); + header.pack_start(&undo); + + let save = gtk4::Button::builder().label(tr("ann_save", lang, &[])).build(); + let copy = gtk4::Button::builder().label(tr("ann_copy", lang, &[])).css_classes(["suggested-action"]).build(); + let text_btn = gtk4::Button::builder().icon_name("edit-select-all-symbolic").tooltip_text(tr("ann_copy_text", lang, &[])).build(); + header.pack_end(©); + header.pack_end(&save); + header.pack_end(&text_btn); + + let e = Rc::clone(&ed); + copy.connect_clicked(move |_| { + if let (Some(t), Some(d)) = (e.texture(), gdk::Display::default()) { + d.clipboard().set_texture(&t); + notify(&tr("ann_copied", current_language(), &[])); + e.window.close(); + } + }); + let e = Rc::clone(&ed); + save.connect_clicked(move |_| { + let lang = current_language(); + let stamp = chrono::Local::now().format("%Y-%m-%d %H.%M.%S"); + let dialog = gtk4::FileDialog::builder().title(tr("ann_save", lang, &[])).initial_name(format!("Menew {stamp}.png")).modal(true).build(); + if let Some(dir) = glib::user_special_dir(glib::UserDirectory::Pictures) { + dialog.set_initial_folder(Some(&gio::File::for_path(dir))); + } + let e2 = Rc::clone(&e); + dialog.save(Some(&e.window), gio::Cancellable::NONE, move |res| { + let Ok(file) = res else { return }; + let Some(path) = file.path() else { return }; + if let Some(bytes) = e2.png_bytes() { + if std::fs::write(&path, bytes).is_ok() { + notify(&tr("ann_saved", current_language(), &[&path.display().to_string()])); + } + } + }); + }); + let p = path.to_path_buf(); + text_btn.connect_clicked(move |_| ocr(p.clone())); + + // drag the annotated image out as a PNG file + let src = gtk4::DragSource::builder().actions(gdk::DragAction::COPY).build(); + let e = Rc::clone(&ed); + src.connect_prepare(move |_, _, _| { + let bytes = e.png_bytes()?; + let dir = glib::user_cache_dir().join("menew").join("captures"); + std::fs::create_dir_all(&dir).ok()?; + let file = dir.join(format!("Menew {}.png", chrono::Local::now().format("%Y-%m-%d %H.%M.%S"))); + std::fs::write(&file, bytes).ok()?; + let list = gdk::FileList::from_array(&[gio::File::for_path(&file)]); + Some(gdk::ContentProvider::for_value(&list.to_value())) + }); + // dragging out only from the hint row, so drawing on the image still works + let hint = gtk4::Label::builder().label(tr("ann_drag_hint", lang, &[])).css_classes(["dim-label", "caption"]).margin_top(6).margin_bottom(6).build(); + hint.add_controller(src); + + let body = gtk4::Box::builder().orientation(gtk4::Orientation::Vertical).build(); + body.append(&area); + body.append(&hint); + let tv = adw::ToolbarView::new(); + tv.add_top_bar(&header); + tv.set_content(Some(&body)); + window.set_content(Some(&tv)); + let esc = gtk4::EventControllerKey::new(); + let w = window.clone(); + let e = Rc::clone(&ed); + esc.connect_key_pressed(move |_, key, _, mods| { + if key == gdk::Key::Escape { + w.close(); + return glib::Propagation::Stop; + } + if mods.contains(gdk::ModifierType::CONTROL_MASK) && (key == gdk::Key::z || key == gdk::Key::Z) { + e.shapes.borrow_mut().pop(); + e.area.queue_draw(); + return glib::Propagation::Stop; + } + if mods.contains(gdk::ModifierType::CONTROL_MASK) && (key == gdk::Key::c || key == gdk::Key::C) { + copy.emit_clicked(); + return glib::Propagation::Stop; + } + glib::Propagation::Proceed + }); + window.add_controller(esc); + window.present(); +} + +/// A window with a QR code, big enough to scan from a phone. +pub fn show_qr(app: &adw::Application, png: &[u8], caption: &str) { + let lang = current_language(); + let Ok(tex) = gdk::Texture::from_bytes(&glib::Bytes::from(png)) else { return }; + let pic = gtk4::Picture::builder().paintable(&tex).can_shrink(true).content_fit(gtk4::ContentFit::Contain).width_request(320).height_request(320).build(); + pic.add_css_class("menew-qr"); + let body = gtk4::Box::builder().orientation(gtk4::Orientation::Vertical).spacing(12).margin_top(12).margin_bottom(18).margin_start(18).margin_end(18).build(); + body.append(&pic); + body.append(>k4::Label::builder().label(caption).wrap(true).max_width_chars(40).selectable(true).build()); + body.append(>k4::Label::builder().label(tr("cap_qr_scan_hint", lang, &[])).css_classes(["dim-label"]).build()); + let tv = adw::ToolbarView::new(); + tv.add_top_bar(&adw::HeaderBar::new()); + tv.set_content(Some(&body)); + let w = adw::ApplicationWindow::builder().application(app).title(tr("cap_qr_title", lang, &[])).default_width(400).default_height(500).content(&tv).build(); + w.present(); +} diff --git a/crates/menew-ui/src/monitor.rs b/crates/menew-ui/src/monitor.rs new file mode 100644 index 0000000..ab948b0 --- /dev/null +++ b/crates/menew-ui/src/monitor.rs @@ -0,0 +1,232 @@ +//! The Performance section (port of `MonitorViews.swift`): CPU and memory with a live graph, GPU, +//! disk space and speed, network, battery, uptime and the apps using the most, with Quit. + +use crate::window; +use gtk4::glib; +use gtk4::prelude::*; +use libadwaita as adw; +use libadwaita::prelude::*; +use menew_core::strings::tr; +use menew_core::sysmon::{self, Process, Snapshot}; +use menew_core::{current_language, Language}; +use std::cell::RefCell; +use std::collections::VecDeque; +use std::rc::Rc; + +const HISTORY: usize = 60; + +struct Card { + value: gtk4::Label, + detail: gtk4::Label, + bar: gtk4::LevelBar, + graph: Option<(gtk4::DrawingArea, Rc>>)>, + root: gtk4::Box, +} + +fn card(title: &str, icon: &str, with_graph: bool) -> Card { + let root = gtk4::Box::builder().orientation(gtk4::Orientation::Vertical).spacing(6).css_classes(["card", "menew-mon-card"]).build(); + let inner = gtk4::Box::builder().orientation(gtk4::Orientation::Vertical).spacing(6).margin_top(12).margin_bottom(12).margin_start(14).margin_end(14).build(); + let top = gtk4::Box::builder().spacing(8).build(); + top.append(>k4::Image::from_icon_name(icon)); + top.append(>k4::Label::builder().label(title).xalign(0.0).hexpand(true).css_classes(["heading"]).build()); + let value = gtk4::Label::builder().xalign(1.0).css_classes(["title-3", "numeric"]).build(); + top.append(&value); + inner.append(&top); + let bar = gtk4::LevelBar::builder().min_value(0.0).max_value(100.0).build(); + inner.append(&bar); + let graph = with_graph.then(|| { + let data = Rc::new(RefCell::new(VecDeque::::with_capacity(HISTORY))); + let area = gtk4::DrawingArea::builder().content_height(48).hexpand(true).build(); + let d = Rc::clone(&data); + area.set_draw_func(move |w, cr, width, height| { + let pts = d.borrow(); + if pts.len() < 2 { + return; + } + let color = w.color(); + let (wf, hf) = (width as f64, height as f64); + let step = wf / (HISTORY - 1) as f64; + let x0 = wf - step * (pts.len() - 1) as f64; + cr.move_to(x0, hf); + for (i, v) in pts.iter().enumerate() { + cr.line_to(x0 + step * i as f64, hf - (*v / 100.0_f64).clamp(0.0, 1.0) * (hf - 2.0)); + } + cr.line_to(wf, hf); + cr.close_path(); + cr.set_source_rgba(color.red() as f64, color.green() as f64, color.blue() as f64, 0.18); + let _ = cr.fill_preserve(); + cr.set_source_rgba(color.red() as f64, color.green() as f64, color.blue() as f64, 0.7); + cr.set_line_width(1.5); + let _ = cr.stroke(); + }); + inner.append(&area); + (area, data) + }); + let detail = gtk4::Label::builder().xalign(0.0).wrap(true).css_classes(["dim-label", "caption"]).build(); + inner.append(&detail); + root.append(&inner); + Card { value, detail, bar, graph, root } +} + +impl Card { + /// Hide or show the card (its FlowBox cell, so no hole is left). + fn show(&self, on: bool) { + match self.root.parent() { + Some(cell) => cell.set_visible(on), + None => self.root.set_visible(on), + } + } + + fn set(&self, value: &str, percent: Option, detail: &str) { + self.value.set_label(value); + self.bar.set_visible(percent.is_some()); + if let Some(p) = percent { + self.bar.set_value(p.clamp(0.0, 100.0)); + if let Some((area, data)) = &self.graph { + let mut d = data.borrow_mut(); + if d.len() == HISTORY { + d.pop_front(); + } + d.push_back(p); + drop(d); + area.queue_draw(); + } + } + self.detail.set_label(detail); + self.detail.set_visible(!detail.is_empty()); + } +} + +pub struct MonitorView { + pub root: gtk4::Widget, + status: gtk4::Label, + cpu: Card, + mem: Card, + gpu: Card, + disk: Card, + net: Card, + battery: Card, + system: Card, + top_cpu: gtk4::ListBox, + top_mem: gtk4::ListBox, + on_quit: Rc, +} + +impl MonitorView { + /// `on_quit(pid)` quits a process; `on_metrics` saves the metrics chosen for the tray. + pub fn new(on_quit: Rc, metrics: Vec, on_metrics: Rc)>) -> Rc { + let lang = current_language(); + let (scroll, body) = window::page(); + let status = gtk4::Label::builder().xalign(0.0).css_classes(["title-4"]).build(); + body.append(&status); + let grid = gtk4::FlowBox::builder().selection_mode(gtk4::SelectionMode::None).min_children_per_line(1).max_children_per_line(3).column_spacing(12).row_spacing(12).homogeneous(true).build(); + let cpu = card(&tr("mon_cpu", lang, &[]), "computer-symbolic", true); + let mem = card(&tr("mon_memory", lang, &[]), "drive-harddisk-solidstate-symbolic", true); + let gpu = card(&tr("mon_gpu", lang, &[]), "video-display-symbolic", true); + let disk = card(&tr("mon_disk", lang, &[]), "drive-harddisk-symbolic", false); + let net = card(&tr("mon_network", lang, &[]), "network-transmit-receive-symbolic", false); + let battery = card(&tr("mon_battery", lang, &[]), "battery-good-symbolic", false); + let system = card(&tr("mon_uptime", lang, &[]), "preferences-system-time-symbolic", false); + for c in [&cpu, &mem, &gpu, &disk, &net, &battery, &system] { + grid.append(&c.root); + } + body.append(&grid); + + let lists = gtk4::Box::builder().spacing(12).homogeneous(true).build(); + let mut boxes = vec![]; + for key in ["mon_top_cpu", "mon_top_memory"] { + let g = adw::PreferencesGroup::builder().title(tr(key, lang, &[])).build(); + let lb = gtk4::ListBox::builder().css_classes(["boxed-list"]).selection_mode(gtk4::SelectionMode::None).build(); + g.add(&lb); + lists.append(&g); + boxes.push(lb); + } + body.append(&lists); + + let mg = adw::PreferencesGroup::builder().title(tr("mon_tray_metrics", lang, &[])).description(tr("mon_tray_metrics_sub", lang, &[])).build(); + let chosen = Rc::new(RefCell::new(metrics)); + for m in sysmon::TRAY_METRICS { + let label = match m { + "cpu" => tr("mon_cpu", lang, &[]), + "memory" => tr("mon_memory", lang, &[]), + "gpu" => tr("mon_gpu", lang, &[]), + "disk" => tr("mon_disk", lang, &[]), + "network" => tr("mon_network", lang, &[]), + _ => tr("mon_battery", lang, &[]), + }; + let sw = adw::SwitchRow::builder().title(label).active(chosen.borrow().iter().any(|x| x == m)).build(); + let (c, f) = (Rc::clone(&chosen), Rc::clone(&on_metrics)); + sw.connect_active_notify(move |s| { + let mut v = c.borrow_mut(); + v.retain(|x| x != m); + if s.is_active() { + v.push(m.to_string()); + } + // keep the order of the list + v.sort_by_key(|x| sysmon::TRAY_METRICS.iter().position(|t| t == x)); + f(v.clone()); + }); + mg.add(&sw); + } + body.append(&mg); + let top_mem = boxes.pop().unwrap(); + let top_cpu = boxes.pop().unwrap(); + Rc::new(Self { root: scroll.upcast(), status, cpu, mem, gpu, disk, net, battery, system, top_cpu, top_mem, on_quit }) + } + + fn fill(&self, lb: >k4::ListBox, list: &[Process], cpu: bool, lang: Language) { + while let Some(c) = lb.first_child() { + lb.remove(&c); + } + for p in list { + let sub = if cpu { format!("{:.0}%", p.cpu) } else { sysmon::bytes(p.memory, lang) }; + let row = adw::ActionRow::builder().title(glib::markup_escape_text(&p.name)).subtitle(sub).build(); + let b = gtk4::Button::builder().label(tr("mon_quit_process", lang, &[])).valign(gtk4::Align::Center).css_classes(["flat"]).build(); + let (f, pid) = (Rc::clone(&self.on_quit), p.pid); + b.connect_clicked(move |_| f(pid)); + row.add_suffix(&b); + lb.append(&row); + } + } + + pub fn update(&self, s: &Snapshot) { + let lang = current_language(); + let warn = sysmon::attention(s, lang); + self.status.set_label(&if warn.is_empty() { tr("mon_all_good", lang, &[]) } else { warn.join(" · ") }); + let load = s.load.map(|l| format!("{} {:.2} {:.2} {:.2}", tr("mon_load", lang, &[]), l.0, l.1, l.2)).unwrap_or_default(); + self.cpu.set(&format!("{:.0}%", s.cpu), Some(s.cpu), &format!("{} cores · {load}", s.cores)); + let m = &s.memory; + let swap = if m.swap_total > 0 { format!(" · {} {}", tr("mon_swap", lang, &[]), tr("mon_used_of", lang, &[&sysmon::bytes(m.swap_used(), lang), &sysmon::bytes(m.swap_total, lang)])) } else { String::new() }; + self.mem.set(&format!("{:.0}%", m.used_percent()), Some(m.used_percent()), &(tr("mon_used_of", lang, &[&sysmon::bytes(m.used(), lang), &sysmon::bytes(m.total, lang)]) + &swap)); + self.gpu.show(s.gpu.is_some()); + if let Some(g) = s.gpu { + self.gpu.set(&format!("{g}%"), Some(g as f64), ""); + } + match &s.disk { + Some(d) => self.disk.set( + &tr("mon_free", lang, &[&sysmon::bytes(d.free, lang)]), + Some(d.used_percent()), + &format!("{} · {}", tr("mon_used_of", lang, &[&sysmon::bytes(d.total - d.free, lang), &sysmon::bytes(d.total, lang)]), tr("mon_read_write", lang, &[&sysmon::speed(s.disk_read, lang), &sysmon::speed(s.disk_write, lang)])), + ), + None => self.disk.show(false), + } + self.net.set(&format!("↓ {}", sysmon::speed(s.net_down, lang)), None, &format!("↑ {}", sysmon::speed(s.net_up, lang))); + self.battery.show(s.battery.is_some()); + if let Some(b) = &s.battery { + let mut parts = vec![tr(if b.charging() { "mon_charging" } else { "mon_on_battery" }, lang, &[])]; + if let Some(h) = b.health { + parts.push(tr("mon_health", lang, &[&h.to_string()])); + } + if let Some(c) = b.cycles { + parts.push(tr("mon_cycles", lang, &[&c.to_string()])); + } + if let Some(w) = b.power { + parts.push(tr("mon_watts", lang, &[&format!("{w:.1}")])); + } + self.battery.set(&format!("{}%", b.percent), Some(b.percent as f64), &parts.join(" · ")); + } + self.system.set(&sysmon::uptime_text(s.uptime), None, menew_core::sys::Desktop::detect().name()); + self.fill(&self.top_cpu, &s.top_cpu, true, lang); + self.fill(&self.top_mem, &s.top_memory, false, lang); + } +} diff --git a/crates/menew-ui/src/notes.rs b/crates/menew-ui/src/notes.rs new file mode 100644 index 0000000..f1c3c76 --- /dev/null +++ b/crates/menew-ui/src/notes.rs @@ -0,0 +1,696 @@ +//! The Notes section (port of `NotesViews.swift`): the list with search and #tags on the left, the +//! editor on the right. Text notes are Markdown, styled while typing, with clickable `- [ ]` +//! checklists. Password notes are a title and `key: value` fields with hidden values that are +//! copied marked as a password and cleared from the clipboard after 30 s. + +use crate::dialogs; +use gtk4::gdk; +use gtk4::gio; +use gtk4::glib; +use gtk4::prelude::*; +use libadwaita as adw; +use menew_core::notes::{self, Block, NoteKind, NotesStore, SecretField}; +use menew_core::strings::tr; +use menew_core::current_language; +use std::cell::{Cell, RefCell}; +use std::rc::Rc; + +pub type SharedNotes = Rc>; + +fn now() -> f64 { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs_f64()).unwrap_or(0.0) +} + +pub struct NotesView { + store: SharedNotes, + pub root: gtk4::Widget, + pub header: Vec, + search: gtk4::SearchEntry, + tags_box: gtk4::Box, + list: gtk4::ListBox, + editor_stack: gtk4::Stack, + text_view: gtk4::TextView, + fields_box: gtk4::Box, + title_entry: gtk4::Entry, + protect_btn: gtk4::ToggleButton, + kind_btn: gtk4::ToggleButton, + delete_btn: gtk4::Button, + selected: RefCell>, + ids: RefCell>, + tag: RefCell>, + /// Set while code changes the widgets, so their handlers do not save. + loading: Cell, + save_pending: Cell>, + on_changed: RefCell>>, +} + +impl NotesView { + pub fn new(store: SharedNotes) -> Rc { + let lang = current_language(); + // ---- list side ---- + let search = gtk4::SearchEntry::builder().placeholder_text(tr("note_search", lang, &[])).margin_top(8).margin_start(8).margin_end(8).build(); + let tags_box = gtk4::Box::builder().spacing(4).margin_start(8).margin_end(8).build(); + let tags_scroll = gtk4::ScrolledWindow::builder().vscrollbar_policy(gtk4::PolicyType::Never).child(&tags_box).build(); + let list = gtk4::ListBox::builder().css_classes(["navigation-sidebar"]).build(); + let list_scroll = gtk4::ScrolledWindow::builder().hscrollbar_policy(gtk4::PolicyType::Never).vexpand(true).child(&list).build(); + let left = gtk4::Box::builder().orientation(gtk4::Orientation::Vertical).spacing(6).width_request(240).build(); + left.append(&search); + left.append(&tags_scroll); + left.append(&list_scroll); + + // ---- editor side ---- + let editor_stack = gtk4::Stack::builder().hexpand(true).vexpand(true).build(); + let empty = adw::StatusPage::builder().icon_name("accessories-text-editor-symbolic").title(tr("note_empty", lang, &[])).description(tr("note_empty_sub", lang, &[])).build(); + editor_stack.add_named(&empty, Some("empty")); + let unlock_btn = gtk4::Button::builder().label(tr("note_unlock", lang, &[])).halign(gtk4::Align::Center).css_classes(["pill", "suggested-action"]).build(); + let locked = adw::StatusPage::builder().icon_name("channel-secure-symbolic").title(tr("note_locked", lang, &[])).child(&unlock_btn).build(); + editor_stack.add_named(&locked, Some("locked")); + let text_view = gtk4::TextView::builder().wrap_mode(gtk4::WrapMode::WordChar).left_margin(18).right_margin(18).top_margin(14).bottom_margin(14).build(); + setup_tags(&text_view.buffer()); + let text_scroll = gtk4::ScrolledWindow::builder().child(&text_view).build(); + editor_stack.add_named(&text_scroll, Some("text")); + let title_entry = gtk4::Entry::builder().placeholder_text(tr("note_title_placeholder", lang, &[])).css_classes(["title-3"]).build(); + let fields_box = gtk4::Box::builder().orientation(gtk4::Orientation::Vertical).spacing(6).build(); + let add_field = gtk4::Button::builder().label(tr("note_add_field", lang, &[])).halign(gtk4::Align::Start).css_classes(["flat"]).build(); + let pw_body = gtk4::Box::builder().orientation(gtk4::Orientation::Vertical).spacing(12).margin_top(18).margin_bottom(18).margin_start(18).margin_end(18).build(); + pw_body.append(&title_entry); + pw_body.append(&fields_box); + pw_body.append(&add_field); + let pw_scroll = gtk4::ScrolledWindow::builder().child(&adw::Clamp::builder().maximum_size(640).child(&pw_body).build()).build(); + editor_stack.add_named(&pw_scroll, Some("passwords")); + + let paned = gtk4::Paned::builder().orientation(gtk4::Orientation::Horizontal).start_child(&left).end_child(&editor_stack).position(260).shrink_start_child(false).build(); + + // ---- header buttons ---- + let new_btn = gtk4::MenuButton::builder().icon_name("list-add-symbolic").tooltip_text(tr("note_new", lang, &[])).build(); + let menu = gio::Menu::new(); + menu.append(Some(&tr("note_new", lang, &[])), Some("notes.new")); + menu.append(Some(&tr("note_new_passwords", lang, &[])), Some("notes.newpasswords")); + menu.append(Some(&tr("note_lock_all", lang, &[])), Some("notes.lockall")); + new_btn.set_menu_model(Some(&menu)); + let protect_btn = gtk4::ToggleButton::builder().icon_name("channel-secure-symbolic").tooltip_text(tr("note_protect_help", lang, &[])).build(); + let kind_btn = gtk4::ToggleButton::builder().icon_name("dialog-password-symbolic").tooltip_text(tr("note_kind_passwords", lang, &[])).build(); + let delete_btn = gtk4::Button::builder().icon_name("user-trash-symbolic").tooltip_text(tr("note_delete", lang, &[])).build(); + + let me = Rc::new(Self { + store, + root: paned.upcast(), + header: vec![new_btn.clone().upcast(), delete_btn.clone().upcast(), protect_btn.clone().upcast(), kind_btn.clone().upcast()], + search, + tags_box, + list, + editor_stack, + text_view, + fields_box, + title_entry, + protect_btn, + kind_btn, + delete_btn, + selected: RefCell::new(None), + ids: RefCell::new(vec![]), + tag: RefCell::new(None), + loading: Cell::new(false), + save_pending: Cell::new(None), + on_changed: RefCell::new(None), + }); + + let group = gio::SimpleActionGroup::new(); + for (name, f) in [ + ("new", Box::new(|m: &Rc| m.new_note(false)) as Box)>), + ("newpasswords", Box::new(|m: &Rc| m.new_note(true))), + ("lockall", Box::new(|m: &Rc| { + m.store.borrow_mut().lock_all(); + m.show_selected(); + })), + ] { + let a = gio::SimpleAction::new(name, None); + let w = Rc::downgrade(&me); + a.connect_activate(move |_, _| { + if let Some(m) = w.upgrade() { + f(&m); + } + }); + group.add_action(&a); + } + me.root.insert_action_group("notes", Some(&group)); + + let w = Rc::downgrade(&me); + me.search.connect_search_changed(move |_| { + if let Some(m) = w.upgrade() { + m.reload_list(); + } + }); + let w = Rc::downgrade(&me); + me.list.connect_row_activated(move |_, row| { + if let Some(m) = w.upgrade() { + let id = m.ids.borrow().get(row.index() as usize).cloned(); + if let Some(id) = id { + m.select(&id); + } + } + }); + let w = Rc::downgrade(&me); + me.text_view.buffer().connect_changed(move |buf| { + if let Some(m) = w.upgrade() { + restyle(buf); + if !m.loading.get() { + m.schedule_save(); + } + } + }); + // click on "[ ]" toggles the task + let click = gtk4::GestureClick::new(); + let w = Rc::downgrade(&me); + click.connect_released(move |g, _, x, y| { + let Some(m) = w.upgrade() else { return }; + let tv = &m.text_view; + let (bx, by) = tv.window_to_buffer_coords(gtk4::TextWindowType::Widget, x as i32, y as i32); + let Some(iter) = tv.iter_at_location(bx, by) else { return }; + let buf = tv.buffer(); + let mut start = iter; + start.set_line_offset(0); + let mut end = start; + end.forward_to_line_end(); + let line = buf.text(&start, &end, false).to_string(); + if !matches!(notes::block_of(&line), Block::Task(_)) { + return; + } + let Some(open) = line.find('[') else { return }; + let col = iter.line_offset() as usize; + let open_c = line[..open].chars().count(); + if col >= open_c && col <= open_c + 3 { + let new = notes::toggle_task(&line); + buf.begin_user_action(); + buf.delete(&mut start.clone(), &mut end.clone()); + let mut at = buf.iter_at_line(iter.line()).unwrap_or(buf.start_iter()); + buf.insert(&mut at, &new); + buf.end_user_action(); + g.set_state(gtk4::EventSequenceState::Claimed); + } + }); + me.text_view.add_controller(click); + let w = Rc::downgrade(&me); + me.title_entry.connect_changed(move |_| { + if let Some(m) = w.upgrade() { + if !m.loading.get() { + m.save_fields(); + } + } + }); + let w = Rc::downgrade(&me); + add_field.connect_clicked(move |_| { + if let Some(m) = w.upgrade() { + m.add_field_row("", "", true); + m.save_fields(); + } + }); + let w = Rc::downgrade(&me); + unlock_btn.connect_clicked(move |_| { + if let Some(m) = w.upgrade() { + m.unlock_selected(); + } + }); + let w = Rc::downgrade(&me); + me.protect_btn.connect_toggled(move |b| { + let Some(m) = w.upgrade() else { return }; + if m.loading.get() { + return; + } + let Some(id) = m.selected.borrow().clone() else { return }; + m.flush_save(); + if b.is_active() && !notes::vault_available() { + m.toast(&tr("note_vault_missing", current_language(), &[])); + m.loading.set(true); + b.set_active(false); + m.loading.set(false); + return; + } + let ok = m.store.borrow_mut().set_secure(&id, b.is_active()); + if !ok { + m.toast(&tr("note_vault_missing", current_language(), &[])); + } + m.reload_list(); + m.show_selected(); + }); + let w = Rc::downgrade(&me); + me.kind_btn.connect_toggled(move |b| { + let Some(m) = w.upgrade() else { return }; + if m.loading.get() { + return; + } + let Some(id) = m.selected.borrow().clone() else { return }; + m.flush_save(); + if b.is_active() && !notes::vault_available() { + m.toast(&tr("note_vault_missing", current_language(), &[])); + m.loading.set(true); + b.set_active(false); + m.loading.set(false); + return; + } + m.store.borrow_mut().set_kind(&id, if b.is_active() { NoteKind::Passwords } else { NoteKind::Text }); + m.reload_list(); + m.show_selected(); + }); + let w = Rc::downgrade(&me); + me.delete_btn.connect_clicked(move |b| { + let Some(m) = w.upgrade() else { return }; + let Some(id) = m.selected.borrow().clone() else { return }; + let lang = current_language(); + let parent = b.root().and_downcast::(); + let w2 = Rc::downgrade(&m); + dialogs::confirm(parent.as_ref(), &tr("note_delete_ask", lang, &[]), &tr("note_delete_body", lang, &[]), &tr("delete", lang, &[]), &tr("cancel", lang, &[]), true, move || { + if let Some(m) = w2.upgrade() { + m.cancel_save(); + m.store.borrow_mut().delete(&id); + *m.selected.borrow_mut() = None; + m.reload_list(); + m.select_first(); + m.changed(); + } + }); + }); + me.reload_list(); + me.select_first(); + me + } + + pub fn set_on_changed(&self, f: Rc) { + *self.on_changed.borrow_mut() = Some(f); + } + + fn changed(&self) { + let f = self.on_changed.borrow().clone(); + if let Some(f) = f { + f(); + } + } + + fn toast(&self, text: &str) { + if let Some(app) = gio::Application::default() { + let n = gio::Notification::new(text); + app.send_notification(Some("menew-notes"), &n); + } + } + + /// Reload from disk (another window or the palette may have changed it). + pub fn refresh(self: &Rc) { + self.flush_save(); + self.store.borrow_mut().reload(); + self.reload_list(); + let sel = self.selected.borrow().clone(); + match sel { + Some(id) if self.store.borrow().note(&id).is_some() => self.show_selected(), + _ => self.select_first(), + } + } + + pub fn new_note(self: &Rc, passwords: bool) { + self.flush_save(); + if passwords && !notes::vault_available() { + self.toast(&tr("note_vault_missing", current_language(), &[])); + return; + } + let id = if passwords { self.store.borrow_mut().create_passwords(current_language(), now()) } else { self.store.borrow_mut().create("", now()) }; + self.search.set_text(""); + *self.tag.borrow_mut() = None; + self.reload_list(); + self.select(&id); + if !passwords { + self.text_view.grab_focus(); + } else { + self.title_entry.grab_focus(); + } + self.changed(); + } + + fn select_first(self: &Rc) { + let first = self.ids.borrow().first().cloned(); + match first { + Some(id) => self.select(&id), + None => { + *self.selected.borrow_mut() = None; + self.show_selected(); + } + } + } + + pub fn select(self: &Rc, id: &str) { + self.flush_save(); + *self.selected.borrow_mut() = Some(id.to_string()); + let idx = self.ids.borrow().iter().position(|x| x == id); + if let Some(i) = idx { + if let Some(r) = self.list.row_at_index(i as i32) { + self.list.select_row(Some(&r)); + } + } + self.show_selected(); + } + + fn reload_list(self: &Rc) { + let lang = current_language(); + while let Some(c) = self.list.first_child() { + self.list.remove(&c); + } + while let Some(c) = self.tags_box.first_child() { + self.tags_box.remove(&c); + } + let store = self.store.borrow(); + let tags = store.all_tags(); + if !tags.is_empty() { + let cur = self.tag.borrow().clone(); + let all = gtk4::ToggleButton::builder().label(tr("note_all_tags", lang, &[])).css_classes(["flat", "menew-chip"]).active(cur.is_none()).build(); + let w = Rc::downgrade(self); + all.connect_clicked(move |_| { + if let Some(m) = w.upgrade() { + *m.tag.borrow_mut() = None; + glib::idle_add_local_once(move || m.reload_list()); + } + }); + self.tags_box.append(&all); + for t in tags { + let b = gtk4::ToggleButton::builder().label(format!("#{t}")).css_classes(["flat", "menew-chip"]).active(cur.as_deref() == Some(t.as_str())).build(); + let w = Rc::downgrade(self); + b.connect_clicked(move |_| { + if let Some(m) = w.upgrade() { + *m.tag.borrow_mut() = Some(t.clone()); + glib::idle_add_local_once(move || m.reload_list()); + } + }); + self.tags_box.append(&b); + } + } + let tag = self.tag.borrow().clone(); + let q = self.search.text().to_string(); + let found = store.filtered(&q, tag.as_deref()); + let mut ids = vec![]; + for n in found { + let row = gtk4::Box::builder().orientation(gtk4::Orientation::Vertical).spacing(2).margin_top(6).margin_bottom(6).margin_start(6).margin_end(6).build(); + let top = gtk4::Box::builder().spacing(6).build(); + if n.secure { + top.append(>k4::Image::from_icon_name(if n.is_passwords() { "dialog-password-symbolic" } else { "channel-secure-symbolic" })); + } + top.append(>k4::Label::builder().label(n.title(lang)).xalign(0.0).ellipsize(gtk4::pango::EllipsizeMode::End).css_classes(["heading"]).build()); + row.append(&top); + let sub = n.preview(lang); + if !sub.is_empty() { + row.append(>k4::Label::builder().label(sub).xalign(0.0).ellipsize(gtk4::pango::EllipsizeMode::End).css_classes(["dim-label", "caption"]).build()); + } + self.list.append(&row); + ids.push(n.id.clone()); + } + drop(store); + let sel = self.selected.borrow().clone(); + if let Some(i) = sel.and_then(|s| ids.iter().position(|x| *x == s)) { + if let Some(r) = self.list.row_at_index(i as i32) { + self.list.select_row(Some(&r)); + } + } + *self.ids.borrow_mut() = ids; + } + + fn show_selected(self: &Rc) { + self.loading.set(true); + let id = self.selected.borrow().clone(); + let store = self.store.borrow(); + let note = id.as_deref().and_then(|i| store.note(i)).cloned(); + let has = note.is_some(); + self.protect_btn.set_sensitive(has); + self.kind_btn.set_sensitive(has); + self.delete_btn.set_sensitive(has); + match note { + None => self.editor_stack.set_visible_child_name("empty"), + Some(n) => { + self.protect_btn.set_active(n.secure); + self.protect_btn.set_tooltip_text(Some(&tr(if n.secure { "note_unprotect" } else { "note_protect_help" }, current_language(), &[]))); + self.kind_btn.set_active(n.is_passwords()); + if store.is_locked(&n.id) { + self.editor_stack.set_visible_child_name("locked"); + } else if n.is_passwords() { + let (title, fields) = notes::parse_fields(&store.text(&n.id)); + drop(store); + self.title_entry.set_text(&title); + while let Some(c) = self.fields_box.first_child() { + self.fields_box.remove(&c); + } + for f in fields { + self.add_field_row(&f.key, &f.value, false); + } + self.editor_stack.set_visible_child_name("passwords"); + self.loading.set(false); + return; + } else { + let text = store.text(&n.id); + self.text_view.buffer().set_text(&text); + self.editor_stack.set_visible_child_name("text"); + } + } + } + self.loading.set(false); + } + + fn add_field_row(self: &Rc, key: &str, value: &str, focus: bool) { + let lang = current_language(); + let row = gtk4::Box::builder().spacing(6).build(); + let k = gtk4::Entry::builder().text(key).placeholder_text(tr("note_field_name", lang, &[])).width_chars(12).build(); + let v = gtk4::PasswordEntry::builder().text(value).placeholder_text(tr("note_field_value", lang, &[])).show_peek_icon(true).hexpand(true).build(); + let copy = gtk4::Button::builder().icon_name("edit-copy-symbolic").tooltip_text(tr("note_copy", lang, &[])).css_classes(["flat"]).build(); + let remove = gtk4::Button::builder().icon_name("list-remove-symbolic").css_classes(["flat"]).build(); + row.append(&k); + row.append(&v); + row.append(©); + row.append(&remove); + self.fields_box.append(&row); + let w = Rc::downgrade(self); + k.connect_changed(move |_| { + if let Some(m) = w.upgrade() { + if !m.loading.get() { + m.save_fields(); + } + } + }); + let w = Rc::downgrade(self); + v.connect_changed(move |_| { + if let Some(m) = w.upgrade() { + if !m.loading.get() { + m.save_fields(); + } + } + }); + let vv = v.clone(); + let w = Rc::downgrade(self); + copy.connect_clicked(move |_| { + if let Some(m) = w.upgrade() { + copy_secret(&vv.text()); + m.toast(&tr("note_secret_copied", current_language(), &[])); + } + }); + let w = Rc::downgrade(self); + let r2 = row.clone(); + remove.connect_clicked(move |_| { + if let Some(m) = w.upgrade() { + m.fields_box.remove(&r2); + m.save_fields(); + } + }); + if focus { + k.grab_focus(); + } + } + + fn save_fields(self: &Rc) { + let Some(id) = self.selected.borrow().clone() else { return }; + let mut fields = vec![]; + let mut c = self.fields_box.first_child(); + while let Some(row) = c { + let k = row.first_child().and_downcast::(); + let v = row.first_child().and_then(|x| x.next_sibling()).and_downcast::(); + if let (Some(k), Some(v)) = (k, v) { + fields.push(SecretField { key: k.text().to_string(), value: v.text().to_string() }); + } + c = row.next_sibling(); + } + let text = notes::format_fields(&self.title_entry.text(), &fields); + self.store.borrow_mut().set_text(&id, &text, now()); + self.reload_list(); + } + + fn schedule_save(self: &Rc) { + self.cancel_save(); + let w = Rc::downgrade(self); + let src = glib::timeout_add_local_once(std::time::Duration::from_millis(400), move || { + if let Some(m) = w.upgrade() { + m.save_pending.set(None); + m.save_text(); + } + }); + self.save_pending.set(Some(src)); + } + + fn cancel_save(&self) { + if let Some(s) = self.save_pending.take() { + s.remove(); + } + } + + /// Save a pending edit now (before switching notes). + fn flush_save(self: &Rc) { + if let Some(s) = self.save_pending.take() { + s.remove(); + self.save_text(); + } + } + + fn save_text(self: &Rc) { + let Some(id) = self.selected.borrow().clone() else { return }; + if self.editor_stack.visible_child_name().as_deref() != Some("text") { + return; + } + let buf = self.text_view.buffer(); + let text = buf.text(&buf.start_iter(), &buf.end_iter(), false).to_string(); + if self.store.borrow().text(&id) == text { + return; + } + self.store.borrow_mut().set_text(&id, &text, now()); + self.reload_list(); + self.changed(); + } + + fn unlock_selected(self: &Rc) { + let Some(id) = self.selected.borrow().clone() else { return }; + let me = Rc::clone(self); + glib::spawn_future_local(async move { + let id2 = id.clone(); + let text = gio::spawn_blocking(move || { + if !notes::authenticate() { + return None; + } + use notes::Vault; + notes::SecretServiceVault.read(&id2) + }) + .await + .ok() + .flatten(); + match text { + Some(t) => { + me.store.borrow_mut().set_unlocked(&id, t); + me.show_selected(); + } + None => me.toast(&tr("note_unlock_fail", current_language(), &[])), + } + }); + } +} + +/// Copy a secret marked as a password (KDE's hint, which Menew and other clipboard managers skip) +/// and clear it after 30 s if nothing else was copied (`SecretCopy` on the Mac). +pub fn copy_secret(value: &str) { + let Some(display) = gdk::Display::default() else { return }; + let clipboard = display.clipboard(); + let bytes = glib::Bytes::from(value.as_bytes()); + let provider = gdk::ContentProvider::new_union(&[ + gdk::ContentProvider::for_bytes("text/plain;charset=utf-8", &bytes), + gdk::ContentProvider::for_bytes("text/plain", &bytes), + gdk::ContentProvider::for_bytes("UTF8_STRING", &bytes), + gdk::ContentProvider::for_bytes("x-kde-passwordManagerHint", &glib::Bytes::from_static(b"secret")), + ]); + if clipboard.set_content(Some(&provider)).is_err() { + return; + } + glib::timeout_add_seconds_local_once(30, move || { + if clipboard.content().as_ref() == Some(&provider) { + let _ = clipboard.set_content(None::<&gdk::ContentProvider>); + } + }); +} + +fn setup_tags(buf: >k4::TextBuffer) { + let table = buf.tag_table(); + let add = |name: &str, f: &dyn Fn(>k4::TextTag)| { + let t = gtk4::TextTag::new(Some(name)); + f(&t); + table.add(&t); + }; + add("h1", &|t| { + t.set_scale(1.6); + t.set_weight(800); + }); + add("h2", &|t| { + t.set_scale(1.35); + t.set_weight(700); + }); + add("h3", &|t| { + t.set_scale(1.15); + t.set_weight(700); + }); + add("bold", &|t| t.set_weight(700)); + add("italic", &|t| t.set_style(gtk4::pango::Style::Italic)); + add("strike", &|t| t.set_strikethrough(true)); + add("code", &|t| t.set_family(Some("monospace"))); + add("quote", &|t| { + t.set_style(gtk4::pango::Style::Italic); + t.set_left_margin(30); + }); + add("done", &|t| { + t.set_strikethrough(true); + t.set_foreground_rgba(Some(&gdk::RGBA::new(0.5, 0.5, 0.5, 1.0))); + }); + add("mark", &|t| t.set_foreground_rgba(Some(&gdk::RGBA::new(0.5, 0.5, 0.5, 1.0)))); + add("tag", &|t| t.set_foreground_rgba(Some(&gdk::RGBA::new(0.21, 0.52, 0.89, 1.0)))); +} + +/// Apply the Markdown styling to the whole buffer (notes are small). +fn restyle(buf: >k4::TextBuffer) { + buf.remove_all_tags(&buf.start_iter(), &buf.end_iter()); + let text = buf.text(&buf.start_iter(), &buf.end_iter(), false).to_string(); + let mut in_code = false; + for (n, line) in text.split('\n').enumerate() { + let Some(start) = buf.iter_at_line(n as i32) else { continue }; + let mut end = start; + if !end.ends_line() { + end.forward_to_line_end(); + } + let block = notes::block_of(line); + if block == Block::Code { + in_code = !in_code; + buf.apply_tag_by_name("code", &start, &end); + continue; + } + if in_code { + buf.apply_tag_by_name("code", &start, &end); + continue; + } + match block { + Block::Heading(1) => buf.apply_tag_by_name("h1", &start, &end), + Block::Heading(2) => buf.apply_tag_by_name("h2", &start, &end), + Block::Heading(_) => buf.apply_tag_by_name("h3", &start, &end), + Block::Quote => buf.apply_tag_by_name("quote", &start, &end), + Block::Task(true) => buf.apply_tag_by_name("done", &start, &end), + _ => {} + } + let at = |c: usize| { + let mut i = start; + i.forward_chars(c as i32); + i + }; + for (a, b, style) in notes::inline_spans(line) { + buf.apply_tag_by_name(style, &at(a), &at(b)); + } + // #tags + let chars: Vec = line.chars().collect(); + let mut i = 0; + while i < chars.len() { + if chars[i] == '#' && (i == 0 || chars[i - 1].is_whitespace()) { + let mut j = i + 1; + while j < chars.len() && (chars[j].is_alphanumeric() || chars[j] == '_' || chars[j] == '-') { + j += 1; + } + if j > i + 1 { + buf.apply_tag_by_name("tag", &at(i), &at(j)); + } + i = j; + } else { + i += 1; + } + } + } +} diff --git a/crates/menew-ui/src/popover.rs b/crates/menew-ui/src/popover.rs new file mode 100644 index 0000000..63fb8f7 --- /dev/null +++ b/crates/menew-ui/src/popover.rs @@ -0,0 +1,314 @@ +//! The tray popover (port of the menu bar popover: `NowView.swift`, `ActionsView.swift`, +//! `Favorites.swift`). A StatusNotifierItem menu can't hold custom views, so a left click on the +//! tray icon opens this small window with the same two tabs: Now (a search box for the palette, the +//! computer's health, running timers, world clocks, favorites) and Actions (favorites, then every +//! action in groups). + +use gtk4::gdk; +use gtk4::glib; +use gtk4::prelude::*; +use libadwaita as adw; +use libadwaita::prelude::*; +use menew_core::current_language; +use menew_core::strings::tr; +use std::cell::{Cell, RefCell}; +use std::rc::Rc; + +/// One action button: command id, title, freedesktop icon. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ActionEntry { + pub command: String, + pub title: String, + pub icon: String, +} + +/// What the Now tab shows, filled by the daemon. +#[derive(Debug, Clone, Default)] +pub struct NowData { + /// "All good" or what needs attention. + pub status: String, + /// (label, value) pills: CPU 12%, RAM 45%, Disk 120 GB, Battery 80%. + pub metrics: Vec<(String, String)>, + /// Running timers, focus, keep awake, paste queue. + pub running: Vec, + /// (city, time) + pub clocks: Vec<(String, String)>, +} + +pub struct Hooks { + pub run: Rc, + /// Open the palette with this text. + pub search: Rc, + /// The groups of actions: (group title, actions). + pub groups: Rc Vec<(String, Vec)>>, + pub favorites: Rc Vec>, + pub set_favorites: Rc)>, + pub now: Rc NowData>, + pub open_window: Rc, +} + +pub struct Popover { + window: adw::ApplicationWindow, + hooks: Hooks, + now_box: gtk4::Box, + now_favs: gtk4::FlowBox, + actions_box: gtk4::Box, + editing: Cell, + search: gtk4::SearchEntry, + stack: adw::ViewStack, + /// The groups as last shown (to find titles of favorites). + catalog: RefCell>, +} + +fn action_button(a: &ActionEntry) -> gtk4::Button { + let b = gtk4::Box::builder().orientation(gtk4::Orientation::Vertical).spacing(4).width_request(96).build(); + b.append(>k4::Image::builder().icon_name(&a.icon).pixel_size(22).build()); + b.append(>k4::Label::builder().label(&a.title).wrap(true).justify(gtk4::Justification::Center).max_width_chars(14).lines(2).ellipsize(gtk4::pango::EllipsizeMode::End).css_classes(["caption"]).build()); + gtk4::Button::builder().child(&b).css_classes(["flat", "menew-action"]).tooltip_text(&a.title).build() +} + +impl Popover { + pub fn new(app: &adw::Application, hooks: Hooks) -> Rc { + let lang = current_language(); + let window = adw::ApplicationWindow::builder().application(app).title("Menew").default_width(400).default_height(600).hide_on_close(true).build(); + let stack = adw::ViewStack::new(); + + // ---- Now ---- + let search = gtk4::SearchEntry::builder().placeholder_text(tr("pop_search", lang, &[])).build(); + let now_box = gtk4::Box::builder().orientation(gtk4::Orientation::Vertical).spacing(10).build(); + let now_favs = gtk4::FlowBox::builder().selection_mode(gtk4::SelectionMode::None).max_children_per_line(4).min_children_per_line(3).homogeneous(true).build(); + let now = gtk4::Box::builder().orientation(gtk4::Orientation::Vertical).spacing(12).margin_top(12).margin_bottom(12).margin_start(12).margin_end(12).build(); + now.append(&search); + now.append(&now_box); + now.append(>k4::Label::builder().label(tr("pop_favorites", lang, &[])).xalign(0.0).css_classes(["heading"]).build()); + now.append(&now_favs); + let now_scroll = gtk4::ScrolledWindow::builder().hscrollbar_policy(gtk4::PolicyType::Never).vexpand(true).child(&now).build(); + stack.add_titled_with_icon(&now_scroll, Some("now"), &tr("pop_now", lang, &[]), "go-home-symbolic"); + + // ---- Actions ---- + let actions_box = gtk4::Box::builder().orientation(gtk4::Orientation::Vertical).spacing(12).margin_top(12).margin_bottom(12).margin_start(12).margin_end(12).build(); + let actions_scroll = gtk4::ScrolledWindow::builder().hscrollbar_policy(gtk4::PolicyType::Never).vexpand(true).child(&actions_box).build(); + stack.add_titled_with_icon(&actions_scroll, Some("actions"), &tr("pop_actions", lang, &[]), "view-app-grid-symbolic"); + + let header = adw::HeaderBar::new(); + let switcher = adw::ViewSwitcher::builder().stack(&stack).policy(adw::ViewSwitcherPolicy::Wide).build(); + header.set_title_widget(Some(&switcher)); + let open = gtk4::Button::builder().icon_name("sidebar-show-symbolic").tooltip_text(tr("tray_open_window", lang, &[])).build(); + header.pack_end(&open); + let tv = adw::ToolbarView::new(); + tv.add_top_bar(&header); + tv.set_content(Some(&stack)); + window.set_content(Some(&tv)); + + let me = Rc::new(Self { window, hooks, now_box, now_favs, actions_box, editing: Cell::new(false), search, stack, catalog: RefCell::new(vec![]) }); + let w = Rc::downgrade(&me); + open.connect_clicked(move |_| { + if let Some(m) = w.upgrade() { + m.window.set_visible(false); + (m.hooks.open_window)(); + } + }); + let w = Rc::downgrade(&me); + me.search.connect_activate(move |e| { + if let Some(m) = w.upgrade() { + let t = e.text().to_string(); + e.set_text(""); + m.window.set_visible(false); + (m.hooks.search)(&t); + } + }); + let w = Rc::downgrade(&me); + me.search.connect_changed(move |e| { + // typing goes straight to the palette, like the Mac's Now tab search box + if let Some(m) = w.upgrade() { + let t = e.text().to_string(); + if !t.is_empty() { + e.set_text(""); + m.window.set_visible(false); + (m.hooks.search)(&t); + } + } + }); + let esc = gtk4::EventControllerKey::new(); + let w = Rc::downgrade(&me); + esc.connect_key_pressed(move |_, key, _, _| { + if key == gdk::Key::Escape { + if let Some(m) = w.upgrade() { + m.window.set_visible(false); + } + return glib::Propagation::Stop; + } + glib::Propagation::Proceed + }); + me.window.add_controller(esc); + // refresh the Now tab while it is open + let w = Rc::downgrade(&me); + glib::timeout_add_seconds_local(2, move || { + let Some(m) = w.upgrade() else { return glib::ControlFlow::Break }; + if m.window.is_visible() { + m.fill_now(); + } + glib::ControlFlow::Continue + }); + me + } + + pub fn is_visible(&self) -> bool { + self.window.is_visible() + } + + pub fn toggle(self: &Rc) { + if self.window.is_visible() { + self.window.set_visible(false); + } else { + self.show(); + } + } + + pub fn show(self: &Rc) { + self.rebuild(); + self.stack.set_visible_child_name("now"); + self.window.present(); + self.search.grab_focus(); + } + + /// Rebuild both tabs (the actions follow the state: mute, dark mode...). + pub fn rebuild(self: &Rc) { + let groups = (self.hooks.groups)(); + *self.catalog.borrow_mut() = groups.iter().flat_map(|g| g.1.clone()).collect(); + self.fill_now(); + self.fill_favorites(&self.now_favs, false); + self.fill_actions(&groups); + } + + fn run(self: &Rc, cmd: &str) { + self.window.set_visible(false); + (self.hooks.run)(cmd); + } + + fn fill_now(&self) { + let lang = current_language(); + while let Some(c) = self.now_box.first_child() { + self.now_box.remove(&c); + } + let d = (self.hooks.now)(); + self.now_box.append(>k4::Label::builder().label(&d.status).xalign(0.0).css_classes(["title-4"]).build()); + let pills = gtk4::Box::builder().spacing(6).homogeneous(true).build(); + for (k, v) in &d.metrics { + let p = gtk4::Box::builder().orientation(gtk4::Orientation::Vertical).css_classes(["card"]).build(); + p.append(>k4::Label::builder().label(v).css_classes(["heading", "numeric"]).margin_top(6).build()); + p.append(>k4::Label::builder().label(k).css_classes(["caption", "dim-label"]).margin_bottom(6).build()); + pills.append(&p); + } + self.now_box.append(&pills); + if !d.running.is_empty() { + for r in &d.running { + self.now_box.append(>k4::Label::builder().label(r).xalign(0.0).build()); + } + } + if !d.clocks.is_empty() { + self.now_box.append(>k4::Label::builder().label(tr("pop_clocks", lang, &[])).xalign(0.0).css_classes(["heading"]).build()); + let grid = gtk4::Box::builder().spacing(6).homogeneous(true).build(); + for (city, time) in d.clocks.iter().take(4) { + let c = gtk4::Box::builder().orientation(gtk4::Orientation::Vertical).css_classes(["card"]).build(); + c.append(>k4::Label::builder().label(time).css_classes(["heading", "numeric"]).margin_top(6).build()); + c.append(>k4::Label::builder().label(city).css_classes(["caption", "dim-label"]).ellipsize(gtk4::pango::EllipsizeMode::End).margin_bottom(6).build()); + grid.append(&c); + } + self.now_box.append(&grid); + } + } + + fn entry_for(&self, cmd: &str) -> Option { + self.catalog.borrow().iter().find(|a| a.command == cmd).cloned() + } + + fn fill_favorites(self: &Rc, flow: >k4::FlowBox, editing: bool) { + while let Some(c) = flow.first_child() { + flow.remove(&c); + } + for cmd in (self.hooks.favorites)() { + let Some(a) = self.entry_for(&cmd) else { continue }; + let b = action_button(&a); + let w = Rc::downgrade(self); + let c = cmd.clone(); + b.connect_clicked(move |_| { + let Some(m) = w.upgrade() else { return }; + if editing { + let mut f = (m.hooks.favorites)(); + f.retain(|x| *x != c); + (m.hooks.set_favorites)(f); + let m2 = Rc::clone(&m); + glib::idle_add_local_once(move || m2.rebuild()); + } else { + m.run(&c); + } + }); + if editing { + b.add_css_class("menew-editing"); + b.set_tooltip_text(Some(&tr("pop_remove_fav", current_language(), &[&a.title]))); + } + flow.append(&b); + } + } + + fn fill_actions(self: &Rc, groups: &[(String, Vec)]) { + let lang = current_language(); + while let Some(c) = self.actions_box.first_child() { + self.actions_box.remove(&c); + } + let editing = self.editing.get(); + let top = gtk4::Box::builder().spacing(6).build(); + top.append(>k4::Label::builder().label(tr("pop_favorites", lang, &[])).xalign(0.0).hexpand(true).css_classes(["heading"]).build()); + let edit = gtk4::ToggleButton::builder().label(tr(if editing { "pop_done" } else { "pop_edit" }, lang, &[])).active(editing).css_classes(["flat"]).build(); + let w = Rc::downgrade(self); + edit.connect_toggled(move |b| { + if let Some(m) = w.upgrade() { + m.editing.set(b.is_active()); + let m2 = Rc::clone(&m); + glib::idle_add_local_once(move || m2.rebuild()); + } + }); + top.append(&edit); + self.actions_box.append(&top); + let favs = gtk4::FlowBox::builder().selection_mode(gtk4::SelectionMode::None).max_children_per_line(4).min_children_per_line(3).homogeneous(true).build(); + self.fill_favorites(&favs, editing); + self.actions_box.append(&favs); + if editing { + self.actions_box.append(>k4::Label::builder().label(tr("pop_edit_hint", lang, &[])).wrap(true).xalign(0.0).css_classes(["dim-label", "caption"]).build()); + } + let current = (self.hooks.favorites)(); + for (title, items) in groups { + if items.is_empty() { + continue; + } + let exp = gtk4::Expander::builder().label(title).expanded(true).build(); + let flow = gtk4::FlowBox::builder().selection_mode(gtk4::SelectionMode::None).max_children_per_line(4).min_children_per_line(3).homogeneous(true).build(); + for a in items { + if editing && current.contains(&a.command) { + continue; + } + let b = action_button(a); + let w = Rc::downgrade(self); + let c = a.command.clone(); + b.connect_clicked(move |_| { + let Some(m) = w.upgrade() else { return }; + if m.editing.get() { + let mut f = (m.hooks.favorites)(); + if !f.contains(&c) { + f.push(c.clone()); + } + (m.hooks.set_favorites)(f); + let m2 = Rc::clone(&m); + glib::idle_add_local_once(move || m2.rebuild()); + } else { + m.run(&c); + } + }); + flow.append(&b); + } + exp.set_child(Some(&flow)); + self.actions_box.append(&exp); + } + } +} diff --git a/crates/menew-ui/src/settings.rs b/crates/menew-ui/src/settings.rs new file mode 100644 index 0000000..cf18130 --- /dev/null +++ b/crates/menew-ui/src/settings.rs @@ -0,0 +1,252 @@ +//! The Settings section (port of `SettingsWindow.swift`): general (language, start at login, +//! turning features off completely, updates, the welcome tour), clipboard, world clocks, focus, +//! quick actions and the global shortcuts. Every change is saved to `config.json` right away. + +use crate::window; +use gtk4::prelude::*; +use libadwaita as adw; +use libadwaita::prelude::*; +use menew_core::config::Config; +use menew_core::strings::tr; +use menew_core::{current_language, time_zones, PasteMode}; +use std::cell::RefCell; +use std::rc::Rc; + +pub struct SettingsHooks { + /// Called after the config changed and was saved (the daemon applies it). + pub changed: Rc, + /// The language changed: offer to restart. + pub language: Rc, + pub check_updates: Rc, + pub welcome: Rc, + /// The global shortcuts: (description, trigger, command for a custom system shortcut). + pub shortcuts: Vec<(String, String, String)>, + /// Whether the Menew GNOME extension answers (`None` on other desktops). + pub gnome_extension: Option, +} + +type Refill = Rc>>>; + +pub struct SettingsView { + pub root: gtk4::Widget, +} + +const LANGS: [(&str, &str); 6] = [("system", ""), ("en", "English"), ("pt", "Português"), ("de", "Deutsch"), ("es", "Español"), ("zh", "中文")]; + +fn save(cfg: &Rc>, hooks: &Rc) { + let c = cfg.borrow().clone(); + if let Err(e) = c.save_to(&Config::default_path()) { + tracing::warn!("Settings: could not save config.json: {}", e); + } + (hooks.changed)(&c); +} + +fn switch(group: &adw::PreferencesGroup, title: &str, sub: Option<&str>, on: bool, f: impl Fn(bool) + 'static) -> adw::SwitchRow { + let row = adw::SwitchRow::builder().title(title).active(on).build(); + if let Some(s) = sub { + row.set_subtitle(s); + } + row.connect_active_notify(move |r| f(r.is_active())); + group.add(&row); + row +} + +impl SettingsView { + pub fn new(hooks: SettingsHooks) -> Rc { + let lang = current_language(); + let hooks = Rc::new(hooks); + let cfg = Rc::new(RefCell::new(Config::load())); + let (scroll, body) = window::page(); + + // ---- General ---- + let g = adw::PreferencesGroup::builder().title(tr("set_general", lang, &[])).build(); + let names: Vec = LANGS.iter().map(|(c, n)| if *c == "system" { tr("set_lang_system", lang, &[]) } else { n.to_string() }).collect(); + let model = gtk4::StringList::new(&names.iter().map(String::as_str).collect::>()); + let lang_row = adw::ComboRow::builder().title(tr("set_language", lang, &[])).model(&model).build(); + let cur = cfg.borrow().language.clone(); + lang_row.set_selected(LANGS.iter().position(|(c, _)| *c == cur).unwrap_or(0) as u32); + let (c, h) = (Rc::clone(&cfg), Rc::clone(&hooks)); + lang_row.connect_selected_notify(move |r| { + let code = LANGS.get(r.selected() as usize).map(|l| l.0).unwrap_or("system"); + c.borrow_mut().language = code.to_string(); + save(&c, &h); + (h.language)(); + }); + g.add(&lang_row); + switch(&g, &tr("tray_start_at_login_r1", lang, &[]), None, menew_core::autostart::is_enabled(), |on| { + let _ = menew_core::autostart::set_enabled(on); + }); + let (c, h) = (Rc::clone(&cfg), Rc::clone(&hooks)); + let upd = switch(&g, &tr("set_updates", lang, &[]), Some(&tr("set_updates_sub", lang, &[])), cfg.borrow().update_check, move |on| { + c.borrow_mut().update_check = on; + save(&c, &h); + }); + let check = gtk4::Button::builder().label(tr("set_check_now", lang, &[])).valign(gtk4::Align::Center).css_classes(["flat"]).build(); + let h = Rc::clone(&hooks); + check.connect_clicked(move |_| (h.check_updates)()); + upd.add_suffix(&check); + let tour = adw::ActionRow::builder().title(tr("set_welcome", lang, &[])).activatable(true).build(); + tour.add_suffix(>k4::Image::from_icon_name("go-next-symbolic")); + let h = Rc::clone(&hooks); + tour.connect_activated(move |_| (h.welcome)()); + g.add(&tour); + body.append(&g); + + // ---- Features ---- + let g = adw::PreferencesGroup::builder().title(tr("set_modules", lang, &[])).description(tr("set_modules_sub", lang, &[])).build(); + for (key, sub, get, set) in [ + ("set_mod_clipboard", "set_mod_clipboard_sub", (|c: &Config| c.module_clipboard) as fn(&Config) -> bool, (|c: &mut Config, v| c.module_clipboard = v) as fn(&mut Config, bool)), + ("set_mod_actions", "set_mod_actions_sub", |c: &Config| c.module_actions, |c: &mut Config, v| c.module_actions = v), + ("set_mod_notes", "set_mod_notes_sub", |c: &Config| c.module_notes, |c: &mut Config, v| c.module_notes = v), + ] { + let (c, h) = (Rc::clone(&cfg), Rc::clone(&hooks)); + let on = get(&cfg.borrow()); + switch(&g, &tr(key, lang, &[]), Some(&tr(sub, lang, &[])), on, move |v| { + set(&mut c.borrow_mut(), v); + save(&c, &h); + }); + } + body.append(&g); + + // ---- Clipboard ---- + let g = adw::PreferencesGroup::builder().title(tr("kind_clip", lang, &[])).build(); + let (c, h) = (Rc::clone(&cfg), Rc::clone(&hooks)); + switch(&g, &tr("set_paste_auto", lang, &[]), Some(&tr("set_paste_auto_sub", lang, &[])), cfg.borrow().paste_mode == PasteMode::Auto, move |on| { + c.borrow_mut().paste_mode = if on { PasteMode::Auto } else { PasteMode::CopyOnly }; + save(&c, &h); + }); + let (c, h) = (Rc::clone(&cfg), Rc::clone(&hooks)); + switch(&g, &tr("set_clip_ocr", lang, &[]), Some(&tr("set_clip_ocr_sub", lang, &[])), cfg.borrow().clipboard_ocr, move |on| { + c.borrow_mut().clipboard_ocr = on; + save(&c, &h); + }); + let size = adw::SpinRow::with_range(20.0, 5000.0, 10.0); + size.set_title(&tr("set_clip_max", lang, &[])); + size.set_value(cfg.borrow().clipboard_max_items as f64); + let (c, h) = (Rc::clone(&cfg), Rc::clone(&hooks)); + size.connect_value_notify(move |r| { + c.borrow_mut().clipboard_max_items = r.value() as usize; + save(&c, &h); + }); + g.add(&size); + let days = adw::SpinRow::with_range(0.0, 365.0, 1.0); + days.set_title(&tr("set_clip_days", lang, &[])); + days.set_subtitle(&tr("set_clip_days_sub", lang, &[])); + days.set_value(cfg.borrow().clipboard_auto_delete_days as f64); + let (c, h) = (Rc::clone(&cfg), Rc::clone(&hooks)); + days.connect_value_notify(move |r| { + c.borrow_mut().clipboard_auto_delete_days = r.value() as u32; + save(&c, &h); + }); + g.add(&days); + let ignored = adw::EntryRow::builder().title(tr("set_clip_ignored", lang, &[])).text(cfg.borrow().clipboard_ignored_apps.join(", ")).show_apply_button(true).build(); + let (c, h) = (Rc::clone(&cfg), Rc::clone(&hooks)); + ignored.connect_apply(move |e| { + c.borrow_mut().clipboard_ignored_apps = e.text().split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect(); + save(&c, &h); + }); + g.add(&ignored); + g.add(&adw::ActionRow::builder().title(tr("set_clip_ignored_sub", lang, &[])).css_classes(["dim-label"]).build()); + if let Some(on) = hooks.gnome_extension { + let row = adw::ActionRow::builder().title(tr("set_gnome_ext", lang, &[])).subtitle(tr(if on { "set_gnome_ext_on" } else { "set_gnome_ext_off" }, lang, &[])).build(); + row.add_prefix(>k4::Image::from_icon_name(if on { "emblem-ok-symbolic" } else { "dialog-warning-symbolic" })); + g.add(&row); + } + body.append(&g); + + // ---- World clocks ---- + let g = adw::PreferencesGroup::builder().title(tr("set_clocks", lang, &[])).description(tr("set_clocks_sub", lang, &[])).build(); + let list = gtk4::ListBox::builder().css_classes(["boxed-list"]).selection_mode(gtk4::SelectionMode::None).build(); + let refill: Refill = Rc::new(RefCell::new(None)); + { + let (c, h, l, rf) = (Rc::clone(&cfg), Rc::clone(&hooks), list.clone(), Rc::clone(&refill)); + let f: Rc = Rc::new(move || { + while let Some(ch) = l.first_child() { + l.remove(&ch); + } + for id in c.borrow().world_clocks.clone() { + let row = adw::ActionRow::builder().title(id.rsplit('/').next().unwrap_or(&id).replace('_', " ")).subtitle(&id).build(); + let b = gtk4::Button::builder().icon_name("list-remove-symbolic").valign(gtk4::Align::Center).css_classes(["flat"]).build(); + let (c2, h2, rf2) = (Rc::clone(&c), Rc::clone(&h), Rc::clone(&rf)); + b.connect_clicked(move |_| { + c2.borrow_mut().world_clocks.retain(|x| *x != id); + save(&c2, &h2); + if let Some(f) = rf2.borrow().clone() { + f(); + } + }); + row.add_suffix(&b); + l.append(&row); + } + }); + *refill.borrow_mut() = Some(Rc::clone(&f)); + f(); + } + g.add(&list); + let add = adw::EntryRow::builder().title(tr("set_clock_add", lang, &[])).show_apply_button(true).build(); + let (c, h, rf) = (Rc::clone(&cfg), Rc::clone(&hooks), Rc::clone(&refill)); + add.connect_apply(move |e| { + let text = e.text().to_string(); + let found = time_zones::named_zone(text.trim()).or_else(|| time_zones::zone(text.trim())); + if let Some(time_zones::Zone::Named(id)) = found { + if !c.borrow().world_clocks.contains(&id) { + c.borrow_mut().world_clocks.push(id); + save(&c, &h); + } + e.set_text(""); + if let Some(f) = rf.borrow().clone() { + f(); + } + } else { + e.add_css_class("error"); + } + }); + g.add(&add); + body.append(&g); + + // ---- Focus and actions ---- + let g = adw::PreferencesGroup::builder().title(tr("set_focus_actions", lang, &[])).build(); + let (c, h) = (Rc::clone(&cfg), Rc::clone(&hooks)); + switch(&g, &tr("set_focus_breaks", lang, &[]), None, cfg.borrow().focus_breaks, move |on| { + c.borrow_mut().focus_breaks = on; + save(&c, &h); + }); + for (key, get, set) in [ + ("set_focus_mute", (|c: &Config| c.focus_mute_mic) as fn(&Config) -> bool, (|c: &mut Config, v| c.focus_mute_mic = v) as fn(&mut Config, bool)), + ("set_focus_awake", |c: &Config| c.focus_keep_awake, |c: &mut Config, v| c.focus_keep_awake = v), + ("set_focus_pause", |c: &Config| c.focus_pause_clipboard, |c: &mut Config, v| c.focus_pause_clipboard = v), + ] { + let (c, h) = (Rc::clone(&cfg), Rc::clone(&hooks)); + let on = get(&cfg.borrow()); + switch(&g, &tr(key, lang, &[]), None, on, move |v| { + set(&mut c.borrow_mut(), v); + save(&c, &h); + }); + } + let never = adw::EntryRow::builder().title(tr("set_never_quit", lang, &[])).text(cfg.borrow().never_quit.join(", ")).show_apply_button(true).build(); + let (c, h) = (Rc::clone(&cfg), Rc::clone(&hooks)); + never.connect_apply(move |e| { + c.borrow_mut().never_quit = e.text().split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect(); + save(&c, &h); + }); + g.add(&never); + body.append(&g); + + // ---- Shortcuts ---- + let g = adw::PreferencesGroup::builder().title(tr("set_shortcuts", lang, &[])).description(tr("set_shortcuts_sub", lang, &[])).build(); + for (desc, trigger, cmd) in &hooks.shortcuts { + let row = adw::ActionRow::builder().title(desc).subtitle(cmd).subtitle_selectable(true).build(); + row.add_suffix(>k4::Label::builder().label(trigger).css_classes(["dim-label", "monospace"]).build()); + g.add(&row); + } + body.append(&g); + + // ---- Privacy ---- + let g = adw::PreferencesGroup::builder().title(tr("set_privacy", lang, &[])).build(); + g.add(&adw::ActionRow::builder().title(tr("set_privacy_body", lang, &[])).title_lines(0).build()); + g.add(&adw::ActionRow::builder().title(tr("set_config_file", lang, &[])).subtitle(Config::default_path().display().to_string()).subtitle_selectable(true).build()); + body.append(&g); + + Rc::new(Self { root: scroll.upcast() }) + } +} diff --git a/crates/menew-ui/src/window.rs b/crates/menew-ui/src/window.rs new file mode 100644 index 0000000..7ba0384 --- /dev/null +++ b/crates/menew-ui/src/window.rs @@ -0,0 +1,160 @@ +//! The Menew window (port of `MenewWindow.swift`): a sidebar like GNOME Settings with the sections +//! (Overview, Notes, Performance, Settings...), each a page built by its own module and handed in by +//! the daemon. Closing the window only hides it; Menew keeps running in the tray. + +use gtk4::glib; +use gtk4::prelude::*; +use libadwaita as adw; +use libadwaita::prelude::*; +use std::cell::RefCell; +use std::rc::Rc; + +/// One section of the sidebar. +pub struct Section { + pub id: &'static str, + pub title: String, + pub icon: &'static str, + pub page: gtk4::Widget, + /// Extra buttons for the header bar of this section. + pub header: Vec, + /// Called each time the section is shown (refresh its data). + pub on_show: Option>, +} + +pub struct MenewWindow { + window: adw::ApplicationWindow, + split: adw::NavigationSplitView, + list: gtk4::ListBox, + stack: gtk4::Stack, + content_page: adw::NavigationPage, + header: adw::HeaderBar, + sections: RefCell>, + header_widgets: RefCell>, +} + +impl MenewWindow { + pub fn new(app: &adw::Application, sections: Vec
) -> Rc { + let window = adw::ApplicationWindow::builder().application(app).title("Menew").default_width(980).default_height(680).hide_on_close(true).build(); + window.set_size_request(360, 400); + + let list = gtk4::ListBox::builder().css_classes(["navigation-sidebar"]).selection_mode(gtk4::SelectionMode::Single).build(); + for s in §ions { + let row = gtk4::Box::builder().spacing(12).margin_top(8).margin_bottom(8).margin_start(6).margin_end(6).build(); + row.append(>k4::Image::from_icon_name(s.icon)); + row.append(>k4::Label::builder().label(&s.title).xalign(0.0).hexpand(true).build()); + list.append(&row); + } + let side_scroll = gtk4::ScrolledWindow::builder().hscrollbar_policy(gtk4::PolicyType::Never).vexpand(true).child(&list).build(); + let side_toolbar = adw::ToolbarView::new(); + side_toolbar.add_top_bar(&adw::HeaderBar::builder().title_widget(&adw::WindowTitle::new("Menew", "")).build()); + side_toolbar.set_content(Some(&side_scroll)); + let sidebar = adw::NavigationPage::builder().title("Menew").child(&side_toolbar).build(); + + let stack = gtk4::Stack::builder().transition_type(gtk4::StackTransitionType::Crossfade).hhomogeneous(false).vhomogeneous(false).build(); + for s in §ions { + stack.add_named(&s.page, Some(s.id)); + } + let header = adw::HeaderBar::new(); + let content_toolbar = adw::ToolbarView::new(); + content_toolbar.add_top_bar(&header); + content_toolbar.set_content(Some(&stack)); + let content_page = adw::NavigationPage::builder().title(sections.first().map(|s| s.title.as_str()).unwrap_or("Menew")).tag("content").child(&content_toolbar).build(); + + let split = adw::NavigationSplitView::builder().sidebar(&sidebar).content(&content_page).min_sidebar_width(200.0).max_sidebar_width(260.0).build(); + window.set_content(Some(&split)); + + // narrow windows collapse the sidebar (phones, tiled halves) + let bp = adw::Breakpoint::new(adw::BreakpointCondition::new_length(adw::BreakpointConditionLengthType::MaxWidth, 600.0, adw::LengthUnit::Sp)); + bp.add_setter(&split, "collapsed", Some(&true.to_value())); + window.add_breakpoint(bp); + + let me = Rc::new(Self { window, split, list, stack, content_page, header, sections: RefCell::new(sections), header_widgets: RefCell::new(vec![]) }); + let weak = Rc::downgrade(&me); + me.list.connect_row_selected(move |_, row| { + if let (Some(me), Some(row)) = (weak.upgrade(), row) { + me.activate_index(row.index() as usize); + } + }); + if let Some(r) = me.list.row_at_index(0) { + me.list.select_row(Some(&r)); + } + me + } + + fn activate_index(&self, i: usize) { + let (id, title, on_show, header) = { + let s = self.sections.borrow(); + let Some(sec) = s.get(i) else { return }; + (sec.id, sec.title.clone(), sec.on_show.clone(), sec.header.clone()) + }; + self.stack.set_visible_child_name(id); + self.content_page.set_title(&title); + for w in self.header_widgets.borrow_mut().drain(..) { + self.header.remove(&w); + } + for w in header { + self.header.pack_end(&w); + self.header_widgets.borrow_mut().push(w); + } + self.split.set_show_content(true); + if let Some(f) = on_show { + f(); + } + } + + /// Open the window on a section (`notes`, `performance`, `settings`...). + pub fn show_section(&self, id: &str) { + let idx = self.sections.borrow().iter().position(|s| s.id == id); + if let Some(i) = idx { + if let Some(row) = self.list.row_at_index(i as i32) { + if self.list.selected_row().as_ref() == Some(&row) { + self.activate_index(i); + } else { + self.list.select_row(Some(&row)); + } + } + } + self.present(); + } + + /// Show or hide a section in the sidebar (a feature turned off). + pub fn set_section_visible(&self, id: &str, visible: bool) { + let idx = self.sections.borrow().iter().position(|s| s.id == id); + if let Some(r) = idx.and_then(|i| self.list.row_at_index(i as i32)) { + r.set_visible(visible); + } + } + + pub fn present(&self) { + self.window.set_visible(true); + self.window.present(); + } + + pub fn visible_section(&self) -> Option { + self.window.is_visible().then(|| self.stack.visible_child_name().map(|s| s.to_string())).flatten() + } + + pub fn window(&self) -> &adw::ApplicationWindow { + &self.window + } + + /// Run `f` every `secs` while the window shows section `id` (live graphs). + pub fn every(self: &Rc, id: &'static str, secs: u32, f: impl Fn() + 'static) { + let weak = Rc::downgrade(self); + glib::timeout_add_seconds_local(secs, move || { + let Some(me) = weak.upgrade() else { return glib::ControlFlow::Break }; + if me.visible_section().as_deref() == Some(id) { + f(); + } + glib::ControlFlow::Continue + }); + } +} + +/// A titled group of rows (`adw::PreferencesGroup`) inside a scrolling, centered page. +pub fn page() -> (gtk4::ScrolledWindow, gtk4::Box) { + let body = gtk4::Box::builder().orientation(gtk4::Orientation::Vertical).spacing(18).margin_top(18).margin_bottom(24).margin_start(12).margin_end(12).build(); + let clamp = adw::Clamp::builder().maximum_size(820).child(&body).build(); + let scroll = gtk4::ScrolledWindow::builder().hscrollbar_policy(gtk4::PolicyType::Never).vexpand(true).child(&clamp).build(); + (scroll, body) +} diff --git a/crates/menew/src/app_window.rs b/crates/menew/src/app_window.rs new file mode 100644 index 0000000..0e35f81 --- /dev/null +++ b/crates/menew/src/app_window.rs @@ -0,0 +1,72 @@ +//! Builds the Menew window with its sections and connects them to the palette commands +//! (`note.*`, `open.*`). + +use crate::commands::Commands; +use libadwaita as adw; +use menew_core::notes::{self, NotesStore}; +use menew_core::strings::tr; +use menew_core::current_language; +use menew_ui::notes::NotesView; +use menew_ui::window::{MenewWindow, Section}; +use std::cell::RefCell; +use std::rc::Rc; + +pub struct AppWindow { + pub window: Rc, + pub notes: Rc, +} + +/// Extra sections from the other modules (performance, settings, overview), built before the window. +pub type SectionFactory = Box Section>; + +pub fn setup(app: &adw::Application, cmds: &Rc, palette: &Rc, before: Vec, after: Vec) -> Rc { + let lang = current_language(); + let store = Rc::new(RefCell::new(NotesStore::open_default())); + let notes_view = NotesView::new(Rc::clone(&store)); + let mut sections: Vec
= before.into_iter().map(|f| f()).collect(); + let nv = Rc::clone(¬es_view); + sections.push(Section { + id: "notes", + title: tr("note_open_all", lang, &[]), + icon: "accessories-text-editor-symbolic", + page: notes_view.root.clone(), + header: notes_view.header.clone(), + on_show: Some(Rc::new(move || nv.refresh())), + }); + sections.extend(after.into_iter().map(|f| f())); + let window = MenewWindow::new(app, sections); + let me = Rc::new(AppWindow { window, notes: notes_view }); + + // palette items for the notes + let s = Rc::clone(&store); + cmds.add_provider("notes", Rc::new(move |raw, lang| notes::palette_items(&s.borrow(), raw, lang))); + + let m = Rc::clone(&me); + let p = Rc::clone(palette); + cmds.add_runner(Rc::new(move |cmd| { + let (name, arg) = cmd.split_once(':').map(|(a, b)| (a, Some(b))).unwrap_or((cmd, None)); + match name { + "note.new" | "note.newpasswords" => { + p.hide(); + m.window.show_section("notes"); + m.notes.new_note(name == "note.newpasswords"); + true + } + "note.open" => { + p.hide(); + m.window.show_section("notes"); + if let Some(id) = arg { + m.notes.select(id); + } + true + } + _ if name.starts_with("open.") => { + p.hide(); + m.window.show_section(&name[5..]); + true + } + _ => false, + } + })); + me +} diff --git a/crates/menew/src/capture.rs b/crates/menew/src/capture.rs new file mode 100644 index 0000000..62da389 --- /dev/null +++ b/crates/menew/src/capture.rs @@ -0,0 +1,134 @@ +//! Screenshot commands (`cap.*`): capture through the portal, then the editor, the screen text or +//! the QR code reader; and the QR code window. + +use crate::commands::Commands; +use gtk4::gio; +use gtk4::glib; +use libadwaita as adw; +use menew_core::strings::tr; +use menew_core::{capture, current_language, ocr}; +use std::path::PathBuf; +use std::rc::Rc; +use std::sync::Arc; +use tracing::{info, warn}; + +fn notify(palette: &menew_ui::PaletteWindow, key: &str, args: &[&str]) { + palette.notify("menew-capture", &tr(key, current_language(), args), None); +} + +/// Read the text of an image and copy it. +fn copy_text_of(palette: Rc, path: PathBuf, delete_after: bool) { + glib::spawn_future_local(async move { + if !ocr::available() { + notify(&palette, "cap_ocr_missing", &[]); + return; + } + let p = path.clone(); + let text = gio::spawn_blocking(move || ocr::recognize(&p)).await; + if delete_after { + let _ = std::fs::remove_file(&path); + } + match text { + Ok(Ok(t)) if !t.trim().is_empty() => { + palette.copy_to_clipboard(t.trim()); + notify(&palette, "cap_ocr_done", &[]); + } + Ok(Err(e)) => { + warn!("OCR: {}", e); + notify(&palette, "cap_ocr_none", &[]); + } + _ => notify(&palette, "cap_ocr_none", &[]), + } + }); +} + +fn show_qr(app: &adw::Application, palette: &menew_ui::PaletteWindow, text: &str, caption: &str) { + match capture::make_qr_png(text) { + Some(png) => menew_ui::annotate::show_qr(app, &png, caption), + None => notify(palette, "cap_qr_make_missing", &[]), + } +} + +pub fn setup(app: &adw::Application, cmds: &Rc, palette: &Rc, rt: Arc) { + let p = Rc::clone(palette); + cmds.add_provider("actions", Rc::new(move |raw, lang| capture::palette_items(raw, p.clipboard_text_now().as_deref(), lang))); + let app = app.clone(); + let p = Rc::clone(palette); + cmds.add_runner(Rc::new(move |cmd| { + let (name, arg) = cmd.split_once(':').map(|(a, b)| (a, Some(b))).unwrap_or((cmd, None)); + match name { + "cap.area" | "cap.full" | "cap.ocr" | "cap.qr" => { + p.hide(); + let interactive = name != "cap.full"; + let what = name.to_string(); + let (app, p, rt) = (app.clone(), Rc::clone(&p), Arc::clone(&rt)); + // let the palette disappear before the desktop takes the picture + glib::timeout_add_local_once(std::time::Duration::from_millis(300), move || { + let job = rt.spawn(menew_desktop::screenshot(interactive)); + glib::spawn_future_local(async move { + let path = match job.await { + Ok(Ok(path)) => path, + Ok(Err(e)) => { + warn!("Screenshot: {}", e); + notify(&p, "cap_failed", &[]); + return; + } + Err(_) => return, + }; + info!("Screenshot at {}", path.display()); + match what.as_str() { + "cap.ocr" => copy_text_of(Rc::clone(&p), path, true), + "cap.qr" => { + let p2 = path.clone(); + let codes = gio::spawn_blocking(move || capture::read_codes(&p2)).await.ok().flatten(); + let _ = std::fs::remove_file(&path); + match codes { + None => notify(&p, "cap_qr_missing", &[]), + Some(c) if c.is_empty() => notify(&p, "cap_qr_none", &[]), + Some(c) => { + let first = c[0].clone(); + if first.starts_with("http://") || first.starts_with("https://") { + p.open_uri(&first); + } + p.copy_to_clipboard(&first); + notify(&p, "cap_qr_found", &[&first]); + } + } + } + _ => { + let p2 = Rc::clone(&p); + menew_ui::annotate::open_editor(&app, &path, Rc::new(move |img| copy_text_of(Rc::clone(&p2), img, false))); + } + } + }); + }); + true + } + "cap.edit" => { + // open the editor on an image file (`menew run cap.edit:/path/shot.png`) + let path = PathBuf::from(arg.unwrap_or_default()); + let p2 = Rc::clone(&p); + menew_ui::annotate::open_editor(&app, &path, Rc::new(move |img| copy_text_of(Rc::clone(&p2), img, false))); + true + } + "cap.qrshow" => { + let text = arg.unwrap_or_default(); + p.hide(); + show_qr(&app, &p, text, text); + true + } + "cap.qrwifi" => { + p.hide(); + let (app, p) = (app.clone(), Rc::clone(&p)); + glib::spawn_future_local(async move { + match gio::spawn_blocking(capture::current_wifi).await.ok().flatten() { + Some((ssid, psk)) => show_qr(&app, &p, &capture::wifi_qr_text(&ssid, psk.as_deref()), &ssid), + None => notify(&p, "cap_qr_wifi_none", &[]), + } + }); + true + } + _ => false, + } + })); +} diff --git a/crates/menew/src/focus_hooks.rs b/crates/menew/src/focus_hooks.rs new file mode 100644 index 0000000..49138ba --- /dev/null +++ b/crates/menew/src/focus_hooks.rs @@ -0,0 +1,57 @@ +//! What a focus session turns on and back off (`Focus.swift`): mute the microphone, keep the +//! computer awake and pause the clipboard, as chosen in Settings. Only what the focus changed is +//! undone at the end. + +use crate::commands::Commands; +use menew_core::focus::FocusHooks; +use menew_core::quick_actions as qa; +use menew_core::Config; +use std::rc::Rc; + +pub struct DaemonFocusHooks { + pub cmds: Rc, + pub pause: Rc)>, + pub resume: Rc, + pub is_paused: Rc bool>, + muted: bool, + awake: bool, + paused: bool, +} + +impl DaemonFocusHooks { + pub fn new(cmds: Rc, pause: Rc)>, resume: Rc, is_paused: Rc bool>) -> Self { + Self { cmds, pause, resume, is_paused, muted: false, awake: false, paused: false } + } +} + +fn now() -> f64 { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs_f64()).unwrap_or(0.0) +} + +impl FocusHooks for DaemonFocusHooks { + fn started(&mut self, minutes: u32) { + let cfg = Config::load(); + if cfg.focus_mute_mic && qa::is_muted(true) == Some(false) { + self.muted = qa::toggle_mute(true) == Some(true); + } + if cfg.focus_keep_awake && !self.cmds.awake.borrow_mut().is_on() { + self.awake = self.cmds.awake.borrow_mut().start(Some(minutes), now(), "Focus"); + } + if cfg.focus_pause_clipboard && cfg.module_clipboard && !(self.is_paused)() { + (self.pause)(Some(minutes)); + self.paused = true; + } + } + + fn ended(&mut self) { + if std::mem::take(&mut self.muted) && qa::is_muted(true) == Some(true) { + qa::toggle_mute(true); + } + if std::mem::take(&mut self.awake) { + self.cmds.awake.borrow_mut().stop(); + } + if std::mem::take(&mut self.paused) { + (self.resume)(); + } + } +} diff --git a/crates/menew/src/monitor.rs b/crates/menew/src/monitor.rs new file mode 100644 index 0000000..2d448d2 --- /dev/null +++ b/crates/menew/src/monitor.rs @@ -0,0 +1,101 @@ +//! Samples the system every 2 s for the tray metrics, the Performance section and the popover. + +use crate::commands::Commands; +use gtk4::glib; +use menew_core::palette::{Icon, ItemAction, Kind, PaletteItem}; +use menew_core::strings::tr; +use menew_core::sysmon::{self, Monitor, Snapshot}; +use menew_core::{current_language, Config}; +use menew_ui::monitor::MonitorView; +use std::cell::RefCell; +use std::rc::Rc; + +/// Called after each sample (the popover's Now tab). +pub type SampleListener = Rc; + +pub struct Sampler { + monitor: RefCell, + pub last: RefCell, + pub view: Rc, + metrics: RefCell>, + /// The tray text for the chosen metrics, read by the daemon's status push. + pub tray_text: Rc>, + /// Whether to read the processes too (the Performance section or the popover is open). + pub detail_check: RefCell bool>>>, + listeners: RefCell>, +} + +fn secs() -> f64 { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs_f64()).unwrap_or(0.0) +} + +impl Sampler { + pub fn new(cmds: &Rc, push: Rc, tray_text: Rc>) -> Rc { + let cfg = Config::load(); + let metrics_cell: Rc>>> = Rc::new(RefCell::new(None)); + let mc = Rc::clone(&metrics_cell); + let push2 = Rc::clone(&push); + let view = MonitorView::new( + Rc::new(|pid| { + menew_core::sys::signal(pid, 15); + }), + cfg.tray_metrics.clone(), + Rc::new(move |m: Vec| { + let mut c = Config::load(); + c.tray_metrics = m.clone(); + let _ = c.save_to(&Config::default_path()); + if let Some(s) = mc.borrow().as_ref() { + *s.metrics.borrow_mut() = m; + s.update_tray(); + push2(); + } + }), + ); + let me = Rc::new(Self { + monitor: RefCell::new(Monitor::default()), + last: RefCell::new(Snapshot::default()), + view, + metrics: RefCell::new(cfg.tray_metrics), + tray_text, + detail_check: RefCell::new(None), + listeners: RefCell::new(vec![]), + }); + *metrics_cell.borrow_mut() = Some(Rc::clone(&me)); + me.sample(); + let w = Rc::downgrade(&me); + glib::timeout_add_seconds_local(2, move || { + let Some(s) = w.upgrade() else { return glib::ControlFlow::Break }; + s.sample(); + push(); + glib::ControlFlow::Continue + }); + cmds.add_provider("always", Rc::new(|_raw, lang| { + vec![PaletteItem::new("action.performance", Kind::Action, &tr("mon_open", lang, &[])) + .subtitle(&tr("mon_open_sub", lang, &[])) + .kw("desempenho performance cpu memória memory ram processos processes monitor sistema system leistung rendimiento 性能 task manager") + .icon(Icon::Symbol("computer-symbolic")) + .act(ItemAction::Command("open.performance".into()))] + })); + me + } + + fn update_tray(&self) { + let lang = current_language(); + *self.tray_text.borrow_mut() = sysmon::tray_text(&self.last.borrow(), &self.metrics.borrow(), lang); + } + + pub fn sample(&self) { + let detailed = self.detail_check.borrow().as_ref().map(|f| f()).unwrap_or(false); + let snap = self.monitor.borrow_mut().sample(secs(), detailed); + *self.last.borrow_mut() = snap; + self.update_tray(); + let s = self.last.borrow().clone(); + if detailed { + self.view.update(&s); + } + let ls = self.listeners.borrow().clone(); + for l in ls { + l(&s); + } + } +} diff --git a/crates/menew/src/shell.rs b/crates/menew/src/shell.rs new file mode 100644 index 0000000..681e5c9 --- /dev/null +++ b/crates/menew/src/shell.rs @@ -0,0 +1,224 @@ +//! The tray popover, the Settings and Clipboard sections, the welcome tour, the update check and the +//! features that can be turned off. + +use crate::alerts; +use crate::commands::Commands; +use crate::monitor::Sampler; +use gtk4::gio; +use gtk4::glib; +use gtk4::prelude::*; +use libadwaita as adw; +use menew_core::palette::ItemAction; +use menew_core::strings::tr; +use menew_core::sysmon; +use menew_core::time_zones::{self, TzCtx}; +use menew_core::{current_language, updates, Config}; +use menew_ui::popover::{ActionEntry, Hooks, NowData, Popover}; +use menew_ui::window::Section; +use std::rc::Rc; +use tracing::{info, warn}; + +fn now_secs() -> u64 { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0) +} + +/// The group of a command id in the Actions tab. +pub fn group_of(cmd: &str) -> &'static str { + let name = cmd.split(':').next().unwrap_or(cmd); + match name { + _ if name.starts_with("cap.") => "grp_screen", + "qa.color" => "grp_screen", + _ if name.starts_with("win.") => "grp_windows", + "qa.bright" => "grp_windows", + "qa.mic" | "qa.sound" | "qa.out" | "qa.in" | "qa.awake" => "grp_sound", + _ if name.starts_with("qa.") => "grp_system", + _ => "grp_menew", + } +} + +const GROUPS: [&str; 5] = ["grp_screen", "grp_windows", "grp_sound", "grp_system", "grp_menew"]; + +fn icon_name(i: &menew_core::palette::Icon) -> String { + match i { + menew_core::palette::Icon::Symbol(s) => s.to_string(), + menew_core::palette::Icon::App(Some(a)) => a.clone(), + _ => "system-run-symbolic".to_string(), + } +} + +/// Every command the Actions tab offers, grouped. +pub fn action_groups(cmds: &Commands) -> Vec<(String, Vec)> { + let lang = current_language(); + let items = cmds.items(""); + let mut out: Vec<(String, Vec)> = GROUPS.iter().map(|g| (tr(g, lang, &[]), vec![])).collect(); + for it in items { + let ItemAction::Command(c) = &it.action else { continue }; + if c.is_empty() || c.starts_with("note.open") || c.starts_with("cap.qrshow") { + continue; + } + let g = GROUPS.iter().position(|x| *x == group_of(c)).unwrap_or(4); + if !out[g].1.iter().any(|a| a.command == *c) { + out[g].1.push(ActionEntry { command: c.clone(), title: it.title.clone(), icon: icon_name(&it.icon) }); + } + } + // the windows group is long: keep the common ones + out[1].1.retain(|a| !a.command.starts_with("win.") || ["win.left", "win.right", "win.max", "win.center", "win.display", "win.almost"].contains(&a.command.as_str())); + out +} + +fn now_data(state: &menew_ui::SharedState, cmds: &Commands, sampler: &Sampler) -> NowData { + let lang = current_language(); + let s = sampler.last.borrow().clone(); + let warn = sysmon::attention(&s, lang); + let mut metrics = vec![("CPU".to_string(), format!("{:.0}%", s.cpu)), (tr("mon_ram", lang, &[]), format!("{:.0}%", s.memory.used_percent()))]; + if let Some(d) = &s.disk { + metrics.push((tr("mon_disk", lang, &[]), sysmon::bytes(d.free, lang))); + } + if let Some(b) = &s.battery { + metrics.push((tr("mon_battery", lang, &[]), format!("{}{}%", if b.charging() { "⚡" } else { "" }, b.percent))); + } + let st = state.borrow(); + let mut running = alerts::tray_status(&st, alerts::now(), lang).lines; + if cmds.tools().awake { + running.push(match cmds.awake_until() { + Some(u) => tr("pop_awake_until", lang, &[&menew_core::timers::clock(u, &TzCtx::system(), lang)]), + None => tr("pop_awake_on", lang, &[]), + }); + } + let ctx = TzCtx::system(); + let ts = now_secs() as i64; + let clocks = st.clocks.iter().map(|z| (time_zones::city(z, lang), time_zones::time(&ctx, ts, z, lang))).collect(); + NowData { status: if warn.is_empty() { tr("mon_all_good", lang, &[]) } else { warn.join(" · ") }, metrics, running, clocks } +} + +/// Check GitHub releases now (`manual`) or when due. Notifies only when there is news, or always +/// when checked by hand. +pub fn check_updates(app: &adw::Application, manual: bool) { + let mut cfg = Config::load(); + if !manual && (!cfg.update_check || !updates::due(cfg.update_checked_at as f64, now_secs() as f64)) { + return; + } + cfg.update_checked_at = now_secs(); + let _ = cfg.save_to(&Config::default_path()); + info!("Update check (GitHub releases)"); + let app = app.clone(); + glib::spawn_future_local(async move { + let lang = current_language(); + let latest = gio::spawn_blocking(updates::fetch_latest).await.ok().flatten(); + let current = env!("CARGO_PKG_VERSION"); + let n = match latest { + Some(tag) if updates::is_newer(&tag, current) => { + let n = gio::Notification::new(&tr("set_update_available", lang, &[tag.trim_start_matches('v')])); + n.set_body(Some(&tr("set_update_how", lang, &[]))); + n.set_default_action_and_target_value("app.open-uri", Some(&updates::RELEASES_PAGE.to_variant())); + Some(n) + } + Some(_) if manual => Some(gio::Notification::new(&tr("set_up_to_date", lang, &[current]))), + None if manual => Some(gio::Notification::new(&tr("set_update_fail", lang, &[]))), + _ => None, + }; + if let Some(n) = n { + app.send_notification(Some("menew-update"), &n); + } + }); +} + +/// Apply the features switched on or off. +pub fn apply_modules(cfg: &Config, palette: &menew_ui::PaletteWindow, cmds: &Commands) { + palette.set_clipboard_enabled(cfg.module_clipboard); + cmds.set_modules(cfg.module_actions, cfg.module_notes); +} + +pub fn restart() { + if let Ok(exe) = std::env::current_exe() { + // the new process becomes the primary instance once this one is gone + let _ = std::process::Command::new("sh").arg("-c").arg("sleep 1; exec \"$0\"").arg(exe).spawn(); + } + if let Some(app) = gio::Application::default() { + app.quit(); + } +} + +pub struct ShellParts { + pub settings: Section, + pub clipboard: Section, +} + +/// The Settings and Clipboard sections. +pub fn sections(app: &adw::Application, palette: &Rc, cmds: &Rc, on_config: Rc, gnome_ext: Option) -> ShellParts { + let lang = current_language(); + let mut shortcuts = vec![ + (tr("shortcut_palette_r1", lang, &[]), "Ctrl+Alt+Space".to_string(), "menew toggle".to_string()), + (menew_core::t("shortcut_clipboard_desc").to_string(), "Ctrl+Alt+V".to_string(), "menew clipboard".to_string()), + (menew_core::t("shortcut_paste_next_desc").to_string(), "Ctrl+Alt+N".to_string(), "menew paste-next".to_string()), + ]; + for (_, key, trigger, cmd) in menew_shortcuts::COMMAND_SHORTCUTS { + shortcuts.push((tr(key, lang, &[]), trigger.replace("Control", "Ctrl"), format!("menew run {cmd}"))); + } + let app2 = app.clone(); + let app3 = app.clone(); + let oc = Rc::clone(&on_config); + let view = menew_ui::settings::SettingsView::new(menew_ui::settings::SettingsHooks { + changed: Rc::new(move |c| oc(c)), + language: Rc::new(move || { + let lang = Config::load().effective_language(); + menew_ui::dialogs::confirm(None, &tr("set_lang_restart", lang, &[]), "", &tr("set_restart", lang, &[]), &tr("set_later", lang, &[]), false, restart); + }), + check_updates: Rc::new(move || check_updates(&app2, true)), + welcome: Rc::new(move || { + let oc = Rc::clone(&on_config); + menew_ui::welcome::show(&app3, Rc::new(move |c| oc(c))); + }), + shortcuts, + gnome_extension: gnome_ext, + }); + let settings = Section { id: "settings", title: tr("set_title", lang, &[]), icon: "emblem-system-symbolic", page: view.root.clone(), header: vec![], on_show: None }; + + let open = gtk4::Button::builder().label(tr("act_clipboard", lang, &[])).halign(gtk4::Align::Center).css_classes(["pill", "suggested-action"]).build(); + let p = Rc::clone(palette); + open.connect_clicked(move |_| p.show_mode(menew_core::PaletteMode::Clipboard)); + let page = adw::StatusPage::builder().icon_name("edit-paste-symbolic").title(tr("act_clipboard", lang, &[])).description(tr("act_sub_clipboard", lang, &[])).child(&open).build(); + let clipboard = Section { id: "clipboard", title: tr("kind_clip", lang, &[]), icon: "edit-paste-symbolic", page: page.upcast(), header: vec![], on_show: None }; + + let _ = cmds; + ShellParts { settings, clipboard } +} + +pub fn popover(app: &adw::Application, cmds: &Rc, palette: &Rc, state: &menew_ui::SharedState, sampler: &Rc, open_window: Rc) -> Rc { + let (c1, c2, c3) = (Rc::clone(cmds), Rc::clone(cmds), Rc::clone(cmds)); + let p = Rc::clone(palette); + let (st, smp) = (Rc::clone(state), Rc::clone(sampler)); + Popover::new( + app, + Hooks { + run: Rc::new(move |c| c1.run(c)), + search: Rc::new(move |t| p.show_with_text(t)), + groups: Rc::new(move || action_groups(&c2)), + favorites: Rc::new(|| Config::load().favorites), + set_favorites: Rc::new(|f| { + let mut c = Config::load(); + c.favorites = f; + if let Err(e) = c.save_to(&Config::default_path()) { + warn!("Could not save the favorites: {}", e); + } + }), + now: Rc::new(move || now_data(&st, &c3, &smp)), + open_window, + }, + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn groups_like_the_mac() { + assert_eq!(group_of("cap.area"), "grp_screen"); + assert_eq!(group_of("qa.color"), "grp_screen"); + assert_eq!(group_of("win.left"), "grp_windows"); + assert_eq!(group_of("qa.out:x"), "grp_sound"); + assert_eq!(group_of("qa.trash"), "grp_system"); + assert_eq!(group_of("note.new"), "grp_menew"); + } +} diff --git a/docs/plan-mvp.md b/docs/plan-mvp.md index 4356ae5..b15a42b 100644 --- a/docs/plan-mvp.md +++ b/docs/plan-mvp.md @@ -27,7 +27,7 @@ Plus CI on GitHub Actions: check/clippy/test on ubuntu-latest. - `CHANGELOG.md` and the release workflow. - **Changed on 2026-11-14:** the maintainer decided that the first public release must have the **core of the Mac app** (every row marked R1 in `docs/parity.md`). The packaging is kept and tested, but **no tag or release** is made until R1 is complete. The license is GPL-3.0-only, like the Mac app. -## Phases 4 to 11: release 1 ("core" parity) +## Phases 4 to 11: release 1 ("core" parity) - DONE (2026-11-15), waiting for a real desktop pass One relay cycle each, reviewed against the Mac app (`../menew`) and `docs/parity.md`: 4. Palette: recent picks, Menew actions, conversions, currency, time zones, text transforms, dev tools, quick links, emoji, timers/alarms/focus, script commands. 5. Clipboard: images and files, filters, pause, ignore apps, paste queue, smart actions, OCR of images, snippets with variables. @@ -38,6 +38,19 @@ One relay cycle each, reviewed against the Mac app (`../menew`) and `docs/parity 10. System monitor with top processes and tray metrics. 11. Tray popover (Now / Actions), Menew window, settings, welcome tour, language picker, update check. Then tag the first release. +Done on 2026-11-15 from a Mac, with the Docker image of `scripts/dev/` (Ubuntu 24.04, headless GNOME +Shell 46 and KWin 5.27) instead of WSL. Order used: 9 (quick actions and windows), 6, 7, 10, 11, then +the focus options. Every phase has unit tests in `menew-core` and the release 1 checks in +`scripts/desktop-test/r1-checks.sh` and `r1-kde-checks.sh`. + +## Before the first tag + +1. A pass on a real GNOME 46+ and a real KDE Plasma 6 desktop: global shortcuts (portal dialog), tray + left click, paste with uinput, Screenshot portal and color picker, polkit dialog and the keyring + for protected notes, audio devices, brightness, eject, window snapping, dark mode. +2. Check the AppImage (`scripts/test-appimage-docker.sh`) and the .deb (polkit policy installed). +3. Tag `v0.1.0`; then Phase 12. + ## Phase 12: `/linux` page on the site (Mac repo, `../menew`), after release 1 - Following `../menew/CLAUDE.md`: `site/` template + i18n in 5 languages, `build-site.py`, sitemap, hreflang. Linux screenshots come from the headless GNOME with **fake data**. - A local commit on a branch. **No push to main** (that deploys the site) without approval. diff --git a/scripts/desktop-test/README.md b/scripts/desktop-test/README.md index 059a6e2..5b82ffc 100644 --- a/scripts/desktop-test/README.md +++ b/scripts/desktop-test/README.md @@ -12,6 +12,33 @@ bash scripts/desktop-test/gnome.sh # headless GNOME Shell + the bridg bash scripts/desktop-test/kde.sh # headless KWin + wl-paste watcher ``` +Release 1 checks run inside the same sessions (`EXPLORE_CMD` runs a script in the live session and +passes on its exit status): + +```bash +EXPLORE_CMD='bash scripts/desktop-test/r1-checks.sh' bash scripts/desktop-test/gnome.sh +EXPLORE_CMD='bash scripts/desktop-test/r1-kde-checks.sh' bash scripts/desktop-test/kde.sh +``` + +GNOME: notes (written to `notes.json` while running, found in the palette), the Performance and +Settings sections, the tray popover (`menew popover`), the screenshot editor on a generated image, +a QR code window, `awake 2h` in the palette, dark mode through `gsettings`, keep awake, and a GTK +window snapped to the left half through the extension's `org.menew.Shell` (geometry read back from +the shell). KDE: a window snapped to the right half through a KWin script, geometry read back with +a second KWin script. Screenshots go to `docs/desktop-tests/gnome-r1-*.png` (not committed). + +From macOS or Windows, everything runs in the Linux dev image (`scripts/dev/Dockerfile`): + +```bash +docker build -t menew-dev scripts/dev +bash scripts/dev/run.sh "cargo test --workspace" +bash scripts/dev/run.sh "bash scripts/dev/desktop-tests.sh" # GNOME and KDE, plus release 1 +``` + +In a container there is no logind: the script removes `/run/systemd/seats` so GNOME Shell uses its +dummy login manager, starts a system bus, and drops `cap_sys_nice` from `kwin_wayland`. Keep awake +therefore reports that `systemd-inhibit` cannot work there, which the check accepts. + Screenshots land in `docs/desktop-tests/`: `gnome-palette.png`, `kde-palette.png` (Apps mode), `gnome-clipboard.png`, `kde-clipboard.png` (clipboard mode, fake data only) and `-palette-units.png`, `-palette-emoji.png` (the palette with `5 km to mi` and `emoji rocket`). diff --git a/scripts/desktop-test/gnome.sh b/scripts/desktop-test/gnome.sh index 079676c..80140fb 100755 --- a/scripts/desktop-test/gnome.sh +++ b/scripts/desktop-test/gnome.sh @@ -51,6 +51,8 @@ trap cleanup EXIT bash -c "cd '$REPO_ROOT/gnome-extension' && ./install.sh" >/dev/null gsettings set org.gnome.shell enabled-extensions "['$UUID']" gsettings set org.gnome.shell disable-user-extensions false +# Ubuntu's default icon theme (Yaru) is not installed in the test images +gsettings set org.gnome.desktop.interface icon-theme Adwaita # start the headless shell (unsafe mode allows org.gnome.Shell.Screenshot) export XDG_SESSION_TYPE=wayland @@ -125,7 +127,7 @@ fi sleep 2 # let the extension proxy reconnect # developer aid: EXPLORE_CMD='...' runs an arbitrary command in the live session and stops -if [ -n "${EXPLORE_CMD:-}" ]; then bash -c "$EXPLORE_CMD" || true; exit 0; fi +if [ -n "${EXPLORE_CMD:-}" ]; then bash -c "$EXPLORE_CMD"; exit $?; fi # Copies are made INSIDE the shell (org.gnome.Shell.Eval, unsafe mode) instead of with wl-copy: # wl-copy/wl-paste need keyboard focus for their helper surface, and a headless gnome-shell has diff --git a/scripts/desktop-test/kde.sh b/scripts/desktop-test/kde.sh index c39fbe6..2e2c873 100755 --- a/scripts/desktop-test/kde.sh +++ b/scripts/desktop-test/kde.sh @@ -93,7 +93,8 @@ else fi sleep 2 -if [ -n "${EXPLORE_CMD:-}" ]; then bash -c "$EXPLORE_CMD" || true; exit 0; fi +export KWIN_LOG +if [ -n "${EXPLORE_CMD:-}" ]; then bash -c "$EXPLORE_CMD"; exit $?; fi # Readiness probe for the real pipeline wl-copy -> wl-paste --watch -> helper -> daemon -> SQLite. # The copy is retried: on a slow runner the compositor/watcher may still be starting when the first diff --git a/scripts/desktop-test/r1-checks.sh b/scripts/desktop-test/r1-checks.sh new file mode 100755 index 0000000..a60b93b --- /dev/null +++ b/scripts/desktop-test/r1-checks.sh @@ -0,0 +1,112 @@ +#!/usr/bin/env bash +# Release 1 checks, run inside a live headless GNOME session by gnome.sh: +# EXPLORE_CMD='bash scripts/desktop-test/r1-checks.sh' bash scripts/desktop-test/gnome.sh +# Screenshots (fake data only) land in docs/desktop-tests/gnome-r1-*.png. +set -uo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=lib.sh +source "$HERE/lib.sh" +MENEW_LOG="$TEST_ROOT/menew.log" +OUT="$REPO_ROOT/docs/desktop-tests" +mkdir -p "$OUT" + +shell_eval() { gdbus call --session --dest org.gnome.Shell --object-path /org/gnome/Shell --method org.gnome.Shell.Eval "$1"; } +shot() { # shot : screenshot of the whole headless screen + shell_eval "Main.messageTray.close(); Main.messageTray._bannerBin && Main.messageTray._bannerBin.hide(); 1" >/dev/null + rm -f "$TEST_ROOT/r1.png" + gdbus call --session --dest org.gnome.Shell.Screenshot --object-path /org/gnome/Shell/Screenshot \ + --method org.gnome.Shell.Screenshot.Screenshot false false "$TEST_ROOT/r1.png" >/dev/null 2>&1 + if [ -s "$TEST_ROOT/r1.png" ]; then cp "$TEST_ROOT/r1.png" "$OUT/gnome-r1-$1.png"; pass "screenshot gnome-r1-$1.png"; else fail "no screenshot for $1"; fi +} +log_has() { grep -a -q "$1" "$MENEW_LOG"; } +close_windows() { shell_eval "global.get_window_actors().forEach(a => { const w = a.meta_window; if (w.get_gtk_application_id && w.get_gtk_application_id() === 'app.menew.Menew') w.delete(global.get_current_time()); }); 1" >/dev/null; } + +shell_eval "Main.overview.hide(); 1" >/dev/null +"$MENEW_BIN" toggle >/dev/null 2>&1; sleep 1; "$MENEW_BIN" toggle >/dev/null 2>&1 # palette closed + +# ---- notes: fake data written while running, the section reloads it ---- +NOTES="$XDG_DATA_HOME/menew/notes.json" +mkdir -p "$(dirname "$NOTES")" +cat >"$NOTES" <<'JSON' +[ + {"id":"a1","text":"# Menew ideas\n- [x] Snippets\n- [ ] Per-app shortcuts\n- [ ] Weather widget\n\n**Bold** and `code` and *italic*\n\n#ideas #menew","secure":false,"created":1794600000,"updated":1794657000}, + {"id":"a2","text":"Friday meeting\n**Agenda:** budget and deadlines\n> Bring the quarterly numbers\n\n#work","secure":false,"created":1794500000,"updated":1794650000}, + {"id":"a3","text":"Groceries\n- coffee\n- bread\n- cheese\n\n#home","secure":false,"created":1794400000,"updated":1794600000} +] +JSON +"$MENEW_BIN" run open.notes >/dev/null 2>&1; sleep 3 +shot notes +"$MENEW_BIN" __palette-query "groceries" >/dev/null 2>&1; sleep 2 +if log_has 'result\[.*\] \[Note\] Groceries\|result\[.*\] .*Groceries'; then pass "palette finds the note 'Groceries'"; else fail "palette did not list the note"; fi +"$MENEW_BIN" toggle >/dev/null 2>&1; sleep 1 + +# ---- performance and settings ---- +"$MENEW_BIN" run open.performance >/dev/null 2>&1; sleep 5 +shot performance +"$MENEW_BIN" run open.settings >/dev/null 2>&1; sleep 2 +shot settings +close_windows; sleep 1 + +# ---- popover ---- +"$MENEW_BIN" popover >/dev/null 2>&1; sleep 3 +shot popover +"$MENEW_BIN" popover >/dev/null 2>&1; sleep 1 + +# ---- screenshot editor and QR code ---- +python3 - "$TEST_ROOT/fake-shot.png" <<'PY' +import sys +from gi.repository import GdkPixbuf +p = GdkPixbuf.Pixbuf.new(GdkPixbuf.Colorspace.RGB, False, 8, 900, 520) +p.fill(0x3b6fd8ff) +p.savev(sys.argv[1], "png", [], []) +PY +"$MENEW_BIN" run "cap.edit:$TEST_ROOT/fake-shot.png" >/dev/null 2>&1; sleep 3 +shot editor +close_windows; sleep 1 +"$MENEW_BIN" run "cap.qrshow:https://menew.web.app" >/dev/null 2>&1; sleep 3 +shot qr +close_windows; sleep 1 + +# ---- quick actions ---- +"$MENEW_BIN" __palette-query "awake 2h" >/dev/null 2>&1; sleep 2 +if log_has 'Keep awake for 2 h'; then pass "palette 'awake 2h' offers keep awake for 2 h"; else fail "no keep awake item for 'awake 2h'"; fi +"$MENEW_BIN" __palette-query "brightness 40" >/dev/null 2>&1; sleep 1 +"$MENEW_BIN" toggle >/dev/null 2>&1 +before="$(gsettings get org.gnome.desktop.interface color-scheme)" +"$MENEW_BIN" run qa.dark >/dev/null 2>&1; sleep 2 +after="$(gsettings get org.gnome.desktop.interface color-scheme)" +if [ "$before" != "$after" ]; then pass "qa.dark switched color-scheme ($before -> $after)"; else fail "qa.dark did not change color-scheme ($before)"; fi +"$MENEW_BIN" run qa.dark >/dev/null 2>&1; sleep 1 +"$MENEW_BIN" run qa.awake:1 >/dev/null 2>&1; sleep 2 +if pgrep -f 'systemd-inhibit --what=idle:sleep --who=Menew' >/dev/null || log_has 'Keep awake needs systemd-inhibit'; then pass "keep awake started systemd-inhibit (or said it is missing)"; else fail "keep awake did nothing"; fi +"$MENEW_BIN" run qa.awake >/dev/null 2>&1 + +# ---- window snapping through the extension ---- +python3 - >/dev/null 2>&1 <<'PY' & +import gi +gi.require_version("Gtk", "4.0") +from gi.repository import Gtk, GLib +app = Gtk.Application(application_id="org.example.SnapTarget") +def on_activate(a): + w = Gtk.ApplicationWindow(application=a, title="Snap target") + w.set_default_size(400, 300) + w.present() + GLib.timeout_add_seconds(40, a.quit) +app.connect("activate", on_activate) +app.run([]) +PY +track $! +sleep 4 +shell_eval "global.display.focus_window && global.display.focus_window.get_gtk_application_id() === 'org.example.SnapTarget'" | grep -q true || shell_eval "global.get_window_actors().map(a => a.meta_window).find(w => w.get_title() === 'Snap target').activate(global.get_current_time()); 1" >/dev/null +sleep 1 +"$MENEW_BIN" run win.left >/dev/null 2>&1; sleep 2 +GEO="$(shell_eval "const w = global.get_window_actors().map(a => a.meta_window).find(w => w.get_title() === 'Snap target'); const r = w.get_frame_rect(); const a = w.get_work_area_current_monitor(); [r.x - a.x, r.width, a.width].join(',')")" +info "snap target geometry (x offset, width, work width): $GEO" +if echo "$GEO" | python3 -c 'import sys,re; v=[int(x) for x in re.findall(r"-?\d+", sys.stdin.read())][-3:]; sys.exit(0 if len(v)==3 and abs(v[0])<=2 and abs(v[1]-v[2]//2)<=4 else 1)'; then + pass "win.left put the window on the left half (through org.menew.Shell)" +else + fail "win.left did not snap the window: $GEO"; grep -a -i 'snap' "$MENEW_LOG" | tail -5 +fi + +if grep -a -q 'panicked' "$MENEW_LOG"; then fail "the daemon panicked"; grep -a -A3 panicked "$MENEW_LOG" | head; else pass "no panic in the daemon log"; fi +[ "$FAILS" -eq 0 ] diff --git a/scripts/desktop-test/r1-kde-checks.sh b/scripts/desktop-test/r1-kde-checks.sh new file mode 100755 index 0000000..df47f9e --- /dev/null +++ b/scripts/desktop-test/r1-kde-checks.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +# Release 1 checks on headless KWin, run by kde.sh: +# EXPLORE_CMD='bash scripts/desktop-test/r1-kde-checks.sh' bash scripts/desktop-test/kde.sh +set -uo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=lib.sh +source "$HERE/lib.sh" +MENEW_LOG="$TEST_ROOT/menew.log" + +# a window to move +python3 - >/dev/null 2>&1 <<'PY' & +import gi +gi.require_version("Gtk", "4.0") +from gi.repository import Gtk, GLib +app = Gtk.Application(application_id="org.example.SnapTarget") +def on_activate(a): + w = Gtk.ApplicationWindow(application=a, title="Snap target") + w.set_default_size(400, 300) + w.present() + GLib.timeout_add_seconds(30, a.quit) +app.connect("activate", on_activate) +app.run([]) +PY +track $! +sleep 4 +"$MENEW_BIN" run win.right >/dev/null 2>&1; sleep 3 + +# ask KWin where the window is: a script prints it to KWin's log +probe="$TEST_ROOT/probe.js" +cat >"$probe" <<'JS' +var list = workspace.windowList ? workspace.windowList() : workspace.clientList(); +for (var i = 0; i < list.length; i++) { + var w = list[i]; + if (w.caption && w.caption.indexOf("Snap target") === 0) { + var a = workspace.clientArea(KWin.MaximizeArea, w); + print("MENEW_GEO " + Math.round(w.frameGeometry.x - a.x) + "," + Math.round(w.frameGeometry.width) + "," + Math.round(a.width)); + } +} +JS +id="$(gdbus call --session --dest org.kde.KWin --object-path /Scripting --method org.kde.kwin.Scripting.loadScript "$probe" menew-probe | grep -o '[0-9]\+' | head -1)" +gdbus call --session --dest org.kde.KWin --object-path "/Scripting/Script$id" --method org.kde.kwin.Script.run >/dev/null 2>&1 \ + || gdbus call --session --dest org.kde.KWin --object-path "/$id" --method org.kde.kwin.Script.run >/dev/null 2>&1 +sleep 1 +GEO="$(grep -a -o 'MENEW_GEO [0-9,-]*' "$KWIN_LOG" | tail -1 | cut -d' ' -f2)" +info "snap target geometry (x offset, width, work width): ${GEO:-none}" +IFS=, read -r x w aw <<<"${GEO:-,,}" +if [ -n "$aw" ] && [ "$x" -ge $((aw / 2 - 4)) ] && [ "$x" -le $((aw / 2 + 4)) ] && [ "$w" -ge $((aw / 2 - 4)) ] && [ "$w" -le $((aw / 2 + 4)) ]; then + pass "win.right put the window on the right half (KWin scripting)" +else + fail "win.right did not snap the window on KWin: ${GEO:-no geometry}"; grep -a -i 'snap' "$MENEW_LOG" | tail -5 +fi +if grep -a -q 'panicked' "$MENEW_LOG"; then fail "the daemon panicked"; else pass "no panic in the daemon log"; fi +[ "$FAILS" -eq 0 ] diff --git a/scripts/dev/Dockerfile b/scripts/dev/Dockerfile new file mode 100644 index 0000000..4c08e96 --- /dev/null +++ b/scripts/dev/Dockerfile @@ -0,0 +1,16 @@ +# Linux build and headless desktop test image (Ubuntu 24.04, GNOME Shell 46, KWin 5.27). +# docker build -t menew-dev scripts/dev +# docker run --rm -v "$PWD:/src" -v menew-target:/target -v menew-cargo:/root/.cargo/registry menew-dev cargo test --workspace +FROM ubuntu:24.04 +ENV DEBIAN_FRONTEND=noninteractive +RUN apt-get update && apt-get install -y --no-install-recommends \ + ca-certificates curl git build-essential pkg-config \ + libgtk-4-dev libadwaita-1-dev libdbus-1-dev \ + gnome-shell gnome-shell-extensions mutter kwin-wayland kde-spectacle qtwayland5 wl-clipboard \ + xdg-desktop-portal xdg-desktop-portal-gtk sqlite3 imagemagick dbus-user-session dbus-x11 dbus-bin \ + libglib2.0-bin python3-gi gir1.2-gtk-4.0 python3-yaml procps psmisc tesseract-ocr \ + qrencode zbar-tools libsecret-tools pulseaudio-utils libcap2-bin \ + && rm -rf /var/lib/apt/lists/* +RUN curl -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --component clippy +ENV PATH=/root/.cargo/bin:$PATH CARGO_TARGET_DIR=/target +WORKDIR /src diff --git a/scripts/dev/desktop-tests.sh b/scripts/dev/desktop-tests.sh new file mode 100755 index 0000000..545af3f --- /dev/null +++ b/scripts/dev/desktop-tests.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# Run the headless GNOME and KDE tests inside the dev container (scripts/dev/Dockerfile). +# bash scripts/dev/run.sh bash scripts/dev/desktop-tests.sh [gnome|kde] +set -uo pipefail +cd /src +cargo build 2>&1 | tail -1 +# no logind in a container: without /run/systemd/seats GNOME Shell uses its dummy login manager +rm -rf /run/systemd/seats +# kwin_wayland carries cap_sys_nice, which a container cannot grant: drop it +command -v setcap >/dev/null && setcap -r /usr/bin/kwin_wayland 2>/dev/null +mkdir -p /run/dbus && [ -S /run/dbus/system_bus_socket ] || dbus-daemon --system --fork +export MENEW_BIN=/target/debug/menew +rc=0 +for de in ${1:-gnome kde}; do + echo "===== $de" + timeout 600 bash "scripts/desktop-test/$de.sh" || rc=1 + echo "===== $de release 1" + checks="scripts/desktop-test/r1-checks.sh" + [ "$de" = kde ] && checks="scripts/desktop-test/r1-kde-checks.sh" + EXPLORE_CMD="bash $checks" timeout 600 bash "scripts/desktop-test/$de.sh" || rc=1 +done +exit $rc diff --git a/scripts/dev/run.sh b/scripts/dev/run.sh new file mode 100755 index 0000000..8433317 --- /dev/null +++ b/scripts/dev/run.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +# Run a command inside the Linux dev image (build it first, see Dockerfile), from macOS or Windows. +# bash scripts/dev/run.sh cargo test --workspace +set -euo pipefail +ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +exec docker run --rm -i -v "$ROOT:/src" -v menew-target:/target -v menew-cargo:/root/.cargo/registry \ + -e CARGO_TERM_COLOR=never menew-dev bash -lc "$*"