add password deserialization framework and UX routines

This commit is contained in:
bunnie 2022-06-22 21:20:19 +08:00
parent 7e65f3db66
commit 9671ef65f5
6 changed files with 333 additions and 95 deletions

View file

@ -1,8 +1,8 @@
use std::thread;
use gam::TextEntryPayload;
use std::sync::{Arc, Mutex};
use std::sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}};
use num_traits::*;
use xous::{SID, msg_blocking_scalar_unpack};
use xous::{SID, msg_blocking_scalar_unpack, Message, send_message};
use locales::t;
use std::io::{Write, Read};
use passwords::PasswordGenerator;
@ -14,11 +14,14 @@ use crate::ux::ListItem;
use crate::VaultMode;
const VAULT_PASSWORD_DICT: &'static str = "vault.passwords";
/// bytes to reserve for a key entry. Making this slightly larger saves on some churn as stuff gets updated
const VAULT_ALLOC_HINT: usize = 256;
const VAULT_PASSWORD_REC_VERSION: u32 = 1;
/// time allowed between dialog box swaps for background operations to redraw
const SWAP_DELAY_MS: usize = 150;
const SWAP_DELAY_MS: usize = 300;
struct PasswordRecord {
version: u32,
description: String,
username: String,
password: String,
@ -34,33 +37,51 @@ pub(crate) enum ActionOp {
MenuAddnew,
MenuEdit,
MenuDelete,
MenuClose,
/// Internal ops
UpdateMode,
Quit,
}
pub(crate) fn start_actions_thread(sid: SID, mode: Arc::<Mutex::<VaultMode>>, item_list: Arc::<Mutex::<Vec::<ListItem>>>) {
pub(crate) fn start_actions_thread(
main_conn: xous::CID,
sid: SID, mode: Arc::<Mutex::<VaultMode>>,
item_list: Arc::<Mutex::<Vec::<ListItem>>>,
action_active: Arc::<AtomicBool>,
) {
let _ = thread::spawn({
move || {
let mut manager = ActionManager::new(mode, item_list);
let mut manager = ActionManager::new(main_conn, mode, item_list, action_active);
loop {
let msg = xous::receive_message(sid).unwrap();
log::trace!("got message {:?}", msg);
match FromPrimitive::from_usize(msg.body.id()) {
let opcode: Option<ActionOp> = FromPrimitive::from_usize(msg.body.id());
log::debug!("{:?}", opcode);
match opcode {
Some(ActionOp::MenuAddnew) => {
manager.activate();
manager.menu_addnew();
manager.deactivate();
},
Some(ActionOp::MenuAutotype) => {
manager.activate();
manager.deactivate();
},
Some(ActionOp::MenuDelete) => {
manager.activate();
manager.deactivate();
},
Some(ActionOp::MenuEdit) => {
manager.activate();
manager.deactivate();
},
Some(ActionOp::MenuClose) => {
// dummy activate/de-activate cycle because we have to trigger a redraw of the underlying UX
manager.activate();
manager.deactivate();
},
Some(ActionOp::UpdateMode) => msg_blocking_scalar_unpack!(msg, _, _, _, _,{
manager.gen_fake_data();
manager.retrieve_db();
xous::return_scalar(msg.sender, 1).unwrap();
}),
Some(ActionOp::Quit) => {
@ -83,21 +104,53 @@ struct ActionManager {
item_list: Arc::<Mutex::<Vec::<ListItem>>>,
pddb: RefCell::<pddb::Pddb>,
tt: ticktimer_server::Ticktimer,
action_active: Arc::<AtomicBool>,
mode_cache: VaultMode,
main_conn: xous::CID,
}
impl ActionManager {
pub fn new(mode: Arc::<Mutex::<VaultMode>>, item_list: Arc::<Mutex::<Vec::<ListItem>>>) -> ActionManager {
pub fn new(
main_conn: xous::CID,
mode: Arc::<Mutex::<VaultMode>>,
item_list: Arc::<Mutex::<Vec::<ListItem>>>,
action_active: Arc::<AtomicBool>
) -> ActionManager {
let xns = xous_names::XousNames::new().unwrap();
let mc = (*mode.lock().unwrap()).clone();
ActionManager {
modals: modals::Modals::new(&xns).unwrap(),
trng: RefCell::new(trng::Trng::new(&xns).unwrap()),
mode_cache: mc,
mode,
item_list,
pddb: RefCell::new(pddb::Pddb::new()),
tt: ticktimer_server::Ticktimer::new().unwrap(),
action_active,
main_conn,
}
}
pub(crate) fn activate(&mut self) {
// there's a "two phase" lock -- we indicate we're "active" with this here AtomicBool
// the drawing thread promises not to change the mode of the UI when this is true
// in return, we get to grab a copy of the operating mode variable, which allows the
// drawing thread to proceed as it relies also on reading this shared state to draw its UI.
self.mode_cache = {
(*self.mode.lock().unwrap()).clone()
};
self.action_active.store(true, Ordering::SeqCst);
self.tt.sleep_ms(SWAP_DELAY_MS).unwrap(); // allow calling menu to close
}
pub(crate) fn deactivate(&self) {
self.action_active.store(false, Ordering::SeqCst);
send_message(self.main_conn,
Message::new_scalar(
crate::VaultOp::FullRedraw.to_usize().unwrap(),
0, 0, 0, 0
)
).ok();
}
pub(crate) fn menu_addnew(&mut self) {
match *self.mode.lock().unwrap() {
match self.mode_cache {
VaultMode::Password => {
let description = match self.modals
.alert_builder(t!("vault.newitem.name", xous::LANG))
@ -107,7 +160,7 @@ impl ActionManager {
Ok(text) => {
text.content()[0].content.as_str().unwrap_or("UTF-8 error").to_string()
},
_ => {log::error!("Name entry failed"); return}
_ => {log::error!("Name entry failed"); self.action_active.store(false, Ordering::SeqCst); return}
};
self.tt.sleep_ms(SWAP_DELAY_MS).unwrap();
let username = match self.modals
@ -116,10 +169,45 @@ impl ActionManager {
.build()
{
Ok(text) => text.content()[0].content.as_str().unwrap_or("UTF-8 error").to_string(),
_ => {log::error!("Name entry failed"); return}
_ => {log::error!("Name entry failed"); self.action_active.store(false, Ordering::SeqCst); return}
};
self.tt.sleep_ms(SWAP_DELAY_MS).unwrap();
let mut approved = false;
// Security note about PasswordGenerator. This is a 3rd party crate. It relies on `rand`'s implementation
// of ThreadRng to generate passwords. As of the version committed to the lockfile, I have evidenced the
// ThreadRng to request 8 bytes of entropy from our TRNG to seed its state. If the docs are to be trusted,
// its thread-local RNG is a ChaCha CSPRNG, although the number of rounds used in it is not clear; code says
// 12 rounds, code comments say 20 and reference an issue about how this should be reduced.
// Audit path
// Cargo.lock is at:
// rand-0.8.5
// rand_core 0.6.3
// getrandom 0.2.6 -> xous fork via Patch in top level Cargo.toml to map crates-io.getrandom to imports/getrandom
// rand_chacha 0.3.1
// passwords 3.1.9
// random-pick 1.2.15
// random-number 0.1.7
// random-number-macro-mipl 0.1.6
// proc-macro-hack : 0.5.19...and more (syn/quote also pulled in)
// - PasswordGenerator
// - PasswordGeneratorIter::generate()
// - random_pick::pick_multiple_from_multiple_slices()
// - random_pick::gen_multiple_usize_with_weights()
// - rng = random_number::rand::thread_rng()
// - ThreadRng::thread_rng()
// - Some crazy unsafe refcell construction that returns a clone of a
// ReseedingRng<Core, OsRng>
// - rand-0.8.5::std line 13: pub(crate) use rand_chacha::ChaCha12Core as Core;
// - confirm no feature flags gating this, it is always used
// - OsRng::try_fill_bytes()
// - getrandom() -> to Xous code
// - getrandom Xous fork - imp::getrandom_inner()
// - getrandom Xous fork - ensure_trng_conn() then fill_bytes() native Xous call
// - random_number::random!(0..high, rng)
// - random_number::random_with_rng
// - random_number::random_inclusively_with_rng()
// - Uniform::new_inclusive().sample()
// - dead end at Distribution Trait and UniformSampler Trait, let's hope this is correct?
let pg = PasswordGenerator {
length: 20,
numbers: true,
@ -140,7 +228,7 @@ impl ActionManager {
Ok(text) => {
text.content()[0].content.as_str().unwrap().to_string()
},
_ => {log::error!("Name entry failed"); return}
_ => {log::error!("Name entry failed"); self.action_active.store(false, Ordering::SeqCst); return}
};
self.tt.sleep_ms(SWAP_DELAY_MS).unwrap();
password = if maybe_password.len() == 0 {
@ -150,7 +238,7 @@ impl ActionManager {
.build()
{
Ok(entry) => entry.content()[0].content.as_str().unwrap().parse::<u32>().unwrap(),
_ => {log::error!("Length entry failed"); return}
_ => {log::error!("Length entry failed"); self.action_active.store(false, Ordering::SeqCst); return}
};
self.tt.sleep_ms(SWAP_DELAY_MS).unwrap();
let mut upper = false;
@ -170,7 +258,7 @@ impl ActionManager {
if opt == t!("vault.newitem.symbols", xous::LANG) {symbol = true;}
}
}
_ => {log::error!("Modal selection error"); return}
_ => {log::error!("Modal selection error"); self.action_active.store(false, Ordering::SeqCst); return}
}
self.tt.sleep_ms(SWAP_DELAY_MS).unwrap();
let pg2 = PasswordGenerator {
@ -191,6 +279,7 @@ impl ActionManager {
};
}
let record = PasswordRecord {
version: VAULT_PASSWORD_REC_VERSION,
description,
username,
password,
@ -205,7 +294,7 @@ impl ActionManager {
VAULT_PASSWORD_DICT,
&guid,
None, true, true,
Some(256), Some(crate::basis_change)
Some(VAULT_ALLOC_HINT), Some(crate::basis_change)
) {
Ok(mut data) => {
data.write(&ser).expect("couldn't store password record");
@ -244,11 +333,59 @@ impl ActionManager {
}
// populates the display list with testing data
pub(crate) fn gen_fake_data(&mut self) {
pub(crate) fn retrieve_db(&mut self) {
self.mode_cache = {
(*self.mode.lock().unwrap()).clone()
};
let il = &mut *self.item_list.lock().unwrap();
il.clear();
match *self.mode.lock().unwrap() {
VaultMode::Fido | VaultMode::Password => {
match self.mode_cache {
VaultMode::Password => {
let keylist = match self.pddb.borrow().list_keys(VAULT_PASSWORD_DICT, None) {
Ok(keylist) => keylist,
Err(e) => {
log::error!("error accessing password database: {:?}", e);
Vec::new()
}
};
for key in keylist {
match self.pddb.borrow().get(
VAULT_PASSWORD_DICT,
&key,
None,
false, false, None,
Some(crate::basis_change)
) {
Ok(mut record) => {
let mut data = Vec::<u8>::new();
match record.read_to_end(&mut data) {
Ok(_len) => {
if let Some(pw) = deserialize_password(data) {
let extra = format!("{}; {}{}",
crate::ux::atime_to_str(pw.atime),
t!("vault.u2f.appinfo.authcount", xous::LANG),
pw.count,
);
let desc = format!("{} @ {}", pw.username, pw.description);
let li = ListItem {
name: desc,
extra,
dirty: true,
guid: key,
};
il.push(li);
} else {
log::error!("couldn't deserialize {}", key);
}
}
Err(e) => log::error!("couldn't access key {}: {:?}", key, e),
}
}
Err(e) => log::error!("couldn't access key {}: {:?}", key, e),
}
}
}
VaultMode::Fido => {
il.push(ListItem { name: "test.com".to_string(), extra: "Used 5 mins ago".to_string(), dirty: true, guid: self.gen_guid() });
il.push(ListItem { name: "google.com".to_string(), extra: "Never used".to_string(), dirty: true, guid: self.gen_guid() });
il.push(ListItem { name: "my app".to_string(), extra: "Used 2 hours ago".to_string(), dirty: true, guid: self.gen_guid() });
@ -304,7 +441,7 @@ fn length_validator(input: TextEntryPayload) -> Option<xous_ipc::String<256>> {
fn serialize_password<'a>(record: &PasswordRecord) -> Vec::<u8> {
format!("{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}\n{}:{}",
"version", VAULT_PASSWORD_REC_VERSION,
"version", record.version,
"description", record.description,
"username", record.username,
"password", record.password,
@ -315,7 +452,63 @@ fn serialize_password<'a>(record: &PasswordRecord) -> Vec::<u8> {
}
fn deserialize_password(data: Vec::<u8>) -> Option<PasswordRecord> {
None
if let Ok(desc_str) = String::from_utf8(data) {
let mut pr = PasswordRecord {
version: 0,
description: String::new(),
username: String::new(),
password: String::new(),
ctime: 0,
atime: 0,
count: 0
};
let lines = desc_str.split('\n');
for line in lines {
if let Some((tag, data)) = line.split_once(':') {
log::info!("tag: {}, data: {}", tag, data);
match tag {
"version" => {
if let Ok(ver) = u32::from_str_radix(data, 10) {
pr.version = ver
} else {
return None;
}
}
"description" => pr.description.push_str(data),
"username" => pr.username.push_str(data),
"password" => pr.password.push_str(data),
"ctime" => {
if let Ok(ctime) = u64::from_str_radix(data, 10) {
pr.ctime = ctime;
} else {
return None;
}
}
"atime" => {
if let Ok(atime) = u64::from_str_radix(data, 10) {
pr.atime = atime;
} else {
return None;
}
}
"count" => {
if let Ok(count) = u64::from_str_radix(data, 10) {
pr.count = count;
} else {
return None;
}
}
_ => {
log::warn!("unexpected tag {} encountered parsing app info, aborting", tag);
return None;
}
}
}
}
Some(pr)
} else {
None
}
}
/// because we don't get Utc::now, as the crate checks your architecture and xous is not recognized as a valid target

View file

@ -8,7 +8,7 @@ use xous_ipc::Buffer;
use xous::{send_message, Message};
use usbd_human_interface_device::device::fido::*;
use std::thread;
use core::sync::atomic::{AtomicU32, Ordering};
use core::sync::atomic::{AtomicU32, AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
mod ctap;
@ -81,6 +81,8 @@ pub(crate) enum VaultOp {
IncrementalLine,
/// redraw our UI
Redraw,
/// ignore dirty rectangles and redraw everything
FullRedraw,
/// change focus
ChangeFocus,
@ -94,6 +96,7 @@ pub(crate) enum VaultOp {
Quit,
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum VaultMode {
Fido,
Totp,
@ -114,12 +117,15 @@ fn main() -> ! {
// global shared state between threads.
let mode = Arc::new(Mutex::new(VaultMode::Fido));
let item_list = Arc::new(Mutex::new(Vec::<ListItem>::new()));
let action_active = Arc::new(AtomicBool::new(false));
// spawn the actions server. This is responsible for grooming the UX elements. It
// has to be in its own thread because it uses blocking modal calls that would cause
// redraws of the background list to block/fail.
let actions_sid = xous::create_server().unwrap();
start_actions_thread(actions_sid, mode.clone(), item_list.clone());
let conn = xous::connect(sid).unwrap();
SELF_CONN.store(conn, Ordering::SeqCst);
start_actions_thread(conn, actions_sid, mode.clone(), item_list.clone(), action_active.clone());
let actions_conn = xous::connect(actions_sid).unwrap();
// spawn the FIDO2 USB handler
@ -173,8 +179,6 @@ fn main() -> ! {
}
});
let conn = xous::connect(sid).unwrap();
SELF_CONN.store(conn, Ordering::SeqCst);
// spawn the icontray handler
let _ = thread::spawn({
move || {
@ -187,7 +191,7 @@ fn main() -> ! {
let xns = xous_names::XousNames::new().unwrap();
// TODO: add a UX loop that indicates we're waiting for a PDDB mount before moving forward
let mut vaultux = VaultUx::new(&xns, sid, menu_mgr, actions_conn, mode.clone(), item_list);
let mut vaultux = VaultUx::new(&xns, sid, menu_mgr, actions_conn, mode.clone(), item_list, action_active.clone());
// Trigger the mode update in the actions
send_message(actions_conn,
Message::new_blocking_scalar(ActionOp::UpdateMode.to_usize().unwrap(), 0, 0, 0, 0)
@ -198,18 +202,33 @@ fn main() -> ! {
let modals = modals::Modals::new(&xns).unwrap();
loop {
let msg = xous::receive_message(sid).unwrap();
log::info!("got message {:?}", msg);
match FromPrimitive::from_usize(msg.body.id()) {
let opcode: Option<VaultOp> = FromPrimitive::from_usize(msg.body.id());
log::debug!("{:?}", opcode);
match opcode {
Some(VaultOp::IncrementalLine) => {
if action_active.load(Ordering::SeqCst) {
log::trace!("action active, skipping incremental input");
send_message(conn,
Message::new_scalar(VaultOp::Redraw.to_usize().unwrap(), 0, 0, 0, 0)
).ok();
continue;
}
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let s = buffer.as_flat::<xous_ipc::String<4000>, _>().unwrap();
log::info!("Incremental input: {}", s.as_str());
log::debug!("Incremental input: {}", s.as_str());
vaultux.input(s.as_str()).expect("Vault couldn't accept input string");
send_message(conn,
Message::new_scalar(VaultOp::Redraw.to_usize().unwrap(), 0, 0, 0, 0)
).ok();
}
Some(VaultOp::Line) => {
if action_active.load(Ordering::SeqCst) {
log::trace!("action active, skipping line input");
send_message(conn,
Message::new_scalar(VaultOp::Redraw.to_usize().unwrap(), 0, 0, 0, 0)
).ok();
continue;
}
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let s = buffer.as_flat::<xous_ipc::String<4000>, _>().unwrap();
log::debug!("vaultux got input line: {}", s.as_str());
@ -264,6 +283,12 @@ fn main() -> ! {
vaultux.redraw().expect("Vault couldn't redraw");
}
}
Some(VaultOp::FullRedraw) => {
vaultux.update_mode();
if allow_redraw {
vaultux.redraw().expect("Vault couldn't redraw");
}
}
Some(VaultOp::BasisChange) => {
// this set of calls will effectively force a reload of any UX data
*mode.lock().unwrap() = VaultMode::Fido;
@ -301,6 +326,7 @@ fn main() -> ! {
},
_ => log::error!("get_radiobutton failed"),
}
vaultux.update_mode();
}
Some(VaultOp::Quit) => {
log::error!("got Quit");

View file

@ -31,8 +31,8 @@ pub fn create_submenu(vault_conn: xous::CID, actions_conn: xous::CID, menu_mgr:
});
menu_items.push(MenuItem {
name: xous_ipc::String::from_str(t!("vault.menu_close", xous::LANG)),
action_conn: None,
action_opcode: 0,
action_conn: Some(actions_conn),
action_opcode: ActionOp::MenuClose.to_u32().unwrap(),
action_payload: MenuPayload::Scalar([0, 0, 0, 0]),
close_on_select: true,
});

View file

@ -3,4 +3,58 @@ pub(crate) use fido::*;
pub(crate) mod framework;
pub(crate) use framework::*;
pub(crate) mod icontray;
pub(crate) use icontray::*;
pub(crate) use icontray::*;
use locales::t;
use chrono::{Utc, DateTime, NaiveDateTime};
use std::time::{SystemTime, UNIX_EPOCH};
pub(crate) fn atime_to_str(req_atime: u64) -> String {
let mut request_str = String::new();
if req_atime == 0 {
request_str.push_str(&format!("{}{}",
t!("vault.u2f.appinfo.last_authtime", xous::LANG),
t!("vault.u2f.appinfo.never", xous::LANG)
));
} else {
let now = utc_now();
let atime = DateTime::<Utc>::from_utc(
NaiveDateTime::from_timestamp(req_atime as i64, 0),
Utc
);
if now.signed_duration_since(atime).num_days() > 1 {
request_str.push_str(&format!("{}{}{}",
t!("vault.u2f.appinfo.last_authtime", xous::LANG),
now.signed_duration_since(atime).num_days(),
t!("vault.u2f.appinfo.days_ago", xous::LANG),
));
} else if now.signed_duration_since(atime).num_hours() > 1 {
request_str.push_str(&format!("{}{}{}",
t!("vault.u2f.appinfo.last_authtime", xous::LANG),
now.signed_duration_since(atime).num_hours(),
t!("vault.u2f.appinfo.hours_ago", xous::LANG),
));
} else if now.signed_duration_since(atime).num_minutes() > 1 {
request_str.push_str(&format!("{}{}{}",
t!("vault.u2f.appinfo.last_authtime", xous::LANG),
now.signed_duration_since(atime).num_minutes(),
t!("vault.u2f.appinfo.minutes_ago", xous::LANG),
));
} else {
request_str.push_str(&format!("{}{}{}",
t!("vault.u2f.appinfo.last_authtime", xous::LANG),
now.signed_duration_since(atime).num_seconds(),
t!("vault.u2f.appinfo.seconds_ago", xous::LANG),
));
}
}
request_str
}
/// because we don't get Utc::now, as the crate checks your architecture and xous is not recognized as a valid target
pub(crate) fn utc_now() -> DateTime::<Utc> {
let now =
SystemTime::now().duration_since(UNIX_EPOCH).expect("system time before Unix epoch");
let naive = NaiveDateTime::from_timestamp(now.as_secs() as i64, now.subsec_nanos() as u32);
DateTime::from_utc(naive, Utc)
}

View file

@ -7,8 +7,7 @@ use locales::t;
use crate::ctap::hid::{CtapHid, KeepaliveStatus};
use usbd_human_interface_device::device::fido::RawFidoMsg;
use std::io::{Write, Read};
use chrono::{Utc, DateTime, NaiveDateTime};
use std::time::{SystemTime, UNIX_EPOCH};
use crate::ux::utc_now;
// conceptual note: this UX conflates both the U2F and the FIDO2 paths.
// - U2F is a polled implementation, where the state goes from Idle->Prompt->Present
@ -279,43 +278,9 @@ pub(crate) fn start_fido_ux_thread() {
request_str.push_str(&format!("\n{}{}",
t!("vault.u2f.appinfo.name", xous::LANG), info.name
));
if info.atime == 0 {
request_str.push_str(&format!("\n{}{}",
t!("vault.u2f.appinfo.last_authtime", xous::LANG),
t!("vault.u2f.appinfo.never", xous::LANG)
));
} else {
let now = utc_now();
let atime = DateTime::<Utc>::from_utc(
NaiveDateTime::from_timestamp(info.atime as i64, 0),
Utc
);
if now.signed_duration_since(atime).num_days() > 1 {
request_str.push_str(&format!("\n{}{}{}",
t!("vault.u2f.appinfo.last_authtime", xous::LANG),
now.signed_duration_since(atime).num_days(),
t!("vault.u2f.appinfo.days_ago", xous::LANG),
));
} else if now.signed_duration_since(atime).num_hours() > 1 {
request_str.push_str(&format!("\n{}{}{}",
t!("vault.u2f.appinfo.last_authtime", xous::LANG),
now.signed_duration_since(atime).num_hours(),
t!("vault.u2f.appinfo.hours_ago", xous::LANG),
));
} else if now.signed_duration_since(atime).num_minutes() > 1 {
request_str.push_str(&format!("\n{}{}{}",
t!("vault.u2f.appinfo.last_authtime", xous::LANG),
now.signed_duration_since(atime).num_minutes(),
t!("vault.u2f.appinfo.minutes_ago", xous::LANG),
));
} else {
request_str.push_str(&format!("\n{}{}{}",
t!("vault.u2f.appinfo.last_authtime", xous::LANG),
now.signed_duration_since(atime).num_seconds(),
t!("vault.u2f.appinfo.seconds_ago", xous::LANG),
));
}
}
request_str.push_str(&format!("\n{}",
crate::ux::atime_to_str(info.atime)
));
request_str.push_str(&format!("\n{}{}",
t!("vault.u2f.appinfo.authcount", xous::LANG),
info.count,
@ -607,11 +572,3 @@ fn serialize_app_info<'a>(appinfo: &AppInfo) -> Vec::<u8> {
"count", appinfo.count,
).into_bytes()
}
/// because we don't get Utc::now, as the crate checks your architecture and xous is not recognized as a valid target
fn utc_now() -> DateTime::<Utc> {
let now =
SystemTime::now().duration_since(UNIX_EPOCH).expect("system time before Unix epoch");
let naive = NaiveDateTime::from_timestamp(now.as_secs() as i64, now.subsec_nanos() as u32);
DateTime::from_utc(naive, Utc)
}

View file

@ -7,6 +7,7 @@ use std::cell::RefCell;
use std::cmp::Ordering;
use std::io::{Read, Write as FsWrite};
use actions::ActionOp;
use std::sync::atomic::Ordering as AtomicOrdering;
/// 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.
@ -61,6 +62,7 @@ pub(crate) struct VaultUx {
/// current operation mode
mode: Arc::<Mutex::<VaultMode>>,
title_dirty: bool,
action_active: Arc::<AtomicBool>,
/// list of all items to be displayed
item_list: Arc::<Mutex::<Vec::<ListItem>>>,
@ -123,6 +125,7 @@ impl VaultUx {
actions_conn: xous::CID,
mode: Arc::<Mutex::<VaultMode>>,
item_list: Arc::<Mutex::<Vec::<ListItem>>>,
action_active: Arc::<AtomicBool>,
) -> Self {
let gam = gam::Gam::new(xns).expect("can't connect to GAM");
@ -201,6 +204,7 @@ impl VaultUx {
menu_mgr,
main_conn: xous::connect(sid).unwrap(),
actions_conn,
action_active,
}
}
pub(crate) fn update_mode(&mut self) {
@ -356,19 +360,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
// handle the title region separately
if self.title_dirty && self.filtered_list.len() != 0 {
self.gam.draw_rectangle(self.content,
Rectangle::new_with_style(
Point::new(0, 0),
Point::new(self.screensize.x, insert_at - 1),
DrawStyle {
fill_color: Some(PixelColor::Light),
stroke_color: None,
stroke_width: 0
}
)).expect("can't clear content area");
} else if self.filtered_list.len() == 0 {
if self.filtered_list.len() == 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(
@ -381,6 +373,18 @@ impl VaultUx {
}
)).expect("can't clear content area");
return;
} else if self.title_dirty && self.filtered_list.len() != 0 {
// handle the title region separately
self.gam.draw_rectangle(self.content,
Rectangle::new_with_style(
Point::new(0, 0),
Point::new(self.screensize.x, insert_at - 1),
DrawStyle {
fill_color: Some(PixelColor::Light),
stroke_color: None,
stroke_width: 0
}
)).expect("can't clear content area");
}
// iterate through every item to figure out the extent of the "dirty" area
let mut dirty_tl: Option<Point> = None;
@ -452,7 +456,7 @@ impl VaultUx {
pub(crate) fn redraw(&mut self) -> Result<(), xous::Error> {
self.clear_area();
// ---- draw title area ----
if self.title_dirty {
if self.title_dirty || self.action_active.load(AtomicOrdering::SeqCst) {
let mut title_text = TextView::new(self.content,
graphics_server::TextBounds::CenteredTop(
Rectangle::new(
@ -472,6 +476,10 @@ impl VaultUx {
self.gam.post_textview(&mut title_text).expect("couldn't post title");
self.title_dirty = false;
}
if self.action_active.load(AtomicOrdering::SeqCst) {
// don't redraw the list in the back when menus are active above
return Ok(())
}
// line up the list to justify to the bottom of the screen, based on the actual font requested
let items_height = self.items_per_screen * self.item_height;