mirror of
https://github.com/saymrwulf/xous-core.git
synced 2026-11-15 08:30:02 +00:00
rework list filtering to use an unsorted vec instead of btreemap
also eliminates references, copying and locking of items in the sorted btreemap. turns out that ... sorting is much cheaper than copying or maintaining references, because copies to heap items require allocs which are under the hoood several sorts to find the place to stick the alloc memory, and shared references require locks.
This commit is contained in:
parent
fa436c0845
commit
bd5b482cb0
4 changed files with 549 additions and 432 deletions
|
|
@ -15,7 +15,7 @@ use vault::{
|
|||
VAULT_PASSWORD_DICT, VAULT_TOTP_DICT, VAULT_ALLOC_HINT, utc_now,
|
||||
atime_to_str
|
||||
};
|
||||
use crate::ListItem;
|
||||
use crate::{ListItem, ListKey};
|
||||
use crate::{ItemLists, VaultMode, SelectedEntry};
|
||||
use crate::storage::{self, PasswordRecord, StorageContent};
|
||||
use crate::totp::TotpAlgorithm;
|
||||
|
|
@ -421,7 +421,7 @@ impl<'a> ActionManager<'a> {
|
|||
|
||||
if choice.is_none() {
|
||||
// we're dealing with FIDO stuff, use the custom code path
|
||||
let dictionary = match usize::from_str_radix(entry.key_name.as_str().unwrap_or("UTF8-error"), 10) {
|
||||
let dictionary = match usize::from_str_radix(entry.key_guid.as_str().unwrap_or("UTF8-error"), 10) {
|
||||
Ok(fido_key) => {
|
||||
if vault::ctap::storage::key::CREDENTIALS.contains(&fido_key) {
|
||||
persistent_store::store::OPENSK2_DICT // heuristic: all fido2 keys are simple integers
|
||||
|
|
@ -431,7 +431,7 @@ impl<'a> ActionManager<'a> {
|
|||
}
|
||||
Err(_) => U2F_APP_DICT, // u2f keys are long hex strings
|
||||
};
|
||||
match self.pddb.borrow().get(dictionary, entry.key_name.as_str().unwrap_or("UTF8-error"),
|
||||
match self.pddb.borrow().get(dictionary, entry.key_guid.as_str().unwrap_or("UTF8-error"),
|
||||
None, false, false, None, None::<fn()>
|
||||
) {
|
||||
Ok(candidate) => {
|
||||
|
|
@ -439,7 +439,7 @@ impl<'a> ActionManager<'a> {
|
|||
match self.pddb.borrow()
|
||||
.delete_key(
|
||||
dictionary,
|
||||
entry.key_name.as_str().unwrap_or("UTF8-error"),
|
||||
entry.key_guid.as_str().unwrap_or("UTF8-error"),
|
||||
Some(&attr.basis)
|
||||
) {
|
||||
Ok(_) => {
|
||||
|
|
@ -455,7 +455,7 @@ impl<'a> ActionManager<'a> {
|
|||
} else {
|
||||
// we're deleting either a password, or a totp
|
||||
let choice = choice.unwrap();
|
||||
let guid = entry.key_name.as_str().unwrap_or("UTF8-error");
|
||||
let guid = entry.key_guid.as_str().unwrap_or("UTF8-error");
|
||||
if entry.mode == VaultMode::Password {
|
||||
// self.modals.show_notification(&format!("deleting key {}", guid), None).ok();
|
||||
// if it's a password, we have to pull the full record, and then reconstitute the item_lists index key so we can remove it from the UX cache
|
||||
|
|
@ -469,8 +469,10 @@ impl<'a> ActionManager<'a> {
|
|||
};
|
||||
let mut desc = String::with_capacity(256);
|
||||
make_pw_name(&pw.description, &pw.username, &mut desc);
|
||||
let key = ListItem::key_from_parts(&desc, guid);
|
||||
self.item_lists.lock().unwrap().remove(entry.mode, key);
|
||||
let key = ListKey::key_from_parts(&desc, guid);
|
||||
assert!(self.item_lists.lock().unwrap().remove(entry.mode, key).is_some(),
|
||||
"requested to delete item, but it wasn't found!"
|
||||
);
|
||||
/*
|
||||
if self.item_lists.lock().unwrap().pw.remove(&key).is_some() {
|
||||
self.modals.show_notification(&format!("deleted UX {}", &key), None).ok();
|
||||
|
|
@ -492,7 +494,7 @@ impl<'a> ActionManager<'a> {
|
|||
match entry.mode {
|
||||
VaultMode::Password => {
|
||||
let choice = storage::ContentKind::Password;
|
||||
let guid = entry.key_name.as_str().unwrap_or("UTF8-error");
|
||||
let guid = entry.key_guid.as_str().unwrap_or("UTF8-error");
|
||||
let storage = self.storage.borrow_mut();
|
||||
let pw: storage::PasswordRecord = match storage.get_record(&choice, guid) {
|
||||
Ok(record) => record,
|
||||
|
|
@ -520,7 +522,7 @@ impl<'a> ActionManager<'a> {
|
|||
};
|
||||
log::debug!("updating {} to list item {}", li.extra, li.key());
|
||||
assert!(
|
||||
self.item_lists.lock().unwrap().insert(entry.mode, li.key(), li).is_some(),
|
||||
self.item_lists.lock().unwrap().insert_unique(entry.mode, li).is_some(),
|
||||
"Somehow, the autotyped record isn't in the UX list for updating!")
|
||||
;
|
||||
},
|
||||
|
|
@ -542,7 +544,7 @@ impl<'a> ActionManager<'a> {
|
|||
// at the moment only U2F records are supported for editing. The FIDO2 stuff is done with a different record
|
||||
// storage format that's a bit funkier to edit.
|
||||
let maybe_update = match self.pddb.borrow().get(
|
||||
dict, entry.key_name.as_str().unwrap(), None,
|
||||
dict, entry.key_guid.as_str().unwrap(), None,
|
||||
false, false, None, Some(basis_change)
|
||||
) {
|
||||
Ok(mut record) => {
|
||||
|
|
@ -586,10 +588,10 @@ impl<'a> ActionManager<'a> {
|
|||
}
|
||||
};
|
||||
if let Some((update, basis)) = maybe_update {
|
||||
self.pddb.borrow().delete_key(dict, entry.key_name.as_str().unwrap(), Some(&basis))
|
||||
self.pddb.borrow().delete_key(dict, entry.key_guid.as_str().unwrap(), Some(&basis))
|
||||
.unwrap_or_else(|e| self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)));
|
||||
match self.pddb.borrow().get(
|
||||
dict, entry.key_name.as_str().unwrap(), Some(&basis),
|
||||
dict, entry.key_guid.as_str().unwrap(), Some(&basis),
|
||||
false, true, Some(VAULT_ALLOC_HINT),
|
||||
Some(basis_change)
|
||||
) {
|
||||
|
|
@ -606,12 +608,12 @@ impl<'a> ActionManager<'a> {
|
|||
}
|
||||
|
||||
let choice = choice.unwrap();
|
||||
let key_name = entry.key_name.as_str().unwrap();
|
||||
let key_guid = entry.key_guid.as_str().unwrap();
|
||||
let mut storage = self.storage.borrow_mut();
|
||||
|
||||
let maybe_edited = match choice {
|
||||
storage::ContentKind::TOTP => {
|
||||
let mut pw: storage::TotpRecord = match storage.get_record(&choice, key_name) {
|
||||
let mut pw: storage::TotpRecord = match storage.get_record(&choice, key_guid) {
|
||||
Ok(record) => record,
|
||||
Err(error) => {
|
||||
self.report_err(t!("vault.error.internal_error", xous::LANG), Some(error));
|
||||
|
|
@ -656,10 +658,10 @@ impl<'a> ActionManager<'a> {
|
|||
pw.digits = d;
|
||||
}
|
||||
|
||||
storage.update(&choice, key_name, &mut pw)
|
||||
storage.update(&choice, key_guid, &mut pw)
|
||||
},
|
||||
storage::ContentKind::Password => {
|
||||
let mut pw: storage::PasswordRecord = match storage.get_record(&choice, key_name) {
|
||||
let mut pw: storage::PasswordRecord = match storage.get_record(&choice, key_guid) {
|
||||
Ok(record) => record,
|
||||
Err(error) => {
|
||||
self.report_err(t!("vault.error.internal_error", xous::LANG), Some(error));
|
||||
|
|
@ -669,11 +671,11 @@ impl<'a> ActionManager<'a> {
|
|||
// remove the entry from the old UX list
|
||||
let mut desc = String::new();
|
||||
make_pw_name(&pw.description, &pw.username, &mut desc);
|
||||
match self.item_lists.try_lock() {
|
||||
Ok(_) => log::debug!("list is not locked"),
|
||||
Err(_) => log::debug!("list is locked"),
|
||||
}
|
||||
self.item_lists.lock().unwrap().remove(VaultMode::Password, ListItem::key_from_parts(&desc, key_name));
|
||||
log::info!("editing {}:{}", desc, key_guid);
|
||||
assert!(self.item_lists.lock().unwrap()
|
||||
.remove(VaultMode::Password, ListKey::key_from_parts(&desc, &key_guid)).is_some()
|
||||
, "requested to edit a selection, but the selected item wasn't found!"
|
||||
);
|
||||
|
||||
// display previous data for edit
|
||||
let edit_data = if pw.notes != t!("vault.notes", xous::LANG) {
|
||||
|
|
@ -810,7 +812,7 @@ impl<'a> ActionManager<'a> {
|
|||
// note the edit access, this counts as an access since the password was revealed
|
||||
pw.count += 1;
|
||||
pw.atime = utc_now().timestamp() as u64;
|
||||
storage.update(&choice, key_name, &mut pw)
|
||||
storage.update(&choice, key_guid, &mut pw)
|
||||
},
|
||||
};
|
||||
|
||||
|
|
@ -880,15 +882,16 @@ impl<'a> ActionManager<'a> {
|
|||
let mut pw_rec = PasswordRecord::alloc();
|
||||
let mut extra = String::with_capacity(256);
|
||||
let mut desc = String::with_capacity(256);
|
||||
let mut lookup_key = String::with_capacity(384);
|
||||
let mut lookup_key = ListKey::reserved();
|
||||
let mut il = self.item_lists.lock().unwrap();
|
||||
// pre-reserve the space at the top, to avoid lots of allocs
|
||||
il.expand(self.mode_cache, keys.len());
|
||||
for key in keys {
|
||||
#[cfg(feature="vaultperf")]
|
||||
self.perfentry(&self.pm, PERFMETA_STARTBLOCK, 2, std::line!());
|
||||
if let Some(data) = key.data {
|
||||
if pw_rec.from_vec(data).is_ok() {
|
||||
// reset the re-usable structures
|
||||
lookup_key.clear();
|
||||
extra.clear();
|
||||
#[cfg(feature="vaultperf")]
|
||||
self.perfentry(&self.pm, PERFMETA_NONE, 2, std::line!());
|
||||
|
|
@ -897,13 +900,11 @@ impl<'a> ActionManager<'a> {
|
|||
make_pw_name(&pw_rec.description, &pw_rec.username, &mut desc);
|
||||
|
||||
// build the storage key in the list array
|
||||
lookup_key.push_str(&desc);
|
||||
lookup_key.push_str(&key.name);
|
||||
lookup_key.reset_from_parts(&desc, &key.name);
|
||||
|
||||
#[cfg(feature="vaultperf")]
|
||||
self.perfentry(&self.pm, PERFMETA_NONE, 2, std::line!());
|
||||
if let Some(prev_entry_locked) = il.get(self.mode_cache, &lookup_key) {
|
||||
let mut prev_entry = prev_entry_locked.lock().unwrap();
|
||||
if let Some(mut prev_entry) = il.get(self.mode_cache, &lookup_key) {
|
||||
#[cfg(feature="vaultperf")]
|
||||
self.perfentry(&self.pm, PERFMETA_STARTBLOCK, 3, std::line!());
|
||||
prev_entry.dirty = true;
|
||||
|
|
@ -953,10 +954,7 @@ impl<'a> ActionManager<'a> {
|
|||
atime: pw_rec.atime,
|
||||
count: pw_rec.count,
|
||||
};
|
||||
unsafe { // safety: fixup_filter() is called after this loop
|
||||
// this push is very slow, but we only have to do it once on boot
|
||||
il.bulk_insert(self.mode_cache, li.key(), li);
|
||||
}
|
||||
il.push(self.mode_cache, li);
|
||||
#[cfg(feature="vaultperf")]
|
||||
self.perfentry(&self.pm, PERFMETA_ENDBLOCK, 4, std::line!());
|
||||
}
|
||||
|
|
@ -985,7 +983,7 @@ impl<'a> ActionManager<'a> {
|
|||
self.perfentry(&self.pm, PERFMETA_ENDBLOCK, 2, std::line!());
|
||||
}
|
||||
log::debug!("before fixup_filter: {}", self.tt.elapsed_ms() - start);
|
||||
il.fixup_filter(); // meets the safety condition for bulk_insert()
|
||||
il.filter_reset(self.mode_cache);
|
||||
if oom_keys != 0 {
|
||||
log::warn!("Ran out of cache space handling password keys. {} keys are not loaded.", oom_keys);
|
||||
self.report_err(&format!("Ran out of cache space handling passwords. {} passwords not loaded", oom_keys), None::<crate::storage::Error>);
|
||||
|
|
@ -1032,7 +1030,7 @@ impl<'a> ActionManager<'a> {
|
|||
count: ai.count,
|
||||
atime: ai.atime,
|
||||
};
|
||||
self.item_lists.lock().unwrap().insert(self.mode_cache, li.key(), li);
|
||||
self.item_lists.lock().unwrap().insert_unique(self.mode_cache, li);
|
||||
} else {
|
||||
let err = format!("{}:{}:{}: ({})[moved data]...",
|
||||
key.basis, U2F_APP_DICT, key.name, key.len
|
||||
|
|
@ -1090,7 +1088,7 @@ impl<'a> ActionManager<'a> {
|
|||
count: 0,
|
||||
atime: 0,
|
||||
};
|
||||
self.item_lists.lock().unwrap().insert(self.mode_cache, li.key(), li);
|
||||
self.item_lists.lock().unwrap().insert_unique(self.mode_cache, li);
|
||||
}
|
||||
None => {
|
||||
// Probably more indicative of a mismatch in OpenSK key range mapping, rather than a hard error.
|
||||
|
|
@ -1149,7 +1147,7 @@ impl<'a> ActionManager<'a> {
|
|||
count: 0,
|
||||
atime: 0,
|
||||
};
|
||||
self.item_lists.lock().unwrap().insert(self.mode_cache, li.key(), li);
|
||||
self.item_lists.lock().unwrap().insert_unique(self.mode_cache, li);
|
||||
} else {
|
||||
let err = format!("{}:{}:{}: ({})[moved data]...",
|
||||
key.basis, VAULT_TOTP_DICT, key.name, key.len
|
||||
|
|
|
|||
|
|
@ -1,16 +1,77 @@
|
|||
use core::num::NonZeroUsize;
|
||||
use std::collections::BTreeMap;
|
||||
use std::cmp::Ordering;
|
||||
use crate::{VaultMode, SelectedEntry};
|
||||
use crate::ux::framework::NavDir;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::ops::Range;
|
||||
|
||||
pub struct ListKey {
|
||||
pub name: String,
|
||||
pub guid: String,
|
||||
}
|
||||
impl ListKey {
|
||||
pub fn key_from_parts(name: &str, guid: &str) -> Self {
|
||||
ListKey {
|
||||
name: name.to_owned(),
|
||||
guid: guid.to_owned(),
|
||||
}
|
||||
}
|
||||
pub fn reserved() -> Self {
|
||||
ListKey {
|
||||
name: String::with_capacity(256),
|
||||
guid: String::with_capacity(256),
|
||||
}
|
||||
}
|
||||
// re-uses the existing storage to avoid allocations
|
||||
pub fn reset_from_parts(&mut self, name: &str, guid: &str) {
|
||||
self.name.clear();
|
||||
self.name.push_str(name);
|
||||
self.guid.clear();
|
||||
self.guid.push_str(guid);
|
||||
}
|
||||
}
|
||||
impl PartialEq for ListKey {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.name == other.name && self.guid == other.guid
|
||||
}
|
||||
}
|
||||
impl PartialOrd for ListKey {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||
Some(
|
||||
match self.name.to_lowercase().cmp(&other.name.to_lowercase()) {
|
||||
Ordering::Equal => {
|
||||
self.guid.cmp(&other.guid)
|
||||
},
|
||||
Ordering::Greater => Ordering::Greater,
|
||||
Ordering::Less => Ordering::Less,
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
impl PartialEq::<ListItem> for ListKey {
|
||||
fn eq(&self, other: &ListItem) -> bool {
|
||||
self.name == other.name && self.guid == other.guid
|
||||
}
|
||||
}
|
||||
impl PartialOrd::<ListItem> for ListKey {
|
||||
fn partial_cmp(&self, other: &ListItem) -> Option<Ordering> {
|
||||
Some(
|
||||
match self.name.to_lowercase().cmp(&other.name.to_lowercase()) {
|
||||
Ordering::Equal => {
|
||||
self.guid.cmp(&other.guid)
|
||||
},
|
||||
Ordering::Greater => Ordering::Greater,
|
||||
Ordering::Less => Ordering::Less,
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
/// Display list for items. "name" is the key by which the list is sorted.
|
||||
/// "extra" is more information about the item, which should not be part of the sort.
|
||||
#[derive(Debug)]
|
||||
pub struct ListItem {
|
||||
pub name: String,
|
||||
pub extra: String,
|
||||
/// used by drawing routines to optimize refresh time
|
||||
pub dirty: bool,
|
||||
/// this is the name of the key used to refer to the item
|
||||
pub guid: String,
|
||||
|
|
@ -19,7 +80,8 @@ pub struct ListItem {
|
|||
pub count: u64,
|
||||
}
|
||||
impl ListItem {
|
||||
pub fn clone(&self) -> ListItem {
|
||||
// good riddance.
|
||||
/* pub fn clone(&self) -> ListItem {
|
||||
ListItem {
|
||||
name: self.name.to_string(),
|
||||
extra: self.extra.to_string(),
|
||||
|
|
@ -28,7 +90,7 @@ impl ListItem {
|
|||
atime: self.atime,
|
||||
count: self.count,
|
||||
}
|
||||
}
|
||||
} */
|
||||
/// This is made available for edit/delete routines to generate the key without having to
|
||||
/// make a whole ListItem record (which is somewhat expensive).
|
||||
pub fn key_from_parts(name: &str, guid: &str) -> String {
|
||||
|
|
@ -40,7 +102,7 @@ impl ListItem {
|
|||
}
|
||||
impl Ord for ListItem {
|
||||
fn cmp(&self, other: &Self) -> Ordering {
|
||||
match self.name.cmp(&other.name) {
|
||||
match self.name.to_lowercase().cmp(&other.name.to_lowercase()) {
|
||||
Ordering::Equal => {
|
||||
self.guid.cmp(&other.guid)
|
||||
},
|
||||
|
|
@ -50,11 +112,29 @@ impl Ord for ListItem {
|
|||
}
|
||||
}
|
||||
impl PartialOrd for ListItem {
|
||||
|
||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
impl PartialOrd::<ListKey> for ListItem {
|
||||
fn partial_cmp(&self, other: &ListKey) -> Option<Ordering> {
|
||||
// log::info!("self {}:{}\nother: {}:{}", self.name, self.guid, other.name, other.guid);
|
||||
Some(
|
||||
match self.name.to_lowercase().cmp(&other.name.to_lowercase()) {
|
||||
Ordering::Equal => {
|
||||
self.guid.cmp(&other.guid)
|
||||
},
|
||||
Ordering::Greater => Ordering::Greater,
|
||||
Ordering::Less => Ordering::Less,
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
impl PartialEq::<ListKey> for ListItem {
|
||||
fn eq(&self, other: &ListKey) -> bool {
|
||||
self.name == other.name && self.guid == other.guid
|
||||
}
|
||||
}
|
||||
impl PartialEq for ListItem {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.name == other.name && self.guid == other.guid
|
||||
|
|
@ -62,337 +142,385 @@ impl PartialEq for ListItem {
|
|||
}
|
||||
impl Eq for ListItem {}
|
||||
|
||||
pub struct ItemLists {
|
||||
fido: BTreeMap::<String, Arc<Mutex<ListItem>>>,
|
||||
totp: BTreeMap::<String, Arc<Mutex<ListItem>>>,
|
||||
pw: BTreeMap::<String, Arc<Mutex<ListItem>>>,
|
||||
/// create a mostly static list of references that we can use to index into the corresponding database
|
||||
/// this gets around both lifetime issues by putting the references in this scope, and also gets
|
||||
/// around slow alloc issues having to deal with copies when avoiding lifetimes.
|
||||
filtered_list: Vec::<Option<Arc<Mutex<ListItem>>>>,
|
||||
/// records the longest possible length of all three lists, so filtered_list() capacity can be adjusted accordingly
|
||||
max_len: usize,
|
||||
/// memoize the filtered length so we don't have to search it every time
|
||||
valid_len: usize,
|
||||
items_per_screen: NonZeroUsize,
|
||||
pub struct FilteredListView {
|
||||
list: Vec<ListItem>,
|
||||
sorted: bool,
|
||||
selection_index: usize,
|
||||
items_per_screen: NonZeroUsize,
|
||||
filter_range: Option<Range::<usize>>,
|
||||
}
|
||||
impl ItemLists {
|
||||
impl FilteredListView {
|
||||
pub fn new() -> Self {
|
||||
ItemLists {
|
||||
fido: BTreeMap::new(),
|
||||
totp: BTreeMap::new(),
|
||||
pw: BTreeMap::new(),
|
||||
filtered_list: Vec::new(),
|
||||
max_len: 0,
|
||||
valid_len: 0,
|
||||
items_per_screen: NonZeroUsize::new(1).unwrap(),
|
||||
Self {
|
||||
list: Vec::new(),
|
||||
sorted: false,
|
||||
selection_index: 0,
|
||||
items_per_screen: NonZeroUsize::new(1).unwrap(),
|
||||
filter_range: None,
|
||||
}
|
||||
}
|
||||
/// safety: caller must call fixup_filter() after successive calls to this are done.
|
||||
pub unsafe fn bulk_insert(&mut self, list_type: VaultMode, key: String, item: ListItem) {
|
||||
match list_type {
|
||||
VaultMode::Fido => self.fido.insert(key, Arc::new(Mutex::new(item))),
|
||||
VaultMode::Totp => self.totp.insert(key, Arc::new(Mutex::new(item))),
|
||||
VaultMode::Password => self.pw.insert(key, Arc::new(Mutex::new(item))),
|
||||
};
|
||||
pub fn expand(&mut self, capacity: usize) {
|
||||
self.list.reserve(capacity.saturating_sub(self.list.len()))
|
||||
}
|
||||
pub fn fixup_filter(&mut self) {
|
||||
// grow the filter to accommodate the largest possible list
|
||||
let new_len = self.fido.len()
|
||||
.max(self.totp.len())
|
||||
.max(self.pw.len());
|
||||
// clear the existing records
|
||||
self.filtered_list.iter_mut().for_each(|i| *i = None);
|
||||
self.valid_len = 0;
|
||||
// fill in any growth with null records, guaranteeing that we can always index using slice offsets
|
||||
for _ in 0..new_len.saturating_sub(self.filtered_list.len()) {
|
||||
self.filtered_list.push(None);
|
||||
}
|
||||
self.max_len = new_len;
|
||||
pub fn push(&mut self, item: ListItem) {
|
||||
self.list.push(item);
|
||||
self.sorted = false;
|
||||
}
|
||||
pub fn insert(&mut self, list_type: VaultMode, key: String, item: ListItem) -> Option<ListItem> {
|
||||
let maybe_replaced = match list_type {
|
||||
VaultMode::Fido => self.fido.insert(key, Arc::new(Mutex::new(item))),
|
||||
VaultMode::Totp => self.totp.insert(key, Arc::new(Mutex::new(item))),
|
||||
VaultMode::Password => self.pw.insert(key, Arc::new(Mutex::new(item))),
|
||||
};
|
||||
let new_len = match list_type {
|
||||
VaultMode::Fido => self.fido.len(),
|
||||
VaultMode::Totp => self.totp.len(),
|
||||
VaultMode::Password => self.pw.len(),
|
||||
};
|
||||
// clear the filter, because we don't know where in the sort that the updated record should go...
|
||||
self.filtered_list.iter_mut().for_each(|i| *i = None);
|
||||
self.valid_len = 0;
|
||||
// fill in any growth with null records, guaranteeing that we can always index using slice offsets
|
||||
for _ in 0..new_len.saturating_sub(self.filtered_list.len()) {
|
||||
self.filtered_list.push(None);
|
||||
}
|
||||
self.max_len = self.max_len.max(new_len);
|
||||
if let Some(replaced) = maybe_replaced {
|
||||
Some(
|
||||
Arc::<_>::try_unwrap(replaced).unwrap().into_inner().unwrap()
|
||||
)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
pub fn get(&self, list_type: VaultMode, key: &String) -> Option<&Arc<Mutex<ListItem>>> {
|
||||
match list_type {
|
||||
VaultMode::Fido => self.fido.get(key),
|
||||
VaultMode::Password => self.pw.get(key),
|
||||
VaultMode::Totp => self.pw.get(key),
|
||||
}
|
||||
}
|
||||
pub fn remove(&mut self, list_type: VaultMode, key: String) -> Option<ListItem> {
|
||||
let maybe_item = match list_type {
|
||||
VaultMode::Fido => self.fido.remove(&key),
|
||||
VaultMode::Totp => self.totp.remove(&key),
|
||||
VaultMode::Password => self.pw.remove(&key),
|
||||
};
|
||||
if let Some(item) = maybe_item {
|
||||
log::debug!("count bef: {}", Arc::<_>::strong_count(&item));
|
||||
self.filtered_list.retain(|x|
|
||||
if let Some(filter_item) = x {
|
||||
if Arc::as_ptr(filter_item) == Arc::as_ptr(&item) {
|
||||
false // don't retain
|
||||
} else {
|
||||
true
|
||||
}
|
||||
} else {
|
||||
true
|
||||
}
|
||||
);
|
||||
log::debug!("count aft: {}", Arc::<_>::strong_count(&item));
|
||||
Some(
|
||||
Arc::<_>::try_unwrap(item).unwrap().into_inner().unwrap()
|
||||
)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
pub fn set_items_per_screen(&mut self, ips: i16) {
|
||||
self.items_per_screen = NonZeroUsize::new(ips as usize).unwrap_or(NonZeroUsize::new(1).unwrap());
|
||||
}
|
||||
pub fn clear_filter(&mut self) {
|
||||
self.filtered_list.iter_mut().for_each(|i| *i = None);
|
||||
self.valid_len = 0;
|
||||
pub fn clear(&mut self) {
|
||||
log::info!("filter clear");
|
||||
self.list.clear();
|
||||
self.sorted = false;
|
||||
self.selection_index = 0;
|
||||
self.filter_range = None;
|
||||
}
|
||||
pub fn clear(&mut self, list_type: VaultMode) {
|
||||
self.filtered_list.iter_mut().for_each(|i| *i = None);
|
||||
self.valid_len = 0;
|
||||
match list_type {
|
||||
VaultMode::Fido => self.fido.clear(),
|
||||
VaultMode::Totp => self.totp.clear(),
|
||||
VaultMode::Password => self.pw.clear(),
|
||||
}
|
||||
// maybe do a search for what is the new max_len? for now we can just "leave it", it just means we have some excess capacity which is good: less mallocs.
|
||||
}
|
||||
pub fn clear_all(&mut self) {
|
||||
self.filtered_list.iter_mut().for_each(|i| *i = None);
|
||||
self.valid_len = 0;
|
||||
self.fido.clear();
|
||||
self.totp.clear();
|
||||
self.pw.clear();
|
||||
self.max_len = 0;
|
||||
}
|
||||
/// Sets up a filter for the selected list type, returns a default selection index.
|
||||
pub fn filter(&mut self, list_type: VaultMode, criteria: &str) {
|
||||
let tt = ticktimer_server::Ticktimer::new().unwrap();
|
||||
let mut ts = [0u64; 5];
|
||||
ts[0] = tt.elapsed_ms();
|
||||
// clear the list
|
||||
self.filtered_list.iter_mut().for_each(|i| *i = None);
|
||||
ts[1] = tt.elapsed_ms();
|
||||
self.valid_len = 0;
|
||||
|
||||
let itemlist = match list_type {
|
||||
VaultMode::Fido => &mut self.fido,
|
||||
VaultMode::Totp => &mut self.totp,
|
||||
VaultMode::Password => &mut self.pw,
|
||||
};
|
||||
ts[2] = tt.elapsed_ms();
|
||||
let mut filter_index = 0;
|
||||
// search the whole list for now -- maybe optimize to a subset later on,
|
||||
// but would require keeping two copies of the filtered list because we can't do
|
||||
// in-place operation on an already filtered list
|
||||
for item in itemlist.values_mut() {
|
||||
if item.lock().unwrap().name.to_lowercase().starts_with(criteria) {
|
||||
item.lock().unwrap().dirty = true;
|
||||
self.filtered_list[filter_index] = Some(item.clone());
|
||||
filter_index += 1;
|
||||
pub fn set_items_per_screen(&mut self, ips: usize) {
|
||||
if ips != self.items_per_screen.get() {
|
||||
for item in self.list.iter_mut() {
|
||||
item.dirty = true;
|
||||
}
|
||||
}
|
||||
ts[3] = tt.elapsed_ms();
|
||||
self.valid_len = filter_index;
|
||||
if self.selection_index >= self.valid_len {
|
||||
if self.valid_len > 0 {
|
||||
self.selection_index = self.valid_len - 1;
|
||||
} else {
|
||||
self.selection_index = 0;
|
||||
self.items_per_screen = NonZeroUsize::new(ips).unwrap_or(NonZeroUsize::new(1).unwrap());
|
||||
}
|
||||
pub fn insert_unique(&mut self, item: ListItem) -> Option<ListItem> {
|
||||
if !self.sorted {
|
||||
self.list.sort();
|
||||
self.sorted = true;
|
||||
}
|
||||
self.filter_range = None;
|
||||
match self.list.binary_search_by(|probe| probe.cmp(&item)) {
|
||||
Ok(index) => Some(std::mem::replace(&mut self.list[index], item)),
|
||||
Err(index) => {
|
||||
self.list.insert(index, item);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn remove(&mut self, item: ListKey) -> Option<ListItem> {
|
||||
if !self.sorted {
|
||||
self.list.sort();
|
||||
self.sorted = true;
|
||||
}
|
||||
self.filter_range = None;
|
||||
match self.list.binary_search_by(|probe| probe.partial_cmp(&item).unwrap()) {
|
||||
Ok(index) => {
|
||||
Some(self.list.remove(index))
|
||||
},
|
||||
Err(_index) => None
|
||||
}
|
||||
}
|
||||
pub fn get(&mut self, item: &ListKey) -> Option<&mut ListItem> {
|
||||
if !self.sorted {
|
||||
self.list.sort();
|
||||
self.sorted = true;
|
||||
}
|
||||
match self.list.binary_search_by(|probe| probe.partial_cmp(item).unwrap()) {
|
||||
Ok(index) => {
|
||||
Some(&mut self.list[index])
|
||||
},
|
||||
Err(_index) => None
|
||||
}
|
||||
}
|
||||
pub fn filter(&mut self, criteria: &String) {
|
||||
let tt = ticktimer_server::Ticktimer::new().unwrap();
|
||||
let mut ts = [0u64; 6];
|
||||
ts[0] = tt.elapsed_ms();
|
||||
// always ensure the list is sorted
|
||||
if !self.sorted {
|
||||
self.list.sort();
|
||||
self.sorted = true;
|
||||
}
|
||||
ts[1] = tt.elapsed_ms();
|
||||
// sanity checks on the request
|
||||
if criteria.len() == 0 {
|
||||
self.filter_reset();
|
||||
return;
|
||||
}
|
||||
if self.list.len() == 0 {
|
||||
log::info!("zero-length list!");
|
||||
return;
|
||||
}
|
||||
// step 1. binary search to find if the criteria is even anywhere in the list.
|
||||
match self.list.binary_search_by(|probe| probe.name.partial_cmp(criteria).unwrap()) {
|
||||
Ok(mut index) | Err(mut index) => {
|
||||
if !self.list[index].name.to_lowercase().starts_with(criteria) {
|
||||
self.filter_range = None
|
||||
} else {
|
||||
// step 2. we have to go backwards in the list because if we have several matches, we are
|
||||
// not guaranteed to be at the first match. Find that first match with a linear search.
|
||||
ts[2] = tt.elapsed_ms();
|
||||
while index.saturating_sub(1) > 0 {
|
||||
if self.list[index - 1].name.to_lowercase().starts_with(criteria) {
|
||||
index -= 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// the index now starts at the range of matches. Find the end of matches with another linear search.
|
||||
let mut end_index = index + 1;
|
||||
ts[3] = tt.elapsed_ms();
|
||||
while end_index < self.list.len() {
|
||||
if self.list[end_index].name.to_lowercase().starts_with(criteria) {
|
||||
end_index += 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.filter_range = Some(index..end_index)
|
||||
}
|
||||
}
|
||||
}
|
||||
ts[4] = tt.elapsed_ms();
|
||||
if let Some(r) = &self.filter_range {
|
||||
if self.selection_index >= r.len() {
|
||||
self.selection_index = 0;
|
||||
}
|
||||
}
|
||||
self.mark_filtered_as_dirty();
|
||||
ts[5] = tt.elapsed_ms();
|
||||
for(index, &elapsed) in ts[1..].iter().enumerate() {
|
||||
log::info!("{}: {}", index + 1, elapsed - ts[0]);
|
||||
}
|
||||
}
|
||||
/// Sets the filter's buffer to point to the entire contents of the specified list (no filtering)
|
||||
pub fn filter_reset(&mut self, list_type: VaultMode) {
|
||||
// clear the list
|
||||
self.filtered_list.iter_mut().for_each(|i| *i = None);
|
||||
self.valid_len = 0;
|
||||
|
||||
let itemlist = match list_type {
|
||||
VaultMode::Fido => &mut self.fido,
|
||||
VaultMode::Totp => &mut self.totp,
|
||||
VaultMode::Password => &mut self.pw,
|
||||
};
|
||||
assert!(itemlist.len() <= self.filtered_list.len(), "consistency error in filter vector size");
|
||||
for (item, filt)
|
||||
in itemlist.values_mut().zip(self.filtered_list.iter_mut()) {
|
||||
item.lock().unwrap().dirty = true;
|
||||
*filt = Some(item.clone());
|
||||
}
|
||||
self.valid_len = itemlist.len();
|
||||
if self.selection_index >= self.valid_len {
|
||||
if self.valid_len > 0 {
|
||||
self.selection_index = self.valid_len - 1;
|
||||
} else {
|
||||
self.selection_index = 0;
|
||||
fn mark_filtered_as_dirty(&mut self) {
|
||||
if let Some(r) = self.filter_range.clone() {
|
||||
for i in self.list[r].iter_mut() {
|
||||
i.dirty = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn filter_reset(&mut self) {
|
||||
self.filter_range = Some(0..self.list.len());
|
||||
self.mark_filtered_as_dirty();
|
||||
}
|
||||
pub fn filter_len(&self) -> usize {
|
||||
self.valid_len
|
||||
}
|
||||
pub fn nav(&mut self, dir: NavDir) {
|
||||
match dir {
|
||||
NavDir::Up => {
|
||||
if self.selection_index > 0 {
|
||||
let starting_page = self.get_page();
|
||||
self.mark_as_dirty(self.selection_index);
|
||||
self.selection_index -= 1;
|
||||
self.mark_as_dirty(self.selection_index);
|
||||
if starting_page != self.get_page() {
|
||||
self.mark_screen_as_dirty(self.selection_index);
|
||||
}
|
||||
}
|
||||
}
|
||||
NavDir::Down => {
|
||||
if self.selection_index < self.valid_len {
|
||||
let starting_page = self.get_page();
|
||||
self.mark_as_dirty(self.selection_index);
|
||||
self.selection_index += 1;
|
||||
self.mark_as_dirty(self.selection_index);
|
||||
if starting_page != self.get_page() {
|
||||
self.mark_screen_as_dirty(self.selection_index);
|
||||
}
|
||||
}
|
||||
}
|
||||
NavDir::PageUp => {
|
||||
if self.selection_index > self.items_per_screen.get() {
|
||||
self.mark_screen_as_dirty(self.selection_index);
|
||||
self.selection_index -= self.items_per_screen.get();
|
||||
self.mark_screen_as_dirty(self.selection_index);
|
||||
} else {
|
||||
self.mark_as_dirty(self.selection_index);
|
||||
self.selection_index = 0;
|
||||
self.mark_as_dirty(self.selection_index);
|
||||
}
|
||||
}
|
||||
NavDir::PageDown => {
|
||||
if self.selection_index < self.valid_len - self.items_per_screen.get() {
|
||||
self.mark_screen_as_dirty(self.selection_index);
|
||||
self.selection_index += self.items_per_screen.get();
|
||||
self.mark_screen_as_dirty(self.selection_index);
|
||||
} else {
|
||||
self.mark_as_dirty(self.selection_index);
|
||||
self.selection_index = self.valid_len - 1;
|
||||
self.mark_as_dirty(self.selection_index);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fn mark_as_dirty(&mut self, index: usize) {
|
||||
if self.valid_len > 0 {
|
||||
if let Some(record) = self.filtered_list[index.min(self.valid_len - 1)].as_mut() {
|
||||
record.lock().unwrap().dirty = true;
|
||||
}
|
||||
if let Some(r) = &self.filter_range {
|
||||
log::info!("filter len {}", r.len());
|
||||
r.len()
|
||||
} else {
|
||||
log::info!("filter is not present (0)");
|
||||
0
|
||||
}
|
||||
}
|
||||
pub fn mark_all_dirty(&mut self) {
|
||||
for maybe_item in self.filtered_list.iter_mut() {
|
||||
if let Some(item) = maybe_item {
|
||||
item.lock().unwrap().dirty = true;
|
||||
}
|
||||
for item in self.list.iter_mut() {
|
||||
item.dirty = true;
|
||||
}
|
||||
}
|
||||
fn mark_screen_as_dirty(&mut self, index: usize) {
|
||||
let page = index as i16 / self.items_per_screen.get() as i16;
|
||||
for item in self.filtered_list[
|
||||
((page as usize) * self.items_per_screen.get()).min(self.valid_len) ..
|
||||
((1 + page as usize) * self.items_per_screen.get()).min(self.valid_len)
|
||||
].iter_mut() {
|
||||
if let Some(record) = item {
|
||||
record.lock().unwrap().dirty = true;
|
||||
}
|
||||
fn mark_filtered_selection_as_dirty(&mut self, index: usize) {
|
||||
let index = index + self.filter_start();
|
||||
if index < self.list.len() {
|
||||
self.list[index].dirty = true;
|
||||
}
|
||||
}
|
||||
fn mark_filtered_screen_as_dirty(&mut self, index: usize) {
|
||||
let index = index + self.filter_start();
|
||||
let page = index / self.items_per_screen.get();
|
||||
let listlen = self.list.len();
|
||||
for item in self.list[
|
||||
((page as usize) * self.items_per_screen.get()).min(listlen) ..
|
||||
((1 + page as usize) * self.items_per_screen.get()).min(listlen)
|
||||
].iter_mut() {
|
||||
item.dirty = true;
|
||||
}
|
||||
}
|
||||
fn filter_start(&self) -> usize {
|
||||
self.filter_range.clone().unwrap_or(0..0).start
|
||||
}
|
||||
pub fn get_page(&self) -> usize {
|
||||
self.selection_index / self.items_per_screen.get()
|
||||
}
|
||||
pub fn selected_index(&self) -> usize {
|
||||
self.selection_index % self.items_per_screen.get()
|
||||
}
|
||||
pub fn selected_page(&mut self) -> &mut [Option<Arc<Mutex<ListItem>>>] {
|
||||
pub fn selected_page(&mut self) -> &mut [ListItem] {
|
||||
let filterlen = self.filter_len();
|
||||
let page = self.get_page();
|
||||
&mut self.filtered_list[
|
||||
(page * self.items_per_screen.get()).min(self.valid_len) ..
|
||||
((1 + page) * self.items_per_screen.get()).min(self.valid_len)
|
||||
let filtered_range = &mut self.list[self.filter_range.clone().unwrap_or(0..0)];
|
||||
&mut filtered_range[
|
||||
(page * self.items_per_screen.get()).min(filterlen) ..
|
||||
((1 + page) * self.items_per_screen.get()).min(filterlen)
|
||||
]
|
||||
}
|
||||
pub fn nav(&mut self, dir: NavDir) {
|
||||
log::info!("index bef: {}, filter: {:?}", self.selection_index, self.filter_range);
|
||||
match dir {
|
||||
NavDir::Up => {
|
||||
if self.selection_index > 0 {
|
||||
let starting_page = self.get_page();
|
||||
self.mark_filtered_selection_as_dirty(self.selection_index);
|
||||
self.selection_index -= 1;
|
||||
self.mark_filtered_selection_as_dirty(self.selection_index);
|
||||
if starting_page != self.get_page() {
|
||||
self.mark_filtered_screen_as_dirty(self.selection_index);
|
||||
}
|
||||
}
|
||||
}
|
||||
NavDir::Down => {
|
||||
if self.selection_index < self.filter_len() {
|
||||
let starting_page = self.get_page();
|
||||
self.mark_filtered_selection_as_dirty(self.selection_index);
|
||||
self.selection_index += 1;
|
||||
self.mark_filtered_selection_as_dirty(self.selection_index);
|
||||
if starting_page != self.get_page() {
|
||||
self.mark_filtered_screen_as_dirty(self.selection_index);
|
||||
}
|
||||
}
|
||||
}
|
||||
NavDir::PageUp => {
|
||||
if self.selection_index > self.items_per_screen.get() {
|
||||
self.mark_filtered_screen_as_dirty(self.selection_index);
|
||||
self.selection_index -= self.items_per_screen.get();
|
||||
self.mark_filtered_screen_as_dirty(self.selection_index);
|
||||
} else {
|
||||
self.mark_filtered_selection_as_dirty(self.selection_index);
|
||||
self.selection_index = 0;
|
||||
self.mark_filtered_selection_as_dirty(self.selection_index);
|
||||
}
|
||||
}
|
||||
NavDir::PageDown => {
|
||||
if self.selection_index < self.filter_len() - self.items_per_screen.get() {
|
||||
self.mark_filtered_screen_as_dirty(self.selection_index);
|
||||
self.selection_index += self.items_per_screen.get();
|
||||
self.mark_filtered_screen_as_dirty(self.selection_index);
|
||||
} else {
|
||||
self.mark_filtered_selection_as_dirty(self.selection_index);
|
||||
self.selection_index = self.filter_len() - 1;
|
||||
self.mark_filtered_selection_as_dirty(self.selection_index);
|
||||
}
|
||||
}
|
||||
}
|
||||
log::info!("index after: {}", self.selection_index);
|
||||
}
|
||||
pub fn selected_guid(&self) -> String {
|
||||
// we unwrap() here because this function is responsible for consistency of the filtered list.
|
||||
self.filtered_list[self.selection_index].as_ref().unwrap().lock().unwrap().guid.to_owned()
|
||||
self.list[self.selection_index + self.filter_start()].guid.to_owned()
|
||||
}
|
||||
pub fn selected_extra(&self) -> String {
|
||||
// we unwrap() here because this function is responsible for consistency of the filtered list.
|
||||
self.filtered_list[self.selection_index].as_ref().unwrap().lock().unwrap().extra.to_owned()
|
||||
self.list[self.selection_index + self.filter_start()].extra.to_owned()
|
||||
}
|
||||
pub fn selected_update_extra(&mut self, extra: String) {
|
||||
self.filtered_list[self.selection_index].as_mut().unwrap().lock().unwrap().extra = extra;
|
||||
self.filtered_list[self.selection_index].as_mut().unwrap().lock().unwrap().dirty = true;
|
||||
let start = self.filter_start();
|
||||
self.list[self.selection_index + start].extra = extra
|
||||
}
|
||||
pub fn selected_update_atime(&mut self, atime: u64) {
|
||||
self.filtered_list[self.selection_index].as_mut().unwrap().lock().unwrap().atime = atime;
|
||||
self.filtered_list[self.selection_index].as_mut().unwrap().lock().unwrap().dirty = true;
|
||||
}
|
||||
pub fn mark_selected_as_dirty(&mut self) {
|
||||
// we unwrap() here because this function is responsible for consistency of the filtered list.
|
||||
self.filtered_list[self.selection_index].as_mut().unwrap().lock().unwrap().dirty = true;
|
||||
let start = self.filter_start();
|
||||
self.list[self.selection_index + start].atime = atime
|
||||
}
|
||||
pub fn selected_entry(&self, mode: VaultMode) -> Option<SelectedEntry> {
|
||||
let ret = if self.selection_index > self.valid_len {
|
||||
None
|
||||
} else {
|
||||
if let Some(entry) = &self.filtered_list[self.selection_index] {
|
||||
let guarded_entry = entry.lock().unwrap();
|
||||
if let Some(r) = self.filter_range.clone() {
|
||||
log::info!("filter range: {:?}", r);
|
||||
log::info!("selection index: {}", self.selection_index);
|
||||
log::info!("filter start: {}", self.filter_start());
|
||||
if r.contains(&(self.selection_index + self.filter_start())) {
|
||||
Some(
|
||||
SelectedEntry {
|
||||
key_name: xous_ipc::String::from_str(guarded_entry.guid.to_string()),
|
||||
description: xous_ipc::String::from_str(guarded_entry.name.to_string()),
|
||||
key_guid: xous_ipc::String::from_str(&self.list[self.selection_index + self.filter_start()].guid),
|
||||
description: xous_ipc::String::from_str(&self.list[self.selection_index + self.filter_start()].name),
|
||||
mode
|
||||
}
|
||||
)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
ret
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
pub struct ItemLists {
|
||||
fido: FilteredListView,
|
||||
totp: FilteredListView,
|
||||
pw: FilteredListView,
|
||||
}
|
||||
impl ItemLists {
|
||||
pub fn new() -> Self {
|
||||
ItemLists {
|
||||
fido: FilteredListView::new(),
|
||||
totp: FilteredListView::new(),
|
||||
pw: FilteredListView::new(),
|
||||
}
|
||||
}
|
||||
fn li_mut(&mut self, list_type: VaultMode) -> &mut FilteredListView {
|
||||
match list_type {
|
||||
VaultMode::Fido => &mut self.fido,
|
||||
VaultMode::Totp => &mut self.totp,
|
||||
VaultMode::Password => &mut self.pw,
|
||||
}
|
||||
}
|
||||
fn li(&self, list_type: VaultMode) -> &FilteredListView {
|
||||
match list_type {
|
||||
VaultMode::Fido => &self.fido,
|
||||
VaultMode::Totp => &self.totp,
|
||||
VaultMode::Password => &self.pw,
|
||||
}
|
||||
}
|
||||
pub fn push(&mut self, list_type: VaultMode, item: ListItem) {
|
||||
self.li_mut(list_type).push(item);
|
||||
}
|
||||
pub fn expand(&mut self, list_type: VaultMode, capacity: usize) {
|
||||
self.li_mut(list_type).expand(capacity);
|
||||
}
|
||||
pub fn insert_unique(&mut self, list_type: VaultMode, item: ListItem) -> Option<ListItem> {
|
||||
self.li_mut(list_type).insert_unique(item)
|
||||
}
|
||||
pub fn get(&mut self, list_type: VaultMode, key: &ListKey) -> Option<&mut ListItem> {
|
||||
self.li_mut(list_type).get(key)
|
||||
}
|
||||
pub fn remove(&mut self, list_type: VaultMode, key: ListKey) -> Option<ListItem> {
|
||||
self.li_mut(list_type).remove(key)
|
||||
}
|
||||
pub fn set_items_per_screen(&mut self, ips: i16) {
|
||||
self.fido.set_items_per_screen(ips as usize);
|
||||
self.totp.set_items_per_screen(ips as usize);
|
||||
self.pw.set_items_per_screen(ips as usize);
|
||||
}
|
||||
pub fn mark_all_dirty(&mut self) {
|
||||
self.fido.mark_all_dirty();
|
||||
self.totp.mark_all_dirty();
|
||||
self.pw.mark_all_dirty();
|
||||
}
|
||||
pub fn clear_filter(&mut self) {
|
||||
}
|
||||
pub fn clear(&mut self, list_type: VaultMode) {
|
||||
self.li_mut(list_type).clear();
|
||||
}
|
||||
pub fn clear_all(&mut self) {
|
||||
self.fido.clear();
|
||||
self.pw.clear();
|
||||
self.totp.clear();
|
||||
}
|
||||
/// Sets up a filter for the selected list type, returns a default selection index.
|
||||
pub fn filter(&mut self, list_type: VaultMode, criteria: &String) {
|
||||
self.li_mut(list_type).filter(criteria);
|
||||
}
|
||||
/// Sets the filter's buffer to point to the entire contents of the specified list (no filtering)
|
||||
pub fn filter_reset(&mut self, list_type: VaultMode) {
|
||||
self.li_mut(list_type).filter_reset();
|
||||
}
|
||||
pub fn filter_len(&self, list_type: VaultMode) -> usize {
|
||||
self.li(list_type).filter_len()
|
||||
}
|
||||
pub fn nav(&mut self, list_type: VaultMode, dir: NavDir) {
|
||||
self.li_mut(list_type).nav(dir);
|
||||
}
|
||||
pub fn selected_index(&self, list_type: VaultMode) -> usize {
|
||||
self.li(list_type).selected_index()
|
||||
}
|
||||
pub fn selected_guid(&self, list_type: VaultMode) -> String {
|
||||
self.li(list_type).selected_guid()
|
||||
}
|
||||
pub fn selected_extra(&self, list_type: VaultMode) -> String {
|
||||
self.li(list_type).selected_extra()
|
||||
}
|
||||
pub fn selected_update_extra(&mut self, list_type: VaultMode, extra: String) {
|
||||
self.li_mut(list_type).selected_update_extra(extra)
|
||||
}
|
||||
pub fn selected_update_atime(&mut self, list_type: VaultMode, atime: u64) {
|
||||
self.li_mut(list_type).selected_update_atime(atime)
|
||||
}
|
||||
pub fn selected_entry(&self, list_type: VaultMode) -> Option<SelectedEntry> {
|
||||
self.li(list_type).selected_entry(list_type)
|
||||
}
|
||||
pub fn selected_page(&mut self, list_type: VaultMode) -> &mut [ListItem] {
|
||||
self.li_mut(list_type).selected_page()
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -104,7 +104,7 @@ pub enum VaultMode {
|
|||
|
||||
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)]
|
||||
pub struct SelectedEntry {
|
||||
pub key_name: xous_ipc::String::<256>,
|
||||
pub key_guid: xous_ipc::String::<256>,
|
||||
pub description: xous_ipc::String::<256>,
|
||||
pub mode: VaultMode,
|
||||
}
|
||||
|
|
@ -171,9 +171,7 @@ fn main() -> ! {
|
|||
Some(ActionOp::MenuEditStage2) => {
|
||||
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
|
||||
let entry = buffer.to_original::<SelectedEntry, _>().unwrap();
|
||||
log::debug!("bef activate");
|
||||
manager.activate();
|
||||
log::debug!("bef edit");
|
||||
manager.menu_edit(entry);
|
||||
manager.retrieve_db();
|
||||
manager.deactivate();
|
||||
|
|
|
|||
|
|
@ -267,21 +267,23 @@ impl VaultUx {
|
|||
self.get_glyph_style();
|
||||
}
|
||||
pub(crate) fn nav(&mut self, dir: NavDir) {
|
||||
self.item_lists.lock().unwrap().nav(dir);
|
||||
self.item_lists.lock().unwrap().nav((*self.mode.lock().unwrap()).clone(), dir);
|
||||
}
|
||||
/// accept a new input string
|
||||
pub(crate) fn input(&mut self, line: &str) -> Result<(), xous::Error> {
|
||||
self.title_dirty = true;
|
||||
self.filter(line);
|
||||
self.last_query = line.to_string();
|
||||
let owned_line = line.to_owned();
|
||||
self.filter(&owned_line);
|
||||
self.last_query = owned_line;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn clear_area(&mut self) {
|
||||
let items_height = self.items_per_screen * self.item_height;
|
||||
let mut insert_at = 1 + self.screensize.y - items_height; // +1 to get the border to overlap at the bottom
|
||||
let mode_cache = (*self.mode.lock().unwrap()).clone();
|
||||
|
||||
if self.item_lists.lock().unwrap().filter_len() == 0 || self.action_active.load(AtomicOrdering::SeqCst) {
|
||||
if self.item_lists.lock().unwrap().filter_len(mode_cache) == 0 || self.action_active.load(AtomicOrdering::SeqCst) {
|
||||
// no items in list case -- just blank the whole area
|
||||
self.gam.draw_rectangle(self.content,
|
||||
Rectangle::new_with_style(
|
||||
|
|
@ -295,7 +297,7 @@ impl VaultUx {
|
|||
)).expect("can't clear content area");
|
||||
self.title_dirty = true; // just blanked the whole area, have to redraw the title.
|
||||
return;
|
||||
} else if self.title_dirty && self.item_lists.lock().unwrap().filter_len() != 0 {
|
||||
} else if self.title_dirty && self.item_lists.lock().unwrap().filter_len(mode_cache) != 0 {
|
||||
// handle the title region separately
|
||||
self.gam.draw_rectangle(self.content,
|
||||
Rectangle::new_with_style(
|
||||
|
|
@ -313,40 +315,35 @@ impl VaultUx {
|
|||
let mut dirty_br: Option<Point> = None;
|
||||
|
||||
let mut guarded_list = self.item_lists.lock().unwrap();
|
||||
let current_page = guarded_list.selected_page();
|
||||
let current_page = guarded_list.selected_page(mode_cache);
|
||||
for item in current_page.iter() {
|
||||
if let Some(item_mutex) = item {
|
||||
let item = item_mutex.lock().unwrap();
|
||||
if item.dirty && dirty_tl.is_none() {
|
||||
// start the dirty area
|
||||
dirty_tl = Some(Point::new(0, insert_at));
|
||||
}
|
||||
if !item.dirty && dirty_tl.is_some() && dirty_br.is_none() {
|
||||
// end the dirty area
|
||||
dirty_br = Some(Point::new(self.screensize.y, insert_at));
|
||||
}
|
||||
if let Some(tl) = dirty_tl {
|
||||
if let Some(br) = dirty_br {
|
||||
// start & end found: now draw a rectangle over it
|
||||
self.gam.draw_rectangle(self.content,
|
||||
Rectangle::new_with_style(
|
||||
tl,
|
||||
br,
|
||||
DrawStyle {
|
||||
fill_color: Some(PixelColor::Light),
|
||||
stroke_color: None,
|
||||
stroke_width: 0
|
||||
}
|
||||
)).expect("can't clear content area");
|
||||
// reset the search
|
||||
dirty_tl = None;
|
||||
dirty_br = None;
|
||||
}
|
||||
}
|
||||
insert_at += self.item_height;
|
||||
} else {
|
||||
log::error!("Filtered list consistency error!")
|
||||
if item.dirty && dirty_tl.is_none() {
|
||||
// start the dirty area
|
||||
dirty_tl = Some(Point::new(0, insert_at));
|
||||
}
|
||||
if !item.dirty && dirty_tl.is_some() && dirty_br.is_none() {
|
||||
// end the dirty area
|
||||
dirty_br = Some(Point::new(self.screensize.y, insert_at));
|
||||
}
|
||||
if let Some(tl) = dirty_tl {
|
||||
if let Some(br) = dirty_br {
|
||||
// start & end found: now draw a rectangle over it
|
||||
self.gam.draw_rectangle(self.content,
|
||||
Rectangle::new_with_style(
|
||||
tl,
|
||||
br,
|
||||
DrawStyle {
|
||||
fill_color: Some(PixelColor::Light),
|
||||
stroke_color: None,
|
||||
stroke_width: 0
|
||||
}
|
||||
)).expect("can't clear content area");
|
||||
// reset the search
|
||||
dirty_tl = None;
|
||||
dirty_br = None;
|
||||
}
|
||||
}
|
||||
insert_at += self.item_height;
|
||||
}
|
||||
if let Some(tl) = dirty_tl {
|
||||
// handle the case that we were dirty all the way to the bottom
|
||||
|
|
@ -443,7 +440,7 @@ impl VaultUx {
|
|||
let items_height = self.items_per_screen * self.item_height;
|
||||
let mut insert_at = 1 + self.screensize.y - items_height; // +1 to get the border to overlap at the bottom
|
||||
|
||||
if self.item_lists.lock().unwrap().filter_len() == 0 {
|
||||
if self.item_lists.lock().unwrap().filter_len(mode_at_entry) == 0 {
|
||||
let mut box_text = TextView::new(self.content,
|
||||
graphics_server::TextBounds::CenteredBot(
|
||||
Rectangle::new(
|
||||
|
|
@ -461,82 +458,77 @@ impl VaultUx {
|
|||
return Ok(());
|
||||
}
|
||||
// ---- draw list body area ----
|
||||
let selected = self.item_lists.lock().unwrap().selected_index();
|
||||
let selected = self.item_lists.lock().unwrap().selected_index(mode_at_entry);
|
||||
let mut guarded_list = self.item_lists.lock().unwrap();
|
||||
let current_page = guarded_list.selected_page();
|
||||
let current_page = guarded_list.selected_page(mode_at_entry);
|
||||
log::debug!("current_page len {}", current_page.len());
|
||||
for (index, maybe_item) in current_page.iter_mut().enumerate() {
|
||||
for (index, item) in current_page.iter_mut().enumerate() {
|
||||
if insert_at - 1 > self.screensize.y - self.item_height { // -1 because of the overlapping border
|
||||
break;
|
||||
}
|
||||
if let Some(item_mutex) = maybe_item {
|
||||
let mut item = item_mutex.lock().unwrap();
|
||||
if item.dirty {
|
||||
log::debug!("drawing {}", item.name);
|
||||
let mut box_text = TextView::new(self.content,
|
||||
graphics_server::TextBounds::BoundingBox(
|
||||
Rectangle::new(
|
||||
Point::new(0, insert_at),
|
||||
Point::new(self.screensize.x, insert_at + self.item_height)
|
||||
)
|
||||
if item.dirty {
|
||||
log::debug!("drawing {}", item.name);
|
||||
let mut box_text = TextView::new(self.content,
|
||||
graphics_server::TextBounds::BoundingBox(
|
||||
Rectangle::new(
|
||||
Point::new(0, insert_at),
|
||||
Point::new(self.screensize.x, insert_at + self.item_height)
|
||||
)
|
||||
);
|
||||
box_text.draw_border = true;
|
||||
box_text.rounded_border = None;
|
||||
box_text.clear_area = true;
|
||||
box_text.style = self.style;
|
||||
box_text.margin = self.margin;
|
||||
if index == selected {
|
||||
box_text.border_width = 4;
|
||||
}
|
||||
match mode_at_entry {
|
||||
VaultMode::Fido | VaultMode::Password => {write!(box_text, "{}\n{}", item.name, item.extra).ok();},
|
||||
VaultMode::Totp => {
|
||||
let fields = item.extra.split(':').collect::<Vec<&str>>();
|
||||
if fields.len() == 5 {
|
||||
let shared_secret = base32::decode(
|
||||
base32::Alphabet::RFC4648 { padding: false }, fields[0])
|
||||
.unwrap_or(vec![]);
|
||||
let digit_count = u8::from_str_radix(fields[1], 10).unwrap_or(6);
|
||||
let step_seconds = u64::from_str_radix(fields[2], 10).unwrap_or(30);
|
||||
let algorithm = TotpAlgorithm::try_from(fields[3]).unwrap_or(TotpAlgorithm::HmacSha1);
|
||||
let is_hotp = fields[4].to_uppercase() == "HOTP";
|
||||
let totp = TotpEntry {
|
||||
step_seconds: if !is_hotp {step_seconds} else {1}, // step_seconds is re-used by hotp as the code.
|
||||
shared_secret,
|
||||
digit_count,
|
||||
algorithm
|
||||
};
|
||||
if !is_hotp {
|
||||
let code = generate_totp_code(
|
||||
get_current_unix_time().unwrap_or(0),
|
||||
&totp
|
||||
).unwrap_or(t!("vault.error.record_error", xous::LANG).to_string());
|
||||
// why code on top? because the item.name can be very long, and it can wrap which would cause
|
||||
// the code to become hidden.
|
||||
write!(box_text, "{}\n{}", code, item.name).ok();
|
||||
} else {
|
||||
let code = generate_totp_code(
|
||||
step_seconds,
|
||||
&totp
|
||||
).unwrap_or(t!("vault.error.record_error", xous::LANG).to_string());
|
||||
// why code on top? because the item.name can be very long, and it can wrap which would cause
|
||||
// the code to become hidden.
|
||||
write!(box_text, "HOTP {}\n{}", code, item.name).ok();
|
||||
}
|
||||
} else {
|
||||
write!(box_text, "{}", t!("vault.error.record_error", xous::LANG)).ok();
|
||||
}
|
||||
},
|
||||
}
|
||||
self.gam.post_textview(&mut box_text).expect("couldn't post list item");
|
||||
item.dirty = false;
|
||||
)
|
||||
);
|
||||
box_text.draw_border = true;
|
||||
box_text.rounded_border = None;
|
||||
box_text.clear_area = true;
|
||||
box_text.style = self.style;
|
||||
box_text.margin = self.margin;
|
||||
if index == selected {
|
||||
box_text.border_width = 4;
|
||||
}
|
||||
|
||||
insert_at += self.item_height;
|
||||
} else {
|
||||
log::error!("Consistency bug! Filtered list has invalid items");
|
||||
match mode_at_entry {
|
||||
VaultMode::Fido | VaultMode::Password => {write!(box_text, "{}\n{}", item.name, item.extra).ok();},
|
||||
VaultMode::Totp => {
|
||||
let fields = item.extra.split(':').collect::<Vec<&str>>();
|
||||
if fields.len() == 5 {
|
||||
let shared_secret = base32::decode(
|
||||
base32::Alphabet::RFC4648 { padding: false }, fields[0])
|
||||
.unwrap_or(vec![]);
|
||||
let digit_count = u8::from_str_radix(fields[1], 10).unwrap_or(6);
|
||||
let step_seconds = u64::from_str_radix(fields[2], 10).unwrap_or(30);
|
||||
let algorithm = TotpAlgorithm::try_from(fields[3]).unwrap_or(TotpAlgorithm::HmacSha1);
|
||||
let is_hotp = fields[4].to_uppercase() == "HOTP";
|
||||
let totp = TotpEntry {
|
||||
step_seconds: if !is_hotp {step_seconds} else {1}, // step_seconds is re-used by hotp as the code.
|
||||
shared_secret,
|
||||
digit_count,
|
||||
algorithm
|
||||
};
|
||||
if !is_hotp {
|
||||
let code = generate_totp_code(
|
||||
get_current_unix_time().unwrap_or(0),
|
||||
&totp
|
||||
).unwrap_or(t!("vault.error.record_error", xous::LANG).to_string());
|
||||
// why code on top? because the item.name can be very long, and it can wrap which would cause
|
||||
// the code to become hidden.
|
||||
write!(box_text, "{}\n{}", code, item.name).ok();
|
||||
} else {
|
||||
let code = generate_totp_code(
|
||||
step_seconds,
|
||||
&totp
|
||||
).unwrap_or(t!("vault.error.record_error", xous::LANG).to_string());
|
||||
// why code on top? because the item.name can be very long, and it can wrap which would cause
|
||||
// the code to become hidden.
|
||||
write!(box_text, "HOTP {}\n{}", code, item.name).ok();
|
||||
}
|
||||
} else {
|
||||
write!(box_text, "{}", t!("vault.error.record_error", xous::LANG)).ok();
|
||||
}
|
||||
},
|
||||
}
|
||||
self.gam.post_textview(&mut box_text).expect("couldn't post list item");
|
||||
item.dirty = false;
|
||||
}
|
||||
|
||||
insert_at += self.item_height;
|
||||
}
|
||||
|
||||
log::trace!("vault app redraw##");
|
||||
|
|
@ -553,7 +545,7 @@ impl VaultUx {
|
|||
self.title_dirty = true;
|
||||
}
|
||||
|
||||
pub(crate) fn filter(&mut self, criteria: &str) {
|
||||
pub(crate) fn filter(&mut self, criteria: &String) {
|
||||
self.item_lists.lock().unwrap()
|
||||
.filter(self.mode.lock().unwrap().clone(), criteria);
|
||||
}
|
||||
|
|
@ -565,7 +557,7 @@ impl VaultUx {
|
|||
let mode_cache = (*self.mode.lock().unwrap()).clone();
|
||||
match mode_cache {
|
||||
VaultMode::Password => {
|
||||
let entry = self.item_lists.lock().unwrap().selected_guid();
|
||||
let entry = self.item_lists.lock().unwrap().selected_guid(mode_cache);
|
||||
// we re-fetch the entry for autotype, because the PDDB could have unmounted a basis.
|
||||
let atime = utc_now().timestamp() as u64;
|
||||
let updated_pw = match self.pddb.borrow().get(
|
||||
|
|
@ -653,10 +645,10 @@ impl VaultUx {
|
|||
}
|
||||
self.pddb.borrow().sync().ok();
|
||||
// force a redraw of the record as the access count updated
|
||||
self.item_lists.lock().unwrap().selected_update_atime(atime);
|
||||
self.item_lists.lock().unwrap().selected_update_atime(mode_cache, atime);
|
||||
}
|
||||
VaultMode::Totp => {
|
||||
let extra = self.item_lists.lock().unwrap().selected_extra();
|
||||
let extra = self.item_lists.lock().unwrap().selected_extra(mode_cache);
|
||||
let fields = extra.split(':').collect::<Vec<&str>>();
|
||||
if fields.len() == 5 {
|
||||
let shared_secret = base32::decode(
|
||||
|
|
@ -687,7 +679,7 @@ impl VaultUx {
|
|||
Ok(_) => {
|
||||
if is_hotp {
|
||||
// update the count once the HOTP has been typed successfully
|
||||
let entry = self.item_lists.lock().unwrap().selected_guid();
|
||||
let entry = self.item_lists.lock().unwrap().selected_guid(mode_cache);
|
||||
|
||||
// this get determines which basis the key is in
|
||||
let (basis, hotp_rec) = match self.pddb.borrow().get(
|
||||
|
|
@ -731,6 +723,7 @@ impl VaultUx {
|
|||
}
|
||||
// update the "extra" field, because the timestep field has been altered
|
||||
self.item_lists.lock().unwrap().selected_update_extra(
|
||||
mode_cache,
|
||||
format!("{}:{}:{}:{}:{}",
|
||||
hotp_rec.secret,
|
||||
hotp_rec.digits,
|
||||
|
|
|
|||
Loading…
Reference in a new issue