pub mod changelog;
pub mod conflict_ops;
pub mod context;
pub mod dashboard;
pub mod detail_panel;
pub mod focus;
pub mod freezer;
pub mod layer;
pub mod palette;
pub mod sync;
pub mod topology;
pub mod workspace_mgr;
use std::collections::HashSet;
use knotra_ui::KnotraTheme;
use knotra_ui::i18n::Catalog;
use knotra_vcs::{
OperationId, WorkspaceStatus,
model::{
operation::{OperationLog, ProjectOperationResult, RetryExclusionReason},
project::ProjectId,
workspace::Workspace,
},
};
use crate::{
config::{AppConfig, AppPaths},
message::{FilterMessage, StatusFilter},
view::dashboard::WidthMode,
};
pub const INITIAL_WINDOW_SIZE: iced::Size = iced::Size::new(1100.0, 720.0);
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Screen {
Dashboard,
History,
Settings,
}
#[derive(Debug, Clone, Default)]
pub struct FilterState {
pub search_text: String,
pub active_group: Option<String>,
pub status_filters: Vec<StatusFilter>,
}
impl FilterState {
pub fn is_active(&self) -> bool {
!self.search_text.is_empty()
|| self.active_group.is_some()
|| !self.status_filters.is_empty()
}
pub fn has_status_filter(&self, sf: &StatusFilter) -> bool {
self.status_filters.contains(sf)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum AddProjectStep {
#[default]
ChooseFolder,
NameProject,
}
#[derive(Debug, Clone, Default)]
pub struct AddProjectDialog {
pub step: AddProjectStep,
pub name: String,
pub path: String,
pub error: Option<String>,
}
#[derive(Debug, Clone)]
pub struct ConfirmRemoveDialog {
pub project_id: ProjectId,
pub project_name: String,
}
#[derive(Debug, Clone)]
pub struct UndoableRemoval {
pub project: knotra_vcs::Project,
pub status_snapshot: Option<knotra_vcs::ProjectStatus>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LoadPhase {
Startup,
Refreshing,
Ready,
}
#[derive(Debug, Clone)]
pub struct SettingsEdit {
pub external_editor: String,
pub external_merge_tool: String,
}
impl SettingsEdit {
pub fn from_config(cfg: &AppConfig) -> Self {
SettingsEdit {
external_editor: cfg.external_editor.clone().unwrap_or_default(),
external_merge_tool: cfg.external_merge_tool.clone().unwrap_or_default(),
}
}
}
#[derive(Debug, Clone)]
pub struct PendingTagPush {
pub freeze_name: String,
pub project_ids: Vec<knotra_vcs::ProjectId>,
pub is_pushing: bool,
}
#[derive(Debug, Clone, Default)]
pub struct SelectionState {
pub selected_ids: HashSet<knotra_vcs::ProjectId>,
pub anchor_id: Option<knotra_vcs::ProjectId>,
}
impl SelectionState {
pub fn toggle(&mut self, id: knotra_vcs::ProjectId) {
if self.selected_ids.contains(&id) {
self.selected_ids.remove(&id);
if self.selected_ids.is_empty() {
self.anchor_id = None;
} else if self.anchor_id.as_ref() == Some(&id) {
self.anchor_id = self.selected_ids.iter().next().cloned();
}
} else {
self.selected_ids.insert(id.clone());
self.anchor_id = Some(id);
}
}
pub fn clear(&mut self) {
self.selected_ids.clear();
self.anchor_id = None;
}
pub fn contains(&self, id: &knotra_vcs::ProjectId) -> bool {
self.selected_ids.contains(id)
}
pub fn select_all(&mut self, ids: &[knotra_vcs::ProjectId]) {
for id in ids {
self.selected_ids.insert(id.clone());
}
if self.anchor_id.is_none() {
self.anchor_id = ids.first().cloned();
}
}
pub fn retain_ids(&mut self, ids: &HashSet<knotra_vcs::ProjectId>) {
self.selected_ids.retain(|id| ids.contains(id));
if self
.anchor_id
.as_ref()
.is_some_and(|anchor| !self.selected_ids.contains(anchor))
{
self.anchor_id = self.selected_ids.iter().next().cloned();
}
if self.selected_ids.is_empty() {
self.anchor_id = None;
}
}
}
#[derive(Debug, Clone, Default)]
pub struct SelectionSummary {
pub selected_count: usize,
pub selected_ids: Vec<knotra_vcs::ProjectId>,
pub visible_ids: Vec<knotra_vcs::ProjectId>,
pub fetchable_ids: Vec<knotra_vcs::ProjectId>,
pub has_upstream: bool,
}
#[derive(Debug, Clone, Default)]
pub enum LatestOpState {
#[default]
Idle,
Running {
operation_id: OperationId,
label: String,
done: usize,
total: usize,
},
Completed {
log: OperationLog,
retry: RetryAvailability,
},
}
#[derive(Debug, Clone)]
pub enum ActivityRetryAction {
FetchFailed {
source_operation_id: OperationId,
project_ids: Vec<ProjectId>,
},
ReviewSmartPull {
source_operation_id: OperationId,
project_ids: Vec<ProjectId>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RetryUnavailableReason {
NoEligibleTargets,
ContextSwitch,
Freeze,
FreezeRollback,
StatusRefresh,
}
impl RetryUnavailableReason {
pub fn i18n_key(self) -> &'static str {
match self {
Self::NoEligibleTargets => "plain.activity.none_available",
Self::ContextSwitch => "plain.activity.retry_context_again",
Self::Freeze | Self::FreezeRollback => "plain.activity.retry_freeze_again",
Self::StatusRefresh => "plain.activity.retry_refresh_again",
}
}
}
#[derive(Debug, Clone)]
pub enum RetryAvailability {
Available(ActivityRetryAction),
Unavailable(RetryUnavailableReason),
NotApplicable,
}
#[derive(Debug, Clone)]
pub struct RetryExclusion {
pub project_id: ProjectId,
pub reason: RetryExclusionReason,
}
#[derive(Debug, Clone)]
pub struct FetchRetryRun {
pub operation_id: OperationId,
pub lease_id: OperationLeaseId,
pub started_at: jiff::Timestamp,
pub total: usize,
pub completed: Vec<ProjectOperationResult>,
pub exclusions: Vec<RetryExclusion>,
}
#[derive(Debug, Clone, Default)]
pub struct ActivityStripState {
pub latest: LatestOpState,
pub completed_secs: u32,
pub fetch_retry: Option<FetchRetryRun>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct OperationLeaseId(pub u64);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OperationOwner {
SingleFetch,
BulkFetch,
SmartPullPreparation,
SmartPullExecution,
ContextSwitch,
FreezeValidation,
FreezeExecution,
ConflictMutation,
TagPush,
ActivityFetchRetry,
ActivitySmartPullPreparation,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OperationLease {
pub id: OperationLeaseId,
pub owner: OperationOwner,
}
#[derive(Debug, Default)]
pub struct OperationInterlock {
active: Option<OperationLease>,
next_id: u64,
}
impl OperationInterlock {
pub fn try_acquire(&mut self, owner: OperationOwner) -> Option<OperationLeaseId> {
if self.active.is_some() {
return None;
}
self.next_id = self.next_id.checked_add(1)?;
let id = OperationLeaseId(self.next_id);
self.active = Some(OperationLease { id, owner });
Some(id)
}
pub fn release_if_matches(&mut self, id: OperationLeaseId) -> bool {
if self.active.is_some_and(|lease| lease.id == id) {
self.active = None;
true
} else {
false
}
}
pub fn is_busy(&self) -> bool {
self.active.is_some()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PaletteEntryKind {
Project,
Workspace,
Action,
}
#[derive(Debug, Clone)]
pub struct PaletteEntry {
pub kind: PaletteEntryKind,
pub label: String,
pub payload: String,
pub disabled_reason_key: Option<&'static str>,
}
#[derive(Debug, Clone, Default)]
pub struct PaletteState {
pub open: bool,
pub query: String,
pub results: Vec<PaletteEntry>,
pub notice_key: Option<&'static str>,
}
impl PaletteState {
pub fn open_palette(&mut self) {
self.open = true;
self.query.clear();
self.notice_key = None;
}
pub fn close(&mut self) {
self.open = false;
self.notice_key = None;
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum ActiveModal {
#[default]
None,
Pull,
Tag,
Switch,
Resolve(knotra_vcs::ProjectId),
Changelog,
}
#[derive(Debug, Clone, Default)]
pub struct KeyboardState {
pub cheat_sheet_open: bool,
}
pub struct AppState {
pub screen: Screen,
pub config: AppConfig,
pub paths: AppPaths,
pub catalog: Catalog,
pub theme: KnotraTheme,
pub workspace: Option<Workspace>,
pub workspace_status: Option<WorkspaceStatus>,
pub load_phase: LoadPhase,
pub filter: FilterState,
pub operation_logs: Vec<OperationLog>,
pub history_unreadable_count: usize,
pub history_directory_unreadable: bool,
pub history_search: String,
pub status_bar: Option<String>,
pub add_project_dialog: Option<AddProjectDialog>,
pub confirm_remove_dialog: Option<ConfirmRemoveDialog>,
pub fetching_projects: HashSet<ProjectId>,
pub is_refreshing: bool,
pub history_expanded: std::collections::HashSet<knotra_vcs::OperationId>,
pub settings_edit: SettingsEdit,
pub settings_save_msg: Option<String>,
pub sync: sync::SyncCenterState,
pub context_ops: context::ContextOpsState,
pub freezer: freezer::FreezerState,
pub conflict_ops: conflict_ops::ConflictOpsState,
pub changelog: changelog::ChangelogState,
pub topology: topology::TopologyState,
pub all_workspaces: Vec<knotra_vcs::Workspace>,
pub active_workspace_idx: usize,
pub workspace_mgr: workspace_mgr::WorkspaceMgrState,
pub missing_projects: std::collections::HashSet<knotra_vcs::ProjectId>,
pub pending_tag_push: Option<PendingTagPush>,
pub operation_interlock: OperationInterlock,
pub fs_poller: knotra_vcs::FsPoller,
pub selection: SelectionState,
pub activity: ActivityStripState,
pub palette: PaletteState,
pub keyboard: KeyboardState,
pub detail_panel: detail_panel::DetailPanelState,
pub active_modal: ActiveModal,
pub selection_mode: bool,
pub show_op_details: bool,
pub dashboard_arrange_open: bool,
pub settings_advanced_open: bool,
pub recent_removal: Option<UndoableRemoval>,
pub dashboard_focus: Option<focus::FocusTarget>,
pub overlay_focus: Option<focus::FocusTarget>,
pub focus_visible: bool,
pub width_mode: WidthMode,
pub window_width: f32,
}
impl AppState {
#[cfg(test)]
pub fn new(config: AppConfig) -> Self {
Self::new_with_paths(config, AppPaths::resolve().0)
}
pub fn new_with_paths(config: AppConfig, paths: AppPaths) -> Self {
let locale = config.locale;
AppState {
screen: Screen::Dashboard,
catalog: Catalog::for_locale(locale),
theme: KnotraTheme::from_choice(config.theme),
workspace: None,
workspace_status: None,
load_phase: LoadPhase::Startup,
filter: FilterState::default(),
operation_logs: Vec::new(),
history_unreadable_count: 0,
history_directory_unreadable: false,
history_search: String::new(),
status_bar: None,
add_project_dialog: None,
confirm_remove_dialog: None,
fetching_projects: HashSet::new(),
is_refreshing: false,
history_expanded: std::collections::HashSet::new(),
settings_edit: SettingsEdit::from_config(&config),
settings_save_msg: None,
sync: sync::SyncCenterState::default(),
context_ops: context::ContextOpsState::default(),
freezer: freezer::FreezerState::default(),
conflict_ops: conflict_ops::ConflictOpsState::default(),
changelog: changelog::ChangelogState::default(),
topology: topology::TopologyState::default(),
all_workspaces: Vec::new(),
active_workspace_idx: 0,
workspace_mgr: workspace_mgr::WorkspaceMgrState::default(),
missing_projects: std::collections::HashSet::new(),
pending_tag_push: None,
operation_interlock: OperationInterlock::default(),
fs_poller: knotra_vcs::FsPoller::default(),
selection: SelectionState::default(),
activity: ActivityStripState::default(),
palette: PaletteState::default(),
keyboard: KeyboardState::default(),
detail_panel: detail_panel::DetailPanelState::default(),
active_modal: ActiveModal::default(),
selection_mode: false,
show_op_details: false,
dashboard_arrange_open: false,
settings_advanced_open: false,
recent_removal: None,
dashboard_focus: None,
overlay_focus: None,
focus_visible: false,
width_mode: WidthMode::from_width(INITIAL_WINDOW_SIZE.width),
window_width: INITIAL_WINDOW_SIZE.width,
paths,
config,
}
}
pub fn t(&self, key: &'static str) -> &'static str {
self.catalog.t(key)
}
pub fn apply_filter(&mut self, msg: FilterMessage) {
match msg {
FilterMessage::SearchChanged(s) => self.filter.search_text = s,
FilterMessage::StatusFilterToggled(sf) => {
if let Some(pos) = self.filter.status_filters.iter().position(|f| f == &sf) {
self.filter.status_filters.remove(pos);
} else {
self.filter.status_filters.push(sf);
}
}
FilterMessage::AllFiltersCleared => self.filter = FilterState::default(),
}
}
pub fn visible_project_ids(&self) -> Vec<knotra_vcs::ProjectId> {
self.dashboard_display().ordered_selectable_ids
}
pub fn visible_projects_unavailable_reason(&self) -> Option<&'static str> {
if !self.visible_project_ids().is_empty() {
return None;
}
let no_projects_registered = self
.workspace
.as_ref()
.is_none_or(|workspace| workspace.projects.is_empty());
if no_projects_registered {
return Some(self.t("plain.selection.no_projects_registered"));
}
let display = self.dashboard_display();
let all_in_closed_groups = !display.sections.is_empty()
&& display.sections.iter().all(|section| section.collapsed);
Some(if all_in_closed_groups {
self.t("plain.selection.all_in_closed_groups")
} else {
self.t("plain.selection.no_visible_projects")
})
}
pub fn find_project_name(&self, id: &knotra_vcs::ProjectId) -> Option<String> {
self.all_workspaces
.iter()
.flat_map(|ws| &ws.projects)
.find(|p| &p.id == id)
.map(|p| p.name.clone())
}
pub fn status_filter_count(&self, filter: &StatusFilter) -> usize {
let projects = self
.workspace
.as_ref()
.map(|ws| ws.projects.as_slice())
.unwrap_or(&[]);
dashboard::count_for_filter(
projects,
self.workspace_status.as_ref(),
&self.missing_projects,
filter,
)
}
pub fn dashboard_display(&self) -> dashboard::DashboardDisplay<'_> {
let projects = self
.workspace
.as_ref()
.map(|ws| ws.projects.as_slice())
.unwrap_or(&[]);
dashboard::build_dashboard_display(
projects,
self.workspace_status.as_ref(),
&self.missing_projects,
&self.filter,
dashboard::DashboardDisplayOptions {
grouping: self.config.dashboard_grouping,
sort: self.config.dashboard_sort,
in_progress_collapsed: self.config.dashboard_in_progress_collapsed,
all_set_collapsed: self.config.dashboard_all_set_collapsed,
},
)
}
pub fn selection_summary(&self) -> SelectionSummary {
let visible_ids = self.visible_project_ids();
let selected_ids: Vec<_> = visible_ids
.iter()
.filter(|id| self.selection.selected_ids.contains(*id))
.cloned()
.collect();
let fetchable_ids: Vec<_> = selected_ids
.iter()
.filter(|id| !self.missing_projects.contains(*id))
.cloned()
.collect();
let has_upstream = self.workspace_status.as_ref().is_some_and(|status| {
status.projects.iter().any(|project_status| {
selected_ids.contains(&project_status.project_id)
&& project_status.remote.upstream.is_some()
&& !self.missing_projects.contains(&project_status.project_id)
})
});
SelectionSummary {
selected_count: selected_ids.len(),
selected_ids,
visible_ids,
fetchable_ids,
has_upstream,
}
}
pub fn reconcile_selection_with_display(&mut self) {
let visible_ids: HashSet<_> = self.visible_project_ids().into_iter().collect();
self.selection.retain_ids(&visible_ids);
}
pub fn clear_selection_mode(&mut self) {
self.selection.clear();
self.selection_mode = false;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn initial_width_mode_is_derived_from_initial_window_size() {
let state = AppState::new(AppConfig::default());
assert_eq!(
state.width_mode,
WidthMode::from_width(INITIAL_WINDOW_SIZE.width)
);
}
}