Nouveau logo, images dans l'interface, dossier de données modifiable, fenêtre mémorisée

- Logo (assets/logo.jpg) décliné par build.rs : exe, zone de notification
  (connecté / déconnecté / silence), fenêtre, identité des notifications
- Icônes des applis et images jointes (bigImageUrl) dans la fenêtre, option pour les masquer
- Dossier des données au choix (sélecteur Windows) avec migration et retour par défaut
- Taille, position et état maximisé de la fenêtre mémorisés

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
linkatplugandClaude Opus 5.5 committed 2026-12-03 17:58:55 +01:00
1 parent e1ec30dd46
commit 4b20c6bdb2
12 files changed
+656 -209

No files matched your search

Generated
+33 -1
View File
@@ -72,7 +72,7 @@ dependencies = [
"objc2-foundation 0.3.2",
"parking_lot",
"percent-encoding",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
"x11rb",
]
@@ -339,6 +339,12 @@ dependencies = [
"bytemuck",
]
[[package]]
name = "color_quant"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
[[package]]
name = "combine"
version = "4.6.9"
@@ -1061,6 +1067,16 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "gif"
version = "0.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159"
dependencies = [
"color_quant",
"weezl",
]
[[package]]
name = "gio"
version = "0.22.11"
@@ -1242,6 +1258,7 @@ name = "gotify-lite"
version = "2.0.0"
dependencies = [
"eframe",
"image",
"native-tls",
"serde",
"serde_json",
@@ -1494,10 +1511,25 @@ checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"
dependencies = [
"bytemuck",
"byteorder-lite",
"color_quant",
"gif",
"image-webp",
"moxcms",
"num-traits",
"png",
"tiff",
"zune-core",
"zune-jpeg",
]
[[package]]
name = "image-webp"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c8d2831f3eb9706eeac62164959a288f12c047a3c53b353c6c00d5d60eb5c7f"
dependencies = [
"byteorder-lite",
"quick-error",
]
[[package]]
+3 -1
View File
@@ -16,8 +16,9 @@ ureq = { version = "3", default-features = false, features = ["native-tls", "gzi
windows = { version = "0.61", features = [
"Win32_Foundation", "Win32_System_Registry", "Win32_Security_Cryptography",
"Win32_System_Threading", "Win32_UI_WindowsAndMessaging", "Win32_UI_Shell",
"Win32_System_LibraryLoader", "Win32_System_DataExchange", "Win32_System_Memory", "Win32_System_SystemInformation", "UI_Notifications", "Data_Xml_Dom", "Foundation",
"Win32_System_LibraryLoader", "Win32_System_Com", "Win32_UI_Shell_Common", "Win32_System_DataExchange", "Win32_System_Memory", "Win32_System_SystemInformation", "UI_Notifications", "Data_Xml_Dom", "Foundation",
] }
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp", "ico", "bmp"] }
[profile.release]
opt-level = "s"
@@ -27,4 +28,5 @@ panic = "abort"
strip = true
[build-dependencies]
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
winresource = "0.1"
+7 -2
View File
@@ -30,7 +30,10 @@ Le service ne charge aucun moteur graphique.
**heures calmes** quotidiennes, seuil de priorité qui passe malgré le silence.
- **Par application** : couper les notifications d'une appli Gotify (clic droit dans la liste ou réglages).
- **Historique** : recherche, filtre par appli, suppression d'un message, d'une appli ou de tout (sur le serveur).
- **Images** : icônes des applications Gotify et images jointes (`client::notification.bigImageUrl`) dans la fenêtre, désactivables.
- **Démarrage avec Windows** (HKCU, sans droits admin), thème **Système / Clair / Sombre**.
- **Fenêtre** : taille, position et état maximisé mémorisés.
- **Dossier des données** modifiable depuis les réglages, avec migration automatique des fichiers existants.
- **Sécurité** : token chiffré avec DPAPI (lié à votre session Windows), TLS natif Windows (SChannel,
donc les autorités de certification installées dans Windows sont reconnues).
- Détecte quand Windows bloque les notifications et le signale, avec un bouton vers le bon réglage.
@@ -43,7 +46,8 @@ Le service ne charge aucun moteur graphique.
Clic gauche sur l'icône : fenêtre. Clic droit : silence, activer/désactiver, reconnecter, quitter.
Données : `%APPDATA%\GotifyLite\config.json` (réglages), `%LOCALAPPDATA%\GotifyLite\` (état, icônes, journal).
Données par défaut : `%APPDATA%\GotifyLite\config.json` (réglages) et `%LOCALAPPDATA%\GotifyLite\` (état, icônes,
journal, fenêtre). Un dossier personnalisé (Paramètres → Dossier des données) regroupe tout au même endroit.
## Compiler
@@ -64,7 +68,8 @@ L'exécutable est `target\release\gotify-lite.exe`. `cargo test` lance les tests
| `src/notify.rs` | Toasts WinRT |
| `src/config.rs` | Réglages + règle de décision (`Config::decide`) |
| `src/sys.rs` | Registre, DPAPI, instance unique, dates |
| `src/icon.rs` | Icônes dessinées en code + encodeur PNG |
| `src/icon.rs` | Icônes incluses dans le binaire |
| `build.rs` | Génère les icônes (tray, fenêtre, .ico) depuis `assets/logo.jpg` |
## Licence
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 371 KiB

+119 -23
View File
@@ -1,36 +1,132 @@
// Génère l'icône .ico à partir du même code de dessin que l'icône de la barre des tâches,
// puis l'embarque dans l'exécutable (Explorateur, Gestionnaire des tâches, démarrage).
#[allow(dead_code)]
#[path = "src/icon.rs"]
mod icon;
//! Prépare les icônes à partir de assets/logo.jpg :
//! fond sombre rendu transparent, recadrage, déclinaisons (connecté / déconnecté / silence),
//! .ico embarqué dans l'exécutable + images brutes incluses dans le binaire.
use image::{imageops::FilterType, Rgba, RgbaImage};
use std::path::Path;
fn main() {
println!("cargo:rerun-if-changed=src/icon.rs");
println!("cargo:rerun-if-changed=assets/logo.jpg");
println!("cargo:rerun-if-changed=build.rs");
let out = std::path::PathBuf::from(std::env::var("OUT_DIR").unwrap());
let sizes = [16u32, 24, 32, 48, 64, 256];
let pngs: Vec<Vec<u8>> = sizes.iter().map(|&s| icon::png(s, &icon::render(s, icon::Look::Connected))).collect();
let mut ico = vec![0, 0, 1, 0];
ico.extend_from_slice(&(sizes.len() as u16).to_le_bytes());
let mut offset = 6 + 16 * sizes.len() as u32;
for (s, p) in sizes.iter().zip(&pngs) {
let d = if *s >= 256 { 0 } else { *s as u8 };
ico.extend_from_slice(&[d, d, 0, 0, 1, 0, 32, 0]);
ico.extend_from_slice(&(p.len() as u32).to_le_bytes());
ico.extend_from_slice(&offset.to_le_bytes());
offset += p.len() as u32;
let src = image::open("assets/logo.jpg").expect("assets/logo.jpg").to_rgba8();
let logo = cut_out(&src);
// Icône principale + .ico multi-tailles
let sizes = [16u32, 20, 24, 32, 40, 48, 64, 128, 256];
let mut pngs = Vec::new();
for &s in &sizes {
let img = resize(&logo, s);
let mut buf = Vec::new();
img.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png).unwrap();
pngs.push(buf);
}
for p in &pngs {
ico.extend_from_slice(p);
}
let ico_path = out.join("app.ico");
std::fs::write(&ico_path, ico).unwrap();
write_ico(&out.join("app.ico"), &sizes, &pngs);
std::fs::write(out.join("logo_256.png"), &pngs[sizes.iter().position(|&s| s == 256).unwrap()]).unwrap();
// Images brutes RGBA pour la zone de notification (32 px) et la fenêtre (64 px)
let tray = resize(&logo, 32);
std::fs::write(out.join("tray_connected.rgba"), tray.as_raw()).unwrap();
std::fs::write(out.join("tray_disconnected.rgba"), grey(&tray).as_raw()).unwrap();
std::fs::write(out.join("tray_muted.rgba"), muted(&tray).as_raw()).unwrap();
std::fs::write(out.join("window_64.rgba"), resize(&logo, 64).as_raw()).unwrap();
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
let mut res = winresource::WindowsResource::new();
res.set_icon(ico_path.to_str().unwrap())
res.set_icon(out.join("app.ico").to_str().unwrap())
.set("FileDescription", "Gotify Lite")
.set("ProductName", "Gotify Lite")
.set("LegalCopyright", "MIT");
res.compile().unwrap();
}
}
/// Rend transparent le fond uni (couleur du coin), recadre sur le contenu et met au carré.
fn cut_out(src: &RgbaImage) -> RgbaImage {
let bg = *src.get_pixel(4, 4);
let mut img = src.clone();
let (mut x0, mut y0, mut x1, mut y1) = (u32::MAX, u32::MAX, 0, 0);
for (x, y, p) in img.enumerate_pixels_mut() {
let d = (0..3).map(|i| (p[i] as f32 - bg[i] as f32).abs()).fold(0.0, f32::max);
let a = ((d - 18.0) / 50.0).clamp(0.0, 1.0);
if a > 0.0 {
// Retire la teinte du fond mélangée sur les bords (dé-matage).
for i in 0..3 {
let c = (p[i] as f32 - bg[i] as f32 * (1.0 - a)) / a;
p[i] = c.clamp(0.0, 255.0) as u8;
}
}
p[3] = (a * 255.0) as u8;
if a > 0.5 {
x0 = x0.min(x);
y0 = y0.min(y);
x1 = x1.max(x);
y1 = y1.max(y);
}
}
let side = (x1 - x0).max(y1 - y0) + 1;
let pad = side / 20;
let full = side + 2 * pad;
let mut sq = RgbaImage::from_pixel(full, full, Rgba([0, 0, 0, 0]));
let ox = pad + (side - (x1 - x0 + 1)) / 2;
let oy = pad + (side - (y1 - y0 + 1)) / 2;
for y in y0..=y1 {
for x in x0..=x1 {
sq.put_pixel(ox + x - x0, oy + y - y0, *img.get_pixel(x, y));
}
}
sq
}
fn resize(img: &RgbaImage, s: u32) -> RgbaImage {
image::imageops::resize(img, s, s, FilterType::Lanczos3)
}
fn grey(img: &RgbaImage) -> RgbaImage {
let mut o = img.clone();
for p in o.pixels_mut() {
let l = (0.3 * p[0] as f32 + 0.59 * p[1] as f32 + 0.11 * p[2] as f32) as u8;
*p = Rgba([l, l, l, (p[3] as f32 * 0.75) as u8]);
}
o
}
/// Logo atténué + pastille orange en bas à droite.
fn muted(img: &RgbaImage) -> RgbaImage {
let mut o = img.clone();
let s = o.width() as f32;
let (cx, cy, r) = (s * 0.76, s * 0.76, s * 0.22);
for (x, y, p) in o.enumerate_pixels_mut() {
let d = ((x as f32 + 0.5 - cx).powi(2) + (y as f32 + 0.5 - cy).powi(2)).sqrt();
if d <= r + 1.0 {
let a = (r + 1.0 - d).clamp(0.0, 1.0);
let inner = d <= r * 0.45;
let c: [u8; 3] = if inner { [255, 255, 255] } else { [240, 140, 30] };
for i in 0..3 {
p[i] = (c[i] as f32 * a + p[i] as f32 * (1.0 - a)) as u8;
}
p[3] = p[3].max((a * 255.0) as u8);
} else {
p[3] = (p[3] as f32 * 0.8) as u8;
}
}
o
}
fn write_ico(path: &Path, sizes: &[u32], pngs: &[Vec<u8>]) {
let mut ico = vec![0, 0, 1, 0];
ico.extend_from_slice(&(sizes.len() as u16).to_le_bytes());
let mut offset = 6 + 16 * sizes.len() as u32;
for (s, p) in sizes.iter().zip(pngs) {
let d = if *s >= 256 { 0 } else { *s as u8 };
ico.extend_from_slice(&[d, d, 0, 0, 1, 0, 32, 0]);
ico.extend_from_slice(&(p.len() as u32).to_le_bytes());
ico.extend_from_slice(&offset.to_le_bytes());
offset += p.len() as u32;
}
for p in pngs {
ico.extend_from_slice(p);
}
std::fs::write(path, ico).unwrap();
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 53 KiB

After

Width:  |  Height:  |  Size: 95 KiB

+3
View File
@@ -42,6 +42,8 @@ pub struct Config {
pub catch_up: bool,
/// "system" | "light" | "dark"
pub theme: String,
/// Afficher les images (icônes d'applis, images jointes) dans la fenêtre.
pub show_images: bool,
}
impl Default for Config {
@@ -64,6 +66,7 @@ impl Default for Config {
silence_bypass_priority: 8,
catch_up: true,
theme: "system".into(),
show_images: true,
}
}
}
+3 -19
View File
@@ -74,7 +74,7 @@ pub fn run() {
sys::log("démarrage");
let icon_path = sys::local_dir().join("icon.png");
let _ = std::fs::write(&icon_path, icon::png(64, &icon::render(64, Look::Connected)));
let _ = std::fs::write(&icon_path, icon::LOGO_PNG);
sys::register_app(&icon_path);
let cfg = Config::load();
@@ -119,7 +119,7 @@ enum Ev {
}
fn make_icon(look: Look) -> Icon {
Icon::from_rgba(icon::render(32, look), 32, 32).expect("icône")
Icon::from_rgba(icon::tray_rgba(look), icon::TRAY_SIZE, icon::TRAY_SIZE).expect("icône")
}
fn tray_loop(shared: Arc<Shared>) {
@@ -486,27 +486,11 @@ fn save_last_id(id: u64) {
}
fn load_apps(client: &Client) -> HashMap<u64, AppInfo> {
let dir = sys::local_dir().join("icons");
let _ = std::fs::create_dir_all(&dir);
let list = client.applications().unwrap_or_else(|e| {
sys::log(&format!("applications : {e}"));
Vec::new()
});
list.into_iter()
.map(|a| {
let icon = (!a.image.is_empty()).then(|| {
// Nom de fichier dérivé du chemin serveur : change quand l'image change.
let h = a.image.bytes().fold(0xcbf29ce484222325u64, |h, b| (h ^ b as u64).wrapping_mul(0x100000001b3));
let p = dir.join(format!("{}-{h:016x}.png", a.id));
if !p.exists()
&& let Ok(bytes) = client.download(&a.image) {
let _ = std::fs::write(&p, bytes);
}
p
});
(a.id, AppInfo { name: a.name, icon: icon.filter(|p| p.exists()) })
})
.collect()
list.into_iter().map(|a| (a.id, AppInfo { icon: client.app_icon(&a), name: a.name })).collect()
}
fn deliver(shared: &Shared, notifier: &Notifier, apps: &HashMap<u64, AppInfo>, m: &Message) {
+36
View File
@@ -36,6 +36,12 @@ impl Message {
let l = url.to_ascii_lowercase();
(l.starts_with("https://") || l.starts_with("http://")).then(|| url.to_string())
}
/// Grande image jointe (`client::notification.bigImageUrl`), uniquement http(s).
pub fn big_image_url(&self) -> Option<String> {
let url = self.extras.as_ref()?.pointer("/client::notification/bigImageUrl")?.as_str()?;
let l = url.to_ascii_lowercase();
(l.starts_with("https://") || l.starts_with("http://")).then(|| url.to_string())
}
pub fn is_markdown(&self) -> bool {
self.extras
.as_ref()
@@ -155,6 +161,36 @@ impl Client {
self.delete("/message")
}
/// Chemin local de l'image d'une appli, téléchargée et mise en cache si besoin.
pub fn app_icon(&self, app: &App) -> Option<std::path::PathBuf> {
if app.image.is_empty() {
return None;
}
let dir = crate::sys::local_dir().join("icons");
let _ = std::fs::create_dir_all(&dir);
// Nom dérivé du chemin serveur : change quand l'image change.
let h = app.image.bytes().fold(0xcbf29ce484222325u64, |h, b| (h ^ b as u64).wrapping_mul(0x100000001b3));
let p = dir.join(format!("{}-{h:016x}.png", app.id));
if !p.exists() {
let bytes = self.download(&app.image).ok()?;
std::fs::write(&p, bytes).ok()?;
}
Some(p)
}
/// Télécharge une URL externe (image jointe) sans envoyer le token.
pub fn fetch_external(&self, url: &str) -> Result<Vec<u8>> {
self.agent
.get(url)
.call()
.map_err(describe)?
.body_mut()
.with_config()
.limit(8 * 1024 * 1024)
.read_to_vec()
.map_err(|e| e.to_string())
}
pub fn download(&self, path: &str) -> Result<Vec<u8>> {
self.agent
.get(format!("{}/{}", self.base, path.trim_start_matches('/')))
+13 -138
View File
@@ -1,4 +1,4 @@
//! Icônes dessinées en code (aucun fichier à embarquer) + encodeur PNG minimal.
//! Icônes générées depuis assets/logo.jpg par build.rs et incluses dans le binaire.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Look {
@@ -7,145 +7,20 @@ pub enum Look {
Muted,
}
impl Look {
fn bg(self) -> [f32; 3] {
match self {
Look::Connected => [0.17, 0.42, 0.69], // bleu
Look::Disconnected => [0.45, 0.47, 0.50], // gris
Look::Muted => [0.80, 0.45, 0.10], // orange
}
pub const TRAY_SIZE: u32 = 32;
pub const WINDOW_SIZE: u32 = 64;
pub fn tray_rgba(look: Look) -> Vec<u8> {
match look {
Look::Connected => include_bytes!(concat!(env!("OUT_DIR"), "/tray_connected.rgba")).to_vec(),
Look::Disconnected => include_bytes!(concat!(env!("OUT_DIR"), "/tray_disconnected.rgba")).to_vec(),
Look::Muted => include_bytes!(concat!(env!("OUT_DIR"), "/tray_muted.rgba")).to_vec(),
}
}
fn rounded_rect(x: f32, y: f32, r: f32) -> bool {
let dx = (x - 0.5).abs() - (0.5 - r);
let dy = (y - 0.5).abs() - (0.5 - r);
let (ox, oy) = (dx.max(0.0), dy.max(0.0));
(ox * ox + oy * oy).sqrt() <= r && dx.max(dy) <= r
pub fn window_rgba() -> Vec<u8> {
include_bytes!(concat!(env!("OUT_DIR"), "/window_64.rgba")).to_vec()
}
fn circle(x: f32, y: f32, cx: f32, cy: f32, r: f32) -> bool {
(x - cx).powi(2) + (y - cy).powi(2) <= r * r
}
fn bell(x: f32, y: f32) -> bool {
let cx = 0.5;
let dome = y <= 0.47 && circle(x, y, cx, 0.47, 0.21);
let body = (0.47..=0.68).contains(&y) && (x - cx).abs() <= 0.21 + (y - 0.47) * 0.35;
let rim = (0.66..=0.72).contains(&y) && (x - cx).abs() <= 0.30;
let knob = circle(x, y, cx, 0.25, 0.05);
let clapper = circle(x, y, cx, 0.78, 0.065);
dome || body || rim || knob || clapper
}
fn slash(x: f32, y: f32, w: f32) -> bool {
// segment (0.22,0.20) -> (0.80,0.80)
let (ax, ay, bx, by) = (0.22, 0.20, 0.80, 0.80);
let (vx, vy) = (bx - ax, by - ay);
let t = (((x - ax) * vx + (y - ay) * vy) / (vx * vx + vy * vy)).clamp(0.0, 1.0);
let (px, py) = (ax + t * vx - x, ay + t * vy - y);
(px * px + py * py).sqrt() <= w
}
/// RGBA `size`×`size`, anti-aliasé par sur-échantillonnage 4×4.
pub fn render(size: u32, look: Look) -> Vec<u8> {
let bg = look.bg();
let mut out = Vec::with_capacity((size * size * 4) as usize);
const SS: u32 = 4;
for py in 0..size {
for px in 0..size {
let (mut a, mut r, mut g, mut b) = (0.0f32, 0.0f32, 0.0f32, 0.0f32);
for sy in 0..SS {
for sx in 0..SS {
let x = (px as f32 + (sx as f32 + 0.5) / SS as f32) / size as f32;
let y = (py as f32 + (sy as f32 + 0.5) / SS as f32) / size as f32;
if !rounded_rect(x, y, 0.24) {
continue;
}
let mut c = bg;
if bell(x, y) {
c = [1.0, 1.0, 1.0];
}
if look == Look::Muted {
if slash(x, y, 0.075) {
c = bg;
}
if slash(x, y, 0.04) {
c = [1.0, 1.0, 1.0];
}
}
a += 1.0;
r += c[0];
g += c[1];
b += c[2];
}
}
let n = (SS * SS) as f32;
if a > 0.0 {
out.extend_from_slice(&[(r / a * 255.0) as u8, (g / a * 255.0) as u8, (b / a * 255.0) as u8, (a / n * 255.0) as u8]);
} else {
out.extend_from_slice(&[0, 0, 0, 0]);
}
}
}
out
}
fn crc32(data: &[u8]) -> u32 {
let mut c = 0xFFFF_FFFFu32;
for &b in data {
c ^= b as u32;
for _ in 0..8 {
c = if c & 1 != 0 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 };
}
}
!c
}
/// PNG RGBA non compressé (blocs deflate « stored ») : suffisant pour une icône de 64 px.
pub fn png(size: u32, rgba: &[u8]) -> Vec<u8> {
let mut raw = Vec::with_capacity(rgba.len() + size as usize);
for row in rgba.chunks(size as usize * 4) {
raw.push(0);
raw.extend_from_slice(row);
}
let mut z = vec![0x78, 0x01];
let chunks: Vec<&[u8]> = raw.chunks(65535).collect();
for (i, ch) in chunks.iter().enumerate() {
z.push((i == chunks.len() - 1) as u8);
z.extend_from_slice(&(ch.len() as u16).to_le_bytes());
z.extend_from_slice(&(!(ch.len() as u16)).to_le_bytes());
z.extend_from_slice(ch);
}
let (mut a, mut b) = (1u32, 0u32);
for &x in &raw {
a = (a + x as u32) % 65521;
b = (b + a) % 65521;
}
z.extend_from_slice(&((b << 16) | a).to_be_bytes());
let mut out = vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
let mut chunk = |ty: &[u8; 4], data: &[u8]| {
out.extend_from_slice(&(data.len() as u32).to_be_bytes());
let mut c = ty.to_vec();
c.extend_from_slice(data);
out.extend_from_slice(&c);
out.extend_from_slice(&crc32(&c).to_be_bytes());
};
let mut ihdr = Vec::new();
ihdr.extend_from_slice(&size.to_be_bytes());
ihdr.extend_from_slice(&size.to_be_bytes());
ihdr.extend_from_slice(&[8, 6, 0, 0, 0]);
chunk(b"IHDR", &ihdr);
chunk(b"IDAT", &z);
chunk(b"IEND", &[]);
out
}
#[cfg(test)]
mod tests {
#[test]
fn crc() {
assert_eq!(super::crc32(b"123456789"), 0xCBF4_3926);
}
}
/// Logo 256 px (PNG), utilisé pour l'identité Windows des notifications.
pub const LOGO_PNG: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/logo_256.png"));
+162 -5
View File
@@ -21,17 +21,128 @@ pub const URL_SCHEME: &str = "gotify-lite";
const RUN_KEY: &str = r"Software\Microsoft\Windows\CurrentVersion\Run";
const RUN_VALUE: &str = "GotifyLite";
fn env_dir(var: &str) -> PathBuf {
let base = std::env::var_os(var).map(PathBuf::from).unwrap_or_else(std::env::temp_dir);
let p = base.join("GotifyLite");
const APP_KEY: &str = r"Software\GotifyLite";
const DATA_VALUE: &str = "DataDir";
fn default_dir(var: &str) -> PathBuf {
std::env::var_os(var).map(PathBuf::from).unwrap_or_else(std::env::temp_dir).join("GotifyLite")
}
/// Dossier personnalisé choisi par l'utilisateur (tout y est regroupé), sinon `None`.
pub fn custom_data_dir() -> Option<PathBuf> {
reg_get_str(APP_KEY, DATA_VALUE).filter(|s| !s.trim().is_empty()).map(PathBuf::from)
}
fn ensure(p: PathBuf) -> PathBuf {
let _ = std::fs::create_dir_all(&p);
p
}
/// Réglages (config.json).
pub fn roaming_dir() -> PathBuf {
env_dir("APPDATA")
ensure(custom_data_dir().unwrap_or_else(|| default_dir("APPDATA")))
}
/// État, icônes, journal.
pub fn local_dir() -> PathBuf {
env_dir("LOCALAPPDATA")
ensure(custom_data_dir().unwrap_or_else(|| default_dir("LOCALAPPDATA")))
}
/// Fichiers gérés par l'appli (chemins relatifs au dossier) : réglages puis données locales.
const ROAMING_FILES: &[&str] = &["config.json"];
const LOCAL_FILES: &[&str] = &["state.json", "window.json", "icon.png", "gotify-lite.log", "gotify-lite.log.old"];
fn copy_dir(from: &Path, to: &Path) -> std::io::Result<()> {
std::fs::create_dir_all(to)?;
for e in std::fs::read_dir(from)? {
let e = e?;
if e.file_type()?.is_file() {
std::fs::copy(e.path(), to.join(e.file_name()))?;
}
}
Ok(())
}
/// Déplace les données vers `target` (`None` = emplacements par défaut de Windows).
/// Copie d'abord tout, bascule ensuite, et ne supprime les anciens fichiers qu'en cas de succès.
pub fn migrate_data(target: Option<PathBuf>) -> Result<PathBuf, String> {
let (old_r, old_l) = (roaming_dir(), local_dir());
let (new_r, new_l) = match &target {
Some(t) => (t.clone(), t.clone()),
None => (default_dir("APPDATA"), default_dir("LOCALAPPDATA")),
};
let same = |a: &Path, b: &Path| a.canonicalize().ok().zip(b.canonicalize().ok()).is_some_and(|(x, y)| x == y) || a == b;
if same(&old_r, &new_r) && same(&old_l, &new_l) {
return Err("C'est déjà le dossier utilisé.".into());
}
for d in [&new_r, &new_l] {
std::fs::create_dir_all(d).map_err(|e| format!("Impossible de créer {} : {e}", d.display()))?;
let probe = d.join(".gotify-lite-test");
std::fs::write(&probe, b"ok").map_err(|e| format!("Dossier non accessible en écriture : {e}"))?;
let _ = std::fs::remove_file(probe);
}
let copy = |from: &Path, to: &Path, names: &[&str]| -> Result<(), String> {
for n in names {
let src = from.join(n);
if src.exists() && !same(&src, &to.join(n)) {
std::fs::copy(&src, to.join(n)).map_err(|e| format!("Copie de {n} : {e}"))?;
}
}
Ok(())
};
copy(&old_r, &new_r, ROAMING_FILES)?;
copy(&old_l, &new_l, LOCAL_FILES)?;
if old_l.join("icons").is_dir() && !same(&old_l.join("icons"), &new_l.join("icons")) {
copy_dir(&old_l.join("icons"), &new_l.join("icons")).map_err(|e| format!("Copie des icônes : {e}"))?;
}
// Bascule.
match &target {
Some(t) => {
if !reg_set_str(APP_KEY, Some(DATA_VALUE), &t.display().to_string()) {
return Err("Impossible d'enregistrer le nouveau dossier dans le registre.".into());
}
}
None => reg_delete_value(APP_KEY, DATA_VALUE),
}
register_app(&local_dir().join("icon.png"));
// Nettoyage de l'ancien emplacement (uniquement nos fichiers).
for (dir, names, new) in [(&old_r, ROAMING_FILES, &new_r), (&old_l, LOCAL_FILES, &new_l)] {
if same(dir, new) {
continue;
}
for n in names {
let _ = std::fs::remove_file(dir.join(n));
}
}
if !same(&old_l, &new_l) {
let _ = std::fs::remove_dir_all(old_l.join("icons"));
}
for d in [&old_r, &old_l] {
let _ = std::fs::remove_dir(d); // seulement s'il est vide
}
Ok(new_l)
}
/// Sélecteur de dossier natif Windows (bloquant : à appeler hors du thread de l'interface).
pub fn pick_folder(start: &Path) -> Option<PathBuf> {
use windows::Win32::System::Com::*;
use windows::Win32::UI::Shell::*;
unsafe {
let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
let dlg: IFileOpenDialog = CoCreateInstance(&FileOpenDialog, None, CLSCTX_INPROC_SERVER).ok()?;
let opts = dlg.GetOptions().ok()?;
dlg.SetOptions(opts | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM).ok()?;
let _ = dlg.SetTitle(w!("Choisir le dossier des données de Gotify Lite"));
if let Ok(item) = SHCreateItemFromParsingName::<_, _, IShellItem>(&HSTRING::from(start.as_os_str()), None) {
let _ = dlg.SetFolder(&item);
}
dlg.Show(None).ok()?;
let item = dlg.GetResult().ok()?;
let p = item.GetDisplayName(SIGDN_FILESYSPATH).ok()?;
let s = p.to_string().ok();
CoTaskMemFree(Some(p.0 as _));
s.map(PathBuf::from)
}
}
pub fn write_atomic(path: &Path, data: &[u8]) -> std::io::Result<()> {
@@ -380,3 +491,49 @@ mod clip_tests {
}
}
#[cfg(test)]
mod migrate_tests {
use super::*;
/// Modifie HKCU\Software\GotifyLite le temps du test : arrêter Gotify Lite avant.
/// `cargo test migrate -- --ignored --test-threads=1`
#[test]
#[ignore]
fn migrate_roundtrip() {
let base = std::env::temp_dir().join(format!("gl-migrate-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
unsafe {
std::env::set_var("APPDATA", base.join("roaming"));
std::env::set_var("LOCALAPPDATA", base.join("local"));
}
let before = custom_data_dir();
assert!(before.is_none(), "un dossier personnalisé est déjà configuré : test annulé");
std::fs::write(roaming_dir().join("config.json"), "{}").unwrap();
std::fs::write(local_dir().join("state.json"), "{}").unwrap();
std::fs::write(local_dir().join("window.json"), "{}").unwrap();
std::fs::create_dir_all(local_dir().join("icons")).unwrap();
std::fs::write(local_dir().join("icons").join("1-a.png"), "x").unwrap();
std::fs::write(local_dir().join("autre-fichier.txt"), "à garder").unwrap();
let target = base.join("D").join("GotifyLite");
let r = migrate_data(Some(target.clone()));
assert_eq!(r.as_deref().ok(), Some(target.as_path()), "{r:?}");
assert_eq!(custom_data_dir().as_deref(), Some(target.as_path()));
for f in ["config.json", "state.json", "window.json", "icons/1-a.png"] {
assert!(target.join(f).exists(), "{f} manquant");
}
assert!(!base.join("roaming/GotifyLite/config.json").exists(), "ancien config non supprimé");
assert!(!base.join("local/GotifyLite/icons").exists(), "anciennes icônes non supprimées");
assert!(base.join("local/GotifyLite/autre-fichier.txt").exists(), "fichier étranger supprimé !");
assert!(migrate_data(Some(target.clone())).is_err(), "même dossier accepté");
let back = migrate_data(None).unwrap();
assert!(custom_data_dir().is_none());
assert_eq!(back, base.join("local").join("GotifyLite"));
assert!(base.join("roaming/GotifyLite/config.json").exists());
assert!(base.join("local/GotifyLite/icons/1-a.png").exists());
assert!(!target.join("config.json").exists());
let _ = std::fs::remove_dir_all(&base);
}
}
+277 -20
View File
@@ -7,7 +7,7 @@ use eframe::egui::{self, Color32, RichText};
use crate::config::{Config, MUTE_FOREVER, State};
use crate::gotify::{self, App, Client, Message};
use crate::icon::{self, Look};
use crate::icon;
use crate::sys;
const PAGE: u32 = 100;
@@ -17,20 +17,65 @@ pub fn run(settings: bool) {
focus_existing();
return;
};
let rgba = icon::render(64, Look::Connected);
let options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_title(sys::APP_NAME)
.with_inner_size([820.0, 600.0])
.with_min_inner_size([560.0, 420.0])
.with_icon(Arc::new(egui::IconData { rgba, width: 64, height: 64 })),
..Default::default()
};
let rgba = icon::window_rgba();
let geom = WindowGeom::load();
let mut viewport = egui::ViewportBuilder::default()
.with_title(sys::APP_NAME)
.with_inner_size(geom.map(|g| [g.w, g.h]).unwrap_or([820.0, 600.0]))
.with_min_inner_size([560.0, 420.0])
.with_icon(Arc::new(egui::IconData { rgba, width: icon::WINDOW_SIZE, height: icon::WINDOW_SIZE }));
if let Some(g) = geom {
if g.on_screen() {
viewport = viewport.with_position([g.x, g.y]);
}
viewport = viewport.with_maximized(g.maximized);
}
let options = eframe::NativeOptions { viewport, ..Default::default() };
if let Err(e) = eframe::run_native(sys::APP_NAME, options, Box::new(move |cc| Ok(Box::new(Gui::new(&cc.egui_ctx, settings))))) {
sys::log(&format!("ui: {e}"));
}
}
/// Taille/position de la fenêtre, mémorisées entre deux ouvertures (window.json).
#[derive(Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
struct WindowGeom {
x: f32,
y: f32,
w: f32,
h: f32,
maximized: bool,
ppp: f32,
}
impl WindowGeom {
fn path() -> std::path::PathBuf {
sys::local_dir().join("window.json")
}
fn load() -> Option<Self> {
let g: Self = serde_json::from_str(&std::fs::read_to_string(Self::path()).ok()?).ok()?;
(g.w >= 200.0 && g.h >= 150.0).then_some(g)
}
fn save(&self) {
if let Ok(j) = serde_json::to_string(self) {
let _ = sys::write_atomic(&Self::path(), j.as_bytes());
}
}
/// Évite de rouvrir la fenêtre hors écran (écran débranché…).
fn on_screen(&self) -> bool {
use windows::Win32::UI::WindowsAndMessaging::*;
let (vx, vy, vw, vh) = unsafe {
(
GetSystemMetrics(SM_XVIRTUALSCREEN) as f32,
GetSystemMetrics(SM_YVIRTUALSCREEN) as f32,
GetSystemMetrics(SM_CXVIRTUALSCREEN) as f32,
GetSystemMetrics(SM_CYVIRTUALSCREEN) as f32,
)
};
let (x, y) = (self.x * self.ppp, self.y * self.ppp);
x + 80.0 > vx && y >= vy - 10.0 && x + 80.0 < vx + vw && y + 40.0 < vy + vh
}
}
fn focus_existing() {
use windows::Win32::UI::WindowsAndMessaging::*;
use windows::core::{HSTRING, PCWSTR};
@@ -54,6 +99,21 @@ enum Done {
DeletedMany(Option<u64>),
Test(Result<String, String>),
Error(String),
Image(String, Option<egui::ColorImage>),
Folder(Option<std::path::PathBuf>),
}
enum Img {
Loading,
Ready(egui::TextureHandle),
Failed,
}
fn decode_image(bytes: &[u8], max: u32) -> Option<egui::ColorImage> {
let img = image::load_from_memory(bytes).ok()?;
let img = if img.width() > max || img.height() > max { img.thumbnail(max, max) } else { img };
let rgba = img.to_rgba8();
Some(egui::ColorImage::from_rgba_unmultiplied([rgba.width() as usize, rgba.height() as usize], rgba.as_raw()))
}
struct Gui {
@@ -81,6 +141,15 @@ struct Gui {
test: Option<Result<String, String>>,
testing: bool,
images: std::collections::HashMap<String, Img>,
pending_dir: Option<std::path::PathBuf>,
logo: Option<egui::TextureHandle>,
geom: Option<WindowGeom>,
geom_saved: Option<WindowGeom>,
geom_changed: Instant,
picking: bool,
data_msg: Option<Result<String, String>>,
tx: mpsc::Sender<Done>,
rx: mpsc::Receiver<Done>,
ctx: egui::Context,
@@ -112,6 +181,14 @@ impl Gui {
error: None,
test: None,
testing: false,
images: Default::default(),
pending_dir: None,
logo: None,
geom: WindowGeom::load(),
geom_saved: WindowGeom::load(),
geom_changed: Instant::now(),
picking: false,
data_msg: None,
tx,
rx,
ctx: ctx.clone(),
@@ -192,6 +269,18 @@ impl Gui {
self.reload(false);
}
}
Done::Folder(p) => {
self.picking = false;
self.pending_dir = p;
self.data_msg = None;
}
Done::Image(key, img) => {
let v = match img {
Some(ci) => Img::Ready(self.ctx.load_texture(&key, ci, egui::TextureOptions::LINEAR)),
None => Img::Failed,
};
self.images.insert(key, v);
}
Done::Error(e) => {
self.loading = false;
self.error = Some(e);
@@ -231,6 +320,39 @@ impl Gui {
}
}
/// Texture de l'icône d'une appli (chargée en arrière-plan au premier appel).
fn app_texture(&mut self, id: u64) -> Option<egui::TextureHandle> {
if !self.cfg.show_images {
return None;
}
let key = format!("app:{id}");
if !self.images.contains_key(&key) {
let app = self.apps.iter().find(|a| a.id == id)?.clone();
self.images.insert(key.clone(), Img::Loading);
self.job(move |c| {
let img = c.app_icon(&app).and_then(|p| std::fs::read(p).ok()).and_then(|b| decode_image(&b, 64));
Done::Image(key, img)
});
return None;
}
match self.images.get(&key) {
Some(Img::Ready(t)) => Some(t.clone()),
_ => None,
}
}
fn url_texture(&mut self, url: &str) -> Option<&Img> {
if !self.images.contains_key(url) {
self.images.insert(url.to_string(), Img::Loading);
let key = url.to_string();
self.job(move |c| {
let img = c.fetch_external(&key).ok().and_then(|b| decode_image(&b, 1024));
Done::Image(key, img)
});
}
self.images.get(url)
}
fn app_name(&self, id: u64) -> &str {
self.apps.iter().find(|a| a.id == id).map(|a| a.name.as_str()).unwrap_or("?")
}
@@ -239,7 +361,12 @@ impl Gui {
fn header(&mut self, ui: &mut egui::Ui) {
ui.horizontal(|ui| {
ui.heading(RichText::new("🔔 Gotify Lite").strong());
let logo = self.logo.get_or_insert_with(|| {
let img = egui::ColorImage::from_rgba_unmultiplied([icon::WINDOW_SIZE as usize; 2], &icon::window_rgba());
ui.ctx().load_texture("logo", img, egui::TextureOptions::LINEAR)
});
ui.add(egui::Image::from_texture(&*logo).fit_to_exact_size(egui::vec2(26.0, 26.0)));
ui.heading(RichText::new("Gotify Lite").strong());
ui.add_space(12.0);
ui.selectable_value(&mut self.tab, Tab::Messages, "Messages");
ui.selectable_value(&mut self.tab, Tab::Settings, "Paramètres");
@@ -298,7 +425,13 @@ impl Gui {
let n = self.messages.iter().filter(|m| m.appid == id).count();
let muted = self.cfg.muted_apps.contains(&id);
let label = format!("{}{} ({n})", if muted { "🔕 " } else { "" }, name);
let r = ui.selectable_label(self.filter == Some(id), label);
let r = match self.app_texture(id) {
Some(t) => ui.selectable_label(
self.filter == Some(id),
(egui::Image::from_texture(&t).fit_to_exact_size(egui::vec2(18.0, 18.0)).corner_radius(4), label),
),
None => ui.selectable_label(self.filter == Some(id), label),
};
if r.clicked() {
self.filter = Some(id);
self.confirm_delete = false;
@@ -399,6 +532,9 @@ impl Gui {
ui.set_width(ui.available_width());
ui.horizontal(|ui| {
ui.colored_label(accent, "▍");
if let Some(t) = self.app_texture(m.appid) {
ui.add(egui::Image::from_texture(&t).fit_to_exact_size(egui::vec2(22.0, 22.0)).corner_radius(5));
}
ui.label(RichText::new(self.app_name(m.appid).to_string()).strong());
ui.label(RichText::new(format!("P{p}")).small().color(accent)).on_hover_text("Priorité");
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
@@ -418,6 +554,34 @@ impl Gui {
}
let body = if m.is_markdown() { gotify::strip_markdown(&m.message) } else { m.message.clone() };
ui.add(egui::Label::new(body).selectable(true).wrap());
if self.cfg.show_images
&& let Some(url) = m.big_image_url()
{
match self.url_texture(&url) {
Some(Img::Ready(t)) => {
let t = t.clone();
ui.add_space(4.0);
let r = ui.add(
egui::Image::from_texture(&t)
.max_width(ui.available_width().min(520.0))
.max_height(360.0)
.corner_radius(6)
.sense(egui::Sense::click()),
);
if r.on_hover_text("Ouvrir l'image").clicked() {
sys::open_url(&url);
}
}
Some(Img::Loading) => {
ui.spinner();
}
_ => {
if ui.link("🖼 Image jointe (non chargée)").clicked() {
sys::open_url(&url);
}
}
}
}
});
ui.add_space(4.0);
}
@@ -561,20 +725,17 @@ impl Gui {
sys::set_autostart(self.autostart);
self.autostart = sys::autostart_enabled();
}
ui.checkbox(&mut self.cfg.show_images, "Afficher les images (icônes des applications, images jointes)");
ui.horizontal(|ui| {
ui.label("Thème");
ui.selectable_value(&mut self.cfg.theme, "system".to_string(), "Système");
ui.selectable_value(&mut self.cfg.theme, "light".to_string(), "☀ Clair");
ui.selectable_value(&mut self.cfg.theme, "dark".to_string(), "🌙 Sombre");
});
ui.horizontal(|ui| {
if ui.button("Dossier des données").clicked() {
sys::open_url(&sys::local_dir().display().to_string());
}
if self.daemon_running && ui.button("Arrêter le service de fond").clicked() {
sys::stop_daemon();
}
});
if self.daemon_running && ui.button("Arrêter le service de fond").clicked() {
sys::stop_daemon();
}
self.data_section(ui);
ui.add_space(8.0);
ui.weak(format!("Gotify Lite {} · réglages enregistrés automatiquement", env!("CARGO_PKG_VERSION")));
});
@@ -606,6 +767,64 @@ fn install_system_fonts(ctx: &egui::Context) {
ctx.set_fonts(fonts);
}
impl Gui {
fn data_section(&mut self, ui: &mut egui::Ui) {
section(ui, "Dossier des données");
let custom = sys::custom_data_dir();
let current = sys::local_dir();
ui.horizontal_wrapped(|ui| {
ui.label("Emplacement :");
ui.monospace(current.display().to_string());
if custom.is_none() {
ui.weak("(par défaut)");
}
});
ui.horizontal(|ui| {
if ui.button("📂 Ouvrir").clicked() {
sys::open_url(&current.display().to_string());
}
if ui.add_enabled(!self.picking, egui::Button::new("Changer…")).clicked() {
self.picking = true;
let (tx, ctx, start) = (self.tx.clone(), self.ctx.clone(), current.clone());
std::thread::spawn(move || {
let _ = tx.send(Done::Folder(sys::pick_folder(&start)));
ctx.request_repaint();
});
}
if custom.is_some() && ui.button("Revenir à l'emplacement par défaut").clicked() {
self.data_msg = Some(sys::migrate_data(None).map(|p| format!("Données déplacées vers {}", p.display())));
}
});
if let Some(target) = self.pending_dir.clone() {
// Un sous-dossier dédié évite de mélanger nos fichiers avec d'autres.
let target = if target.file_name().is_some_and(|n| n.eq_ignore_ascii_case("GotifyLite")) { target } else { target.join("GotifyLite") };
egui::Frame::group(ui.style()).show(ui, |ui| {
ui.label(format!("Déplacer les réglages, l'historique local et les icônes vers :\n{}", target.display()));
ui.horizontal(|ui| {
if ui.button("Déplacer les données").clicked() {
self.data_msg = Some(sys::migrate_data(Some(target.clone())).map(|p| format!("Données déplacées vers {}", p.display())));
self.pending_dir = None;
self.cfg_mtime = Config::mtime();
}
if ui.button("Annuler").clicked() {
self.pending_dir = None;
}
});
});
}
match &self.data_msg {
Some(Ok(m)) => {
ui.colored_label(Color32::from_rgb(40, 170, 90), format!("✔ {m}"));
}
Some(Err(e)) => {
ui.colored_label(Color32::from_rgb(220, 70, 70), format!("✖ {e}"));
}
None => {}
}
ui.weak("Le token reste chiffré pour votre session Windows : il n'est utilisable que par votre compte.");
}
}
fn section(ui: &mut egui::Ui, title: &str) {
ui.add_space(14.0);
ui.label(RichText::new(title).strong().size(16.0));
@@ -621,8 +840,46 @@ fn time_edit(ui: &mut egui::Ui, minutes: &mut u16) {
*minutes = h * 60 + m;
}
impl Gui {
fn track_window(&mut self, ctx: &egui::Context) {
let (info_rect, inner, maximized, minimized, ppp, closing) = ctx.input(|i| {
let v = i.viewport();
(v.outer_rect, v.inner_rect, v.maximized.unwrap_or(false), v.minimized.unwrap_or(false), v.native_pixels_per_point.unwrap_or(1.0), v.close_requested())
});
if !minimized
&& let (Some(outer), Some(inner)) = (info_rect, inner)
{
let mut g = self.geom.unwrap_or(WindowGeom { x: outer.min.x, y: outer.min.y, w: inner.width(), h: inner.height(), maximized, ppp });
g.maximized = maximized;
if !maximized {
// On garde la taille « normale » pendant qu'elle est maximisée.
g = WindowGeom { x: outer.min.x, y: outer.min.y, w: inner.width(), h: inner.height(), maximized, ppp };
}
if Some(g) != self.geom {
self.geom = Some(g);
self.geom_changed = Instant::now();
}
}
let quiet = self.geom_changed.elapsed() > Duration::from_millis(800);
if self.geom != self.geom_saved && (quiet || closing) {
if let Some(g) = self.geom {
g.save();
}
self.geom_saved = self.geom;
}
}
}
impl eframe::App for Gui {
fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) {
if let Some(g) = self.geom {
g.save();
}
}
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
let ctx = ui.ctx().clone();
self.track_window(&ctx);
self.poll();
egui::Panel::top("top").show(ui, |ui| {
ui.add_space(6.0);