knotra 0.25.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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
//! The short handlers (RFC-040 Stage 3 commit 7): project, history, settings,
//! external-tool launch, topology, 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).
//!
//! `handle_dashboard` calls `handle_workspace` directly - a documented
//! `misc -> workspace` edge per `.git-exclude/reviewed/089-...md`'s ruling
//! (handler modules may call another handler where the domain genuinely
//! requires it, provided the dependency graph stays acyclic) and RFC-040
//! D7. As of RFC-040 Stage 4 this is a real cross-handler-module import -
//! `handle_workspace` calls nothing in this module, so the graph stays
//! acyclic. `workspace.rs` must not import `misc.rs`.

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

// `handle_dashboard` calls `handle_workspace` directly - the documented
// `misc -> workspace` edge (RFC-040 D7). See this module's doc comment.
use super::focus_ops;
use super::shared;
use super::workspace;
use crate::{
    config::{DashboardGrouping, save_config},
    message::{
        BackgroundMessage, DashboardMessage, HistoryMessage, LaunchMessage, Message,
        PaletteMessage, ProjectMessage, SelectionMessage, SettingsMessage, TagPushMessage,
        TopologyMessage, WorkspaceMessage,
    },
    state::{
        AppState, LoadPhase, OperationOwner, PendingTagPush, Screen, focus, topology::TopologyPhase,
    },
};

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);
            }
        }
        HistoryMessage::LogCopyRequested(_id) => {
            // Clipboard access is platform-dependent; Phase 7 can wire iced's clipboard API.
            // For now we record the intent and show a status-bar note.
            // Real clipboard write is handled by Message::CopyToClipboard.
            // This is a fallback status note in case no text was available.
            state.status_bar = Some("Copy command sent.".to_owned());
        }
        HistoryMessage::BackToDashboard => {
            state.screen = Screen::Dashboard;
        }
    }
    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) => {
            state.settings_edit.refresh_interval_secs = s.to_string();
            state.config.refresh_interval_secs = s;
        }
        SettingsMessage::MaxConcurrentChanged(n) => {
            state.settings_edit.max_concurrent_reads = n.to_string();
            state.config.max_concurrent_reads = n;
        }
        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(n) => {
            state.settings_edit.max_log_entries = n.to_string();
            state.config.max_log_entries = n;
        }
        SettingsMessage::FsWatchEnabledChanged(v) => {
            state.config.fs_watch_enabled = v;
            if !v {
                state.settings_save_msg = Some("FS watching disabled.".to_owned());
            }
        }
        SettingsMessage::FsDebounceSecs(n) => {
            state.settings_edit.refresh_interval_secs = n.to_string();
            state.config.fs_debounce_secs = n;
        }
        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")));
            }
        },
        SettingsMessage::BackToDashboard => {
            state.screen = Screen::Dashboard;
        }
    }
    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!("Launched: {} {:?}", tool, file_path));
        }
        Err(e) => {
            state.status_bar = Some(format!("{} {}: {e}", state.t("tool.launch_failed"), tool));
        }
    }
    Task::none()
}

pub(super) fn handle_topology(state: &mut AppState, msg: TopologyMessage) -> Task<Message> {
    match msg {
        TopologyMessage::ScanRequested => {
            let projects: Vec<_> = state
                .workspace
                .as_ref()
                .map(|ws| ws.projects.clone())
                .unwrap_or_default();
            state.topology.phase = TopologyPhase::Scanning;

            Task::perform(
                async move { VcsAdapter::scan_topology(&projects).await },
                |graph| Message::Background(BackgroundMessage::TopologyScanned(graph)),
            )
        }
    }
}

pub(super) fn handle_tag_push(state: &mut AppState, msg: TagPushMessage) -> Task<Message> {
    match msg {
        TagPushMessage::OfferShown {
            freeze_name,
            project_ids,
        } => {
            state.pending_tag_push = Some(PendingTagPush {
                freeze_name,
                project_ids,
                is_pushing: false,
            });
            Task::none()
        }

        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::RangeTo(id) => {
            if !ordered.contains(&id) {
                return Task::none();
            }
            state.selection_mode = true;
            state.selection.select_range(&ordered, &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(),
        SelectionMessage::FocusMoved(_) => {} // focus tracking only
    }
    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::MoveUp => {
            if state.palette.highlighted > 0 {
                state.palette.highlighted -= 1;
            }
        }
        PaletteMessage::MoveDown => {
            let max = state.palette.results.len().saturating_sub(1);
            if state.palette.highlighted < max {
                state.palette.highlighted += 1;
            }
        }
        PaletteMessage::Confirmed | PaletteMessage::EntryClicked(_) => {
            if let PaletteMessage::EntryClicked(i) = msg {
                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::ErrorDetailsToggled => {
            if matches!(state.load_phase, LoadPhase::Error(_)) {
                state.dashboard_error_details_open = !state.dashboard_error_details_open;
            }
        }
        DashboardMessage::ErrorRetryRequested => {
            if matches!(state.load_phase, LoadPhase::Error(_)) && state.workspace.is_some() {
                state.is_refreshing = false;
                return workspace::handle_workspace(state, WorkspaceMessage::RefreshRequested);
            }
        }
        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());
    }
}