siggy 1.8.0

Terminal-based Signal messenger client with vim keybindings
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
//! TOML configuration at the platform-specific user config dir.
//!
//! Held as [`Config`]; persists account (E.164 phone), `signal_cli_path`,
//! `download_dir`, and assorted UI preferences. Includes silent migrations:
//! the legacy `~/.config/signal-tui/` -> `~/.config/siggy/` rename and the
//! `inline_images` / `native_images` -> `image_mode` field collapse.

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

/// Notification preview detail level. Drives whether desktop notification
/// bodies show the message text, just the sender, or nothing beyond
/// "new message". Persisted in `notification_preview` config field.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum NotificationPreview {
    /// Show sender + body.
    #[default]
    Full,
    /// Show sender only.
    Sender,
    /// Show "new message" only.
    Minimal,
}

impl NotificationPreview {
    /// Cycle to the next preview level (Full -> Sender -> Minimal -> Full).
    pub fn cycle(self) -> Self {
        match self {
            Self::Full => Self::Sender,
            Self::Sender => Self::Minimal,
            Self::Minimal => Self::Full,
        }
    }

    /// User-facing label for the settings overlay.
    pub fn label(self) -> &'static str {
        match self {
            Self::Full => "full",
            Self::Sender => "sender",
            Self::Minimal => "minimal",
        }
    }
}

/// Image rendering mode. Selects the protocol used to draw inline image
/// previews in the chat pane. Persisted in `image_mode` config field.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ImageMode {
    /// Native terminal image protocols (Kitty, iTerm2, Sixel).
    Native,
    /// Unicode halfblock approximation. Universal fallback.
    #[default]
    Halfblock,
    /// Do not render images.
    None,
}

impl ImageMode {
    /// Cycle to the next image mode (Native -> Halfblock -> None -> Native).
    pub fn cycle(self) -> Self {
        match self {
            Self::Native => Self::Halfblock,
            Self::Halfblock => Self::None,
            Self::None => Self::Native,
        }
    }

    /// User-facing label for the settings overlay.
    pub fn label(self) -> &'static str {
        match self {
            Self::Native => "native",
            Self::Halfblock => "halfblock",
            Self::None => "none",
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    /// Phone number in E.164 format (e.g., +15551234567)
    #[serde(default)]
    pub account: String,

    /// Path to signal-cli binary
    #[serde(default = "default_signal_cli_path")]
    pub signal_cli_path: String,

    /// Directory for downloaded attachments
    #[serde(default = "default_download_dir")]
    pub download_dir: PathBuf,

    /// Terminal bell for 1:1 messages in background conversations
    #[serde(default = "default_true")]
    pub notify_direct: bool,

    /// Terminal bell for group messages in background conversations
    #[serde(default = "default_true")]
    pub notify_group: bool,

    /// OS-level desktop notifications for incoming messages
    #[serde(default)]
    pub desktop_notifications: bool,

    /// Notification preview level (full / sender / minimal).
    #[serde(default)]
    pub notification_preview: NotificationPreview,

    /// Seconds before clipboard is auto-cleared after copying (0 = disabled)
    #[serde(default = "default_clipboard_clear_seconds")]
    pub clipboard_clear_seconds: u64,

    /// Image display mode (native / halfblock / none). `None` here means the
    /// field was absent from the on-disk TOML and migration should fill it in
    /// from the legacy `inline_images` / `native_images` flags.
    #[serde(default)]
    pub image_mode: Option<ImageMode>,

    /// Override cell pixel width for Sixel sizing (0 = auto-detect)
    #[serde(default)]
    pub cell_pixel_width: u16,

    /// Override cell pixel height for Sixel sizing (0 = auto-detect)
    #[serde(default)]
    pub cell_pixel_height: u16,

    /// Legacy: show inline halfblock image previews (migrated to image_mode)
    #[serde(default = "default_true", skip_serializing)]
    pub inline_images: bool,

    /// Show link previews (title, description, thumbnail) for URLs in messages
    #[serde(default = "default_true")]
    pub show_link_previews: bool,

    /// Legacy: use native terminal image protocols (migrated to image_mode)
    #[serde(default, skip_serializing)]
    pub native_images: bool,

    /// Show date separator lines between messages from different days
    #[serde(default = "default_true")]
    pub date_separators: bool,

    /// Show delivery/read receipt status symbols on outgoing messages
    #[serde(default = "default_true")]
    pub show_receipts: bool,

    /// Use colored status symbols (vs monochrome DarkGray)
    #[serde(default = "default_true")]
    pub color_receipts: bool,

    /// Use Nerd Font glyphs for status symbols
    #[serde(default)]
    pub nerd_fonts: bool,

    /// Convert emoji to text emoticons/shortcodes in message display
    #[serde(default)]
    pub emoji_to_text: bool,

    /// Show emoji reactions on messages
    #[serde(default = "default_true")]
    pub show_reactions: bool,

    /// Show verbose reaction display (usernames instead of counts)
    #[serde(default)]
    pub reaction_verbose: bool,

    /// Send read receipts to message senders when viewing conversations
    #[serde(default = "default_true")]
    pub send_read_receipts: bool,

    /// Enable mouse support (click sidebar, scroll messages, click links)
    #[serde(default = "default_true")]
    pub mouse_enabled: bool,

    /// Display sidebar on the right side instead of left
    #[serde(default)]
    pub sidebar_on_right: bool,

    /// Sidebar width in columns (14-40, default 22)
    #[serde(default = "default_sidebar_width")]
    pub sidebar_width: u16,

    /// Color theme name (matches a built-in or custom theme)
    #[serde(default = "default_theme")]
    pub theme: String,

    /// Keybinding profile name (matches a built-in or custom profile)
    #[serde(default = "default_keybinding_profile")]
    pub keybinding_profile: String,

    /// Settings profile name (matches a built-in or custom profile)
    #[serde(default = "default_settings_profile")]
    pub settings_profile: String,

    /// Signal TLS proxy URL passed through to signal-cli (e.g., `<https://signal-proxy.example.com>`)
    #[serde(default)]
    pub proxy: String,
}

fn default_true() -> bool {
    true
}

fn default_theme() -> String {
    "Default".to_string()
}

fn default_keybinding_profile() -> String {
    "Default".to_string()
}

fn default_settings_profile() -> String {
    "Default".to_string()
}

fn default_clipboard_clear_seconds() -> u64 {
    30
}

fn default_sidebar_width() -> u16 {
    22
}

fn default_signal_cli_path() -> String {
    "signal-cli".to_string()
}

fn default_download_dir() -> PathBuf {
    dirs::home_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join("signal-downloads")
}

impl Default for Config {
    fn default() -> Self {
        Self {
            account: String::new(),
            signal_cli_path: default_signal_cli_path(),
            download_dir: default_download_dir(),
            notify_direct: true,
            notify_group: true,
            desktop_notifications: false,
            notification_preview: NotificationPreview::Full,
            clipboard_clear_seconds: default_clipboard_clear_seconds(),
            image_mode: Some(ImageMode::Halfblock),
            cell_pixel_width: 0,
            cell_pixel_height: 0,
            inline_images: true,
            show_link_previews: true,
            native_images: false,
            date_separators: true,
            show_receipts: true,
            color_receipts: true,
            nerd_fonts: false,
            emoji_to_text: false,
            show_reactions: true,
            reaction_verbose: false,
            send_read_receipts: true,
            mouse_enabled: true,
            sidebar_on_right: false,
            sidebar_width: default_sidebar_width(),
            theme: default_theme(),
            keybinding_profile: default_keybinding_profile(),
            settings_profile: default_settings_profile(),
            proxy: String::new(),
        }
    }
}

impl Config {
    pub fn load(path: Option<&str>) -> Result<Self> {
        let config_path = match path {
            Some(p) => PathBuf::from(p),
            None => {
                let new_path = Self::default_config_path();
                if let (Some(new_dir), Some(old_dir)) = (new_path.parent(), legacy_config_dir()) {
                    crate::fs_migrate::migrate_path(&old_dir, new_dir);
                }
                new_path
            }
        };

        if config_path.exists() {
            let contents = std::fs::read_to_string(&config_path)
                .with_context(|| format!("Failed to read config from {}", config_path.display()))?;
            let mut config: Config = toml::from_str(&contents).with_context(|| {
                format!("Failed to parse config from {}", config_path.display())
            })?;
            config.migrate_legacy_image_mode();
            Ok(config)
        } else {
            Ok(Config::default())
        }
    }

    /// Backfill `image_mode` from the legacy `inline_images` / `native_images`
    /// flags when upgrading from a config written by siggy < v1.6.0. No-op
    /// once `image_mode` is set.
    fn migrate_legacy_image_mode(&mut self) {
        if self.image_mode.is_some() {
            return;
        }
        self.image_mode = Some(if self.native_images {
            ImageMode::Native
        } else if self.inline_images {
            ImageMode::Halfblock
        } else {
            ImageMode::None
        });
    }

    /// Serialize this config to TOML and write it to the default config path.
    pub fn save(&self) -> Result<()> {
        let config_path = Self::default_config_path();
        if let Some(parent) = config_path.parent() {
            std::fs::create_dir_all(parent).with_context(|| {
                format!("Failed to create config directory {}", parent.display())
            })?;
            Self::set_dir_permissions(parent);
        }
        let contents = toml::to_string_pretty(self).context("Failed to serialize config")?;
        std::fs::write(&config_path, contents)
            .with_context(|| format!("Failed to write config to {}", config_path.display()))?;
        Self::set_file_permissions(&config_path);
        Ok(())
    }

    /// Set restrictive permissions (0600) on a sensitive file (Unix only).
    #[cfg(unix)]
    fn set_file_permissions(path: &std::path::Path) {
        use std::os::unix::fs::PermissionsExt;
        let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
    }

    #[cfg(not(unix))]
    fn set_file_permissions(_path: &std::path::Path) {}

    /// Set restrictive permissions (0700) on a sensitive directory (Unix only).
    #[cfg(unix)]
    fn set_dir_permissions(path: &std::path::Path) {
        use std::os::unix::fs::PermissionsExt;
        let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700));
    }

    #[cfg(not(unix))]
    fn set_dir_permissions(_path: &std::path::Path) {}

    /// Returns true if the account is empty and setup is needed.
    pub fn needs_setup(&self) -> bool {
        self.account.is_empty()
    }

    pub fn default_config_path() -> PathBuf {
        dirs::config_dir()
            .unwrap_or_else(|| PathBuf::from(".config"))
            .join("siggy")
            .join("config.toml")
    }
}

/// Path to the legacy `signal-tui` config directory, if `dirs::config_dir()`
/// is resolvable on this platform.
fn legacy_config_dir() -> Option<PathBuf> {
    dirs::config_dir().map(|d| d.join("signal-tui"))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn legacy_config(inline: bool, native: bool) -> Config {
        // image_mode MUST be explicitly None here -- Config::default()
        // sets it to Some(Halfblock), which would early-return the migration.
        Config {
            image_mode: None,
            inline_images: inline,
            native_images: native,
            ..Config::default()
        }
    }

    #[test]
    fn migrate_legacy_image_mode_native_wins() {
        let mut c = legacy_config(true, true);
        c.migrate_legacy_image_mode();
        assert_eq!(c.image_mode, Some(ImageMode::Native));
    }

    #[test]
    fn migrate_legacy_image_mode_halfblock_when_only_inline() {
        let mut c = legacy_config(true, false);
        c.migrate_legacy_image_mode();
        assert_eq!(c.image_mode, Some(ImageMode::Halfblock));
    }

    #[test]
    fn migrate_legacy_image_mode_none_when_both_disabled() {
        let mut c = legacy_config(false, false);
        c.migrate_legacy_image_mode();
        assert_eq!(c.image_mode, Some(ImageMode::None));
    }

    #[test]
    fn migrate_legacy_image_mode_preserves_existing() {
        let mut c = Config {
            image_mode: Some(ImageMode::Native),
            inline_images: false,
            native_images: false,
            ..Config::default()
        };
        c.migrate_legacy_image_mode();
        assert_eq!(c.image_mode, Some(ImageMode::Native));
    }

    // Filesystem migrations are tested in db::tests::migrate_path_*.
    // The Config::load wiring is exercised by integration; the rename
    // semantics live in `db::migrate_path`.
}