use std::time::Duration;
use egui::{Align, CursorIcon, Layout, RichText};
use bigtext::encoding::{Encoding, LineEnding};
use bigtext::file;
use bigtext::jobs::human_bytes;
use super::commands::Cmd;
use super::i18n::{tr, trf};
use super::{filter_panel, follow_id, marks, BigTextApp};
#[derive(Default)]
pub struct StatusSeen {
pub fields_w: f32,
pub left_end: f32,
pub right_start: f32,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct StatusFields {
pub offset: bool,
pub sel: bool,
pub dt: bool,
pub legend: bool,
pub kind: bool,
pub index_time: bool,
pub path: bool,
}
impl Default for StatusFields {
fn default() -> Self {
StatusFields {
offset: true,
sel: true,
dt: true,
legend: true,
kind: false,
index_time: false,
path: false,
}
}
}
impl StatusFields {
const NAMES: [&'static str; 7] = [
"offset",
"selection",
"time",
"legend",
"access",
"index-time",
"path",
];
fn flags(&mut self) -> [&mut bool; 7] {
[
&mut self.offset,
&mut self.sel,
&mut self.dt,
&mut self.legend,
&mut self.kind,
&mut self.index_time,
&mut self.path,
]
}
pub fn to_line(mut self) -> String {
Self::NAMES
.iter()
.zip(self.flags())
.filter(|(_, on)| **on)
.map(|(n, _)| *n)
.collect::<Vec<_>>()
.join(",")
}
pub fn from_line(v: &str) -> StatusFields {
let on: Vec<&str> = v.split(',').map(str::trim).collect();
let mut f = StatusFields::default();
for (n, flag) in Self::NAMES.iter().zip(f.flags()) {
*flag = on.contains(n);
}
f
}
fn menu(mut self, ui: &mut egui::Ui) -> Option<StatusFields> {
let old = self;
ui.label(RichText::new(tr("Show in the status bar")).strong());
let labels = [
tr("Byte offset"),
tr("Selection size"),
tr("Time since the previous line"),
tr("Merged log's files"),
tr("File access (mapped or chunked)"),
tr("Indexing time"),
tr("File path"),
];
for (label, flag) in labels.into_iter().zip(self.flags()) {
ui.checkbox(flag, label);
}
(self != old).then_some(self)
}
}
pub(crate) fn lone_cr_applies(d: &super::document::Document) -> bool {
d.line_ending == LineEnding::Mixed && d.buf.codec.nl == bigtext::encoding::NlByte::Lf
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum StatusAct {
GotoLine,
GotoOffset,
Reopen(Option<Encoding>),
Eol(Option<LineEnding>),
LoneCr(bool),
ToggleReadOnly,
CopyPath,
Fields(StatusFields),
Skew(i64),
JsonGoto {
version: u64,
off: u64,
},
CopyText(String),
Alerts,
}
fn crumb(
ui: &mut egui::Ui,
c: &super::json_crumb::JsonCrumb,
stale: bool,
acts: &mut Vec<StatusAct>,
) {
let path = c.path();
let tip = format!(
"{path}\n{}",
tr("Click a part to go to it; right-click copies the path")
);
let short = |s: String| {
if s.chars().count() > 24 {
s.chars().take(23).chain(['…']).collect()
} else {
s
}
};
let parts: Vec<String> = c
.steps
.iter()
.map(|(s, _)| {
short(match s {
bigtext::json::Step::Key(k) => k.clone(),
bigtext::json::Step::Index(i) => format!("[{i}]"),
})
})
.collect();
let skip = parts.len().saturating_sub(4);
ui.spacing_mut().item_spacing.x = 3.0;
let mut part = |ui: &mut egui::Ui, text: String, off: u64| {
let text = if stale {
RichText::new(text).weak()
} else {
RichText::new(text)
};
let r = ui.add(egui::Link::new(text)).on_hover_text(&tip);
if r.clicked() {
acts.push(StatusAct::JsonGoto {
version: c.version,
off,
});
}
if r.secondary_clicked() {
acts.push(StatusAct::CopyText(path.clone()));
}
};
part(ui, "$".into(), 0);
if skip > 0 {
ui.weak("› …").on_hover_text(&tip);
}
for (i, p) in parts.into_iter().enumerate().skip(skip) {
ui.weak("›");
part(ui, p, c.steps[i].1);
}
if let Some((_, _, p)) = &c.building {
ui.add(egui::ProgressBar::new(p.fraction()).desired_width(60.0))
.on_hover_text(tr("Reading the JSON's structure"));
}
}
fn field(ui: &mut egui::Ui, text: impl Into<egui::WidgetText>, tip: &str) -> egui::Response {
ui.add(egui::Button::new(text).frame(false))
.on_hover_cursor(CursorIcon::PointingHand)
.on_hover_text(tip)
}
fn field_menu(
ui: &mut egui::Ui,
text: impl Into<egui::WidgetText>,
tip: &str,
content: impl FnOnce(&mut egui::Ui),
) {
let (r, _) =
egui::containers::menu::MenuButton::from_button(egui::Button::new(text).frame(false))
.ui(ui, content);
r.on_hover_cursor(CursorIcon::PointingHand)
.on_hover_text(tip);
}
impl BigTextApp {
pub(super) fn status_bar(&mut self, ui: &mut egui::Ui) {
let ids = self.caret_ids();
let delta = self.caret_time_delta();
let fields = self.settings.status;
let json_crumb = self.settings.json_crumb;
let tip = |cmd: Cmd| match self.keymap.get(cmd) {
Some(k) => format!("{} ({})", tr(cmd.label()), super::commands::key_text(k)),
None => tr(cmd.label()).to_string(),
};
let (line_tip, offset_tip) = (tip(Cmd::GotoLine), tip(Cmd::GotoOffset));
let mut follow = None;
let mut acts = Vec::new();
let (mut fields_w, mut left_end, mut right_start) = (0.0, 0.0, f32::MAX);
let bar = ui.scope_builder(egui::UiBuilder::new().sense(egui::Sense::click()), |ui| {
ui.horizontal(|ui| {
if let Some(d) = self.docs.get(self.active).filter(|d| d.is_ready()) {
let caret = d.view.caret;
let (line, exact) = d.buf.line_of(caret);
let col = match d.buf.line_start(line) {
Some((ls, true)) if caret >= ls && caret - ls <= 128 * 1024 => {
let b = d.buf.read(ls..caret);
b.map(|b| format!("{}", bigtext::text::rows::cell_width(&d.buf.codec, &b, ls) + 1)).unwrap_or_else(|| "…".into())
}
Some((ls, _)) if caret >= ls => format!("~{}", caret - ls + 1),
_ => "?".into(),
};
let pos = trf("Ln {line}, Col {col}", &[("line", &format!("{}{}", if exact { "" } else { "~" }, line + 1)), ("col", &col)]);
if field(ui, pos, &line_tip).clicked() {
acts.push(StatusAct::GotoLine);
}
if let Some(ms) = delta.filter(|_| fields.dt) {
ui.separator();
ui.label(format!("Δ {}", bigtext::timestamp::format_delta(ms))).on_hover_text(tr("Time since the previous line with a timestamp"));
}
if !d.view.extra.is_empty() {
ui.separator();
ui.label(trf("{n} cursors", &[("n", &(d.view.extra.len() + 1).to_string())])).on_hover_text(tr("Esc: back to one cursor"));
}
if fields.offset {
ui.separator();
if field(ui, trf("Offset {n}", &[("n", &format!("{caret} (0x{caret:X})"))]), &offset_tip).clicked() {
acts.push(StatusAct::GotoOffset);
}
}
if let Some(c) = d.json_crumb.as_ref().filter(|c| json_crumb && !c.steps.is_empty() && c.version != u64::MAX) {
ui.separator();
crumb(ui, c, c.version != d.version || c.caret != d.view.caret || c.error, &mut acts);
}
if let Some((lines, exact, chars, bytes)) = d.selection_stats().filter(|_| fields.sel) {
ui.separator();
let n = |x: u64| filter_panel::fmt_count(x);
let lines = format!("{}{}", if exact { "" } else { "~" }, n(lines));
let text = match chars {
Some(c) => trf("Sel: {lines} lines, {chars} chars, {bytes} bytes", &[("lines", &lines), ("chars", &n(c)), ("bytes", &n(bytes))]),
None => trf("Sel: {lines} lines, {bytes} bytes", &[("lines", &lines), ("bytes", &n(bytes))]),
};
ui.label(text);
if let Some(ms) = d.selection_time_delta().filter(|_| fields.dt) {
ui.separator();
ui.label(format!("Δt {}", bigtext::timestamp::format_delta(ms))).on_hover_text(tr("Time between the timestamps of the first and last selected lines"));
}
}
if let Some(b) = d.view.block {
let (lo, hi) = b.cells();
ui.separator();
ui.label(trf("Block: {cols} columns wide", &[("cols", &(hi - lo).to_string())]));
}
let (lines, lexact) = d.buf.line_count();
ui.separator();
ui.label(trf("{n} lines", &[("n", &format!("{}{}", if lexact { "" } else { "~" }, lines))]));
if !ids.is_empty() {
ui.separator();
follow = follow_id::id_chips(ui, &ids);
}
if let Some(t) = &d.merged {
ui.separator();
let dark = ui.visuals().dark_mode;
if fields.legend {
for (i, l) in t.labels.iter().enumerate() {
ui.label(RichText::new(l).background_color(marks::fill(i, dark)));
}
} else {
ui.label(trf("{n} files", &[("n", &t.labels.len().to_string())])).on_hover_ui(|ui| {
for (i, l) in t.labels.iter().enumerate() {
ui.label(RichText::new(l).background_color(marks::fill(i, dark)));
}
});
}
}
}
left_end = ui.min_rect().right();
let right = ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
field_menu(ui, "…", tr("Choose the fields of the status bar"), |ui| {
if let Some(f) = fields.menu(ui) {
acts.push(StatusAct::Fields(f));
}
});
self.tasks_status(ui);
let Some(d) = self.docs.get(self.active) else { return };
let fields_from = ui.min_rect().left();
if let Some((p, c)) = &d.growing {
if ui.small_button(tr("Cancel")).on_hover_text(tr("Stop unpacking; what is unpacked stays open")).clicked() {
c.cancel();
}
ui.add(egui::ProgressBar::new(p.fraction()).desired_width(140.0).text(format!("{} {:.0}%", tr("Unpacking"), p.fraction() * 100.0)));
ui.ctx().request_repaint_after(Duration::from_millis(250));
ui.separator();
}
if let Some(j) = &d.save_job {
if ui.small_button(tr("Cancel")).clicked() {
j.cancel.cancel();
}
ui.add(egui::ProgressBar::new(j.progress.fraction()).desired_width(160.0).text(format!("{} {:.0}%", j.label, j.progress.fraction() * 100.0)));
ui.separator();
}
if d.follow {
let label = if d.rotations > 0 { format!("{} ×{}", tr("FOLLOW"), d.rotations + 1) } else { tr("FOLLOW").to_string() };
ui.label(RichText::new(label).color(super::theme::ok_text(ui))).on_hover_text(trf("Following the file; it was rotated {n} times so far", &[("n", &d.rotations.to_string())]));
ui.separator();
}
if let Some(a) = &d.alerts {
let text = RichText::new(format!("🔔 {}", super::filter_panel::fmt_count(a.total)));
let text = if a.total > 0 { text.color(super::theme::warn_text(ui)) } else { text };
let tip = trf("Alerts on new lines: {n} patterns; click to see the lines that matched", &[("n", &a.patterns.len().to_string())]);
if ui.add(egui::Label::new(text).sense(egui::Sense::click())).on_hover_text(tip).clicked() {
acts.push(StatusAct::Alerts);
}
ui.separator();
}
if let Some(l) = d.link.as_ref().filter(|l| l.mode == super::time_link::LinkMode::Time) {
let mut secs = l.skew_ms as f64 / 1000.0;
let r = ui.add(egui::DragValue::new(&mut secs).speed(0.1).suffix(" s").max_decimals(3));
if r.on_hover_text(tr("Added to this log's times before they are looked up in the linked one")).changed() {
acts.push(StatusAct::Skew((secs * 1000.0).round() as i64));
}
ui.label(tr("Skew"));
ui.separator();
}
if d.table && !d.hex {
let delim = d.table_state.dialect.map(|x| tr(x.name())).unwrap_or("…");
ui.label(RichText::new(format!("{} · {delim}", tr("TABLE"))).color(super::theme::info_text(ui)));
ui.separator();
}
if let Some(r) = d.results.as_ref().filter(|r| r.is_running()) {
ui.add(egui::ProgressBar::new(r.progress.fraction()).desired_width(140.0).text(format!("{} {:.0}%", tr("Searching"), r.progress.fraction() * 100.0)));
ui.separator();
} else if d.find_job.is_some() {
ui.label(tr("Searching…"));
ui.separator();
}
if d.read_only {
let text = RichText::new(tr("READ-ONLY")).color(super::theme::warn_text(ui));
if d.merged.is_some() || d.growing.is_some() {
ui.label(text);
} else if field(ui, text, tr("Click to allow editing")).clicked() {
acts.push(StatusAct::ToggleReadOnly);
}
ui.separator();
}
if fields.kind {
ui.label(d.buf.source.kind_name());
ui.separator();
}
ui.label(human_bytes(d.buf.len()));
ui.separator();
let eol = match d.eol_on_save {
Some(to) if to != d.line_ending => format!("{} → {}", d.line_ending.name(), to.name()),
_ => d.line_ending.name().to_string(),
};
field_menu(ui, eol, tr("Line endings on save"), |ui| {
for (to, label) in [(None, "Keep as is"), (Some(LineEnding::Lf), "Convert to LF"), (Some(LineEnding::CrLf), "Convert to CRLF"), (Some(LineEnding::Cr), "Convert to CR")] {
if ui.radio(d.eol_on_save == to, tr(label)).clicked() {
acts.push(StatusAct::Eol(to));
}
}
if lone_cr_applies(d) {
ui.separator();
let mut on = d.eol_lone_cr;
let can = matches!(d.eol_on_save, Some(LineEnding::Lf | LineEnding::CrLf));
if ui.add_enabled(can, egui::Checkbox::new(&mut on, tr("Lone CR characters become line breaks too"))).on_hover_text(tr("Otherwise a CR not followed by LF (shown as ←) stays as it is")).changed() {
acts.push(StatusAct::LoneCr(on));
}
}
});
ui.separator();
field_menu(ui, d.buf.codec.enc.name(), tr("Reopen with encoding"), |ui| {
if ui.add_enabled(d.forced_enc.is_some(), egui::Button::new(tr("Auto-detect (forget)"))).clicked() {
acts.push(StatusAct::Reopen(None));
}
ui.separator();
for enc in Encoding::ALL {
if ui.radio(d.forced_enc == Some(enc), enc.name()).clicked() {
acts.push(StatusAct::Reopen(Some(enc)));
}
}
});
if d.is_ready() && d.buf.source.is_remote() {
ui.separator();
let read = d.buf.source.bytes_read();
ui.label(trf("{read} of {size} read", &[("read", &human_bytes(read)), ("size", &human_bytes(d.buf.source.len()))]))
.on_hover_text(tr("A remote file read in place: only what is shown, and what a search reaches, is downloaded."));
if d.buf.source.has_io_error() {
ui.colored_label(ui.visuals().error_fg_color, tr("read failed"));
}
} else if d.is_ready() && !d.buf.index.is_done() && !d.buf.is_empty() {
ui.separator();
ui.add(egui::ProgressBar::new(d.buf.index.progress()).desired_width(120.0).text(format!("{} {:.0}%", tr("Indexing"), d.buf.index.progress() * 100.0)));
} else if let Some(t) = d.buf.index.finished_after().filter(|t| fields.index_time && *t > Duration::ZERO) {
ui.separator();
ui.label(trf("Indexed in {t}s", &[("t", &format!("{:.2}", t.as_secs_f32()))]));
}
fields_w = fields_from - ui.min_rect().left();
if let Some(p) = d.unpacked_from.as_deref().or(d.path.as_deref()).filter(|_| fields.path) {
ui.separator();
let r = ui.add(egui::Label::new(file::display_path(p)).truncate().sense(egui::Sense::click()));
if r.on_hover_cursor(CursorIcon::PointingHand).on_hover_text(tr("Click to copy the path")).clicked() {
acts.push(StatusAct::CopyPath);
}
}
});
right_start = right.response.rect.left();
});
});
self.status_seen = StatusSeen {
fields_w,
left_end,
right_start,
};
if let Some(t) = &self.announcement {
crate::view::a11y::live_region(ui.ctx(), egui::Id::new("bigtext-announcement"), t);
}
bar.response.context_menu(|ui| {
if let Some(f) = fields.menu(ui) {
acts.push(StatusAct::Fields(f));
}
});
let ctx = ui.ctx().clone();
for a in acts {
self.status_act(&ctx, a);
}
if let Some(id) = follow {
self.follow_id(&id);
}
}
pub(super) fn zen_menu(&mut self, ctx: &egui::Context) {
let id = egui::Id::new("zen-menu");
let near_top = ctx.input(|i| i.pointer.hover_pos().is_some_and(|p| p.y <= 4.0));
let was_shown = ctx.data(|d| d.get_temp::<bool>(id).unwrap_or(false));
let hovered = was_shown
&& ctx.input(|i| i.pointer.hover_pos()).is_some_and(|p| {
ctx.layer_id_at(p)
.is_some_and(|l| l.id == id || l.order == egui::Order::Foreground)
});
let show = near_top || hovered || egui::Popup::is_any_open(ctx);
ctx.data_mut(|d| d.insert_temp(id, show));
let since = ctx.data(|d| d.get_temp::<std::time::Instant>(egui::Id::new("zen-hint")));
if let Some(t) = since.filter(|t| t.elapsed() < Duration::from_secs(4)) {
let key = self
.keymap
.get(Cmd::Zen)
.map(super::commands::key_text)
.unwrap_or_else(|| tr(Cmd::Zen.label()).to_string());
let hint = trf(
"Zen mode: Esc or {key} leaves it; move the pointer to the top edge for the menu.",
&[("key", &key)],
);
egui::Area::new(egui::Id::new("zen-hint-area"))
.order(egui::Order::Tooltip)
.anchor(egui::Align2::CENTER_TOP, egui::vec2(0.0, 12.0))
.interactable(false)
.show(ctx, |ui| {
egui::Frame::popup(ui.style()).show(ui, |ui| ui.label(hint));
});
ctx.request_repaint_after(Duration::from_secs(4).saturating_sub(t.elapsed()));
}
if !show {
return;
}
let width = ctx.content_rect().width();
egui::Area::new(id)
.order(egui::Order::Foreground)
.fixed_pos(egui::pos2(0.0, 0.0))
.show(ctx, |ui| {
egui::Frame::side_top_panel(ui.style()).show(ui, |ui| {
ui.set_width(width);
self.menu_bar(ui);
});
});
}
pub(crate) fn announce(&mut self, text: impl Into<String>) {
self.announcement = Some(text.into());
}
pub(super) fn announce_results(&mut self) {
let Some(d) = self.docs.get(self.active) else {
return;
};
let running = d.results.as_ref().is_some_and(|r| r.is_running());
if !std::mem::replace(&mut self.results_running, running) || running {
return;
}
if let Some(n) = d
.results
.as_ref()
.map(|r| r.data.lock().unwrap().matches.len())
{
self.announce(trf("{n} matches", &[("n", &n.to_string())]));
}
}
pub(crate) fn status_act(&mut self, ctx: &egui::Context, a: StatusAct) {
match a {
StatusAct::GotoLine => self.run(ctx, Cmd::GotoLine),
StatusAct::Alerts => self.open_alerts(),
StatusAct::GotoOffset => self.run(ctx, Cmd::GotoOffset),
StatusAct::Reopen(enc) => self.reopen_with(enc),
StatusAct::Eol(to) => {
if let Some(d) = self.docs.get_mut(self.active) {
d.eol_on_save = to;
}
}
StatusAct::LoneCr(on) => {
if let Some(d) = self.docs.get_mut(self.active) {
d.eol_lone_cr = on;
}
}
StatusAct::ToggleReadOnly => self.run(ctx, Cmd::ReadOnly),
StatusAct::CopyPath => {
if let Some(p) = self
.docs
.get(self.active)
.and_then(|d| d.unpacked_from.as_deref().or(d.path.as_deref()))
{
ctx.copy_text(file::display_path(p));
}
}
StatusAct::JsonGoto { version, off } => {
if let Some(d) = self
.docs
.get_mut(self.active)
.filter(|d| d.version == version)
{
d.goto_offset(off);
}
}
StatusAct::CopyText(t) => {
ctx.copy_text(t);
self.announce(tr("Copied"));
}
StatusAct::Skew(ms) => {
if let Some(l) = self.docs.get_mut(self.active).and_then(|d| d.link.as_mut()) {
l.skew_ms = ms;
l.synced = None;
}
}
StatusAct::Fields(f) => {
self.settings.status = f;
self.persist_state();
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fields_line() {
let d = StatusFields::default();
assert_eq!(d.to_line(), "offset,selection,time,legend");
assert_eq!(StatusFields::from_line(&d.to_line()), d);
let f = StatusFields {
offset: false,
path: true,
index_time: true,
..d
};
assert_eq!(StatusFields::from_line(&f.to_line()), f);
assert_eq!(
StatusFields::from_line(""),
StatusFields {
offset: false,
sel: false,
dt: false,
legend: false,
kind: false,
index_time: false,
path: false
}
);
}
}