tracexec 0.8.2

Tracer for execve{,at} and pre-exec behavior, launcher for debuggers.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
// Copyright (c) 2023 Ratatui Developers
// Copyright (c) 2024 Levi Zim

// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
// associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute,
// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all copies or substantial
// portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
// NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
// OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

use std::sync::Arc;

use indexmap::IndexMap;
use nix::sys::signal;
use ratatui::{
  layout::Alignment::Right,
  prelude::{Buffer, Rect},
  style::{Color, Modifier, Style},
  text::Line,
  widgets::{
    HighlightSpacing, List, ListItem, ListState, Scrollbar, ScrollbarOrientation, ScrollbarState,
    StatefulWidget, StatefulWidgetRef, Widget,
  },
};

use crate::{
  cli::args::ModifierArgs,
  event::{
    EventStatus, ProcessStateUpdate, ProcessStateUpdateEvent, RuntimeModifier, TracerEventDetails,
  },
  proc::BaselineInfo,
  ptrace::Signal,
  tracer::state::ProcessExit,
};

use super::{
  event_line::EventLine,
  partial_line::PartialLine,
  query::{Query, QueryResult},
  theme::THEME,
};

pub struct Event {
  pub details: Arc<TracerEventDetails>,
  pub status: Option<EventStatus>,
}

impl Event {
  fn to_event_line(&self, list: &EventList) -> EventLine {
    self.details.to_event_line(
      &list.baseline,
      false,
      &list.modifier_args,
      list.runtime_modifier(),
      self.status,
      true,
    )
  }
}

pub struct EventList {
  state: ListState,
  events: Vec<Event>,
  /// The string representation of the events, used for searching
  event_lines: Vec<EventLine>,
  /// Current window of the event list, [start, end)
  window: (usize, usize),
  /// Cache of the list items in the view
  list_cache: List<'static>,
  should_refresh_list_cache: bool,
  /// How many items are there in the window
  nr_items_in_window: usize,
  horizontal_offset: usize,
  /// width that could be used for the list items(not including the selection indicator)
  inner_width: u16,
  /// max width of the lines in the current window
  max_width: usize,
  pub max_window_len: usize,
  pub baseline: Arc<BaselineInfo>,
  follow: bool,
  pub modifier_args: ModifierArgs,
  rt_modifier: RuntimeModifier,
  query: Option<Query>,
  query_result: Option<QueryResult>,
}

impl EventList {
  pub fn new(baseline: Arc<BaselineInfo>, follow: bool, modifier_args: ModifierArgs) -> Self {
    Self {
      state: ListState::default(),
      events: vec![],
      event_lines: vec![],
      window: (0, 0),
      nr_items_in_window: 0,
      horizontal_offset: 0,
      inner_width: 0,
      max_width: 0,
      max_window_len: 0,
      baseline,
      follow,
      should_refresh_list_cache: true,
      list_cache: List::default(),
      modifier_args,
      rt_modifier: Default::default(),
      query: None,
      query_result: None,
    }
  }

  pub fn runtime_modifier(&self) -> RuntimeModifier {
    self.rt_modifier
  }

  pub fn is_env_in_cmdline(&self) -> bool {
    self.rt_modifier.show_env
  }

  pub fn is_cwd_in_cmdline(&self) -> bool {
    self.rt_modifier.show_cwd
  }

  pub fn is_following(&self) -> bool {
    self.follow
  }

  pub fn toggle_follow(&mut self) {
    self.follow = !self.follow;
  }

  pub fn stop_follow(&mut self) {
    self.follow = false;
  }

  pub fn toggle_env_display(&mut self) {
    self.rt_modifier.show_env = !self.rt_modifier.show_env;
    for line in &mut self.event_lines {
      if let Some(mask) = &mut line.env_mask {
        mask.toggle(&mut line.line);
      }
    }
    self.should_refresh_list_cache = true;
    self.search();
  }

  pub fn toggle_cwd_display(&mut self) {
    self.rt_modifier.show_cwd = !self.rt_modifier.show_cwd;
    for line in &mut self.event_lines {
      if let Some(mask) = &mut line.cwd_mask {
        mask.toggle(&mut line.line);
      }
    }
    self.should_refresh_list_cache = true;
    self.search();
  }

  /// returns the index of the selected item if there is any
  pub fn selection_index(&self) -> Option<usize> {
    self.state.selected().map(|i| self.window.0 + i)
  }

  /// returns the selected item if there is any
  pub fn selection(&self) -> Option<&Event> {
    self.selection_index().map(|i| &self.events[i])
  }

  /// Reset the window and force clear the list cache
  pub fn set_window(&mut self, window: (usize, usize)) {
    self.window = window;
    self.should_refresh_list_cache = true;
  }

  pub fn get_window(&self) -> (usize, usize) {
    self.window
  }

  // TODO: this is ugly due to borrow checking.
  pub fn window(items: &[EventLine], window: (usize, usize)) -> &[EventLine] {
    &items[window.0..window.1.min(items.len())]
  }

  pub fn statistics(&self) -> Line {
    let id = self.selection_index().unwrap_or(0);
    Line::raw(format!(
      "{}/{}──",
      (id + 1).min(self.events.len()),
      self.events.len()
    ))
    .alignment(Right)
  }

  pub fn len(&self) -> usize {
    self.events.len()
  }
}

impl Widget for &mut EventList {
  fn render(self, area: Rect, buf: &mut Buffer)
  where
    Self: Sized,
  {
    self.inner_width = area.width - 2; // for the selection indicator
    let mut max_len = area.width as usize - 1;
    // Iterate through all elements in the `items` and stylize them.
    let events_in_window = EventList::window(&self.event_lines, self.window);
    self.nr_items_in_window = events_in_window.len();
    // tracing::debug!(
    //   "Should refresh list cache: {}",
    //   self.should_refresh_list_cache
    // );
    if self.should_refresh_list_cache {
      self.should_refresh_list_cache = false;
      tracing::debug!("Refreshing list cache");
      let items = self
        .event_lines
        .iter()
        .enumerate()
        .skip(self.window.0)
        .take(self.window.1 - self.window.0)
        .map(|(i, full_line)| {
          max_len = max_len.max(full_line.line.width());
          let highlighted = self
            .query_result
            .as_ref()
            .is_some_and(|query_result| query_result.indices.contains_key(&i));
          let mut base = full_line
            .line
            .clone()
            .substring(self.horizontal_offset, area.width);
          if highlighted {
            base = base.style(THEME.search_match);
          }
          ListItem::from(base)
        });
      // Create a List from all list items and highlight the currently selected one
      let list = List::new(items)
        .highlight_style(
          Style::default()
            .add_modifier(Modifier::BOLD)
            .bg(Color::DarkGray),
        )
        .highlight_symbol("➡️")
        .highlight_spacing(HighlightSpacing::Always);
      // FIXME: It's a little late to set the max width here. The max width is already used
      //        Though this should only affect the first render.
      self.max_width = max_len;
      self.list_cache = list;
    }

    // We can now render the item list
    // (look careful we are using StatefulWidget's render.)
    // ratatui::widgets::StatefulWidget::render as stateful_render
    StatefulWidgetRef::render_ref(&self.list_cache, area, buf, &mut self.state);

    // Render scrollbars
    if self.max_width + 1 > area.width as usize {
      // Render horizontal scrollbar, assuming there is a border we can overwrite
      let scrollbar = Scrollbar::new(ScrollbarOrientation::HorizontalBottom).thumb_symbol("");
      let scrollbar_area = Rect {
        x: area.x,
        y: area.y + area.height,
        width: area.width,
        height: 1,
      };
      scrollbar.render(
        scrollbar_area,
        buf,
        &mut ScrollbarState::new(self.max_width + 1 - area.width as usize)
          .position(self.horizontal_offset),
      );
    }
    if self.events.len() > area.height as usize {
      // Render vertical scrollbar
      let scrollbar = Scrollbar::new(ScrollbarOrientation::VerticalRight);
      let scrollbar_area = Rect {
        x: area.x + area.width,
        y: area.y,
        width: 1,
        height: area.height,
      };
      scrollbar.render(
        scrollbar_area,
        buf,
        &mut ScrollbarState::new(self.events.len() - area.height as usize)
          .position(self.window.0 + self.state.selected().unwrap_or(0)),
      );
    }

    if let Some(query_result) = self.query_result.as_ref() {
      let statistics = query_result.statistics();
      let statistics_len = statistics.width();
      if statistics_len > buf.area().width as usize {
        return;
      }
      let statistics_area = Rect {
        x: buf.area().right().saturating_sub(statistics_len as u16),
        y: 1,
        width: statistics_len as u16,
        height: 1,
      };
      statistics.render(statistics_area, buf);
    }
  }
}

/// Query Management
impl EventList {
  pub fn set_query(&mut self, query: Option<Query>) {
    if query.is_some() {
      self.query = query;
      self.search();
    } else {
      self.query = None;
      self.query_result = None;
      self.should_refresh_list_cache = true;
    }
  }

  /// Search for the query in the event list
  /// And update query result,
  /// Then set the selection to the first result(if any) and scroll to it
  pub fn search(&mut self) {
    let Some(query) = self.query.as_ref() else {
      return;
    };
    let mut indices = IndexMap::new();
    // Events won't change during the search because this is Rust and we already have a reference to it.
    // Rust really makes the code more easier to reason about.
    let searched_len = self.events.len();
    for (i, evt) in self.event_lines.iter().enumerate() {
      if query.matches(evt) {
        indices.insert(i, 0);
      }
    }
    let mut result = QueryResult {
      indices,
      searched_len,
      selection: None,
    };
    result.next_result();
    let selection = result.selection();
    self.query_result = Some(result);
    self.should_refresh_list_cache = true;
    self.scroll_to(selection);
  }

  /// Incremental search for newly added events
  pub fn incremental_search(&mut self) {
    let Some(query) = self.query.as_ref() else {
      return;
    };
    let Some(existing_result) = self.query_result.as_mut() else {
      self.search();
      return;
    };
    let mut modified = false;
    for (i, evt) in self
      .event_lines
      .iter()
      .enumerate()
      .skip(existing_result.searched_len)
    {
      if query.matches(evt) {
        existing_result.indices.insert(i, 0);
        modified = true;
      }
    }
    existing_result.searched_len = self.event_lines.len();
    if modified {
      self.should_refresh_list_cache = true;
    }
  }

  pub fn next_match(&mut self) {
    if let Some(query_result) = self.query_result.as_mut() {
      query_result.next_result();
      let selection = query_result.selection();
      self.scroll_to(selection);
      self.stop_follow();
    }
  }

  pub fn prev_match(&mut self) {
    if let Some(query_result) = self.query_result.as_mut() {
      query_result.prev_result();
      let selection = query_result.selection();
      self.scroll_to(selection);
      self.stop_follow();
    }
  }
}

/// Event Management
impl EventList {
  pub fn push(&mut self, event: impl Into<Arc<TracerEventDetails>>) {
    let event = event.into();
    let event = Event {
      status: match event.as_ref() {
        TracerEventDetails::NewChild { .. } => Some(EventStatus::ProcessRunning),
        TracerEventDetails::Exec(exec) => {
          match exec.result {
            0 => Some(EventStatus::ProcessRunning),
            -2 => Some(EventStatus::ExecENOENT), // ENOENT
            _ => Some(EventStatus::ExecFailure),
          }
        }
        _ => None,
      },
      details: event,
    };
    self.event_lines.push(event.to_event_line(self));
    self.events.push(event);
    self.incremental_search();
    if (self.window.0..self.window.1).contains(&(self.events.len() - 1)) {
      self.should_refresh_list_cache = true;
    }
  }

  pub fn update(&mut self, update: ProcessStateUpdateEvent) {
    for i in update.ids {
      let i = i as usize;
      if let TracerEventDetails::Exec(exec) = self.events[i].details.as_ref() {
        if exec.result != 0 {
          // Don't update the status for failed exec events
          continue;
        }
      }
      self.events[i].status = match update.update {
        ProcessStateUpdate::Exit(ProcessExit::Code(0)) => Some(EventStatus::ProcessExitedNormally),
        ProcessStateUpdate::Exit(ProcessExit::Code(c)) => {
          Some(EventStatus::ProcessExitedAbnormally(c))
        }
        ProcessStateUpdate::Exit(ProcessExit::Signal(Signal::Standard(signal::SIGTERM))) => {
          Some(EventStatus::ProcessTerminated)
        }
        ProcessStateUpdate::Exit(ProcessExit::Signal(Signal::Standard(signal::SIGKILL))) => {
          Some(EventStatus::ProcessKilled)
        }
        ProcessStateUpdate::Exit(ProcessExit::Signal(Signal::Standard(signal::SIGINT))) => {
          Some(EventStatus::ProcessInterrupted)
        }
        ProcessStateUpdate::Exit(ProcessExit::Signal(Signal::Standard(signal::SIGSEGV))) => {
          Some(EventStatus::ProcessSegfault)
        }
        ProcessStateUpdate::Exit(ProcessExit::Signal(Signal::Standard(signal::SIGABRT))) => {
          Some(EventStatus::ProcessAborted)
        }
        ProcessStateUpdate::Exit(ProcessExit::Signal(Signal::Standard(signal::SIGILL))) => {
          Some(EventStatus::ProcessIllegalInstruction)
        }
        ProcessStateUpdate::Exit(ProcessExit::Signal(s)) => Some(EventStatus::ProcessSignaled(s)),
        ProcessStateUpdate::BreakPointHit { .. } => Some(EventStatus::ProcessPaused),
        ProcessStateUpdate::Resumed => Some(EventStatus::ProcessRunning),
        ProcessStateUpdate::Detached { .. } => Some(EventStatus::ProcessDetached),
        _ => unimplemented!(),
      };
      self.event_lines[i] = self.events[i].to_event_line(self);
      if self.window.0 <= i && i < self.window.1 {
        self.should_refresh_list_cache = true;
      }
    }
  }

  pub fn rebuild_lines(&mut self) {
    // TODO: only update spans that are affected by the change
    self.event_lines = self
      .events
      .iter()
      .map(|evt| evt.to_event_line(self))
      .collect();
    self.should_refresh_list_cache = true;
  }
}

/// Scrolling implementation for the EventList
impl EventList {
  /// Scroll to the given index and select it,
  /// Usually the item will be at the top of the window,
  /// but if there are not enough items or the item is already in current window,
  /// no scrolling will be done,
  /// And if the item is in the last window, we won't scroll past it.
  fn scroll_to(&mut self, index: Option<usize>) {
    let Some(index) = index else {
      return;
    };
    if index < self.window.0 {
      // Scroll up
      self.window.0 = index;
      self.window.1 = self.window.0 + self.max_window_len;
      self.should_refresh_list_cache = true;
      self.state.select(Some(0));
    } else if index >= self.window.1 {
      // Scroll down
      self.window.0 = index.min(self.events.len().saturating_sub(self.max_window_len));
      self.window.1 = self.window.0 + self.max_window_len;
      self.should_refresh_list_cache = true;
      self.state.select(Some(index - self.window.0));
    } else {
      self.state.select(Some(index - self.window.0));
    }
  }

  /// Returns the index(absolute) of the last item in the window
  #[allow(dead_code)]
  fn last_item_in_window_absolute(&self) -> Option<usize> {
    if self.events.is_empty() {
      return None;
    }
    Some(
      self
        .window
        .1
        .saturating_sub(1)
        .min(self.events.len().saturating_sub(1)),
    )
  }

  /// Returns the index(relative) of the last item in the window
  fn last_item_in_window_relative(&self) -> Option<usize> {
    if !self.events.is_empty() {
      Some(
        self
          .window
          .1
          .min(self.events.len())
          .saturating_sub(self.window.0)
          .saturating_sub(1),
      )
    } else {
      None
    }
  }

  fn select_last(&mut self) {
    if !self.events.is_empty() {
      self.state.select(self.last_item_in_window_relative());
    }
  }

  fn select_first(&mut self) {
    if !self.events.is_empty() {
      self.state.select(Some(0));
    }
  }

  /// Try to slide down the window by one item
  /// Returns true if the window was slid down, false otherwise
  pub fn next_window(&mut self) -> bool {
    if self.events.is_empty() {
      return false;
    }
    if self.window.1 < self.events.len() {
      self.window.0 += 1;
      self.window.1 += 1;
      self.should_refresh_list_cache = true;
      true
    } else {
      false
    }
  }

  pub fn previous_window(&mut self) -> bool {
    if self.window.0 > 0 {
      self.window.0 -= 1;
      self.window.1 -= 1;
      self.should_refresh_list_cache = true;
      true
    } else {
      false
    }
  }

  pub fn next(&mut self) {
    // i is the number of the selected item relative to the window
    let i = match self.state.selected() {
      Some(i) => Some(
        if i >= self.window.1 - self.window.0 - 1 {
          self.next_window();
          i
        } else {
          i + 1
        }
        .min(self.nr_items_in_window.saturating_sub(1)),
      ),
      None => {
        if !self.events.is_empty() {
          Some(0)
        } else {
          None
        }
      }
    };
    self.state.select(i);
  }

  pub fn previous(&mut self) {
    let i = match self.state.selected() {
      Some(i) => Some(if i == 0 {
        self.previous_window();
        i
      } else {
        i - 1
      }),
      None => {
        if !self.events.is_empty() {
          Some(0)
        } else {
          None
        }
      }
    };
    self.state.select(i);
  }

  pub fn page_down(&mut self) {
    if self.window.1 + self.max_window_len <= self.events.len() {
      self.window.0 += self.max_window_len;
      self.window.1 += self.max_window_len;
      self.should_refresh_list_cache = true;
    } else {
      // If we can't slide down the window by the number of items in the window
      // just set the window to the last items
      let old_window = self.window;
      self.window.0 = self.events.len().saturating_sub(self.max_window_len);
      self.window.1 = self.window.0 + self.max_window_len;
      self.should_refresh_list_cache = old_window != self.window;
    }
    self.state.select(self.last_item_in_window_relative());
  }

  pub fn page_up(&mut self) {
    // Try to slide up the window by the number of items in the window
    if self.window.0 >= self.max_window_len {
      self.window.0 -= self.max_window_len;
      self.window.1 -= self.max_window_len;
      self.should_refresh_list_cache = true;
    } else {
      // If we can't slide up the window by the number of items in the window
      // just set the window to the first items
      let old_window = self.window;
      self.window.0 = 0;
      self.window.1 = self.window.0 + self.max_window_len;
      self.should_refresh_list_cache = old_window != self.window;
    }
    self.select_first();
  }

  pub fn page_left(&mut self) {
    let old_offset = self.horizontal_offset;
    self.horizontal_offset = self
      .horizontal_offset
      .saturating_sub(self.inner_width as usize);
    if self.horizontal_offset != old_offset {
      self.should_refresh_list_cache = true;
    }
  }

  pub fn page_right(&mut self) {
    let old_offset = self.horizontal_offset;
    self.horizontal_offset = (self.horizontal_offset + self.inner_width as usize)
      .min(self.max_width.saturating_sub(self.inner_width as usize));
    if self.horizontal_offset != old_offset {
      self.should_refresh_list_cache = true;
    }
  }

  pub fn scroll_left(&mut self) {
    if self.horizontal_offset > 0 {
      self.horizontal_offset = self.horizontal_offset.saturating_sub(1);
      self.should_refresh_list_cache = true;
      tracing::trace!(
        "scroll_left: should_refresh_list_cache = {}",
        self.should_refresh_list_cache
      );
    }
  }

  pub fn scroll_right(&mut self) {
    let new_offset =
      (self.horizontal_offset + 1).min(self.max_width.saturating_sub(self.inner_width as usize));
    if new_offset != self.horizontal_offset {
      self.horizontal_offset = new_offset;
      self.should_refresh_list_cache = true;
      tracing::trace!(
        "scroll_right: should_refresh_list_cache = {}",
        self.should_refresh_list_cache
      );
    }
  }

  pub fn scroll_to_top(&mut self) {
    let old_window = self.window;
    self.window.0 = 0;
    self.window.1 = self.max_window_len;
    self.should_refresh_list_cache = old_window != self.window;
    self.select_first();
  }

  pub fn scroll_to_bottom(&mut self) {
    if self.events.is_empty() {
      return;
    }
    let old_window = self.window;
    self.window.0 = self.events.len().saturating_sub(self.max_window_len);
    self.window.1 = self.window.0 + self.max_window_len;
    self.select_last();
    self.should_refresh_list_cache = old_window != self.window;
  }

  pub fn scroll_to_start(&mut self) {
    if self.horizontal_offset > 0 {
      self.horizontal_offset = 0;
      self.should_refresh_list_cache = true;
      tracing::trace!(
        "scroll_to_start: should_refresh_list_cache = {}",
        self.should_refresh_list_cache
      );
    }
  }

  pub fn scroll_to_end(&mut self) {
    let new_offset = self.max_width.saturating_sub(self.inner_width as usize);
    if self.horizontal_offset < new_offset {
      self.horizontal_offset = new_offset;
      self.should_refresh_list_cache = true;
      tracing::trace!(
        "scroll_to_end: should_refresh_list_cache = {}",
        self.should_refresh_list_cache
      );
    }
  }
}