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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
use crate::app;
use crate::vault_selector::{VaultAction, VaultSelector, VaultSelectorMode};
use async_trait::async_trait;
use chamber_import_export::{ExportFormat, export_items, import_items};
use chamber_password_gen::PasswordConfig;
use chamber_vault::{AutoLockCallback, AutoLockConfig, AutoLockService, Item, ItemKind, NewItem, Vault, VaultManager};
use color_eyre::Result;
use color_eyre::eyre::eyre;
use ratatui::prelude::Style;
use ratatui::style::Color;
use std::path::PathBuf;
use std::sync::Arc;
use tui_textarea::TextArea;
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Screen {
Unlock,
Main,
AddItem,
ViewItem,
EditItem,
ChangeMaster,
GeneratePassword,
ImportExport,
VaultSelector,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum UnlockField {
Master,
Confirm,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum ChangeKeyField {
Current,
New,
Confirm,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum AddItemField {
Name,
Kind,
Value,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum PasswordGenField {
Length,
Options,
Generate,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum ImportExportField {
Path,
Format,
Action,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum ImportExportMode {
Export,
Import,
}
#[allow(dead_code)]
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum ViewMode {
All,
Passwords,
Environment,
Notes,
}
impl ViewMode {
pub const fn as_str(self) -> &'static str {
match self {
ViewMode::All => "Items",
ViewMode::Passwords => "Passwords",
ViewMode::Environment => "Environment",
ViewMode::Notes => "Notes",
}
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum StatusType {
Info,
Success,
Warning,
Error,
}
#[derive(Debug, Clone)]
pub struct ItemCounts {
pub total: usize,
pub passwords: usize,
pub env_vars: usize,
pub notes: usize,
pub api_keys: usize,
pub ssh_keys: usize,
pub certificates: usize,
pub databases: usize,
pub credit_cards: usize,
pub secure_notes: usize,
pub identities: usize,
pub servers: usize,
pub wifi_passwords: usize,
pub licenses: usize,
pub bank_accounts: usize,
pub documents: usize,
pub recovery_codes: usize,
pub oauth_tokens: usize,
}
#[derive(Debug, Clone)]
pub struct CountdownInfo {
pub enabled: bool,
pub minutes_left: i64,
pub seconds_left: i64,
}
pub struct TuiAutoLockCallback {
// Callback to lock the TUI app
}
#[async_trait]
impl AutoLockCallback for TuiAutoLockCallback {
async fn on_auto_lock(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
// Lock the vault in TUI mode
// This could set a flag that the main loop checks
Ok(())
}
}
#[allow(clippy::struct_excessive_bools)]
pub struct App {
pub vault: Vault,
pub vault_manager: VaultManager,
pub vault_selector: VaultSelector,
pub screen: Screen,
pub master_input: String,
pub master_confirm_input: String,
pub master_mode_is_setup: bool,
pub unlock_focus: UnlockField,
pub error: Option<String>,
pub items: Vec<Item>,
pub selected: usize,
pub view_mode: ViewMode,
pub filtered_items: Vec<Item>,
pub search_query: String,
pub search_mode: bool,
pub add_name: String,
pub add_kind_idx: usize,
pub add_value: String,
pub add_value_scroll: usize,
pub status_message: Option<String>,
pub status_type: StatusType,
pub scroll_offset: usize,
pub add_value_textarea: TextArea<'static>,
pub auto_lock_service: Option<Arc<AutoLockService>>,
pub auto_locked: bool,
pub countdown_info: Option<CountdownInfo>,
// Change passes key dialog fields
pub ck_current: String,
pub ck_new: String,
pub ck_confirm: String,
pub ck_focus: ChangeKeyField,
pub add_focus: AddItemField,
pub view_item: Option<Item>,
pub view_show_value: bool,
pub edit_item: Option<Item>,
pub edit_value: String,
// Password generation fields
pub gen_focus: PasswordGenField,
pub gen_length_str: String,
pub gen_config: PasswordConfig,
pub generated_password: Option<String>,
// Import/Export fields
pub ie_focus: ImportExportField,
pub ie_mode: ImportExportMode,
pub ie_path: String,
pub ie_format_idx: usize,
pub ie_formats: Vec<&'static str>,
}
impl App {
/// Initializes a new instance of the struct.
///
/// This function creates or opens a vault, determines whether the master mode setup
/// is required, and initializes the various fields required for managing the application state.
///
/// # Returns
/// - `Result<Self>`: A `Result` containing the initialized struct instance on success,
/// or an error if the vault fails to open or create.
///
/// # Fields
/// - `vault`: Handles secure storage by opening or creating a vault.
/// - `screen`: Represents the current active screen, initialized to the `Unlock` screen.
/// - `master_input`: Stores user input for the master password during setup or unlock phase.
/// - `master_confirm_input`: Stores user input for confirming the master password during setup.
/// - `master_mode_is_setup`: Indicates whether the master mode is set up (false if initialization is incomplete).
/// - `unlock_focus`: Tracks which unlock field is currently focused (e.g., Master field).
/// - `error`: Holds any error message or state, defaulted to `None`.
/// - `items`: A vector holding all items stored in the vault.
/// - `selected`: Tracks the index of the currently selected item in the items list.
/// - `view_mode`: Specifies the current filter/view mode for items (e.g., All items).
/// - `filtered_items`: A vector holding the subset of items that match the current search query or filter.
/// - `search_query`: Stores the user's current search input or query.
/// - `add_name`: Field for the name of an item to be added.
/// - `add_kind_idx`: Indicates the index of the kind/type of the item being added.
/// - `add_value`: The value of the item being added.
/// - `add_value_scroll`: Tracks the scroll state for long values when adding an item.
/// - `status_message`: Holds transient status messages to display to the user.
/// - `status_type`: Indicates the type of status message (e.g., Info, Warning, Error).
///
/// # Change Key Fields
/// - `ck_current`: Stores the current master key value.
/// - `ck_new`: Stores the new master key value.
/// - `ck_confirm`: Confirms the new master key value.
/// - `ck_focus`: Tracks which field is focused during the change key process.
///
/// # Add Item Fields
/// - `add_focus`: Tracks which field is focused when adding a new item (e.g., Name).
///
/// # Viewing and Editing Items
/// - `view_item`: The currently selected item for viewing, if any.
/// - `view_show_value`: Indicates whether to reveal the value of the viewed item.
/// - `edit_item`: The item currently being edited, if any.
/// - `edit_value`: The edited value of the currently selected item.
///
/// # Password Generation
/// - `gen_focus`: The current focus field in the password generation process (e.g., Length).
/// - `gen_length_str`: String representation of the desired password length (default: "16").
/// - `gen_config`: Configuration settings for password generation (e.g., character set, length).
/// - `generated_password`: Holds the last generated password, if any.
///
/// # Import/Export
/// - `ie_focus`: Tracks which field is focused during import/export operations (e.g., File Path).
/// - `ie_mode`: Indicates the mode (Import or Export) for import/export operations.
/// - `ie_path`: Stores the file path selected for import/export.
/// - `ie_format_idx`: Tracks the index of the currently selected format for import/export.
/// - `ie_formats`: A vector containing supported file formats for import/export (e.g., "json", "csv").
///
/// # Errors
/// Return an error if the vault cannot be opened or created successfully.
///
/// # Panics
pub fn new() -> Result<Self> {
let vault = Vault::open_default()?;
let vault_manager = VaultManager::new()?;
let vault_selector = VaultSelector::new();
// Determine initial screen based on vault state
let (_, master_mode_is_setup) = if vault.is_initialized() {
(Screen::Unlock, false) // Just unlock, no setup
} else {
(Screen::Unlock, true) // Setup mode (create master password)
};
let auto_lock_config = AutoLockConfig::default();
let callback = Arc::new(TuiAutoLockCallback {});
let auto_lock_service = Some(Arc::new(AutoLockService::new(auto_lock_config, callback)));
Ok(Self {
vault,
vault_manager,
vault_selector,
screen: Screen::Unlock,
master_input: String::new(),
master_confirm_input: String::new(),
master_mode_is_setup,
unlock_focus: UnlockField::Master,
error: None,
items: vec![],
selected: 0,
view_mode: ViewMode::All,
filtered_items: vec![],
search_query: String::new(),
search_mode: false,
add_name: String::new(),
add_kind_idx: 0,
add_value: String::new(),
add_value_scroll: 0,
status_message: None,
status_type: StatusType::Info,
scroll_offset: 0,
add_value_textarea: {
let mut textarea = TextArea::default();
// Enable line numbers
textarea.set_line_number_style(Style::default().fg(Color::DarkGray));
textarea.set_cursor_line_style(Style::default());
// Optional: set a placeholder text
textarea.set_placeholder_text("Enter your value here...");
textarea
},
auto_lock_service,
auto_locked: false,
countdown_info: None,
ck_current: String::new(),
ck_new: String::new(),
ck_confirm: String::new(),
ck_focus: ChangeKeyField::Current,
add_focus: AddItemField::Name,
view_item: None,
view_show_value: false,
edit_item: None,
edit_value: String::new(),
// Initialize password generation fields
gen_focus: PasswordGenField::Length,
gen_length_str: "16".to_string(),
gen_config: PasswordConfig::default(),
generated_password: None,
// Initialize import/export fields
ie_focus: ImportExportField::Path,
ie_mode: ImportExportMode::Export,
ie_path: String::new(),
ie_format_idx: 0,
ie_formats: vec!["json", "csv", "backup"],
})
}
fn validate_master_strength(s: &str) -> Result<()> {
if s.len() < 8 {
return Err(eyre!("Master key must be at least 8 characters long"));
}
if !s.chars().any(|c| c.is_ascii_lowercase()) {
return Err(eyre!("Master key must contain a lowercase letter"));
}
if !s.chars().any(|c| c.is_ascii_uppercase()) {
return Err(eyre!("Master key must contain an uppercase letter"));
}
if !s.chars().any(|c| c.is_ascii_digit()) {
return Err(eyre!("Master key must contain a digit"));
}
Ok(())
}
/// Unlocks the application vault using the provided master key and performs necessary validations.
///
/// This function checks if the master key setup process is initiated, validates the user input,
/// and sets up or unlocks the vault accordingly. In case of errors during validation or unlocking
/// operations, appropriate error messages are set.
///
/// ## Steps
/// 1. If `master_mode_is_setup` is true:
/// - Validate the presence of master input and confirmation input. If either is empty, an error
/// message is set, and the function will return early.
/// - Compare `master_input` and `master_confirm_input`. If they do not match, an error message
/// is set, and the function exits.
/// - Validate the strength of the `master_input` using `validate_master_strength`. If it fails,
/// sets an error message and exits.
/// - Initialize the vault with `master_input` and reset the `master_mode_is_setup` flag to false.
/// 2. Unlock the vault with the provided `master_input`. On failure to unlock, sets an error message
/// with the reason and exits with the corresponding error.
/// 3. Refresh the items in the application to reflect the unlocked state.
/// 4. Set the current screen to `Screen::Main`.
/// 5. Clear any existing error messages to indicate successful operation.
/// 6. Return `Ok(())` if no errors occurred.
///
/// ## Returns
/// - `Ok(())` on successful unlocking and initialization of the vault.
/// - `Err` with the propagation of error from validation or unlocking operations.
///
/// ## Errors
/// This function sets the `error` field with one of the following messages on failure:
/// - "Please enter and confirm your master key." - if either master input or confirmation input is missing.
/// - "Master keys do not match." - if the confirmation of the master key does not match the input.
/// - Error message returned by `validate_master_strength` - if the master key is deemed weak or invalid.
/// - "Unlock failed: {e}" - if unlocking the vault fails.
///
/// ## Side Effects
/// - Updates the `error` field in the struct to reflect any issues encountered during execution.
/// - Modifies the state of `screen`, `master_mode_is_setup`, and `vault` upon successful execution.
pub fn unlock(&mut self) -> Result<()> {
if self.master_mode_is_setup {
// Setup mode: create new master password (needs confirmation)
if self.master_input != self.master_confirm_input {
self.error = Some("Passwords do not match".to_string());
return Ok(());
}
Self::validate_master_strength(&self.master_input)?;
// Initialize the vault
self.vault.initialize(&self.master_input)?;
}
// Always try to unlock (works for both setup and normal mode)
if let Ok(()) = self.vault.unlock(&self.master_input) {
self.refresh_items()?;
self.screen = Screen::Main;
self.error = None;
self.master_input.clear();
self.master_confirm_input.clear();
} else {
self.error = Some("Invalid master password".to_string());
self.master_input.clear();
if self.master_mode_is_setup {
self.master_confirm_input.clear();
}
}
Ok(())
}
/// Refreshes the list of items and updates the filtered items.
///
/// This method performs the following actions:
/// 1. Updates the `items` field by retrieving the latest list of items from the `vault`.
/// 2. Applies filtering logic to update the `filtered_items` list.
/// 3. Ensures that the current selection (`selected`) is within the bounds of the updated `filtered_items` list.
/// If the current selection is out of bounds but the `filtered_items` list is not empty,
/// it adjusts `selected` to the last valid index.
///
/// # Errors
/// Returns an error if fetching the list of items from the `vault` fails.
///
/// # Returns
/// - `Ok(())` if the operation is successful.
/// - `Err` with the specific error encountered when listing items from the `vault`.
pub fn refresh_items(&mut self) -> Result<()> {
self.items = self.vault.list_items()?;
self.update_filtered_items();
if self.selected >= self.filtered_items.len() && !self.filtered_items.is_empty() {
self.selected = self.filtered_items.len().saturating_sub(1);
}
Ok(())
}
pub fn update_filtered_items(&mut self) {
let mut filtered = self.items.clone();
// Apply view mode filter
if self.view_mode != ViewMode::All {
filtered.retain(|item| match self.view_mode {
ViewMode::Passwords => matches!(item.kind, ItemKind::Password),
ViewMode::Environment => matches!(item.kind, ItemKind::EnvVar),
ViewMode::Notes => matches!(item.kind, ItemKind::Note),
ViewMode::All => true,
});
}
// Apply search filter
if !self.search_query.is_empty() {
let query_lower = self.search_query.to_lowercase();
filtered.retain(|item| {
item.name.to_lowercase().contains(&query_lower) || item.value.to_lowercase().contains(&query_lower)
});
}
// Sort by kind first, then by name
filtered.sort_by(|a, b| {
use std::cmp::Ordering;
match a.kind.as_str().cmp(b.kind.as_str()) {
Ordering::Equal => a.name.to_lowercase().cmp(&b.name.to_lowercase()),
other => other,
}
});
self.filtered_items = filtered;
// Adjust selection if needed
if self.selected >= self.filtered_items.len() && !self.filtered_items.is_empty() {
self.selected = self.filtered_items.len() - 1;
}
}
pub fn get_selected_item(&self) -> Option<&Item> {
self.filtered_items.get(self.selected)
}
pub fn get_item_counts(&self) -> ItemCounts {
let passwords = self
.items
.iter()
.filter(|i| matches!(i.kind, ItemKind::Password))
.count();
let env_vars = self.items.iter().filter(|i| matches!(i.kind, ItemKind::EnvVar)).count();
let notes = self.items.iter().filter(|i| matches!(i.kind, ItemKind::Note)).count();
let api_keys = self.items.iter().filter(|i| matches!(i.kind, ItemKind::ApiKey)).count();
let ssh_keys = self.items.iter().filter(|i| matches!(i.kind, ItemKind::SshKey)).count();
let certificates = self
.items
.iter()
.filter(|i| matches!(i.kind, ItemKind::Certificate))
.count();
let databases = self
.items
.iter()
.filter(|i| matches!(i.kind, ItemKind::Database))
.count();
// New categories
let credit_cards = self
.items
.iter()
.filter(|i| matches!(i.kind, ItemKind::CreditCard))
.count();
let secure_notes = self
.items
.iter()
.filter(|i| matches!(i.kind, ItemKind::SecureNote))
.count();
let identities = self
.items
.iter()
.filter(|i| matches!(i.kind, ItemKind::Identity))
.count();
let servers = self.items.iter().filter(|i| matches!(i.kind, ItemKind::Server)).count();
let wifi_passwords = self
.items
.iter()
.filter(|i| matches!(i.kind, ItemKind::WifiPassword))
.count();
let licenses = self
.items
.iter()
.filter(|i| matches!(i.kind, ItemKind::License))
.count();
let bank_accounts = self
.items
.iter()
.filter(|i| matches!(i.kind, ItemKind::BankAccount))
.count();
let documents = self
.items
.iter()
.filter(|i| matches!(i.kind, ItemKind::Document))
.count();
let recovery_codes = self
.items
.iter()
.filter(|i| matches!(i.kind, ItemKind::Recovery))
.count();
let oauth_tokens = self.items.iter().filter(|i| matches!(i.kind, ItemKind::OAuth)).count();
ItemCounts {
total: self.items.len(),
passwords,
env_vars,
notes,
api_keys,
ssh_keys,
certificates,
databases,
credit_cards,
secure_notes,
identities,
servers,
wifi_passwords,
licenses,
bank_accounts,
documents,
recovery_codes,
oauth_tokens,
}
}
/// Adds a new item to the vault with the specified details and updates the UI.
///
/// # Description
/// This function creates a new item based on the user input, validates it,
/// and stores it in the vault. If the operation is successful, the UI is updated
/// to reflect the addition and the input fields are reset. If an error occurs,
/// appropriate error messages and statuses are set.
///
/// # Fields Used
/// - `add_kind_idx`: Determines the type of item being added (e.g., `Password`, `EnvVar`, `Note`, etc.).
/// - `add_name`: The name of the new item, trimmed of whitespace.
/// - `add_value_textarea`: The content or value of the new item, usually multi-line.
/// - `vault`: The storage structure which handles item creation.
/// - `add_value`: Secondary field for item value, cleared after addition.
/// - `add_value_scroll`: Resets the scroll position of the textarea after addition.
/// - `screen`: Sets the screen to the main view upon successful addition.
/// - `error`: Displays error messages for failed operations.
/// - `status`: Updates the user-visible status of the addition operation.
///
/// # Process
/// 1. Determines the item type (`kind`) based on `add_kind_idx`:
/// - `0` -> Password
/// - `1` -> Environment Variable
/// - `3` -> API Key
/// - `4` -> SSH Key
/// - `5` -> Certificate
/// - `6` -> Database
/// - Default -> Note
/// 2. Fetches the item's value from the textarea (`add_value_textarea`), joining multiple lines with `\n`.
/// 3. Creates a `NewItem` structure with the gathered data.
/// 4. Attempts to add the item using `vault.create_item`.
/// 5. Handles responses:
/// - **Success**: Resets input fields, updates item list, switches to the main screen, and displays a success message.
/// - **Failure**: If the name already exists, prompts the user to choose a different name. For other errors, displays a generic error message.
///
/// # Returns
/// Returns an `Ok(())` on successful completion of the process or propagates an error if any step fails.
///
/// # Errors
/// - Returns an error if refreshing the items (`refresh_items`) fails.
/// - Updates the `error` and `status` fields with detailed context if item creation fails.
///
/// # Notes
/// - Resets both single-line (`add_value`) and multi-line (`add_value_textarea`) value fields upon successful addition.
/// - Automatically trims leading and trailing whitespace from the item name.
pub fn add_item(&mut self) -> Result<()> {
let kind = ItemKind::all()[self.add_kind_idx.min(ItemKind::all().len() - 1)];
// Get the value from the textarea instead of add_value
let value = self.add_value_textarea.lines().join("\n");
let new_item = NewItem {
name: self.add_name.trim().to_string(),
kind,
value, // Use the textarea content
};
match self.vault.create_item(&new_item) {
Ok(()) => {
self.add_name.clear();
self.add_value.clear();
// Reset the textarea as well
self.add_value_textarea = TextArea::default();
self.add_value_scroll = 0;
self.refresh_items()?;
self.screen = Screen::Main;
self.error = Some("Item added.".into());
self.set_status("Item added successfully.".to_string(), StatusType::Success);
}
Err(e) => {
let msg = e.to_string();
if msg.contains("already exists") {
self.error = Some(format!("Item '{}' already exists.", new_item.name));
self.set_status(
format!(
"Item '{}' already exists. Please choose a different name.",
new_item.name
),
StatusType::Warning,
);
} else {
self.error = Some(format!("Failed to add item: {msg}"));
self.set_status(format!("Failed to add item: {msg}"), StatusType::Error);
}
}
}
Ok(())
}
/// Deletes the currently selected item from the vault.
///
/// This function retrieves the currently selected item, deletes it from the vault
/// using its unique identifier, and then refreshes the list of items to reflect the changes.
/// If no item is selected, the function does nothing.
///
/// # Errors
///
/// Returns an error if:
/// - Retrieving the selected item fails.
/// - Deleting the item from the vault fails.
/// - Refreshing the item list fails.
pub fn delete_selected(&mut self) -> Result<()> {
if let Some(item) = self.get_selected_item() {
let item_id = item.id;
self.vault.delete_item(item_id)?;
self.refresh_items()?;
}
Ok(())
}
/// Changes the master key for the application if provided inputs meet the necessary conditions.
///
/// This function performs several validations to ensure the master key change process is secure:
/// 1. It checks if all required input fields (`ck_current`, `ck_new`, and `ck_confirm`) are filled.
/// 2. It validates that the new master key (`ck_new`) matches the confirmation key (`ck_confirm`).
/// 3. It verifies the strength of the new master key using the `validate_master_strength` method.
///
/// If any of these conditions fail, an appropriate error message is stored in the `error` field,
/// and the process halts without changing the master key.
///
/// Once all validations are passed, the function updates the master key by calling the
/// `change_master_key` method of the `vault`. After a successful update, it clears all input fields,
/// resets the error message, and navigates back to the main screen.
///
/// # Returns
///
/// * `Ok(())` - If the master key has been successfully changed or
/// the process ended due to a validation failure without panicking.
/// * `Err(Error)` - If an error occurs while attempting to change the key in the `vault`.
///
/// # Errors
///
/// - If any of the following conditions occur, an error is stored in the `error` field,
/// and the function returns `Ok`:
/// - Any of the required fields (`ck_current`, `ck_new`, or `ck_confirm`) are empty.
/// - The new master key and confirmation key do not match.
/// - The new master key fails the strength validation.
/// - If the `vault.change_master_key` method returns an error, it will propagate as a `Result::Err`.
pub fn change_master(&mut self) -> Result<()> {
if self.ck_current.is_empty() || self.ck_new.is_empty() || self.ck_confirm.is_empty() {
self.error = Some("Please fill out all fields.".into());
return Ok(());
}
if self.ck_new != self.ck_confirm {
self.error = Some("New master keys do not match.".into());
return Ok(());
}
if let Err(e) = Self::validate_master_strength(&self.ck_new) {
self.error = Some(e.to_string());
return Ok(());
}
self.vault.change_master_key(&self.ck_current, &self.ck_new)?;
self.ck_current.clear();
self.ck_new.clear();
self.ck_confirm.clear();
self.screen = Screen::Main;
self.error = None;
Ok(())
}
/// Copies the currently selected item to the clipboard.
///
/// This function retrieves the currently selected item using the `get_selected_item` method.
/// If an item is selected, it initializes the system clipboard, attempts to copy the selected
/// item's value to the clipboard, and updates the status message to indicate success.
///
/// # Returns
///
/// * `Ok(())` - If the item is successfully copied to the clipboard or no item is selected.
/// * `Err(anyhow::Error)` - If there's an error while accessing the clipboard or copying the
/// item to the clipboard.
///
/// # Errors
///
/// - Returns an error if accessing the clipboard fails.
/// - Returns an error if copying the selected item's value to the clipboard fails.
///
/// # Behavior
///
/// - If no item is selected (`get_selected_item` returns `None`), the function does nothing and
/// returns `Ok(())`.
///
/// - If an item is selected (`get_selected_item` returns `Some`), it:
/// - Initializes a new `arboard::Clipboard` instance.
/// - Copies the `value` of the selected item to the clipboard.
/// - Sets a status message indicating that the item has been successfully copied to the clipboard.
///
/// # Dependencies
///
/// This function relies on the `arboard` crate for clipboard interactions and the `anyhow` crate
/// for error handling. It also assumes the existence of the following methods:
/// - `get_selected_item`: Retrieves the currently selected item, returning an option.
/// - `set_status`: Updates the application's status message and type.
///
pub fn copy_selected(&mut self) -> Result<()> {
if let Some(item) = self.get_selected_item() {
let mut clipboard = arboard::Clipboard::new().map_err(|e| eyre!("Failed to access clipboard: {}", e))?;
clipboard
.set_text(&item.value)
.map_err(|e| eyre!("Failed to copy to clipboard: {}", e))?;
self.set_status(format!("Copied '{}' to clipboard", item.name), StatusType::Success);
}
Ok(())
}
pub fn view_selected(&mut self) {
if let Some(item) = self.get_selected_item() {
self.view_item = Some(item.clone());
self.view_show_value = false;
self.screen = Screen::ViewItem;
}
}
pub const fn toggle_value_visibility(&mut self) {
self.view_show_value = !self.view_show_value;
}
pub fn edit_selected(&mut self) {
let selected_item = self.get_selected_item().cloned();
if let Some(item) = selected_item {
self.edit_item = Some(item.clone());
self.edit_value.clone_from(&item.value);
self.screen = Screen::EditItem;
}
}
/// Attempts to save edits made to an item in the vault and updates the user interface accordingly.
///
/// # Behavior
/// - If the `edit_value` is empty (after trimming), it sets an error message ("Value cannot be empty") and exits early.
/// - Otherwise, it updates the item in the vault identified by `edit_item.id` with the new `edit_value`.
/// - After updating the item, it clears the `edit_item` and `edit_value`, refreshes the list of items, and switches
/// the application's screen back to the main screen while clearing any previous errors.
///
/// # Errors
/// - If updating the vault fails, an error is propagated from the `vault.update_item` method.
/// - If refreshing items fails, an error is propagated from the `refresh_items` method.
///
/// # Returns
/// - `Ok(())` if the edit is successfully saved or if the `edit_value` is empty.
/// - `Err` if an error occurs during vault updates or refreshing items.
///
/// # Fields/State
/// - `self.edit_item`: The item currently being edited. If `None`, the method does nothing.
/// - `self.edit_value`: The new value to be saved to the item. If empty (once trimmed), the method sets an error message and exits early.
/// - `self.error`: An optional error message for display purposes. This is set if the `edit_value` is empty or cleared on successful operation.
/// - `self.vault`: The storage mechanism used to update the item.
/// - `self.screen`: Controls the application screen flow. Set to `Screen::Main` after a successful edit.
///
pub fn save_edit(&mut self) -> Result<()> {
if let Some(item) = &self.edit_item {
if self.edit_value.trim().is_empty() {
self.error = Some("Value cannot be empty".into());
return Ok(());
}
self.vault.update_item(item.id, &self.edit_value)?;
self.edit_item = None;
self.edit_value.clear();
self.refresh_items()?;
self.screen = Screen::Main;
self.error = None;
}
Ok(())
}
// Password generation methods
pub fn open_password_generator(&mut self) {
self.gen_focus = PasswordGenField::Length;
self.gen_length_str = self.gen_config.length.to_string();
self.generated_password = None;
self.error = None;
self.screen = Screen::GeneratePassword;
}
pub fn generate_password(&mut self) {
if let Ok(length) = self.gen_length_str.parse::<usize>() {
self.gen_config.length = length.clamp(4, 128);
} else {
self.error = Some("Invalid length".into());
return;
}
match self.gen_config.generate() {
Ok(password) => {
self.generated_password = Some(password);
self.error = None;
}
Err(e) => {
self.error = Some(format!("Generation failed: {e}"));
}
}
}
/// Copies the generated password to the system clipboard.
///
/// This function attempts to access the generated password stored in the `self.generated_password`
/// field and copies it to the system clipboard using the `arboard` crate. If the operation succeeds,
/// a success message is set in the `self.error` field. In the event of an error while accessing the
/// clipboard or copying the text, the function returns a corresponding error.
///
/// # Returns
///
/// * `Ok(())` - If the password is successfully copied to the clipboard or no password was generated.
/// * `Err(anyhow::Error)` - If accessing the clipboard or copying the password fails.
///
/// # Errors
///
/// This function may return an error in the following scenarios:
/// * Failure to access or initialize the system clipboard.
/// * Failure to copy the generated password to the clipboard.
///
/// # Side Effects
///
/// * If a password is successfully copied to the clipboard, the `self.error` field is set with a success message.
///
/// # Dependencies
///
/// This function makes use of the `arboard` crate for clipboard access and text manipulation.
pub fn copy_generated_password(&mut self) -> Result<()> {
if let Some(password) = &self.generated_password {
let mut clipboard = arboard::Clipboard::new().map_err(|e| eyre!("Failed to access clipboard: {}", e))?;
clipboard
.set_text(password)
.map_err(|e| eyre!("Failed to copy to clipboard: {}", e))?;
self.error = Some("Password copied to clipboard".into());
}
Ok(())
}
pub fn use_generated_password(&mut self) {
if let Some(password) = &self.generated_password {
self.add_value = password.clone();
self.screen = Screen::AddItem;
self.add_focus = AddItemField::Name;
}
}
// Import/Export methods
pub fn open_import_export(&mut self, mode: ImportExportMode) {
self.ie_mode = mode;
self.ie_focus = ImportExportField::Path;
self.ie_path.clear();
self.ie_format_idx = 0;
self.error = None;
self.screen = Screen::ImportExport;
}
/// Executes the import or export operation based on the current application state.
///
/// This method performs the following operations:
/// 1. Validates the provided file path and ensures it is not empty.
/// 2. Normalizes the file path to handle different path separators and expand the home directory.
/// 3. Determines the format of import/export (CSV, JSON, or backup).
/// 4. Executes the import or export operation based on the selected mode (`ImportExportMode`).
///
/// ### Export Mode
/// - Creates necessary parent directories if they do not exist.
/// - Exports the current items to the specified file path in the selected format.
/// - Sets an appropriate success message indicating the number of items exported and the file path.
///
/// ### Import Mode
/// - Ensures the specified file exists before proceeding.
/// - Imports items from the file in the specified format.
/// - Avoids importing duplicate items by checking against existing item names.
/// - Records the number of imported and skipped items due to duplication or errors.
/// - Updates the item list after a successful import and presents an appropriate summary message.
///
/// ### Errors
/// - If the file path is empty, a user-friendly error message is set and the operation is aborted.
/// - If a directory creation fails during export, an error is returned.
/// - If certain items cannot be imported due to conflicts or other errors, they are counted as skipped.
///
/// ### Remarks
/// - Upon completion (successful or not), the application state is updated to the main screen.
///
/// ### Returns
/// - `Ok(())` if the operation completes successfully (even if some items were skipped).
/// - `Err` if a file path normalization or file operation fails during the execution.
///
/// ### Preconditions
/// - `self.ie_path` must be set to a valid file path.
/// - The `self.ie_formats` array must include supported formats ("csv", "backup", "json").
/// - The `self.items` list is expected to contain the current application items for export/import validation.
///
/// ### Postconditions
/// - Updates `self.error` with a descriptive message about the operation result.
/// - Changes the application state screen to `Screen::Main`.
pub fn execute_import_export(&mut self) -> Result<()> {
if self.ie_path.trim().is_empty() {
self.error = Some("Please enter a file path".into());
return Ok(());
}
// Normalize the path to handle different separators and expand the home directory
let normalized_path = app::App::normalize_path(&self.ie_path)?;
let path = PathBuf::from(normalized_path);
let format = match self.ie_formats[self.ie_format_idx] {
"csv" => ExportFormat::Csv,
"backup" => ExportFormat::ChamberBackup,
_ => ExportFormat::Json,
};
match self.ie_mode {
ImportExportMode::Export => {
// Create parent directories if they don't exist
if let Some(parent) = path.parent() {
if !parent.exists() {
std::fs::create_dir_all(parent)
.map_err(|e| eyre!("Failed to create directory {}: {}", parent.display(), e))?;
}
}
export_items(&self.items, &format, &path)?;
self.error = Some(format!("Exported {} items to {}", self.items.len(), path.display()));
}
ImportExportMode::Import => {
if !path.exists() {
self.error = Some(format!("File does not exist: {}", path.display()));
return Ok(());
}
let new_items = import_items(&path, &format)?;
if new_items.is_empty() {
self.error = Some("No items found in file".into());
return Ok(());
}
let existing_names: std::collections::HashSet<String> =
self.items.iter().map(|item| item.name.clone()).collect();
let mut imported_count = 0;
let mut skipped_count = 0;
for item in new_items {
if existing_names.contains(&item.name) {
skipped_count += 1;
continue;
}
match self.vault.create_item(&item) {
Ok(()) => imported_count += 1,
Err(_) => skipped_count += 1,
}
}
self.refresh_items()?;
self.error = Some(format!("Imported {imported_count} items, skipped {skipped_count}"));
}
}
self.screen = Screen::Main;
Ok(())
}
// Helper method to normalize file paths
fn normalize_path(input_path: &str) -> Result<String> {
let path_str = input_path.trim();
// Handle home directory expansion
let expanded_path = if path_str.strip_prefix('~').is_some() {
if let Some(home_dir) = dirs::home_dir() {
let rest = &path_str[1..];
let rest = if rest.starts_with('/') || rest.starts_with('\\') {
&rest[1..]
} else {
rest
};
home_dir.join(rest).to_string_lossy().to_string()
} else {
return Err(eyre!("Unable to determine home directory"));
}
} else {
path_str.to_string()
};
// Convert forward slashes to native path separators on Windows
#[cfg(windows)]
let normalized = expanded_path.replace('/', "\\");
#[cfg(not(windows))]
let normalized = expanded_path;
Ok(normalized)
}
pub fn set_status(&mut self, message: String, status_type: StatusType) {
self.status_message = Some(message);
self.status_type = status_type;
}
pub fn clear_status(&mut self) {
self.status_message = None;
}
pub fn is_in_input_mode(&self) -> bool {
match self.screen {
Screen::AddItem
| Screen::EditItem
| Screen::ChangeMaster
| Screen::GeneratePassword
| Screen::ImportExport
| Screen::Unlock => true,
Screen::Main if !self.search_query.is_empty() => true, // Search mode
_ => false,
}
}
/// Pastes content from the clipboard to the add item value field.
///
/// This function retrieves text content from the system clipboard and appends it to
/// the current `add_value` field. If the clipboard contains text, it will be added
/// to the existing value. If accessing the clipboard fails, an appropriate status
/// message is displayed.
///
/// # Returns
///
/// * `Ok(())` - If the paste operation completes successfully or if there's no text in clipboard.
/// * `Err(anyhow::Error)` - If accessing the clipboard fails.
///
/// # Errors
///
/// - Returns an error if accessing the clipboard fails.
/// - Sets a warning status if the clipboard is empty or contains no text.
///
/// # Behavior
///
/// - Retrieves text from the system clipboard using `arboard::Clipboard`.
/// - Appends the clipboard content to the current `add_value` field.
/// - Sets a success status message indicating the paste operation completed.
/// - If clipboard is empty or contains no text, shows a warning message.
pub fn paste_to_add_value(&mut self) -> Result<()> {
if let Ok(mut clipboard) = arboard::Clipboard::new() {
if let Ok(text) = clipboard.get_text() {
// Clear existing content and insert new text
self.add_value_textarea.select_all();
self.add_value_textarea.cut();
self.add_value_textarea.insert_str(text);
self.set_status("Pasted from clipboard".to_string(), StatusType::Success);
Ok(())
} else {
self.set_status("No text in clipboard".to_string(), StatusType::Warning);
Ok(())
}
} else {
self.set_status("Failed to access clipboard".to_string(), StatusType::Error);
Ok(())
}
}
pub fn open_vault_selector(&mut self) {
self.vault_selector.load_vaults(&self.vault_manager);
self.vault_selector.show();
self.screen = Screen::VaultSelector;
}
/// Handles various actions related to vault management.
///
/// This function processes the provided `VaultAction` and executes the corresponding logic
/// to manage vaults, such as creating, updating, deleting, importing, and more.
///
/// # Arguments
///
/// * `action` - A `VaultAction` enum that specifies the action to be performed. Each variant
/// of `VaultAction` corresponds to a specific vault-related operation.
///
/// # Returns
///
/// * `Result<()>` - Returns `Ok(())` if the action was processed successfully; otherwise,
/// an error is returned if any operation fails.
///
/// # `VaultAction` Variants
///
/// - `VaultAction::Switch(vault_id)`
/// Switches to the specified vault by its ID.
///
/// - `VaultAction::Create { name, description, category }`
/// Creates a new vault with the provided name, description, and category.
///
/// - `VaultAction::Update { vault_id, name, description, category, favorite }`
/// Updates an existing vault with the given parameters, including optional fields like the
/// vault name, description, category, and favorite status.
///
/// - `VaultAction::Delete { vault_id, delete_file }`
/// Deletes a vault specified by its ID. If `delete_file` is true, related files are also deleted.
///
/// - `VaultAction::Import { path }`
/// Imports a vault from a specified file path.
///
/// - `VaultAction::Refresh`
/// Reloads the list of available vaults and updates the UI to reflect any changes. Sets
/// a success status message indicating the vaults have been refreshed.
///
/// - `VaultAction::Close`
/// Hides the vault selector and switches back to the main screen.
///
/// - `VaultAction::ShowHelp`
/// Displays help information. (This action may be handled or ignored based on needs.)
///
/// # Errors
///
/// Returns an error if:
/// - Switching to a vault fails.
/// - The requested vault action encounters an issue (e.g., file access issues during imports or
/// failures in vault creation/deletion).
pub fn handle_vault_action(&mut self, action: VaultAction) -> Result<()> {
match action {
VaultAction::Switch(vault_id) => {
self.switch_to_vault(&vault_id)?;
}
VaultAction::Create {
name,
description,
category,
} => {
self.create_vault(&name, description, &category);
}
VaultAction::Update {
vault_id,
name,
description,
category,
favorite,
} => {
self.update_vault(vault_id, name, description, category, favorite);
}
VaultAction::Delete { vault_id, delete_file } => {
self.delete_vault(&vault_id, delete_file);
}
VaultAction::Import { path } => {
self.import_vault(&path);
}
VaultAction::Refresh => {
self.vault_selector.load_vaults(&self.vault_manager);
self.set_status("Vaults refreshed".to_string(), StatusType::Success);
}
VaultAction::Close => {
self.vault_selector.hide();
self.screen = Screen::Main;
}
VaultAction::ShowHelp => {
// You can handle help display here or ignore it
}
}
Ok(())
}
fn switch_to_vault(&mut self, vault_id: &str) -> Result<String> {
// First, switch the active vault in the registry
self.vault_manager.switch_active_vault(vault_id)?;
// Try to open the vault with the current master password
match self.vault_manager.open_vault(vault_id, &self.master_input) {
Ok(()) => {
// Successfully opened vault in the manager
// Now we need to create our own unlocked instance
let vault_info = self
.vault_manager
.registry
.get_vault(vault_id)
.ok_or_else(|| eyre!("Vault with id {} not found", vault_id))?;
let mut new_vault = chamber_vault::Vault::open_or_create(Some(&vault_info.path))?;
new_vault.unlock(&self.master_input)?;
// Replace our vault with the newly unlocked one
self.vault = new_vault;
self.refresh_items()?;
self.set_status(format!("Switched to vault: {vault_id}"), StatusType::Success);
}
Err(_) => {
// This vault has a different master password
self.vault_selector.error_message = Some(format!(
"Vault '{vault_id}' was created with a different master password. \
Please delete this vault and create a new one, or use the master password change feature to migrate it."
));
}
}
Ok(String::from(vault_id))
}
fn create_vault(&mut self, name: &str, description: Option<String>, category: &str) {
// Parse category
let vault_category = match category.to_lowercase().as_str() {
"personal" => chamber_vault::VaultCategory::Personal,
"work" => chamber_vault::VaultCategory::Work,
"team" => chamber_vault::VaultCategory::Team,
"project" => chamber_vault::VaultCategory::Project,
"testing" => chamber_vault::VaultCategory::Testing,
"archive" => chamber_vault::VaultCategory::Archive,
custom => chamber_vault::VaultCategory::Custom(custom.to_string()),
};
// In a real implementation, you'd prompt for a password
let password = &self.master_input;
// Validate that we have a password
if password.is_empty() {
self.vault_selector.error_message = Some("Master password is required to create vault".to_string());
}
match self
.vault_manager
.create_vault(name.to_string(), None, vault_category, description, password)
{
Ok(_vault_id) => {
self.vault_selector.load_vaults(&self.vault_manager);
self.vault_selector.mode = VaultSelectorMode::Select;
self.set_status(format!("Created vault: {name}"), StatusType::Success);
}
Err(e) => {
self.vault_selector.error_message = Some(format!("Failed to create vault: {e}"));
}
}
}
fn update_vault(
&mut self,
vault_id: String,
name: Option<String>,
description: Option<String>,
category: Option<String>,
favorite: Option<bool>,
) {
let vault_category = category.map(|cat_str| match cat_str.to_lowercase().as_str() {
"personal" => chamber_vault::VaultCategory::Personal,
"work" => chamber_vault::VaultCategory::Work,
"team" => chamber_vault::VaultCategory::Team,
"project" => chamber_vault::VaultCategory::Project,
"testing" => chamber_vault::VaultCategory::Testing,
"archive" => chamber_vault::VaultCategory::Archive,
custom => chamber_vault::VaultCategory::Custom(custom.to_string()),
});
match self
.vault_manager
.update_vault_info(&vault_id, name.clone(), description, vault_category, favorite)
{
Ok(()) => {
self.vault_selector.load_vaults(&self.vault_manager);
self.vault_selector.mode = VaultSelectorMode::Select;
self.set_status(
format!("Updated vault: {}", name.unwrap_or(vault_id)),
StatusType::Success,
);
}
Err(e) => {
self.vault_selector.error_message = Some(format!("Failed to update vault: {e}"));
}
}
}
fn delete_vault(&mut self, vault_id: &str, delete_file: bool) {
let is_active_vault = self.vault_manager.registry.active_vault_id.as_ref() == Some(&vault_id.to_string());
let vault_count = self.vault_manager.registry.vaults.len();
// Prevent deletion of an active vault unless it's the only one
if is_active_vault && vault_count > 1 {
self.set_status(
"Cannot delete active vault. Switch to another vault first.".to_string(),
StatusType::Error,
);
return;
}
match self.vault_manager.delete_vault(vault_id, delete_file) {
Ok(()) => {
self.vault_selector.load_vaults(&self.vault_manager);
self.vault_selector.mode = VaultSelectorMode::Select;
self.set_status(format!("Deleted vault: {vault_id}"), StatusType::Success);
}
Err(e) => {
self.set_status(format!("Failed to delete vault: {e}"), StatusType::Error);
}
}
}
fn import_vault(&mut self, path: &str) {
let path_buf = std::path::PathBuf::from(&path);
let name = path_buf
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("Imported Vault")
.to_string();
match self
.vault_manager
.import_vault(&path_buf, name.clone(), chamber_vault::VaultCategory::Personal, true)
{
Ok(_vault_id) => {
self.vault_selector.load_vaults(&self.vault_manager);
self.vault_selector.mode = VaultSelectorMode::Select;
self.set_status(format!("Imported vault: {name}"), StatusType::Success);
}
Err(e) => {
self.vault_selector.error_message = Some(format!("Failed to import vault: {e}"));
}
}
}
pub async fn update_activity(&mut self) {
if let Some(service) = &self.auto_lock_service {
service.update_activity().await;
}
}
pub async fn check_auto_lock(&mut self) -> bool {
if let Some(service) = &self.auto_lock_service {
if service.activity_tracker.should_auto_lock().await {
self.auto_locked = true;
self.screen = Screen::Unlock;
return true;
}
}
false
}
pub async fn get_time_until_auto_lock(&self) -> Option<chrono::Duration> {
if let Some(service) = &self.auto_lock_service {
service.get_time_until_lock().await
} else {
None
}
}
pub async fn update_countdown_info(&mut self) {
if let Some(time_left) = self.get_time_until_auto_lock().await {
self.countdown_info = Some(CountdownInfo {
enabled: true,
minutes_left: time_left.num_minutes(),
seconds_left: time_left.num_seconds(),
});
} else {
self.countdown_info = None;
}
}
// Synchronous method for the drawing function
pub const fn get_countdown_info(&self) -> Option<&CountdownInfo> {
self.countdown_info.as_ref()
}
}