knotra 0.29.0

knotra: multi-project VCS dashboard and bulk-operation tool.
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
//! The short handlers (RFC-040 Stage 3 commit 7): project, history, settings,
//! external-tool launch, tag push, selection, palette, and dashboard-display
//! messages, plus the one helper used only by the last of those. Grouped by
//! size, not by a shared domain - each function here still owns exactly one
//! `Message` variant group end to end, same as every other `app/` module;
//! they are simply too small individually to each warrant their own file
//! (RFC-040 D1).
//!
//! RFC-043 Handoff 054: the documented `misc -> workspace` edge (RFC-040
//! D7, `.git-exclude/reviewed/089-...md`) existed solely for
//! `DashboardMessage::ErrorRetryRequested`'s call into
//! `handle_workspace`. That variant is gone with the rest of the dashboard
//! error path (`LoadPhase::Error` had zero production constructors), so
//! the edge and the `workspace` import it justified are gone too.
//!
//! RFC-044: `handle_topology` (`TopologyMessage::ScanRequested`) is gone —
//! scanning is automatic now (`shared::scan_topology_task`), triggered from
//! workspace load and every place the project set changes, not a message a
//! user sends.

use iced::Task;
use knotra_vcs::{
    VcsAdapter,
    model::operation::{OperationId, OperationKind, OperationLog, OperationResult},
};

use super::focus_ops;
use super::shared;
use crate::{
    config::{DashboardGrouping, save_config},
    message::{
        BackgroundMessage, DashboardMessage, HistoryMessage, LaunchMessage, Message,
        PaletteMessage, ProjectMessage, SelectionMessage, SettingsMessage, TagPushMessage,
    },
    state::{AppState, OperationOwner, focus},
};

pub(super) fn handle_project(state: &mut AppState, msg: ProjectMessage) -> Task<Message> {
    match msg {
        ProjectMessage::StatusRefreshRequested(id) => {
            let project = shared::find_project(state, &id);
            if let Some(p) = project {
                Task::perform(
                    async move { VcsAdapter::read_project_status(&p).await },
                    |s| {
                        Message::Background(BackgroundMessage::WorkspaceStatusRefreshed(
                            knotra_vcs::WorkspaceStatus {
                                projects: vec![s],
                                last_refresh: Some(chrono::Utc::now()),
                            },
                        ))
                    },
                )
            } else {
                Task::none()
            }
        }
        ProjectMessage::FetchRequested(id) => {
            let project = shared::find_project(state, &id);
            if let Some(p) = project {
                let Some(lease_id) = shared::acquire_operation(state, OperationOwner::SingleFetch)
                else {
                    return Task::none();
                };
                state.fetching_projects.insert(id.clone());
                Task::perform(
                    async move {
                        let started = chrono::Utc::now();
                        let op_id = OperationId::new();
                        let result = VcsAdapter::fetch(&p).await;
                        OperationLog {
                            result: OperationResult {
                                operation_id: op_id,
                                kind: OperationKind::Fetch,
                                started_at: started,
                                finished_at: chrono::Utc::now(),
                                per_project: vec![result],
                                rollback_attempted: false,
                                rollback_succeeded: None,
                            },
                            recovery_hints: vec![],
                        }
                    },
                    move |log| {
                        Message::Background(BackgroundMessage::SingleFetchCompleted {
                            lease_id,
                            log,
                        })
                    },
                )
            } else {
                state.fetching_projects.remove(&id);
                Task::none()
            }
        }
    }
}

pub(super) fn handle_history(state: &mut AppState, msg: HistoryMessage) -> Task<Message> {
    match msg {
        HistoryMessage::SearchChanged(s) => {
            state.history_search = s;
        }
        HistoryMessage::EntryToggled(id) => {
            if state.history_expanded.contains(&id) {
                state.history_expanded.remove(&id);
            } else {
                state.history_expanded.insert(id);
            }
        }
    }
    Task::none()
}

pub(super) fn handle_settings(state: &mut AppState, msg: SettingsMessage) -> Task<Message> {
    match msg {
        SettingsMessage::LocaleChanged(l) => {
            state.config.locale = l;
            state.catalog = knotra_ui::i18n::Catalog::for_locale(l);
        }
        SettingsMessage::ThemeChanged(dark) => {
            state.config.dark_theme = dark;
            state.theme = if dark {
                knotra_ui::KnotraTheme::dark()
            } else {
                knotra_ui::KnotraTheme::light()
            };
        }
        SettingsMessage::RefreshIntervalChanged(s) => {
            // 0 is a valid value here (means manual refresh only) — any
            // parseable u32 is accepted. On invalid input, the edit buffer
            // still shows exactly what the user typed; `config` keeps its
            // last valid value rather than silently coercing.
            if let Ok(n) = s.parse::<u32>() {
                state.config.refresh_interval_secs = n;
            }
            state.settings_edit.refresh_interval_secs = s;
        }
        SettingsMessage::MaxConcurrentChanged(s) => {
            // Must be > 0 — a concurrency limit of 0 would mean nothing
            // could ever read, so it's rejected the same as unparseable text.
            if let Ok(n) = s.parse::<usize>()
                && n > 0
            {
                state.config.max_concurrent_reads = n;
            }
            state.settings_edit.max_concurrent_reads = s;
        }
        SettingsMessage::ExternalEditorChanged(s) => {
            state.settings_edit.external_editor = s.clone();
            state.config.external_editor = if s.trim().is_empty() {
                None
            } else {
                Some(s.trim().to_owned())
            };
        }
        SettingsMessage::ExternalMergeToolChanged(s) => {
            state.settings_edit.external_merge_tool = s.clone();
            state.config.external_merge_tool = if s.trim().is_empty() {
                None
            } else {
                Some(s.trim().to_owned())
            };
        }
        SettingsMessage::MaxLogEntriesChanged(s) => {
            // Must be > 0 — zero retained log entries isn't a meaningful
            // setting, same reasoning as max concurrent reads above.
            if let Ok(n) = s.parse::<usize>()
                && n > 0
            {
                state.config.max_log_entries = n;
            }
            state.settings_edit.max_log_entries = s;
        }
        SettingsMessage::FsWatchEnabledChanged(v) => {
            state.config.fs_watch_enabled = v;
            if !v {
                state.settings_save_msg =
                    Some(state.t("plain.activity.fs_watch_disabled").to_owned());
            }
        }
        SettingsMessage::FsDebounceSecs(s) => {
            // Like the refresh interval, 0 is a legitimate value here.
            if let Ok(n) = s.parse::<u32>() {
                state.config.fs_debounce_secs = n;
            }
            state.settings_edit.fs_debounce_secs = s;
        }
        SettingsMessage::SaveRequested => match save_config(&state.config, &state.paths) {
            Ok(()) => {
                state.settings_save_msg = Some(state.t("settings.saved_ok").to_owned());
                state.status_bar = Some(state.t("settings.saved_ok").to_owned());
            }
            Err(e) => {
                state.settings_save_msg = Some(format!("{} {e}", state.t("settings.save_error")));
            }
        },
    }
    Task::none()
}

pub(super) fn handle_launch(state: &mut AppState, msg: LaunchMessage) -> Task<Message> {
    let (tool_path, file_path) = match msg {
        LaunchMessage::OpenInEditor(path) => (state.config.external_editor.clone(), path),
        LaunchMessage::OpenInMergeTool(path) => (state.config.external_merge_tool.clone(), path),
    };

    let Some(tool) = tool_path else {
        state.status_bar = Some(state.t("tool.not_configured").to_owned());
        return Task::none();
    };

    match std::process::Command::new(&tool).arg(&file_path).spawn() {
        Ok(_) => {
            state.status_bar = Some(format!(
                "{} {} {:?}",
                state.t("plain.activity.launched"),
                tool,
                file_path
            ));
        }
        Err(e) => {
            state.status_bar = Some(format!("{} {}: {e}", state.t("tool.launch_failed"), tool));
        }
    }
    Task::none()
}

pub(super) fn handle_tag_push(state: &mut AppState, msg: TagPushMessage) -> Task<Message> {
    match msg {
        TagPushMessage::PushConfirmed => {
            let push = match &state.pending_tag_push {
                Some(p) => p.clone(),
                None => return Task::none(),
            };
            let Some(lease_id) = shared::acquire_operation(state, OperationOwner::TagPush) else {
                return Task::none();
            };
            if let Some(ref mut p) = state.pending_tag_push {
                p.is_pushing = true;
            }

            let projects: Vec<_> = push
                .project_ids
                .iter()
                .filter_map(|id| shared::find_project(state, id))
                .collect();
            let tag_name = push.freeze_name.clone();
            let max = state.config.max_concurrent_reads;

            Task::perform(
                async move {
                    use std::sync::Arc;
                    use tokio::sync::Semaphore;

                    let sem = Arc::new(Semaphore::new(max));
                    let mut handles = Vec::new();
                    for project in projects {
                        let sem = Arc::clone(&sem);
                        let tag = tag_name.clone();
                        handles.push(tokio::spawn(async move {
                            let _permit = sem.acquire().await.expect("open");
                            knotra_vcs::VcsAdapter::push_tag(&project, &tag).await
                        }));
                    }
                    let mut results = Vec::new();
                    for h in handles {
                        if let Ok(r) = h.await {
                            results.push(r);
                        }
                    }
                    let success = results.iter().filter(|r| r.success).count();
                    let failed = results.iter().filter(|r| !r.success).count();
                    (success, failed)
                },
                move |(success_count, fail_count)| {
                    Message::Background(BackgroundMessage::TagPushCompleted {
                        lease_id,
                        success_count,
                        fail_count,
                    })
                },
            )
        }

        TagPushMessage::PushDeclined => {
            if state
                .pending_tag_push
                .as_ref()
                .is_some_and(|push| push.is_pushing)
            {
                return Task::none();
            }
            state.pending_tag_push = None;
            Task::none()
        }
    }
}

pub(super) fn handle_selection(state: &mut AppState, msg: SelectionMessage) -> Task<Message> {
    let ordered: Vec<knotra_vcs::ProjectId> = state.visible_project_ids();

    match msg {
        SelectionMessage::ModeEntered => state.selection_mode = true,
        SelectionMessage::ModeExited => state.clear_selection_mode(),
        SelectionMessage::Toggled(id) => {
            let active_ids: std::collections::HashSet<_> = ordered.iter().cloned().collect();
            if !active_ids.contains(&id) {
                return Task::none();
            }
            state.selection_mode = true; // selecting anything enters mode
            state.selection.toggle(id);
        }
        SelectionMessage::SelectAll => {
            state.selection_mode = true;
            let ids = state.visible_project_ids();
            state.selection.clear();
            state.selection.select_all(&ids);
        }
        SelectionMessage::Clear => state.clear_selection_mode(),
    }
    Task::none()
}

pub(super) fn handle_palette(state: &mut AppState, msg: PaletteMessage) -> Task<Message> {
    match msg {
        PaletteMessage::Opened => {
            state.palette.open_palette();
            crate::state::palette::update_results(state);
            return focus_ops::open_overlay_focus(
                state,
                focus::FocusTarget::text_input(knotra_ui::widget::focus_id::PALETTE_QUERY.clone()),
            );
        }
        PaletteMessage::Closed => state.palette.close(),
        PaletteMessage::QueryChanged(q) => {
            state.palette.query = q;
            state.palette.notice_key = None;
            crate::state::palette::update_results(state);
        }
        PaletteMessage::EntryClicked(i) => {
            state.palette.highlighted = i;
            match crate::state::palette::dispatch_entry(state) {
                crate::state::palette::PaletteDispatch::Dispatched(msg) => {
                    state.palette.close();
                    return Task::done(msg);
                }
                crate::state::palette::PaletteDispatch::Disabled(reason) => {
                    state.palette.notice_key = Some(reason);
                }
                crate::state::palette::PaletteDispatch::Noop => {
                    state.palette.notice_key = Some("palette.disabled.unavailable");
                }
            }
        }
    }
    Task::none()
}

pub(super) fn handle_dashboard(state: &mut AppState, msg: DashboardMessage) -> Task<Message> {
    match msg {
        DashboardMessage::GroupingChanged(grouping) => {
            state.config.dashboard_grouping = grouping;
            persist_dashboard_preferences(state);
            state.reconcile_selection_with_display();
        }
        DashboardMessage::SortChanged(sort) => {
            state.config.dashboard_sort = sort;
            persist_dashboard_preferences(state);
        }
        DashboardMessage::TierToggled(tier) => {
            if state.config.dashboard_grouping == DashboardGrouping::Attention {
                match tier {
                    crate::state::dashboard::DashboardTier::NeedsHelp => {}
                    crate::state::dashboard::DashboardTier::InProgress => {
                        state.config.dashboard_in_progress_collapsed =
                            !state.config.dashboard_in_progress_collapsed;
                    }
                    crate::state::dashboard::DashboardTier::AllSet => {
                        state.config.dashboard_all_set_collapsed =
                            !state.config.dashboard_all_set_collapsed;
                    }
                }
                persist_dashboard_preferences(state);
                state.reconcile_selection_with_display();
            }
        }
        DashboardMessage::ToolbarOverflowToggled => {
            state.dashboard_toolbar_overflow_open = !state.dashboard_toolbar_overflow_open;
        }
        DashboardMessage::ToolbarSelectorsToggled => {
            state.dashboard_toolbar_selectors_open = !state.dashboard_toolbar_selectors_open;
        }
    }
    Task::none()
}

fn persist_dashboard_preferences(state: &mut AppState) {
    if let Err(error) = save_config(&state.config, &state.paths) {
        tracing::warn!("failed to persist dashboard preferences: {error}");
        state.status_bar = Some(state.t("dashboard.preference_save_failed").to_owned());
    }
}