1use std::path::PathBuf;
2
3use gitkraft_core::*;
4use iced::{Color, Point, Task};
5
6use crate::message::Message;
7use crate::theme::ThemeColors;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum DragTarget {
14 SidebarRight,
16 CommitLogRight,
18 DiffFileListRight,
21}
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum DragTargetH {
26 StagingTop,
28}
29
30#[derive(Debug, Clone)]
32pub enum ContextMenu {
33 Branch {
35 name: String,
36 is_current: bool,
37 local_index: usize,
40 },
41 RemoteBranch { name: String },
43 Commit { index: usize, oid: String },
45}
46
47pub struct RepoTab {
51 pub repo_path: Option<PathBuf>,
54 pub repo_info: Option<RepoInfo>,
56
57 pub branches: Vec<BranchInfo>,
60 pub current_branch: Option<String>,
62
63 pub commits: Vec<CommitInfo>,
66 pub selected_commit: Option<usize>,
68 pub graph_rows: Vec<gitkraft_core::GraphRow>,
70
71 pub unstaged_changes: Vec<DiffInfo>,
74 pub staged_changes: Vec<DiffInfo>,
76 pub commit_files: Vec<gitkraft_core::DiffFileEntry>,
78 pub selected_commit_oid: Option<String>,
80 pub selected_file_index: Option<usize>,
82 pub is_loading_file_diff: bool,
84 pub selected_diff: Option<DiffInfo>,
86 pub commit_message: String,
88
89 pub stashes: Vec<StashEntry>,
92
93 pub remotes: Vec<RemoteInfo>,
96
97 pub show_commit_detail: bool,
100 pub new_branch_name: String,
102 pub show_branch_create: bool,
104 pub local_branches_expanded: bool,
106 pub remote_branches_expanded: bool,
108 pub stash_message: String,
110
111 pub pending_discard: Option<String>,
113
114 pub status_message: Option<String>,
117 pub error_message: Option<String>,
119 pub is_loading: bool,
121 pub context_menu_pos: (f32, f32),
124
125 pub context_menu: Option<ContextMenu>,
127 pub rename_branch_target: Option<String>,
129 pub rename_branch_input: String,
131
132 pub create_tag_target_oid: Option<String>,
134 pub create_tag_annotated: bool,
136 pub create_tag_name: String,
138 pub create_tag_message: String,
140
141 pub commit_scroll_offset: f32,
145
146 pub diff_scroll_offset: f32,
148 pub commit_display: Vec<(String, String, String)>,
152
153 pub has_more_commits: bool,
155 pub is_loading_more_commits: bool,
157}
158
159impl RepoTab {
160 pub fn new_empty() -> Self {
162 Self {
163 repo_path: None,
164 repo_info: None,
165 branches: Vec::new(),
166 current_branch: None,
167 commits: Vec::new(),
168 selected_commit: None,
169 graph_rows: Vec::new(),
170 unstaged_changes: Vec::new(),
171 staged_changes: Vec::new(),
172 commit_files: Vec::new(),
173 selected_commit_oid: None,
174 selected_file_index: None,
175 is_loading_file_diff: false,
176 selected_diff: None,
177 commit_message: String::new(),
178 stashes: Vec::new(),
179 remotes: Vec::new(),
180 show_commit_detail: false,
181 new_branch_name: String::new(),
182 show_branch_create: false,
183 local_branches_expanded: true,
184 remote_branches_expanded: true,
185 stash_message: String::new(),
186 pending_discard: None,
187 status_message: None,
188 error_message: None,
189 is_loading: false,
190 context_menu: None,
191 context_menu_pos: (0.0, 0.0),
192 rename_branch_target: None,
193 rename_branch_input: String::new(),
194 create_tag_target_oid: None,
195 create_tag_annotated: false,
196 create_tag_name: String::new(),
197 create_tag_message: String::new(),
198 commit_scroll_offset: 0.0,
199 diff_scroll_offset: 0.0,
200 commit_display: Vec::new(),
201 has_more_commits: true,
202 is_loading_more_commits: false,
203 }
204 }
205
206 pub fn has_repo(&self) -> bool {
208 self.repo_path.is_some()
209 }
210
211 pub fn display_name(&self) -> &str {
213 self.repo_path
214 .as_ref()
215 .and_then(|p| p.file_name())
216 .and_then(|n| n.to_str())
217 .unwrap_or("New Tab")
218 }
219
220 pub fn apply_payload(
222 &mut self,
223 payload: crate::message::RepoPayload,
224 path: std::path::PathBuf,
225 ) {
226 self.current_branch = payload.info.head_branch.clone();
227 self.repo_path = Some(path);
228 self.repo_info = Some(payload.info);
229 self.branches = payload.branches;
230 self.commits = payload.commits;
231 self.graph_rows = payload.graph_rows;
232 self.unstaged_changes = payload.unstaged;
233 self.staged_changes = payload.staged;
234 self.stashes = payload.stashes;
235 self.remotes = payload.remotes;
236
237 self.selected_commit = None;
239 self.selected_diff = None;
240 self.commit_files.clear();
241 self.selected_commit_oid = None;
242 self.selected_file_index = None;
243 self.is_loading_file_diff = false;
244 self.commit_message.clear();
245 self.error_message = None;
246 self.status_message = Some("Repository loaded.".into());
247 self.commit_scroll_offset = 0.0;
248 self.diff_scroll_offset = 0.0;
249 self.has_more_commits = true;
250 self.is_loading_more_commits = false;
251 }
252}
253
254pub struct GitKraft {
258 pub tabs: Vec<RepoTab>,
261 pub active_tab: usize,
263
264 pub sidebar_expanded: bool,
267
268 pub sidebar_width: f32,
271 pub commit_log_width: f32,
273 pub staging_height: f32,
275 pub diff_file_list_width: f32,
277
278 pub ui_scale: f32,
280
281 pub dragging: Option<DragTarget>,
284 pub dragging_h: Option<DragTargetH>,
286 pub drag_start_x: f32,
288 pub drag_start_y: f32,
290 pub drag_initialized: bool,
294 pub drag_initialized_h: bool,
296
297 pub cursor_pos: Point,
302
303 pub current_theme_index: usize,
306
307 pub recent_repos: Vec<gitkraft_core::RepoHistoryEntry>,
310}
311
312impl Default for GitKraft {
313 fn default() -> Self {
314 Self::new()
315 }
316}
317
318impl GitKraft {
319 fn from_settings(settings: gitkraft_core::AppSettings) -> Self {
325 let current_theme_index = settings
326 .theme_name
327 .as_deref()
328 .map(gitkraft_core::theme_index_by_name)
329 .unwrap_or(0);
330
331 let recent_repos = settings.recent_repos;
332
333 let (
334 sidebar_width,
335 commit_log_width,
336 staging_height,
337 diff_file_list_width,
338 sidebar_expanded,
339 ui_scale,
340 ) = if let Some(ref layout) = settings.layout {
341 (
342 layout.sidebar_width.unwrap_or(220.0),
343 layout.commit_log_width.unwrap_or(500.0),
344 layout.staging_height.unwrap_or(200.0),
345 layout.diff_file_list_width.unwrap_or(180.0),
346 layout.sidebar_expanded.unwrap_or(true),
347 layout.ui_scale.unwrap_or(1.0),
348 )
349 } else {
350 (220.0, 500.0, 200.0, 180.0, true, 1.0)
351 };
352
353 Self {
354 tabs: vec![RepoTab::new_empty()],
355 active_tab: 0,
356
357 sidebar_expanded,
358
359 sidebar_width,
360 commit_log_width,
361 staging_height,
362 diff_file_list_width,
363
364 ui_scale,
365
366 dragging: None,
367 dragging_h: None,
368 drag_start_x: 0.0,
369 drag_start_y: 0.0,
370 drag_initialized: false,
371 drag_initialized_h: false,
372 cursor_pos: Point::ORIGIN,
373
374 current_theme_index,
375
376 recent_repos,
377 }
378 }
379
380 pub fn new() -> Self {
386 Self::from_settings(
387 gitkraft_core::features::persistence::ops::load_settings().unwrap_or_default(),
388 )
389 }
390
391 pub fn new_with_session_paths() -> (Self, Vec<PathBuf>) {
397 let settings =
398 gitkraft_core::features::persistence::ops::load_settings().unwrap_or_default();
399 let open_tabs = settings.open_tabs.clone();
400 let active_tab_index = settings.active_tab_index;
401
402 let mut state = Self::from_settings(settings);
403
404 if !open_tabs.is_empty() {
405 state.tabs = open_tabs
406 .iter()
407 .map(|path| {
408 let mut tab = RepoTab::new_empty();
409 tab.repo_path = Some(path.clone());
412 if path.exists() {
413 tab.is_loading = true;
414 tab.status_message = Some(format!(
415 "Loading {}…",
416 path.file_name().unwrap_or_default().to_string_lossy()
417 ));
418 } else {
419 tab.error_message =
420 Some(format!("Repository not found: {}", path.display()));
421 }
422 tab
423 })
424 .collect();
425 state.active_tab = active_tab_index.min(state.tabs.len().saturating_sub(1));
426 }
427
428 (state, open_tabs)
429 }
430
431 pub fn open_tab_paths(&self) -> Vec<PathBuf> {
434 self.tabs
435 .iter()
436 .filter(|t| t.repo_info.is_some())
437 .filter_map(|t| t.repo_path.clone())
438 .collect()
439 }
440
441 pub fn active_tab(&self) -> &RepoTab {
443 &self.tabs[self.active_tab]
444 }
445
446 pub fn active_tab_mut(&mut self) -> &mut RepoTab {
448 &mut self.tabs[self.active_tab]
449 }
450
451 pub fn has_repo(&self) -> bool {
453 self.active_tab().has_repo()
454 }
455
456 pub fn repo_display_name(&self) -> &str {
458 self.active_tab().display_name()
459 }
460
461 pub fn colors(&self) -> ThemeColors {
468 ThemeColors::from_core(&gitkraft_core::theme_by_index(self.current_theme_index))
469 }
470
471 pub fn iced_theme(&self) -> iced::Theme {
480 let core = gitkraft_core::theme_by_index(self.current_theme_index);
481 let name = self.current_theme_name().to_string();
482
483 let palette = iced::theme::Palette {
484 background: rgb_to_iced(core.background),
485 text: rgb_to_iced(core.text_primary),
486 primary: rgb_to_iced(core.accent),
487 success: rgb_to_iced(core.success),
488 warning: rgb_to_iced(core.warning),
489 danger: rgb_to_iced(core.error),
490 };
491
492 iced::Theme::custom(name, palette)
493 }
494
495 pub fn current_theme_name(&self) -> &'static str {
497 gitkraft_core::THEME_NAMES
498 .get(self.current_theme_index)
499 .copied()
500 .unwrap_or("Default")
501 }
502
503 pub fn refresh_active_tab(&mut self) -> Task<Message> {
507 match self.active_tab().repo_path.clone() {
508 Some(path) => crate::features::repo::commands::refresh_repo(path),
509 None => Task::none(),
510 }
511 }
512
513 pub fn on_ok_refresh(
520 &mut self,
521 result: Result<(), String>,
522 ok_msg: &str,
523 err_prefix: &str,
524 ) -> Task<Message> {
525 match result {
526 Ok(()) => {
527 {
528 let tab = self.active_tab_mut();
529 tab.is_loading = false;
530 tab.status_message = Some(ok_msg.to_string());
531 }
532 self.refresh_active_tab()
533 }
534 Err(e) => {
535 let tab = self.active_tab_mut();
536 tab.is_loading = false;
537 tab.error_message = Some(format!("{err_prefix}: {e}"));
538 tab.status_message = None;
539 Task::none()
540 }
541 }
542 }
543
544 pub fn current_layout(&self) -> gitkraft_core::LayoutSettings {
546 gitkraft_core::LayoutSettings {
547 sidebar_width: Some(self.sidebar_width),
548 commit_log_width: Some(self.commit_log_width),
549 staging_height: Some(self.staging_height),
550 diff_file_list_width: Some(self.diff_file_list_width),
551 sidebar_expanded: Some(self.sidebar_expanded),
552 ui_scale: Some(self.ui_scale),
553 }
554 }
555}
556
557fn rgb_to_iced(rgb: gitkraft_core::Rgb) -> Color {
559 Color::from_rgb8(rgb.r, rgb.g, rgb.b)
560}
561
562#[cfg(test)]
565mod tests {
566 use super::*;
567
568 #[test]
569 fn new_defaults() {
570 let state = GitKraft::new();
571 assert!(state.active_tab().repo_path.is_none());
572 assert!(!state.has_repo());
573 assert_eq!(state.repo_display_name(), "New Tab");
574 assert!(state.active_tab().commits.is_empty());
575 assert!(state.sidebar_expanded);
576 assert!(state.current_theme_index < gitkraft_core::THEME_COUNT);
578 assert!(state.sidebar_width > 0.0);
580 assert!(state.commit_log_width > 0.0);
581 assert!(state.staging_height > 0.0);
582 assert!(state.dragging.is_none());
583 assert!(state.dragging_h.is_none());
584 assert_eq!(state.tabs.len(), 1);
586 assert_eq!(state.active_tab, 0);
587 }
588
589 #[test]
590 fn repo_display_name_extracts_basename() {
591 let mut state = GitKraft::new();
592 state.active_tab_mut().repo_path = Some(std::path::PathBuf::from("/home/user/my-project"));
593 assert_eq!(state.repo_display_name(), "my-project");
594 }
595
596 #[test]
597 fn colors_returns_theme_colors() {
598 let state = GitKraft::new();
599 let c = state.colors();
600 assert!(c.bg.r < 0.5);
602 }
603
604 #[test]
605 fn iced_theme_is_custom_with_correct_palette() {
606 let mut state = GitKraft::new();
607
608 state.current_theme_index = 0;
610 let iced_t = state.iced_theme();
611 let pal = iced_t.palette();
612 assert!(pal.background.r < 0.5, "Default theme bg should be dark");
613 assert_eq!(iced_t.to_string(), "Default");
614
615 state.current_theme_index = 11;
617 let iced_t = state.iced_theme();
618 let pal = iced_t.palette();
619 assert!(pal.background.r > 0.5, "Solarized Light bg should be light");
620 assert_eq!(iced_t.to_string(), "Solarized Light");
621
622 state.current_theme_index = 12;
624 let iced_t = state.iced_theme();
625 let pal = iced_t.palette();
626 let core = gitkraft_core::theme_by_index(12);
627 let expected_accent = rgb_to_iced(core.accent);
628 assert!(
629 (pal.primary.r - expected_accent.r).abs() < 0.01
630 && (pal.primary.g - expected_accent.g).abs() < 0.01
631 && (pal.primary.b - expected_accent.b).abs() < 0.01,
632 "Gruvbox Dark accent should match core accent"
633 );
634 }
635
636 #[test]
637 fn iced_theme_name_round_trips_through_core() {
638 for i in 0..gitkraft_core::THEME_COUNT {
641 let mut state = GitKraft::new();
642 state.current_theme_index = i;
643 let iced_t = state.iced_theme();
644 let name = iced_t.to_string();
645 let resolved = gitkraft_core::theme_index_by_name(&name);
646 assert_eq!(
647 resolved,
648 i,
649 "theme index {i} ({}) did not round-trip through iced_theme name",
650 gitkraft_core::THEME_NAMES[i]
651 );
652 }
653 }
654
655 #[test]
656 fn current_theme_name_round_trips() {
657 let mut state = GitKraft::new();
658 state.current_theme_index = 8;
659 assert_eq!(state.current_theme_name(), "Dracula");
660 state.current_theme_index = 0;
661 assert_eq!(state.current_theme_name(), "Default");
662 }
663
664 #[test]
665 fn repo_tab_new_empty() {
666 let tab = RepoTab::new_empty();
667 assert!(tab.repo_path.is_none());
668 assert!(!tab.has_repo());
669 assert_eq!(tab.display_name(), "New Tab");
670 assert!(tab.commits.is_empty());
671 assert!(tab.branches.is_empty());
672 assert!(!tab.is_loading);
673 }
674
675 #[test]
676 fn repo_tab_display_name_with_path() {
677 let mut tab = RepoTab::new_empty();
678 tab.repo_path = Some(std::path::PathBuf::from("/some/path/cool-repo"));
679 assert!(tab.has_repo());
680 assert_eq!(tab.display_name(), "cool-repo");
681 }
682}