use clap::Parser;
use crossterm::{
event::{
self, DisableMouseCapture, EnableMouseCapture, KeyCode, KeyModifiers, MouseButton,
MouseEvent, MouseEventKind,
},
execute,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::layout::Rect;
use ratatui::{backend::CrosstermBackend, Terminal};
use std::fs::OpenOptions;
use std::io::{self, Write};
use std::path::PathBuf;
use std::sync::Once;
use tokio::sync::mpsc;
use tracing::{debug, error, info};
use tracing_subscriber::EnvFilter;
use memtui::action::Action;
use memtui::actions::{async_handlers, sync_handlers};
use memtui::app::{sync_event_context, AppState, EventRunner};
use memtui::cli::{parse_connection_string, Cli, LogLevel};
use memtui::config::Config;
use memtui::events::{Event, EventKind};
use memtui::keybindings::{BindingContext, KeybindingsConfig};
use memtui::types::ConnectionConfig;
use memtui::ui::{self, init_theme, Panel, UiState};
use memtui::userdata;
pub struct App {
pub app_state: AppState,
pub ui_state: UiState,
pub action_tx: mpsc::UnboundedSender<Action>,
pub action_rx: mpsc::UnboundedReceiver<Action>,
pub config: Config,
pub keybindings: KeybindingsConfig,
needs_render: bool,
temp_connection_id: Option<String>,
auto_connect_name: Option<String>,
}
impl App {
pub fn new(cli: &Cli) -> Self {
let (tx, rx) = mpsc::unbounded_channel();
let config = if let Some(ref config_path) = cli.config {
userdata::load_config_from_path(config_path)
} else {
userdata::load_config()
};
let keybindings = userdata::load_keybindings();
let mut app_state = AppState::new_with_config(&config);
let mut ui_state = UiState::new();
if let Ok(connections) = userdata::load_connections() {
app_state.connection_manager.load_configs(connections);
}
if let Ok(recents) = userdata::load_recent_connection_ids() {
ui_state.recent_connection_ids = recents;
}
let mut temp_connection_id = None;
let mut auto_connect_name = None;
if let Some(ref conn_str) = cli.connection_string {
match parse_connection_string(conn_str) {
Ok(parsed) => {
let temp_config = parsed.to_config(config.connection.default_timeout);
temp_connection_id = Some(temp_config.id.clone());
ui_state.show_temp_connection_warning = true;
app_state
.connection_manager
.add_connection(temp_config.clone());
auto_connect_name = Some(temp_config.id.clone());
}
Err(e) => {
eprintln!("Error parsing connection string: {}", e);
std::process::exit(1);
}
}
}
if let Some(ref name) = cli.connect {
let configs = app_state.connection_manager.get_configs();
if let Some(cfg) = configs.iter().find(|c| c.name == *name) {
auto_connect_name = Some(cfg.id.clone());
} else {
eprintln!("Connection not found: {}", name);
eprintln!("Available connections:");
for cfg in configs {
eprintln!(" - {}", cfg.name);
}
std::process::exit(1);
}
}
let configs = app_state.connection_manager.get_configs();
if !configs.is_empty() {
ui_state.connection_list.state.select(Some(0));
}
Self {
app_state,
ui_state,
action_tx: tx,
action_rx: rx,
config,
keybindings,
needs_render: true, temp_connection_id,
auto_connect_name,
}
}
pub fn take_auto_connect(&mut self) -> Option<String> {
self.auto_connect_name.take()
}
pub fn is_temp_connection(&self, id: &str) -> bool {
self.temp_connection_id.as_deref() == Some(id)
}
pub async fn run(
&mut self,
terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
) -> io::Result<()> {
let tick_interval = self.config.performance.tick_interval;
info!(
tick_interval=?tick_interval,
"Starting app event loop with EventRunner"
);
let mut interval = tokio::time::interval(tick_interval);
let mut event_runner = EventRunner::new(self.action_tx.clone(), &self.config);
loop {
if self.needs_render {
terminal.draw(|f| {
ui::render(
f,
&mut self.app_state,
&mut self.ui_state,
&self.keybindings,
);
})?;
self.needs_render = false;
event_runner.update_context(|ctx| {
sync_event_context(ctx, &self.ui_state, &self.app_state);
});
}
let action = tokio::select! {
biased;
Some(action) = self.action_rx.recv() => action,
Some(event) = event_runner.poll() => {
let actions = self.dispatch_event(&event);
for action in actions {
if matches!(action, Action::ConfirmQuit) {
info!("Quit confirmed from event dispatch, cancelling event runner");
event_runner.cancel();
return Ok(());
}
self.update(action).await;
}
self.needs_render = true;
continue;
},
_ = interval.tick() => Action::Tick,
};
if let Action::ConfirmQuit = action {
let mut drained = 0;
while let Ok(pending) = self.action_rx.try_recv() {
drained += 1;
if !matches!(pending, Action::ConfirmQuit | Action::Tick) {
debug!("Draining pending action during quit");
}
}
if drained > 0 {
debug!(drained, "Drained pending actions before quit");
}
info!("Quit confirmed, cancelling event runner");
event_runner.cancel();
break;
}
self.update(action).await;
}
info!("Event loop finished");
Ok(())
}
fn dispatch_event(&mut self, event: &Event) -> Vec<Action> {
use memtui::ui::components::Component;
match &event.kind {
EventKind::Mouse(mouse) => {
return self.dispatch_mouse_event(*mouse);
}
EventKind::Scroll { column, row, delta } => {
return self.dispatch_scroll_event(*column, *row, *delta);
}
EventKind::Resize(w, h) => {
return vec![Action::Resize(*w, *h)];
}
EventKind::Tick => {
return vec![Action::Tick];
}
EventKind::Key(_) => {} }
let EventKind::Key(key) = &event.kind else {
return vec![];
};
if self.ui_state.show_connection_form {
return self.dispatch_connection_form_key(*key);
}
if self.ui_state.show_help {
return vec![Action::ToggleHelp];
}
if self.ui_state.show_quit_confirmation {
return self.dispatch_quit_confirmation_key(*key);
}
if self.ui_state.show_connection_palette {
return self.dispatch_connection_palette_key(*key);
}
if self.app_state.connection_manager.get_active_id().is_none() {
let configs = self.app_state.connection_manager.get_configs();
let recent_configs: Vec<_> = self
.ui_state
.recent_connection_ids
.iter()
.filter_map(|id| configs.iter().find(|c| c.id == *id).copied())
.collect();
let props = memtui::ui::components::welcome::WelcomeScreenProps {
recent_configs,
animation: &self.ui_state.animation,
keybindings: &self.keybindings,
};
let actions = self.ui_state.welcome_screen.handle_event(event, props);
if !actions.is_empty() {
return actions;
}
return self.dispatch_keybinding(*key, BindingContext::Welcome);
}
if self.app_state.is_searching || !self.app_state.search_query.is_empty() {
return self.dispatch_search_key(*key);
}
match self.ui_state.active_panel {
Panel::Keys => {
let backend_type = self
.app_state
.connection_manager
.get_active_id()
.and_then(|id| self.app_state.connection_manager.get_config(id))
.map(|config| config.backend_type);
let active_search_query =
if self.app_state.is_searching || !self.app_state.search_query.is_empty() {
Some(self.app_state.search_query.as_str())
} else {
None
};
let props = memtui::ui::components::key_list::KeyListProps {
keys: &self.app_state.keys,
total_count: self.app_state.total_key_count,
is_loading: self.app_state.is_loading_keys,
active_search_query,
is_active: true,
backend_type,
is_searching: self.app_state.is_searching,
search_results_local: &self.app_state.search_results_local,
search_results_server: &self.app_state.search_results_server,
is_server_searching: self.app_state.is_server_searching,
search_selection_index: self.app_state.search_selection_index,
animation: &self.ui_state.animation,
search_match_positions: &self.app_state.search_match_positions,
};
let actions = self.ui_state.key_list.handle_event(event, props);
if !actions.is_empty() {
return actions;
}
}
Panel::Value => {
if let KeyCode::Down | KeyCode::Up | KeyCode::Char('j') | KeyCode::Char('k') = key.code {
return self.dispatch_value_viewer_key(*key);
}
}
}
self.dispatch_keybinding(*key, BindingContext::Default)
}
fn dispatch_connection_form_key(&mut self, key: event::KeyEvent) -> Vec<Action> {
self.ui_state.connection_form.handle_key_event(key);
self.dispatch_keybinding(key, BindingContext::ConnectionForm)
}
fn dispatch_quit_confirmation_key(&mut self, key: event::KeyEvent) -> Vec<Action> {
self.dispatch_keybinding(key, BindingContext::QuitConfirmation)
}
fn dispatch_connection_palette_key(&mut self, key: event::KeyEvent) -> Vec<Action> {
match key.code {
KeyCode::Down | KeyCode::Char('j') => {
let len = self.app_state.connection_manager.get_configs().len();
if len > 0 {
self.ui_state.connection_list.next(len);
}
return vec![Action::Tick]; }
KeyCode::Up | KeyCode::Char('k') => {
let len = self.app_state.connection_manager.get_configs().len();
if len > 0 {
self.ui_state.connection_list.prev(len);
}
return vec![Action::Tick]; }
KeyCode::Enter => {
if let Some(idx) = self.ui_state.connection_list.state.selected() {
let configs = self.app_state.connection_manager.get_configs();
if let Some(config) = configs.get(idx) {
let id = config.id.clone();
self.ui_state.close_connection_palette();
return vec![Action::FocusConnection(id)];
}
}
return vec![];
}
_ => {}
}
self.dispatch_keybinding(key, BindingContext::ConnectionPalette)
}
fn dispatch_search_key(&mut self, key: event::KeyEvent) -> Vec<Action> {
match key.code {
KeyCode::Backspace if self.app_state.is_searching => {
return vec![Action::SearchDeleteChar];
}
KeyCode::Char(c) if self.app_state.is_searching && !key.modifiers.contains(KeyModifiers::CONTROL) => {
return vec![Action::SearchAddChar(c)];
}
_ => {}
}
self.dispatch_keybinding(key, BindingContext::Search)
}
fn dispatch_value_viewer_key(&mut self, key: event::KeyEvent) -> Vec<Action> {
match key.code {
KeyCode::Down | KeyCode::Char('j') => {
self.ui_state.value_viewer.scroll_down();
vec![Action::Tick]
}
KeyCode::Up | KeyCode::Char('k') => {
self.ui_state.value_viewer.scroll_up();
vec![Action::Tick]
}
_ => vec![],
}
}
fn dispatch_mouse_event(&mut self, mouse: MouseEvent) -> Vec<Action> {
if self.ui_state.show_connection_form
|| self.ui_state.show_help
|| self.ui_state.show_quit_confirmation
{
return vec![];
}
match mouse.kind {
MouseEventKind::Down(MouseButton::Left) => {
if let Some(body_area) = self.ui_state.last_body_area {
if self.ui_state.pane_split.is_on_handle(body_area, mouse.column)
&& mouse.row >= body_area.y
&& mouse.row < body_area.y + body_area.height
{
self.ui_state.start_resize();
return vec![Action::Tick];
}
}
self.handle_mouse_click(mouse.column, mouse.row);
vec![Action::Tick]
}
MouseEventKind::Up(MouseButton::Left) => {
self.ui_state.end_resize();
vec![Action::Tick]
}
MouseEventKind::Drag(MouseButton::Left) => {
if self.ui_state.is_resizing {
if let Some(body_area) = self.ui_state.last_body_area {
let relative_x = mouse.column.saturating_sub(body_area.x) as f32;
let new_ratio = relative_x / body_area.width as f32;
self.ui_state.pane_split.ratio = new_ratio.clamp(
self.ui_state.pane_split.min,
self.ui_state.pane_split.max,
);
}
}
vec![Action::Tick]
}
_ => vec![],
}
}
fn dispatch_scroll_event(&mut self, column: u16, row: u16, delta: isize) -> Vec<Action> {
if let Some(key_area) = self.ui_state.last_key_area {
if column >= key_area.x
&& column < key_area.x + key_area.width
&& row >= key_area.y
&& row < key_area.y + key_area.height
{
let total_count = self
.app_state
.total_key_count
.map(|t| t as usize)
.unwrap_or(self.app_state.keys.len());
if total_count > 0 {
let current = self.ui_state.key_list.state.selected().unwrap_or(0);
let new_index = if delta > 0 {
let next = current.saturating_add(delta.unsigned_abs());
if next >= total_count {
0
} else {
next
}
} else {
let amount = delta.unsigned_abs();
if amount > current {
total_count.saturating_sub(1)
} else {
current - amount
}
};
if new_index != current {
self.ui_state.key_list.select(Some(new_index));
return vec![Action::SelectKey(new_index)];
}
}
return vec![Action::Tick];
}
}
if let Some(value_area) = self.ui_state.last_value_area {
if column >= value_area.x
&& column < value_area.x + value_area.width
&& row >= value_area.y
&& row < value_area.y + value_area.height
{
if delta > 0 {
for _ in 0..delta.unsigned_abs() {
self.ui_state.value_viewer.scroll_down();
}
} else {
for _ in 0..delta.unsigned_abs() {
self.ui_state.value_viewer.scroll_up();
}
}
return vec![Action::Tick];
}
}
vec![]
}
fn dispatch_keybinding(&self, key: event::KeyEvent, context: BindingContext) -> Vec<Action> {
if let Some(command) = self.keybindings.get_command(key, context) {
if let Some(action) = self.command_to_action(&command) {
return vec![action];
}
}
vec![]
}
fn command_to_action(&self, command: &str) -> Option<Action> {
match command {
"quit.show" => Some(Action::ShowQuitConfirmation),
"quit.confirm" => Some(Action::ConfirmQuit),
"quit.cancel" => Some(Action::CancelQuit),
"help.toggle" => Some(Action::ToggleHelp),
"search.start" => {
if self.app_state.connection_manager.get_active_id().is_some()
&& !self.app_state.keys.is_empty()
{
Some(Action::StartSearch)
} else {
None
}
}
"search.clear" => Some(Action::ClearSearch),
"search.confirm" => Some(Action::Tick),
"navigation.next_panel" => Some(Action::NextPanel),
"navigation.prev_panel" => Some(Action::PrevPanel),
"navigation.next_item" => Some(Action::NextItem),
"navigation.prev_item" => Some(Action::PrevItem),
"navigation.enter" => Some(Action::Enter),
"connection.palette.toggle" => {
if self.ui_state.show_connection_palette {
Some(Action::CloseConnectionPalette)
} else {
Some(Action::OpenConnectionPalette)
}
}
"connection.palette.open" => Some(Action::OpenConnectionPalette),
"connection.palette.close" => Some(Action::CloseConnectionPalette),
"connection.form.open" => Some(Action::OpenConnectionForm),
"connection.form.close" => Some(Action::CloseConnectionForm),
"connection.form.submit" => Some(Action::Enter),
"connection.form.next_field" => Some(Action::ConnectionFormNextField),
"connection.form.prev_field" => Some(Action::ConnectionFormPrevField),
"connection.tab.next" => Some(Action::NextConnectionTab),
"connection.tab.prev" => Some(Action::PrevConnectionTab),
_ => None,
}
}
async fn update(&mut self, action: Action) {
use async_handlers::*;
use sync_handlers::*;
let should_render = match action {
Action::Tick => true,
Action::Quit => false,
Action::ConfirmQuit => false,
Action::Resize(_, _) => true,
Action::ShowQuitConfirmation
| Action::CancelQuit
| Action::ToggleHelp
| Action::OpenConnectionForm
| Action::CloseConnectionForm
| Action::OpenConnectionPalette
| Action::CloseConnectionPalette => {
handle_ui_toggle(&mut self.ui_state, &self.app_state, &action)
}
Action::NextPanel | Action::PrevPanel | Action::NextItem | Action::PrevItem => {
handle_navigation(
&mut self.ui_state,
&self.app_state,
&self.action_tx,
&action,
)
}
Action::NextConnectionTab => {
self.cycle_connection_tab(true);
true
}
Action::PrevConnectionTab => {
self.cycle_connection_tab(false);
true
}
Action::ConnectionFormNextField | Action::ConnectionFormPrevField => {
handle_connection_form(
&mut self.ui_state,
&mut self.app_state,
&self.action_tx,
&self.config,
&action,
)
}
Action::SubmitConnectionForm(_) => handle_connection_form(
&mut self.ui_state,
&mut self.app_state,
&self.action_tx,
&self.config,
&action,
),
Action::Enter => {
if self.ui_state.show_connection_form {
handle_connection_form(
&mut self.ui_state,
&mut self.app_state,
&self.action_tx,
&self.config,
&action,
)
} else if self.ui_state.show_connection_palette {
handle_enter_connection_palette(
&mut self.ui_state,
&self.app_state,
&self.action_tx,
)
} else {
true
}
}
Action::DeleteConnection(_) => {
handle_connection_management(&mut self.ui_state, &mut self.app_state, &action)
}
Action::FocusConnection(id) => {
self.focus_connection(id);
true
}
Action::Connect(id) => {
handle_connect(&mut self.app_state, &self.action_tx, id);
true
}
Action::Disconnect(id) => {
handle_disconnect(&mut self.app_state, &mut self.ui_state, &id).await;
true
}
Action::DidConnect(id, backend) => {
handle_did_connect(
&mut self.app_state,
&mut self.ui_state,
&self.config,
&self.action_tx,
id,
backend,
);
true
}
Action::DidFailConnect(id, error) => {
handle_did_fail_connect(&mut self.app_state, &id, error);
true
}
Action::LoadKeys => {
handle_load_keys(&mut self.app_state, &self.action_tx);
true
}
Action::LoadMoreKeys(center) => {
handle_load_more_keys(&mut self.app_state, &self.action_tx, center)
}
Action::SelectKey(idx) => {
self.app_state.selected_key_index = Some(idx);
self.app_state.selected_value = None;
self.ui_state.value_viewer.reset_scroll();
if self.app_state.needs_loading_around(idx) {
let _ = self.action_tx.send(Action::LoadMoreKeys(idx));
}
self.schedule_value_load(idx);
true
}
Action::LoadValueDebounced { index, token } => {
if self.app_state.value_request_token == token
&& self.app_state.selected_key_index == Some(index)
{
let _ = self.action_tx.send(Action::LoadValue { index, token });
}
false
}
Action::LoadValue { index, token } => {
handle_load_value(&self.app_state, &self.action_tx, index, token);
false
}
Action::DidScanKeys {
keys,
cursor,
has_more,
total_count,
reset,
center,
} => {
handle_did_scan_keys(
&mut self.app_state,
&mut self.ui_state,
&self.action_tx,
keys,
cursor,
has_more,
total_count,
reset,
center,
);
true
}
Action::DidFailScanKeys(e) => {
handle_did_fail_scan_keys(&mut self.app_state, e);
true
}
Action::DidLoadValue { value, token } => {
handle_did_load_value(&mut self.app_state, value, token)
}
Action::DidFailLoadValue(e) => {
handle_did_fail_load_value(&mut self.app_state, e);
true
}
Action::StartSearch
| Action::ClearSearch
| Action::SearchAddChar(_)
| Action::SearchDeleteChar
| Action::UpdateSearchQuery(_) => {
if let Some((render, needs_search)) =
handle_search(&mut self.app_state, &mut self.ui_state, &action)
{
if needs_search {
trigger_search(&mut self.app_state, &self.action_tx);
}
render
} else {
false
}
}
Action::DidSearchLocal {
indices,
match_positions,
token,
} => handle_did_search_local(
&mut self.app_state,
&self.action_tx,
indices,
match_positions,
token,
),
Action::DidSearchServer { result, token } => {
handle_did_search_server(&mut self.app_state, result.keys, token)
}
Action::Error(e) => {
handle_error(&mut self.app_state, e);
true
}
_ => true,
};
if should_render {
self.needs_render = true;
}
}
fn handle_mouse_click(&mut self, column: u16, row: u16) {
if self.ui_state.show_connection_palette {
if let Some(area) = self.ui_state.connection_palette_area {
if Self::point_in_rect(area, column, row) {
let total = self.app_state.connection_manager.get_configs().len();
if total > 0 {
if let Some(idx) = self
.ui_state
.connection_list
.index_at_position(area, column, row, total)
{
self.ui_state.connection_list.state.select(Some(idx));
if let Some(config) =
self.app_state.connection_manager.get_configs().get(idx)
{
let _ = self
.action_tx
.send(Action::FocusConnection(config.id.clone()));
}
}
}
} else {
let _ = self.action_tx.send(Action::CloseConnectionPalette);
}
} else {
let _ = self.action_tx.send(Action::CloseConnectionPalette);
}
return;
}
if self.app_state.connection_manager.get_active_id().is_none() {
if let Some(area) = self.ui_state.welcome_screen.last_list_area {
let configs = self.app_state.connection_manager.get_configs();
let recent_configs: Vec<&ConnectionConfig> = self
.ui_state
.recent_connection_ids
.iter()
.filter_map(|id| configs.iter().find(|c| c.id == *id).copied())
.collect();
let total = recent_configs.len();
if total > 0 {
if let Some(idx) = self
.ui_state
.welcome_screen
.index_at_position(area, column, row, total)
{
self.ui_state.welcome_screen.state.select(Some(idx));
if let Some(config) = recent_configs.get(idx) {
let _ = self
.action_tx
.send(Action::FocusConnection(config.id.clone()));
}
}
}
}
return;
}
if let Some(region) = self
.ui_state
.tab_regions
.iter()
.find(|region| Self::point_in_rect(region.area, column, row))
{
let _ = self
.action_tx
.send(Action::FocusConnection(region.id.clone()));
return;
}
if let Some(area) = self.ui_state.last_key_area {
if Self::point_in_rect(area, column, row) {
self.ui_state.active_panel = Panel::Keys;
let has_search = !self.app_state.search_query.is_empty();
if has_search {
if let Some(result_idx) = self.search_result_index_from_position(column, row) {
self.app_state.search_selection_index = Some(result_idx);
if let Some(&key_idx) = self.app_state.search_results_local.get(result_idx)
{
self.ui_state.key_list.select(Some(key_idx));
self.app_state.selected_key_index = Some(key_idx);
self.app_state.selected_value = None;
let _ = self.action_tx.send(Action::SelectKey(key_idx));
}
}
} else {
if let Some(index) = self.key_index_from_position(column, row) {
self.ui_state.key_list.select(Some(index));
self.app_state.selected_key_index = Some(index);
self.app_state.selected_value = None;
let _ = self.action_tx.send(Action::SelectKey(index));
}
}
return;
}
}
if let Some(area) = self.ui_state.last_value_area {
if Self::point_in_rect(area, column, row) {
self.ui_state.active_panel = Panel::Value;
}
}
}
fn schedule_value_load(&mut self, idx: usize) {
self.app_state.value_request_token = self.app_state.value_request_token.wrapping_add(1);
let token = self.app_state.value_request_token;
let tx = self.action_tx.clone();
let debounce = self.config.data.value_load_debounce;
tokio::spawn(async move {
tokio::time::sleep(debounce).await;
let _ = tx.send(Action::LoadValueDebounced { index: idx, token });
});
}
fn focus_connection(&mut self, id: String) {
if !self.app_state.connection_manager.set_active(&id) {
return;
}
self.ui_state.close_connection_palette();
self.ui_state.active_panel = Panel::Keys;
self.ui_state.key_list.select(None);
self.app_state.reset_pagination();
self.app_state.error_message = None;
if self.app_state.connection_manager.is_connected(&id) {
if let Ok(ids) = userdata::record_recent_connection_id_with_config(&id, &self.config) {
self.ui_state.recent_connection_ids = ids;
}
let _ = self.action_tx.send(Action::LoadKeys);
} else {
let _ = self.action_tx.send(Action::Connect(id));
}
}
fn cycle_connection_tab(&mut self, forward: bool) {
let target_id = {
let configs = self.app_state.connection_manager.get_configs();
if configs.is_empty() {
return;
}
let len = configs.len();
let current_idx = self
.app_state
.connection_manager
.get_active_id()
.and_then(|active| configs.iter().position(|cfg| cfg.id == active));
let idx = if forward {
current_idx.map(|i| (i + 1) % len).unwrap_or(0)
} else {
current_idx
.map(|i| if i == 0 { len - 1 } else { i - 1 })
.unwrap_or(len.saturating_sub(1))
};
configs[idx].id.clone()
};
self.focus_connection(target_id);
}
fn key_index_from_position(&self, column: u16, row: u16) -> Option<usize> {
let area = self.ui_state.last_key_area?;
if area.height <= 2 || area.width <= 2 {
return None;
}
let inner_left = area.x.saturating_add(1);
let inner_right = area.x.saturating_add(area.width.saturating_sub(1));
if column < inner_left || column >= inner_right {
return None;
}
let inner_top = area.y.saturating_add(1);
let inner_bottom = area.y.saturating_add(area.height.saturating_sub(1));
if row < inner_top || row >= inner_bottom {
return None;
}
let total_count = self
.app_state
.total_key_count
.map(|t| t as usize)
.unwrap_or_else(|| self.app_state.keys.len());
if total_count == 0 {
return None;
}
let (start_index, visible_len) = self.ui_state.key_list.view_bounds(total_count)?;
let rel = (row - inner_top) as usize;
if rel >= visible_len {
return None;
}
let index = start_index + rel;
if index >= total_count {
return None;
}
Some(index)
}
fn search_result_index_from_position(&self, column: u16, row: u16) -> Option<usize> {
let area = self.ui_state.last_key_area?;
if area.height <= 2 || area.width <= 2 {
return None;
}
let inner_left = area.x.saturating_add(1);
let inner_right = area.x.saturating_add(area.width.saturating_sub(1));
if column < inner_left || column >= inner_right {
return None;
}
let inner_top = area.y.saturating_add(1);
let inner_bottom = area.y.saturating_add(area.height.saturating_sub(1));
if row < inner_top || row >= inner_bottom {
return None;
}
let result_count = self.app_state.search_results_local.len();
if result_count == 0 {
return None;
}
let rel = (row - inner_top) as usize;
if rel >= result_count {
return None;
}
Some(rel)
}
fn point_in_rect(area: Rect, column: u16, row: u16) -> bool {
let within_x = column >= area.x && column < area.x.saturating_add(area.width);
let within_y = row >= area.y && row < area.y.saturating_add(area.height);
within_x && within_y
}
}
fn init_tracing(log_file: Option<&PathBuf>, log_level: LogLevel) {
static TRACING: Once = Once::new();
TRACING.call_once(|| {
let Some(log_path) = log_file else {
return;
};
let level_str = format!("memtui={}", log_level);
let env_filter = EnvFilter::try_from_default_env()
.or_else(|_| EnvFilter::try_new(&level_str))
.unwrap_or_else(|_| EnvFilter::new("info"));
if let Ok(file) = OpenOptions::new().create(true).append(true).open(log_path) {
tracing_subscriber::fmt()
.with_env_filter(env_filter)
.with_target(true)
.with_ansi(false)
.with_writer(file)
.try_init()
.ok();
} else {
eprintln!("Warning: Could not open log file: {}", log_path.display());
}
});
}
#[tokio::main]
async fn main() -> Result<(), io::Error> {
let cli = Cli::parse();
init_tracing(cli.log_file.as_ref(), cli.log_level);
let theme = userdata::load_theme();
init_theme(theme);
let original_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |panic_info| {
let _ = disable_raw_mode();
let _ = execute!(io::stdout(), LeaveAlternateScreen, DisableMouseCapture);
let _ = io::stdout().flush(); original_hook(panic_info);
}));
enable_raw_mode()?;
let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
let mut app = App::new(&cli);
info!("memtui initialized");
if let Some(id) = app.take_auto_connect() {
let _ = app.action_tx.send(Action::FocusConnection(id));
}
let res = app.run(&mut terminal).await;
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
terminal.show_cursor()?;
if let Err(err) = res {
error!(?err, "Application exited with error");
println!("Error: {:?}", err);
} else {
info!("Application exited cleanly");
}
Ok(())
}