-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode_archive.txt
More file actions
2669 lines (2399 loc) · 98.7 KB
/
code_archive.txt
File metadata and controls
2669 lines (2399 loc) · 98.7 KB
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
archive of functions and code from project's misty past...
oh, those were the days...
*/
/// Recursively collects file system entries from directory and all subdirectories
///
/// # Purpose
/// Traverses a directory tree starting from the specified root directory,
/// collecting all files and subdirectories for searching operations.
///
/// # Critical Implementation Note
/// This function MUST receive the actual directory to search, not assume
/// any particular directory. The caller is responsible for providing the
/// correct starting directory based on the application's navigation state.
///
/// # Arguments
/// * `start_directory` - The root directory from which to start collecting.
/// This should be the user's current navigation location,
/// NOT the process working directory.
///
/// # Common Mistake
/// DO NOT use std::env::current_dir() here or in calling code.
/// The process working directory is NOT the same as the file manager's
/// current navigation directory.
fn collect_entries_recursive(
&self,
start_directory: &Path, // Must be the actual navigation directory
) -> Result<Vec<FileSystemEntry>> {
let mut all_entries = Vec::new();
let mut directories_to_process = vec![start_directory.to_path_buf()];
while let Some(current_dir) = directories_to_process.pop() {
// Try to read the current directory, skip if we can't
let dir_entries = match fs::read_dir(¤t_dir) {
Ok(entries) => entries,
Err(_) => continue, // Skip directories we can't read
};
for entry_result in dir_entries {
// Skip entries we can't read
let entry = match entry_result {
Ok(e) => e,
Err(_) => continue,
};
// Get metadata, skip if we can't read it
let metadata = match entry.metadata() {
Ok(m) => m,
Err(_) => continue,
};
// Get the file name as a string, skip if invalid
let file_name = match entry.file_name().into_string() {
Ok(name) => name,
Err(_) => continue,
};
let path = entry.path();
// Add to entries list
all_entries.push(FileSystemEntry {
file_system_item_name: file_name,
file_system_item_path: path.clone(),
file_system_item_size_in_bytes: metadata.len(),
file_system_item_last_modified_time: metadata.modified()
.unwrap_or(SystemTime::UNIX_EPOCH),
is_directory: metadata.is_dir(),
});
// If it's a directory, add it to the processing queue
if metadata.is_dir() {
directories_to_process.push(path);
}
}
}
Ok(all_entries)
}
// Pass the correct is_grep flag to display function
display_extended_search_results(&search_results).map_err(|e| {
eprintln!("Failed to display search results: {}", e);
FileFantasticError::Io(e)
})?;
// Wait for user to select from results or press enter to continue
print!("\nEnter number to select or press Enter to continue: ");
io::stdout().flush().map_err(|e| {
eprintln!("Failed to flush stdout: {}", e);
FileFantasticError::Io(e)
})?;
let mut selection = String::new();
io::stdin().read_line(&mut selection).map_err(|e| {
eprintln!("Failed to read input: {}", e);
FileFantasticError::Io(e)
})?;
/// simple, works, no pagination
/// Displays search results with appropriate formatting based on search type
///
/// # Purpose
/// Presents search results to the user in a readable tabular format,
/// automatically detecting the search type from the result enum and displaying
/// the appropriate format for each type.
///
/// # Arguments
/// * `results` - Slice of UnifiedSearchResult items to display
/// The enum variant determines the display format
///
/// # Returns
/// * `io::Result<()>` - Ok(()) on successful display, or an IO error if terminal
/// output operations fail
///
/// # Display Formats
///
/// ## Fuzzy Name Search Format:
/// Shows the Levenshtein distance to help users understand match quality
/// ```text
/// Search Results (Fuzzy Match)
/// # Name Distance
/// -------------------------------------------------------
/// 1 example.txt 1
/// 2 example2.doc 2
/// ```
///
/// ## Grep Content Search Format:
/// Shows the line number and content for each match
/// ```text
/// Search Results (Content Match)
/// # File Line Content
/// --------------------------------------------------------------
/// 1 src/main.rs 42 // TODO: implement
/// 2 src/lib.rs 15 // TODO: document
/// ```
///
/// # Implementation Details
/// - Clears the terminal screen before displaying results for clean presentation
/// - Truncates long filenames to maintain table alignment (max 38 characters)
/// - Automatically detects search type from enum variant
/// - Shows "No matches found" message for empty result sets
///
/// # User Interface Flow
/// After displaying results, the user can:
/// - Enter a number to select and navigate to that file
/// - Press Enter to continue without selection
///
/// # Error Handling
/// - Returns IO errors from terminal output operations
/// - Handles empty result sets gracefully with informative message
pub fn display_extended_search_results(
results: &[UnifiedSearchResult],
) -> io::Result<()> { // Note: removed is_grep parameter - not needed with enum
// Handle empty results with user-friendly message
if results.is_empty() {
println!("No matches found");
return Ok(());
}
// Clear screen for clean display
print!("\x1B[2J\x1B[1;1H");
// Determine search type from first result and display accordingly
match &results[0] {
UnifiedSearchResult::Grep(_) => {
// Display header for grep results
println!("\nContent Search Results (try: -g -r -c)"); // -fg --fuzzygrep
println!("{:<5} {:<30} {:<7} {}", "#", "File", "Line", "Content");
println!("{}", "-".repeat(80));
// Display each grep result
for result in results {
if let UnifiedSearchResult::Grep(grep_result) = result {
// Truncate filename if too long
let display_name = if grep_result.file_name.len() > 28 {
format!("{}...", &grep_result.file_name[..25])
} else {
grep_result.file_name.clone()
};
// Truncate content if too long
let display_content = if grep_result.line_content.len() > 35 {
format!("{}...", &grep_result.line_content[..32])
} else {
grep_result.line_content.clone()
};
println!(
"{:<5} {:<30} {:<7} {}",
grep_result.display_index,
display_name,
grep_result.line_number,
display_content
);
}
}
}
UnifiedSearchResult::Fuzzy(_) => {
// Display header for fuzzy search results
println!("\nFuzzy Name Search Results (try: --grep --recursive --case-sensitive)");
println!("{:<5} {:<40} {:<10}", "#", "Name", "Distance");
println!("{}", "-".repeat(55));
// Display each fuzzy result
for result in results {
if let UnifiedSearchResult::Fuzzy(fuzzy_result) = result {
// Truncate filename if too long
let display_name = if fuzzy_result.item_name.len() > 38 {
format!("{}...", &fuzzy_result.item_name[..35])
} else {
fuzzy_result.item_name.clone()
};
println!(
"{:<5} {:<40} {:<10}",
fuzzy_result.display_index,
display_name,
fuzzy_result.distance
);
}
}
}
}
Ok(())
}
// /// Creates archive directory if it doesn't exist
// ///
// /// # Purpose
// /// Ensures that an "archive" subdirectory exists in the specified parent directory,
// /// creating it if necessary. This directory is used to store copies of files
// /// when avoiding overwrites.
// ///
// /// # Arguments
// /// * `parent_directory` - The directory where the archive folder should exist
// ///
// /// # Returns
// /// * `Result<PathBuf>` - Absolute path to the archive directory, or error
// ///
// /// # Error Conditions
// /// - IO errors when creating the directory
// /// - Permission denied when writing to parent directory
// /// - Invalid parent directory path
// ///
// /// # Archive Directory Structure
// /// ```text
// /// parent_directory/
// /// ├── existing_files...
// /// └── archive/ <- Created by this function
// /// ├── file1_timestamp.ext
// /// └── file2_timestamp.ext
// /// ```
// ///
// /// # Example
// /// ```rust
// /// let current_dir = PathBuf::from("/home/user/documents");
// /// match ensure_archive_directory_exists(¤t_dir) {
// /// Ok(archive_path) => {
// /// // archive_path is "/home/user/documents/archive"
// /// println!("Archive directory ready: {}", archive_path.display());
// /// },
// /// Err(e) => eprintln!("Failed to create archive directory: {}", e),
// /// }
// /// ```
// fn ensure_archive_directory_exists(parent_directory: &PathBuf) -> Result<PathBuf> {
// let archive_directory_path = parent_directory.join("archive");
// // Check if archive directory already exists
// if !archive_directory_path.exists() {
// // Create the archive directory
// fs::create_dir(&archive_directory_path).map_err(|e| {
// match e.kind() {
// io::ErrorKind::PermissionDenied => {
// FileFantasticError::PermissionDenied(archive_directory_path.clone())
// },
// _ => FileFantasticError::Io(e)
// }
// })?;
// println!("Created archive directory: {}", archive_directory_path.display());
// }
// // Verify it's actually a directory
// if !archive_directory_path.is_dir() {
// return Err(FileFantasticError::InvalidName(
// format!("Archive path exists but is not a directory: {}",
// archive_directory_path.display())
// ));
// }
// Ok(archive_directory_path)
// }
// /// Opens a file in a tmux split pane
// ///
// /// # Arguments
// /// * `editor` - The editor command to use
// /// * `file_path` - Path to the file to open
// /// * `split_type` - Either "-v" for vertical or "-h" for horizontal split
// ///
// /// # Returns
// /// * `Result<()>` - Success or error
// ///
// /// # Prerequisites
// /// - tmux must be installed and available
// /// - Must be running inside a tmux session
// ///
// /// # Behavior
// /// Creates a new tmux pane and opens the editor in it
// /// The pane closes automatically when the editor exits
// fn open_in_tmux_split(editor: &str, file_path: &PathBuf, split_type: &str) -> Result<()> {
// // Check if the specified editor is available
// if !is_command_available(editor) {
// return Err(FileFantasticError::EditorLaunchFailed(format!(
// "Editor '{}' is not available on this system",
// editor
// )));
// }
// // Build the command to run in the new split
// let editor_command = format!("{} {}", editor, file_path.to_string_lossy());
// // Create the tmux split with the editor
// let output = std::process::Command::new("tmux")
// .args([
// "split-window",
// split_type, // "-v" for vertical, "-h" for horizontal
// &editor_command,
// ])
// .output()
// .map_err(|e| {
// eprintln!("Failed to create tmux split: {}", e);
// FileFantasticError::Io(e)
// })?;
// if output.status.success() {
// println!(
// "Opened {} in tmux {} split",
// editor,
// if split_type == "-v" {
// "vertical"
// } else {
// "horizontal"
// }
// );
// Ok(())
// } else {
// Err(FileFantasticError::EditorLaunchFailed(format!(
// "Failed to create tmux split: {}",
// String::from_utf8_lossy(&output.stderr)
// )))
// }
// }
/// Parses special flags from user input for headless mode, tmux splits, and CSV analysis
///
/// # Arguments
/// * `input` - The user input string
///
/// # Returns
/// * `Option<(String, String)>` - Some((editor, flag)) if a special flag is found, None otherwise
///
/// # Supported Flags
/// * `-h` or `--headless` - Open in current terminal
/// * `-vsplit` or `--vertical-split-tmux` - Open in vertical tmux split
/// * `-hsplit` or `--horizontal-split-tmux` - Open in horizontal tmux split
/// * `-rc` or `--rows-and-columns` - Analyze CSV file before opening (CSV files only)
///
/// # Examples
/// * "vim -h" -> Some(("vim", "-h"))
/// * "nano -rc" -> Some(("nano", "-rc"))
/// * "code -h -rc" -> Some(("code", "-h -rc")) // Combined flags preserved
fn parse_special_flags(input: &str) -> Option<(String, String)> {
let flags = [
"-h",
"--headless",
"-vsplit",
"--vertical-split-tmux",
"-hsplit",
"--horizontal-split-tmux",
"-rc",
"--rows-and-columns",
];
// Check if input contains any special flags
let mut found_flags = Vec::new();
let mut editor_parts = Vec::new();
let parts: Vec<&str> = input.split_whitespace().collect();
for part in &parts {
if flags.contains(&part.as_ref()) {
found_flags.push(part.to_string());
} else {
editor_parts.push(part.to_string());
}
}
if !found_flags.is_empty() {
let editor = editor_parts.join(" ");
let flags_str = found_flags.join(" ");
Some((editor, flags_str))
} else {
None
}
}
// // Now handle the other flags with the appropriate file
// // Extract the primary action flag (for headless/tmux)
// let primary_flag = if flags.contains("-h") || flags.contains("--headless") {
// "--headless"
// } else if flags.contains("-vsplit") || flags.contains("--vertical-split-tmux") {
// "-vsplit"
// } else if flags.contains("-hsplit") || flags.contains("--horizontal-split-tmux") {
// "-hsplit"
// } else if flags.contains("-rc") || flags.contains("--rows-and-columns") {
// // If only -rc flag, open normally (no special terminal mode)
// ""
// } else {
// ""
// };
/// Interactive interface to add a file to the file stack
///
/// # Purpose
/// Provides a simple interactive interface for adding files to the file stack.
/// Shows the current directory listing and prompts user to select a file by number.
/// Works with the current page view only, utilizing existing navigation state.
///
/// # Arguments
/// * `nav_state` - Current navigation state with lookup table for numbered selection
/// * `current_directory_entries` - Current directory entries to display for selection (current page only)
/// * `current_directory_path` - Current directory path for display context
///
/// # Returns
/// * `Result<()>` - Success or error with context
///
/// # User Interface Workflow
///
/// ## Step 1: Display Current View
/// - Show current directory contents with numbered items (same as main navigation)
/// - This respects current filter and pagination state
///
/// ## Step 2: Selection Prompt
/// - User selects item by number (same interface as navigation)
/// - Can cancel with 'b' for back
///
/// ## Step 3: Validation
/// - Verify selected item exists in lookup table
/// - Ensure selected item is a file (not a directory)
///
/// ## Step 4: Add to Stack
/// - Add file path to the file stack
/// - Display confirmation with updated stack count
///
/// # Example Interaction
/// ```text
/// Current Directory: /home/user/documents
///
/// Num Name Size Modified
/// ------------------------------------------------
/// 1) folder1/ - 14:30
/// 2) document.txt 1.2 KB 15:45
/// 3) image.png 500 KB 16:20
///
/// === Add File to Stack ===
/// Select file to add to stack
/// Enter file number (or 'b' to back/cancel): 2
///
/// ✓ Added 'document.txt' to file stack. Total files: 1
/// ```
///
/// # Error Handling
/// - Validates numbered selections against navigation lookup table
/// - Ensures selected items are files, not directories
/// - Provides clear error messages for invalid selections
/// - Handles cancellation gracefully
/// - Manages IO errors during user interaction
pub fn interactive_add_file_tostack(
&mut self,
nav_state: &NavigationState,
current_directory_entries: &[FileSystemEntry],
current_directory_path: &PathBuf,
) -> Result<()> {
// WORKFLOW STEP 1: Display current directory contents
// This shows the current page with existing filters and numbering
display_directory_contents(
current_directory_entries,
current_directory_path,
None, // Pagination info handled by main navigation
nav_state.current_filter,
nav_state,
)
.map_err(|e| FileFantasticError::Io(e))?;
// WORKFLOW STEP 2: Prompt for file selection
println!("\n=== Add File to Stack ===");
println!("Select file to add to stack");
print!("Enter file number (or 'b' to back/cancel): ");
io::stdout()
.flush()
.map_err(|e| FileFantasticError::Io(e))?;
// Read user input
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.map_err(|e| FileFantasticError::Io(e))?;
let input = input.trim();
// Handle cancellation request
if input.eq_ignore_ascii_case("b") {
println!("Back/Cancelled.");
return Ok(());
}
// WORKFLOW STEP 3: Validate and process the user's selection
if let Ok(number) = input.parse::<usize>() {
// Use navigation state's lookup to find the selected item
if let Some(item_info) = nav_state.lookup_item(number) {
// Check if selected item is a file (not a directory)
if item_info.item_type == FileSystemItemType::Directory {
// User selected a directory - show error and return
let item_name = item_info
.item_path
.file_name()
.unwrap_or_default()
.to_string_lossy();
eprintln!(
"\n✗ Error: '{}' is a directory. Please select a file.",
item_name
);
} else {
// WORKFLOW STEP 4: It's a file - add to stack
// Extract file name for display
let file_name = item_info
.item_path
.file_name()
.unwrap_or_default()
.to_string_lossy();
// Add the file to the stack
match self.add_file_to_stack(item_info.item_path.clone()) {
Ok(()) => {
// Success - show confirmation with stack count
println!(
"\n✓ Added '{}' to file stack. Total files: {}",
file_name,
self.file_path_stack.len()
);
}
Err(e) => {
// Failed to add to stack - show error
eprintln!("\n✗ Failed to add file to stack: {}", e);
}
}
}
} else {
// Invalid item number - not in lookup table
println!("Error: Invalid item number {}. Please try again.", number);
}
} else {
// Input was not a valid number
println!("Error: Please enter a valid number or 'b' to cancel.");
}
// Wait for user acknowledgment before returning to main interface
println!("\nPress Enter to continue...");
let _ = io::stdin().read_line(&mut String::new());
Ok(())
}
// /// Helper function to select and retrieve a file from the file stack
// ///
// /// # Purpose
// /// Internal helper that handles the file-specific retrieval logic.
// /// This is essentially the existing `interactive_get_file_from_stack` function
// /// but renamed to clarify its role as a helper in the new architecture.
// ///
// /// # Returns
// /// * `Result<Option<PathBuf>>` - Selected file path, None if canceled, or error
// ///
// /// # Behavior
// /// - Displays all files in the stack (most recent first)
// /// - Allows selection by number or default to most recent
// /// - Returns the file path without removing it from stack
// /// - No destructive operations performed
// ///
// /// # Note
// /// This function maintains the exact same behavior as the original
// /// `interactive_get_file_from_stack` for consistency.
// fn get_file_from_stack_helper(&mut self) -> Result<Option<PathBuf>> {
// // Check if stack is empty (redundant check for safety)
// if self.file_path_stack.is_empty() {
// println!("File stack is empty.");
// return Ok(None);
// }
// println!("\n=== File Stack ===");
// // Display files in reverse order (most recent first) for user-friendly numbering
// for (i, file) in self.file_path_stack.iter().enumerate().rev() {
// println!(
// "{}. {}",
// self.file_path_stack.len() - i,
// file.file_name().unwrap_or_default().to_string_lossy()
// );
// }
// print!("Select file number (Enter for most recent, 'c' to cancel): ");
// io::stdout()
// .flush()
// .map_err(|e| FileFantasticError::Io(e))?;
// let mut input = String::new();
// io::stdin()
// .read_line(&mut input)
// .map_err(|e| FileFantasticError::Io(e))?;
// let input = input.trim();
// // Handle cancellation
// if input.eq_ignore_ascii_case("c") {
// println!("Cancelled.");
// return Ok(None);
// }
// // Default to most recent if no input
// if input.is_empty() {
// if let Some(file) = self.file_path_stack.last() {
// println!(
// "Retrieved: {}",
// file.file_name().unwrap_or_default().to_string_lossy()
// );
// return Ok(Some(file.clone()));
// }
// }
// // Try to parse as index and validate
// if let Ok(index) = input.parse::<usize>() {
// if index > 0 && index <= self.file_path_stack.len() {
// // Convert to actual vector index (1-based display to 0-based storage)
// let actual_index = self.file_path_stack.len() - index;
// // Use .get() for bounds-checked access
// if let Some(file) = self.file_path_stack.get(actual_index) {
// println!(
// "Retrieved: {}",
// file.file_name().unwrap_or_default().to_string_lossy()
// );
// return Ok(Some(file.clone()));
// } else {
// println!("Error: Index out of bounds");
// }
// } else {
// println!(
// "Error: Invalid file number {}. Valid range: 1-{}",
// index,
// self.file_path_stack.len()
// );
// }
// } else {
// println!(
// "Error: Please enter a valid number, press Enter for most recent, or 'c' to cancel."
// );
// }
// Ok(None)
// }
// /// Gets and removes the most recent file from the file stack
// ///
// /// # Purpose
// /// Removes and returns the most recently added file from the file stack,
// /// implementing LIFO (Last In, First Out) behavior.
// ///
// /// # Returns
// /// * `Option<PathBuf>` - The most recent file path, or None if stack is empty
// ///
// /// # Stack Behavior
// /// - Removes the last element added to the stack
// /// - Returns None if the stack is empty
// /// - Modifies the stack by removing the returned element
// ///
// /// # Usage Context
// /// Used when performing operations on collected files:
// /// - Processing files in reverse order of collection
// /// - Undoing file additions
// /// - Batch operations where order matters
// ///
// /// # Example
// /// ```rust
// /// match state_manager.pop_file_from_stack() {
// /// Some(file_path) => println!("Processing: {}", file_path.display()),
// /// None => println!("No files in stack"),
// /// }
// /// ```
// pub fn pop_file_from_stack(&mut self) -> Option<PathBuf> {
// self.file_path_stack.pop()
// }
// /// Q&A interface to select and return file from stack
// ///
// /// # Purpose
// /// Provides an interactive interface for selecting a file from the file stack,
// /// displaying all available files and allowing selection by number.
// /// This uses the same numbered selection paradigm as the rest of the application.
// ///
// /// # Returns
// /// * `Result<Option<PathBuf>>` - Selected file path, None if canceled, or error
// ///
// /// # User Interface Flow
// /// 1. Check if file stack is empty
// /// 2. Display all files in the stack with numbers (most recent first)
// /// 3. Allow user to select by number or default to most recent
// /// 4. Remove and return the selected file
// /// 5. Display confirmation of selection
// ///
// /// # Selection Options
// /// - Enter number: Select specific file by index
// /// - Enter (empty): Select most recent file (top of stack)
// /// - 'c': Cancel operation
// /// - Invalid number: Display error and return None
// ///
// /// # Display Format
// /// Files are displayed in reverse order (most recent first) with 1-based indexing
// /// to match user expectations and maintain consistency with main interface.
// ///
// /// # Example Interaction
// /// ```text
// /// === File Stack ===
// /// 1. document.txt
// /// 2. image.png
// /// 3. script.sh
// /// Select file number (Enter for most recent, 'c' to cancel): 2
// /// Retrieved: image.png
// /// ```
// pub fn interactive_get_file_from_stack(&mut self) -> Result<Option<PathBuf>> {
// // Check if stack is empty
// if self.file_path_stack.is_empty() {
// println!("File stack is empty.");
// return Ok(None);
// }
// println!("\n=== File Stack ===");
// // Display files in reverse order (most recent first) for user-friendly numbering
// for (i, file) in self.file_path_stack.iter().enumerate().rev() {
// println!(
// "{}. {}",
// self.file_path_stack.len() - i,
// file.file_name().unwrap_or_default().to_string_lossy()
// );
// }
// print!("Select file number (Enter for most recent, 'c' to cancel): ");
// io::stdout()
// .flush()
// .map_err(|e| FileFantasticError::Io(e))?;
// let mut input = String::new();
// io::stdin()
// .read_line(&mut input)
// .map_err(|e| FileFantasticError::Io(e))?;
// let input = input.trim();
// // Handle cancellation
// if input.eq_ignore_ascii_case("c") {
// println!("Cancelled.");
// return Ok(None);
// }
// // Default to most recent (pop from end) if no input
// if input.is_empty() {
// if let Some(file) = self.pop_file_from_stack() {
// println!(
// "Retrieved: {}",
// file.file_name().unwrap_or_default().to_string_lossy()
// );
// return Ok(Some(file));
// }
// }
// // Try to parse as index and validate
// if let Ok(index) = input.parse::<usize>() {
// if index > 0 && index <= self.file_path_stack.len() {
// // Convert to actual vector index (1-based display to 0-based storage)
// let actual_index = self.file_path_stack.len() - index;
// // Use .get() for bounds-checked access
// if let Some(file) = self.file_path_stack.get(actual_index) {
// println!(
// "Retrieved: {}",
// file.file_name().unwrap_or_default().to_string_lossy()
// );
// return Ok(Some(file.clone())); // Clone to return ownership
// } else {
// println!("Error: Index out of bounds");
// }
// } else {
// println!(
// "Error: Invalid file number {}. Valid range: 1-{}",
// index,
// self.file_path_stack.len()
// );
// }
// } else {
// println!(
// "Error: Please enter a valid number, press Enter for most recent, or 'c' to cancel."
// );
// }
// Ok(None)
// }
GetSendModeAction::GetFileFromStack => {
match state_manager.interactive_get_item_from_stack() {
Ok(Some(source_file_path)) => {
println!(
"Retrieved file: {}",
source_file_path.display()
);
println!(
"Copying to current directory: {}",
current_directory_path.display()
);
// Copy the file to current directory with archive handling
match copy_file_with_archive_handling(
&source_file_path,
¤t_directory_path,
) {
Ok(final_destination_path) => {
println!(
"✓ Copy operation completed successfully!"
);
println!(
"Final location: {}",
final_destination_path.display()
);
}
Err(e) => {
eprintln!("✗ Copy operation failed: {}", e);
}
}
println!("Press Enter to continue...");
let _ = io::stdin().read_line(&mut String::new());
}
Ok(None) => println!("No file selected."),
Err(e) => {
println!("Error getting file from stack: {}", e)
}
}
}
/*
pending future functions to used saved dir-stack items
*/
// GetSendModeAction::AddDirectoryToStack => {
// match state_manager.interactive_save_directory_to_stack(¤t_directory_path) {
// Ok(_) => println!("Directory added to stack successfully."),
// Err(e) => println!("Error adding directory to stack: {}", e),
// }
// },
/ /// Vanilla home made pair compair levenshtein_distance
// /// e.g. for simple fuzzy search
// /// Calculates the Levenshtein distance between two strings
// ///
// /// # Purpose
// /// Provides fuzzy text matching capability for the search functionality,
// /// measuring how many single-character edits (insertions, deletions, substitutions)
// /// are needed to transform one string into another.
// ///
// /// # Arguments
// /// * `s` - First string for comparison
// /// * `t` - Second string for comparison
// ///
// /// # Returns
// /// * `usize` - The edit distance between the strings (lower = more similar)
// ///
// /// # Algorithm
// /// Uses a dynamic programming approach with two work vectors to calculate
// /// the minimum edit distance between strings:
// /// - 0 means strings are identical
// /// - Higher values indicate greater differences
// /// - Equal to max(s.len(), t.len()) when strings share no characters
// ///
// /// # Performance Considerations
// /// - O(m*n) time complexity where m and n are string lengths
// /// - O(n) space complexity using the two-vector approach
// /// - Efficient for short strings like filenames, but may not scale well
// /// for very long strings
// ///
// /// # Usage Context
// /// Used in the `fuzzy_search` method to find files matching a partial query,
// /// allowing for approximate/inexact matches when users don't know the exact filename.
// ///
// /// # Examples
// /// ```
// /// assert_eq!(levenshtein_distance("kitten", "sitting"), 3);
// /// assert_eq!(levenshtein_distance("rust", "dust"), 1);
// /// assert_eq!(levenshtein_distance("", "test"), 4);
// /// ```
// fn levenshtein_distance(s: &str, t: &str) -> usize {
// // Convert strings to vectors of chars for easier indexing
// // Do this FIRST to get correct character counts
// let s_chars: Vec<char> = s.chars().collect();
// let t_chars: Vec<char> = t.chars().collect();
// // Get the CHARACTER lengths, not byte lengths
// let m = s_chars.len();
// let n = t_chars.len();
// // Handle empty string cases
// if m == 0 {
// return n;
// }
// if n == 0 {
// return m;
// }
// // Create two work vectors
// let mut v0: Vec<usize> = (0..=n).collect();
// let mut v1: Vec<usize> = vec![0; n + 1];
// // Iterate through each character of s
// for i in 0..m {
// // First element of v1 is the deletion cost
// v1[0] = i + 1;
// // Calculate costs for each character of t
// for j in 0..n {
// let deletion_cost = v0[j + 1] + 1;
// let insertion_cost = v1[j] + 1;
// let substitution_cost = v0[j] + if s_chars[i] == t_chars[j] { 0 } else { 1 };
// v1[j + 1] = deletion_cost.min(insertion_cost).min(substitution_cost);
// }
// // Swap vectors for next iteration
// std::mem::swap(&mut v0, &mut v1);
// }
// // Return final distance
// v0[n]
// }
/*
pending use of saved directories
*/
// /// Q&A interface to save current directory to directory stack
// ///
// /// # Purpose
// /// Provides an interactive interface for adding the current directory
// /// to the directory stack, with user confirmation.
// ///
// /// # Arguments
// /// * `current_directory` - The current directory to potentially add
// ///
// /// # Returns
// /// * `Result<()>` - Success or error with context
// ///
// /// # User Interface Flow
// /// 1. Display the current directory path
// /// 2. Ask for user confirmation to add it to the stack
// /// 3. Add to stack if user confirms (default is yes)
// /// 4. Display confirmation with current stack size
// ///
// /// # Confirmation Logic
// /// - Empty input or 'y'/'Y': Add to stack
// /// - Any other input: Do not add to stack
// ///
// /// # Example Interaction
// /// ```text
// /// === Add Directory to Stack ===
// /// Current directory: /home/user/projects
// /// Add current directory to stack? (Y/n):
// /// Added to directory stack. Total directories: 2
// /// ```
// pub fn interactive_save_directory_to_stack(&mut self, current_directory: &PathBuf) -> Result<()> {
// println!("\n=== Add Directory to Stack ===");
// println!("Current directory: {}", current_directory.display());
// print!("Add current directory to stack? (Y/n): ");