🐝 I really like where this mua is(was?) headed, but it seems as though there has not been much activity recently.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1066 lines
38 KiB

3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
  1. /*
  2. * meli
  3. *
  4. * Copyright 2017-2018 Manos Pitsidianakis
  5. *
  6. * This file is part of meli.
  7. *
  8. * meli is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * meli is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with meli. If not, see <http://www.gnu.org/licenses/>.
  20. */
  21. /*! The application's state.
  22. The UI crate has an Box<dyn Component>-Component-System design. The System part, is also the application's state, so they're both merged in the `State` struct.
  23. `State` owns all the Components of the UI. In the application's main event loop, input is handed to the state in the form of `UIEvent` objects which traverse the component graph. Components decide to handle each input or not.
  24. Input is received in the main loop from threads which listen on the stdin for user input, observe folders for file changes etc. The relevant struct is `ThreadEvent`.
  25. */
  26. use super::*;
  27. use crate::plugins::PluginManager;
  28. use melib::backends::{AccountHash, MailboxHash, NotifyFn};
  29. use crossbeam::channel::{unbounded, Receiver, Sender};
  30. use smallvec::SmallVec;
  31. use std::collections::HashMap;
  32. use std::env;
  33. use std::io::Write;
  34. use std::os::unix::io::RawFd;
  35. use std::thread;
  36. use termion::raw::IntoRawMode;
  37. use termion::screen::AlternateScreen;
  38. use termion::{clear, cursor};
  39. pub type StateStdout = termion::screen::AlternateScreen<termion::raw::RawTerminal<std::io::Stdout>>;
  40. struct InputHandler {
  41. pipe: (RawFd, RawFd),
  42. rx: Receiver<InputCommand>,
  43. tx: Sender<InputCommand>,
  44. }
  45. impl InputHandler {
  46. fn restore(&self, tx: Sender<ThreadEvent>) {
  47. /* Clear channel without blocking. switch_to_main_screen() issues a kill when
  48. * returning from a fork and there's no input thread, so the newly created thread will
  49. * receive it and die. */
  50. //let _ = self.rx.try_iter().count();
  51. let rx = self.rx.clone();
  52. let pipe = self.pipe.0;
  53. thread::Builder::new()
  54. .name("input-thread".to_string())
  55. .spawn(move || {
  56. get_events(
  57. |i| {
  58. tx.send(ThreadEvent::Input(i)).unwrap();
  59. },
  60. &rx,
  61. pipe,
  62. )
  63. })
  64. .unwrap();
  65. }
  66. fn kill(&self) {
  67. let _ = nix::unistd::write(self.pipe.1, &[1]);
  68. self.tx.send(InputCommand::Kill).unwrap();
  69. }
  70. }
  71. /// A context container for loaded settings, accounts, UI changes, etc.
  72. pub struct Context {
  73. pub accounts: Vec<Account>,
  74. pub account_hashes: HashMap<AccountHash, usize>,
  75. pub settings: Settings,
  76. pub runtime_settings: Settings,
  77. /// Areas of the screen that must be redrawn in the next render
  78. pub dirty_areas: VecDeque<Area>,
  79. /// Events queue that components send back to the state
  80. pub replies: VecDeque<UIEvent>,
  81. sender: Sender<ThreadEvent>,
  82. receiver: Receiver<ThreadEvent>,
  83. input: InputHandler,
  84. work_controller: WorkController,
  85. pub children: Vec<std::process::Child>,
  86. pub plugin_manager: PluginManager,
  87. pub temp_files: Vec<File>,
  88. }
  89. impl Context {
  90. pub fn replies(&mut self) -> smallvec::SmallVec<[UIEvent; 8]> {
  91. self.replies.drain(0..).collect()
  92. }
  93. pub fn input_kill(&self) {
  94. self.input.kill();
  95. }
  96. pub fn restore_input(&self) {
  97. self.input.restore(self.sender.clone());
  98. }
  99. pub fn is_online(&mut self, account_pos: usize) -> Result<()> {
  100. let Context {
  101. ref mut accounts,
  102. ref mut replies,
  103. ..
  104. } = self;
  105. let was_online = accounts[account_pos].is_online;
  106. let ret = accounts[account_pos].is_online();
  107. if ret.is_ok() {
  108. if !was_online {
  109. for mailbox_node in accounts[account_pos].list_mailboxes() {
  110. debug!(
  111. "hash & mailbox: {:?} {}",
  112. mailbox_node.hash,
  113. accounts[account_pos][&mailbox_node.hash].name()
  114. );
  115. }
  116. /* Account::watch() needs
  117. * - work_controller to pass `work_context` to the watcher threads and then add them
  118. * to the controller's static thread list,
  119. * - sender to pass a RefreshEventConsumer closure to watcher threads for them to
  120. * inform the main binary that refresh events arrived
  121. * - replies to report any failures to the user
  122. */
  123. accounts[account_pos].watch();
  124. replies.push_back(UIEvent::AccountStatusChange(account_pos));
  125. }
  126. }
  127. ret
  128. }
  129. pub fn work_controller(&self) -> &WorkController {
  130. &self.work_controller
  131. }
  132. }
  133. /// A State object to manage and own components and components of the UI. `State` is responsible for
  134. /// managing the terminal and interfacing with `melib`
  135. pub struct State {
  136. cols: usize,
  137. rows: usize,
  138. grid: CellBuffer,
  139. overlay_grid: CellBuffer,
  140. draw_rate_limit: RateLimit,
  141. stdout: Option<StateStdout>,
  142. child: Option<ForkType>,
  143. draw_horizontal_segment_fn: fn(&mut CellBuffer, &mut StateStdout, usize, usize, usize) -> (),
  144. pub mode: UIMode,
  145. overlay: Vec<Box<dyn Component>>,
  146. components: Vec<Box<dyn Component>>,
  147. pub context: Context,
  148. timer: thread::JoinHandle<()>,
  149. display_messages: SmallVec<[DisplayMessage; 8]>,
  150. display_messages_expiration_start: Option<UnixTimestamp>,
  151. display_messages_active: bool,
  152. display_messages_pos: usize,
  153. }
  154. #[derive(Debug)]
  155. struct DisplayMessage {
  156. timestamp: UnixTimestamp,
  157. msg: String,
  158. }
  159. impl Drop for State {
  160. fn drop(&mut self) {
  161. // When done, restore the defaults to avoid messing with the terminal.
  162. self.switch_to_main_screen();
  163. use nix::sys::wait::{waitpid, WaitPidFlag};
  164. for child in self.context.children.iter_mut() {
  165. if let Err(err) = waitpid(
  166. nix::unistd::Pid::from_raw(child.id() as i32),
  167. Some(WaitPidFlag::WNOHANG),
  168. ) {
  169. debug!("Failed to wait on subprocess {}: {}", child.id(), err);
  170. }
  171. }
  172. if let Some(ForkType::Embed(child_pid)) = self.child.take() {
  173. /* Try wait, we don't want to block */
  174. if let Err(e) = waitpid(child_pid, Some(WaitPidFlag::WNOHANG)) {
  175. debug!("Failed to wait on subprocess {}: {}", child_pid, e);
  176. }
  177. }
  178. }
  179. }
  180. impl State {
  181. pub fn new(sender: Sender<ThreadEvent>, receiver: Receiver<ThreadEvent>) -> Result<Self> {
  182. /*
  183. * Create async channel to block the input-thread if we need to fork and stop it from reading
  184. * stdin, see get_events() for details
  185. * */
  186. let input_thread = unbounded();
  187. let input_thread_pipe = nix::unistd::pipe()
  188. .map_err(|err| Box::new(err) as Box<dyn std::error::Error + Send + Sync + 'static>)?;
  189. let mut backends = Backends::new();
  190. let settings = Settings::new()?;
  191. let mut plugin_manager = PluginManager::new();
  192. for (_, p) in settings.plugins.clone() {
  193. if crate::plugins::PluginKind::Backend == p.kind() {
  194. debug!("registering {:?}", &p);
  195. crate::plugins::backend::PluginBackend::register(
  196. plugin_manager.listener(),
  197. p.clone(),
  198. &mut backends,
  199. );
  200. }
  201. plugin_manager.register(p)?;
  202. }
  203. let termsize = termion::terminal_size()?;
  204. let cols = termsize.0 as usize;
  205. let rows = termsize.1 as usize;
  206. let mut account_hashes = HashMap::with_capacity_and_hasher(1, Default::default());
  207. let work_controller = WorkController::new(sender.clone());
  208. let accounts: Vec<Account> = {
  209. let mut file_accs = settings
  210. .accounts
  211. .iter()
  212. .collect::<Vec<(&String, &AccountConf)>>();
  213. file_accs.sort_by(|a, b| a.0.cmp(&b.0));
  214. file_accs
  215. .into_iter()
  216. .enumerate()
  217. .map(|(index, (n, a_s))| {
  218. let sender = sender.clone();
  219. let account_hash = {
  220. use std::collections::hash_map::DefaultHasher;
  221. use std::hash::Hasher;
  222. let mut hasher = DefaultHasher::new();
  223. hasher.write(n.as_bytes());
  224. hasher.finish()
  225. };
  226. account_hashes.insert(account_hash, index);
  227. Account::new(
  228. index,
  229. account_hash,
  230. n.to_string(),
  231. a_s.clone(),
  232. &backends,
  233. work_controller.get_context(),
  234. sender.clone(),
  235. NotifyFn::new(Box::new(move |f: MailboxHash| {
  236. sender
  237. .send(ThreadEvent::UIEvent(UIEvent::WorkerProgress(
  238. account_hash,
  239. f,
  240. )))
  241. .unwrap();
  242. })),
  243. )
  244. })
  245. .collect::<Result<Vec<Account>>>()?
  246. };
  247. let timer = {
  248. let sender = sender.clone();
  249. thread::Builder::new().spawn(move || {
  250. let sender = sender;
  251. loop {
  252. thread::park();
  253. sender.send(ThreadEvent::Pulse).unwrap();
  254. thread::sleep(std::time::Duration::from_millis(100));
  255. }
  256. })
  257. }?;
  258. timer.thread().unpark();
  259. let mut s = State {
  260. cols,
  261. rows,
  262. grid: CellBuffer::new(cols, rows, Cell::with_char(' ')),
  263. overlay_grid: CellBuffer::new(cols, rows, Cell::with_char(' ')),
  264. stdout: None,
  265. child: None,
  266. mode: UIMode::Normal,
  267. components: Vec::with_capacity(8),
  268. overlay: Vec::new(),
  269. timer,
  270. draw_rate_limit: RateLimit::new(1, 3),
  271. draw_horizontal_segment_fn: if settings.terminal.use_color() {
  272. State::draw_horizontal_segment
  273. } else {
  274. State::draw_horizontal_segment_no_color
  275. },
  276. display_messages: SmallVec::new(),
  277. display_messages_expiration_start: None,
  278. display_messages_pos: 0,
  279. display_messages_active: false,
  280. context: Context {
  281. accounts,
  282. account_hashes,
  283. settings: settings.clone(),
  284. runtime_settings: settings,
  285. dirty_areas: VecDeque::with_capacity(5),
  286. replies: VecDeque::with_capacity(5),
  287. temp_files: Vec::new(),
  288. work_controller,
  289. children: vec![],
  290. plugin_manager,
  291. sender,
  292. receiver,
  293. input: InputHandler {
  294. pipe: input_thread_pipe,
  295. rx: input_thread.1,
  296. tx: input_thread.0,
  297. },
  298. },
  299. };
  300. s.draw_rate_limit
  301. .timer
  302. .set_value(std::time::Duration::from_millis(3));
  303. if s.context.settings.terminal.ascii_drawing {
  304. s.grid.set_ascii_drawing(true);
  305. s.overlay_grid.set_ascii_drawing(true);
  306. }
  307. s.switch_to_alternate_screen();
  308. debug!("inserting mailbox hashes:");
  309. for i in 0..s.context.accounts.len() {
  310. if s.context.is_online(i).is_ok() && s.context.accounts[i].is_empty() {
  311. return Err(MeliError::new(format!(
  312. "Account {} has no mailboxes configured.",
  313. s.context.accounts[i].name()
  314. )));
  315. }
  316. }
  317. s.context.restore_input();
  318. Ok(s)
  319. }
  320. /*
  321. * When we receive a mailbox hash from a watcher thread,
  322. * we match the hash to the index of the mailbox, request a reload
  323. * and startup a thread to remind us to poll it every now and then till it's finished.
  324. */
  325. pub fn refresh_event(&mut self, event: RefreshEvent) {
  326. let account_hash = event.account_hash();
  327. let mailbox_hash = event.mailbox_hash();
  328. if let Some(&idxa) = self.context.account_hashes.get(&account_hash) {
  329. if self.context.accounts[idxa]
  330. .mailbox_entries
  331. .contains_key(&mailbox_hash)
  332. {
  333. if self.context.accounts[idxa].load(mailbox_hash).is_err() {
  334. self.context.replies.push_back(UIEvent::from(event));
  335. return;
  336. }
  337. let Context {
  338. ref mut accounts, ..
  339. } = &mut self.context;
  340. if let Some(notification) = accounts[idxa].reload(event, mailbox_hash) {
  341. if let UIEvent::Notification(_, _, _) = notification {
  342. self.rcv_event(UIEvent::MailboxUpdate((idxa, mailbox_hash)));
  343. }
  344. self.rcv_event(notification);
  345. }
  346. } else {
  347. if let melib::backends::RefreshEventKind::Failure(err) = event.kind() {
  348. debug!(err);
  349. }
  350. }
  351. }
  352. }
  353. pub fn new_thread(&mut self, id: thread::ThreadId, name: String) {
  354. self.context
  355. .work_controller
  356. .static_threads
  357. .lock()
  358. .unwrap()
  359. .insert(id, name.into());
  360. }
  361. /// Switch back to the terminal's main screen (The command line the user sees before opening
  362. /// the application)
  363. pub fn switch_to_main_screen(&mut self) {
  364. write!(
  365. self.stdout(),
  366. "{}{}{}{}",
  367. termion::screen::ToMainScreen,
  368. cursor::Show,
  369. RestoreWindowTitleIconFromStack,
  370. BracketModeEnd,
  371. )
  372. .unwrap();
  373. self.flush();
  374. self.stdout = None;
  375. }
  376. pub fn switch_to_alternate_screen(&mut self) {
  377. let s = std::io::stdout();
  378. let mut stdout = AlternateScreen::from(s.into_raw_mode().unwrap());
  379. write!(
  380. &mut stdout,
  381. "{save_title_to_stack}{}{}{}{window_title}{}{}",
  382. termion::screen::ToAlternateScreen,
  383. cursor::Hide,
  384. clear::All,
  385. cursor::Goto(1, 1),
  386. BracketModeStart,
  387. save_title_to_stack = SaveWindowTitleIconToStack,
  388. window_title = if let Some(ref title) = self.context.settings.terminal.window_title {
  389. format!("\x1b]2;{}\x07", title)
  390. } else {
  391. String::new()
  392. },
  393. )
  394. .unwrap();
  395. self.stdout = Some(stdout);
  396. self.flush();
  397. }
  398. pub fn receiver(&self) -> Receiver<ThreadEvent> {
  399. self.context.receiver.clone()
  400. }
  401. pub fn sender(&self) -> Sender<ThreadEvent> {
  402. self.context.sender.clone()
  403. }
  404. pub fn restore_input(&mut self) {
  405. self.context.restore_input();
  406. }
  407. /// On `SIGWNICH` the `State` redraws itself according to the new terminal size.
  408. pub fn update_size(&mut self) {
  409. let termsize = termion::terminal_size().ok();
  410. let termcols = termsize.map(|(w, _)| w);
  411. let termrows = termsize.map(|(_, h)| h);
  412. if termcols.unwrap_or(72) as usize != self.cols
  413. || termrows.unwrap_or(120) as usize != self.rows
  414. {
  415. debug!(
  416. "Size updated, from ({}, {}) -> ({:?}, {:?})",
  417. self.cols, self.rows, termcols, termrows
  418. );
  419. }
  420. self.cols = termcols.unwrap_or(72) as usize;
  421. self.rows = termrows.unwrap_or(120) as usize;
  422. self.grid.resize(self.cols, self.rows, Cell::with_char(' '));
  423. self.overlay_grid
  424. .resize(self.cols, self.rows, Cell::with_char(' '));
  425. self.rcv_event(UIEvent::Resize);
  426. // Invalidate dirty areas.
  427. self.context.dirty_areas.clear();
  428. }
  429. /// Force a redraw for all dirty components.
  430. pub fn redraw(&mut self) {
  431. if !self.draw_rate_limit.tick() {
  432. return;
  433. }
  434. for i in 0..self.components.len() {
  435. self.draw_component(i);
  436. }
  437. let mut areas: smallvec::SmallVec<[Area; 8]> =
  438. self.context.dirty_areas.drain(0..).collect();
  439. if self.display_messages_active {
  440. let now = melib::datetime::now();
  441. if self
  442. .display_messages_expiration_start
  443. .map(|t| t + 5 < now)
  444. .unwrap_or(false)
  445. {
  446. self.display_messages_active = false;
  447. self.display_messages_expiration_start = None;
  448. areas.push((
  449. (0, 0),
  450. (self.cols.saturating_sub(1), self.rows.saturating_sub(1)),
  451. ));
  452. }
  453. }
  454. /* Sort by x_start, ie upper_left corner's x coordinate */
  455. areas.sort_by(|a, b| (a.0).0.partial_cmp(&(b.0).0).unwrap());
  456. /* draw each dirty area */
  457. let rows = self.rows;
  458. for y in 0..rows {
  459. let mut segment = None;
  460. for ((x_start, y_start), (x_end, y_end)) in &areas {
  461. if y < *y_start || y > *y_end {
  462. continue;
  463. }
  464. if let Some((x_start, x_end)) = segment.take() {
  465. (self.draw_horizontal_segment_fn)(
  466. &mut self.grid,
  467. self.stdout.as_mut().unwrap(),
  468. x_start,
  469. x_end,
  470. y,
  471. );
  472. }
  473. match segment {
  474. ref mut s @ None => {
  475. *s = Some((*x_start, *x_end));
  476. }
  477. ref mut s @ Some(_) if s.unwrap().1 < *x_start => {
  478. (self.draw_horizontal_segment_fn)(
  479. &mut self.grid,
  480. self.stdout.as_mut().unwrap(),
  481. s.unwrap().0,
  482. s.unwrap().1,
  483. y,
  484. );
  485. *s = Some((*x_start, *x_end));
  486. }
  487. ref mut s @ Some(_) if s.unwrap().1 < *x_end => {
  488. (self.draw_horizontal_segment_fn)(
  489. &mut self.grid,
  490. self.stdout.as_mut().unwrap(),
  491. s.unwrap().0,
  492. s.unwrap().1,
  493. y,
  494. );
  495. *s = Some((s.unwrap().1, *x_end));
  496. }
  497. Some((_, ref mut x)) => {
  498. *x = *x_end;
  499. }
  500. }
  501. }
  502. if let Some((x_start, x_end)) = segment {
  503. (self.draw_horizontal_segment_fn)(
  504. &mut self.grid,
  505. self.stdout.as_mut().unwrap(),
  506. x_start,
  507. x_end,
  508. y,
  509. );
  510. }
  511. }
  512. if self.display_messages_active {
  513. if let Some(DisplayMessage {
  514. ref timestamp,
  515. ref msg,
  516. ..
  517. }) = self.display_messages.get(self.display_messages_pos)
  518. {
  519. let noto_colors = crate::conf::value(&self.context, "status.notification");
  520. use crate::melib::text_processing::{Reflow, TextProcessing};
  521. let msg_lines = msg.split_lines_reflow(Reflow::All, Some(self.cols / 3));
  522. let width = msg_lines
  523. .iter()
  524. .map(|line| line.grapheme_len() + 4)
  525. .max()
  526. .unwrap_or(0);
  527. let displ_area = place_in_area(
  528. (
  529. (0, 0),
  530. (self.cols.saturating_sub(1), self.rows.saturating_sub(1)),
  531. ),
  532. (width, std::cmp::min(self.rows, msg_lines.len() + 4)),
  533. false,
  534. false,
  535. );
  536. for row in self.overlay_grid.bounds_iter(displ_area) {
  537. for c in row {
  538. self.overlay_grid[c]
  539. .set_ch(' ')
  540. .set_fg(noto_colors.fg)
  541. .set_bg(noto_colors.bg)
  542. .set_attrs(noto_colors.attrs);
  543. }
  544. }
  545. let ((x, mut y), box_displ_area_bottom_right) =
  546. create_box(&mut self.overlay_grid, displ_area);
  547. for line in msg_lines
  548. .into_iter()
  549. .chain(Some(String::new()))
  550. .chain(Some(melib::datetime::timestamp_to_string(*timestamp, None)))
  551. {
  552. write_string_to_grid(
  553. &line,
  554. &mut self.overlay_grid,
  555. noto_colors.fg,
  556. noto_colors.bg,
  557. noto_colors.attrs,
  558. ((x, y), box_displ_area_bottom_right),
  559. Some(x),
  560. );
  561. y += 1;
  562. }
  563. if self.display_messages.len() > 1 {
  564. write_string_to_grid(
  565. if self.display_messages_pos == 0 {
  566. "Next: >"
  567. } else if self.display_messages_pos + 1 == self.display_messages.len() {
  568. "Prev: <"
  569. } else {
  570. "Prev: <, Next: >"
  571. },
  572. &mut self.overlay_grid,
  573. noto_colors.fg,
  574. noto_colors.bg,
  575. noto_colors.attrs,
  576. ((x, y), box_displ_area_bottom_right),
  577. Some(x),
  578. );
  579. }
  580. for y in get_y(upper_left!(displ_area))..=get_y(bottom_right!(displ_area)) {
  581. (self.draw_horizontal_segment_fn)(
  582. &mut self.overlay_grid,
  583. self.stdout.as_mut().unwrap(),
  584. get_x(upper_left!(displ_area)),
  585. get_x(bottom_right!(displ_area)),
  586. y,
  587. );
  588. }
  589. }
  590. }
  591. if !self.overlay.is_empty() {
  592. let area = center_area(
  593. (
  594. (0, 0),
  595. (self.cols.saturating_sub(1), self.rows.saturating_sub(1)),
  596. ),
  597. (
  598. if self.cols / 3 > 30 {
  599. self.cols / 3
  600. } else {
  601. self.cols
  602. },
  603. if self.rows / 5 > 10 {
  604. self.rows / 5
  605. } else {
  606. self.rows
  607. },
  608. ),
  609. );
  610. copy_area(&mut self.overlay_grid, &mut self.grid, area, area);
  611. self.overlay
  612. .get_mut(0)
  613. .unwrap()
  614. .draw(&mut self.overlay_grid, area, &mut self.context);
  615. for y in get_y(upper_left!(area))..=get_y(bottom_right!(area)) {
  616. (self.draw_horizontal_segment_fn)(
  617. &mut self.overlay_grid,
  618. self.stdout.as_mut().unwrap(),
  619. get_x(upper_left!(area)),
  620. get_x(bottom_right!(area)),
  621. y,
  622. );
  623. }
  624. }
  625. self.flush();
  626. }
  627. /// Draw only a specific `area` on the screen.
  628. fn draw_horizontal_segment(
  629. grid: &mut CellBuffer,
  630. stdout: &mut StateStdout,
  631. x_start: usize,
  632. x_end: usize,
  633. y: usize,
  634. ) {
  635. write!(
  636. stdout,
  637. "{}",
  638. cursor::Goto(x_start as u16 + 1, (y + 1) as u16)
  639. )
  640. .unwrap();
  641. let mut current_fg = Color::Default;
  642. let mut current_bg = Color::Default;
  643. let mut current_attrs = Attr::DEFAULT;
  644. write!(stdout, "\x1B[m").unwrap();
  645. for x in x_start..=x_end {
  646. let c = &grid[(x, y)];
  647. if c.attrs() != current_attrs {
  648. c.attrs().write(current_attrs, stdout).unwrap();
  649. current_attrs = c.attrs();
  650. }
  651. if c.bg() != current_bg {
  652. c.bg().write_bg(stdout).unwrap();
  653. current_bg = c.bg();
  654. }
  655. if c.fg() != current_fg {
  656. c.fg().write_fg(stdout).unwrap();
  657. current_fg = c.fg();
  658. }
  659. if !c.empty() {
  660. write!(stdout, "{}", c.ch()).unwrap();
  661. }
  662. }
  663. }
  664. fn draw_horizontal_segment_no_color(
  665. grid: &mut CellBuffer,
  666. stdout: &mut StateStdout,
  667. x_start: usize,
  668. x_end: usize,
  669. y: usize,
  670. ) {
  671. write!(
  672. stdout,
  673. "{}",
  674. cursor::Goto(x_start as u16 + 1, (y + 1) as u16)
  675. )
  676. .unwrap();
  677. let mut current_attrs = Attr::DEFAULT;
  678. write!(stdout, "\x1B[m").unwrap();
  679. for x in x_start..=x_end {
  680. let c = &grid[(x, y)];
  681. if c.attrs() != current_attrs {
  682. c.attrs().write(current_attrs, stdout).unwrap();
  683. current_attrs = c.attrs();
  684. }
  685. if !c.empty() {
  686. write!(stdout, "{}", c.ch()).unwrap();
  687. }
  688. }
  689. }
  690. /// Draw the entire screen from scratch.
  691. pub fn render(&mut self) {
  692. self.update_size();
  693. let cols = self.cols;
  694. let rows = self.rows;
  695. self.context
  696. .dirty_areas
  697. .push_back(((0, 0), (cols - 1, rows - 1)));
  698. self.redraw();
  699. }
  700. pub fn draw_component(&mut self, idx: usize) {
  701. let component = &mut self.components[idx];
  702. let upper_left = (0, 0);
  703. let bottom_right = (self.cols - 1, self.rows - 1);
  704. if component.is_dirty() {
  705. component.draw(
  706. &mut self.grid,
  707. (upper_left, bottom_right),
  708. &mut self.context,
  709. );
  710. }
  711. }
  712. pub fn can_quit_cleanly(&mut self) -> bool {
  713. let State {
  714. ref mut components,
  715. ref context,
  716. ..
  717. } = self;
  718. components.iter_mut().all(|c| c.can_quit_cleanly(context))
  719. }
  720. pub fn register_component(&mut self, component: Box<dyn Component>) {
  721. self.components.push(component);
  722. }
  723. /// Convert user commands to actions/method calls.
  724. fn exec_command(&mut self, cmd: Action) {
  725. match cmd {
  726. SetEnv(key, val) => {
  727. env::set_var(key.as_str(), val.as_str());
  728. }
  729. PrintEnv(key) => {
  730. self.context
  731. .replies
  732. .push_back(UIEvent::StatusEvent(StatusEvent::DisplayMessage(
  733. env::var(key.as_str()).unwrap_or_else(|e| e.to_string()),
  734. )));
  735. }
  736. Mailbox(account_name, op) => {
  737. if let Some(account) = self
  738. .context
  739. .accounts
  740. .iter_mut()
  741. .find(|a| a.name() == account_name)
  742. {
  743. match account.mailbox_operation(op) {
  744. Err(err) => {
  745. self.context.replies.push_back(UIEvent::StatusEvent(
  746. StatusEvent::DisplayMessage(err.to_string()),
  747. ));
  748. }
  749. Ok(msg) => {
  750. self.context.replies.push_back(UIEvent::StatusEvent(
  751. StatusEvent::DisplayMessage(format!("`{}`: {}", account_name, msg)),
  752. ));
  753. }
  754. }
  755. } else {
  756. self.context.replies.push_back(UIEvent::StatusEvent(
  757. StatusEvent::DisplayMessage(format!(
  758. "Account with name `{}` not found.",
  759. account_name
  760. )),
  761. ));
  762. }
  763. }
  764. AccountAction(ref account_name, ReIndex) => {
  765. #[cfg(feature = "sqlite3")]
  766. match crate::sqlite3::index(&mut self.context, account_name) {
  767. Ok(()) => {
  768. self.context.replies.push_back(UIEvent::Notification(
  769. None,
  770. "Message index rebuild started.".to_string(),
  771. Some(NotificationType::INFO),
  772. ));
  773. }
  774. Err(e) => {
  775. self.context.replies.push_back(UIEvent::Notification(
  776. None,
  777. format!("Message index rebuild failed: {}.", e),
  778. Some(NotificationType::ERROR),
  779. ));
  780. }
  781. }
  782. #[cfg(not(feature = "sqlite3"))]
  783. {
  784. self.context.replies.push_back(UIEvent::Notification(
  785. None,
  786. "Message index rebuild failed: meli is not built with sqlite3 support."
  787. .to_string(),
  788. Some(NotificationType::ERROR),
  789. ));
  790. }
  791. }
  792. v => {
  793. self.rcv_event(UIEvent::Action(v));
  794. }
  795. }
  796. }
  797. /// The application's main loop sends `UIEvents` to state via this method.
  798. pub fn rcv_event(&mut self, mut event: UIEvent) {
  799. if let UIEvent::Input(_) = event {
  800. if self.display_messages_expiration_start.is_none() {
  801. self.display_messages_expiration_start = Some(melib::datetime::now());
  802. }
  803. }
  804. match event {
  805. // Command type is handled only by State.
  806. UIEvent::Command(cmd) => {
  807. if let Ok(action) = parse_command(&cmd.as_bytes()) {
  808. if action.needs_confirmation() {
  809. self.overlay.push(Box::new(UIConfirmationDialog::new(
  810. "You sure?",
  811. vec![(true, "yes".to_string()), (false, "no".to_string())],
  812. true,
  813. Some(Box::new(move |id: ComponentId, result: bool| {
  814. Some(UIEvent::FinishedUIDialog(
  815. id,
  816. Box::new(if result { Some(action) } else { None }),
  817. ))
  818. })),
  819. &mut self.context,
  820. )));
  821. } else {
  822. self.exec_command(action);
  823. }
  824. } else {
  825. self.context.replies.push_back(UIEvent::StatusEvent(
  826. StatusEvent::DisplayMessage("invalid command".to_string()),
  827. ));
  828. }
  829. return;
  830. }
  831. UIEvent::Fork(ForkType::Finished) => {
  832. /*
  833. * Fork has finished in the past.
  834. * We're back in the AlternateScreen, but the cursor is reset to Shown, so fix
  835. * it.
  836. write!(self.stdout(), "{}", cursor::Hide,).unwrap();
  837. self.flush();
  838. */
  839. self.switch_to_main_screen();
  840. self.switch_to_alternate_screen();
  841. self.context.restore_input();
  842. return;
  843. }
  844. UIEvent::Fork(ForkType::Generic(child)) => {
  845. self.context.children.push(child);
  846. return;
  847. }
  848. UIEvent::Fork(child) => {
  849. self.mode = UIMode::Fork;
  850. self.child = Some(child);
  851. return;
  852. }
  853. UIEvent::WorkerProgress(account_hash, mailbox_hash) => {
  854. if let Some(&account_idx) = self.context.account_hashes.get(&account_hash) {
  855. let _ = self.context.accounts[account_idx].load(mailbox_hash);
  856. }
  857. return;
  858. }
  859. UIEvent::ChangeMode(m) => {
  860. self.context
  861. .sender
  862. .send(ThreadEvent::UIEvent(UIEvent::ChangeMode(m)))
  863. .unwrap();
  864. }
  865. UIEvent::Timer(id) if id == self.draw_rate_limit.id() => {
  866. self.draw_rate_limit.reset();
  867. self.redraw();
  868. return;
  869. }
  870. UIEvent::Input(Key::Alt('<')) => {
  871. self.display_messages_expiration_start = Some(melib::datetime::now());
  872. self.display_messages_active = true;
  873. self.display_messages_pos = self.display_messages_pos.saturating_sub(1);
  874. return;
  875. }
  876. UIEvent::Input(Key::Alt('>')) => {
  877. self.display_messages_expiration_start = Some(melib::datetime::now());
  878. self.display_messages_active = true;
  879. self.display_messages_pos = std::cmp::min(
  880. self.display_messages.len().saturating_sub(1),
  881. self.display_messages_pos + 1,
  882. );
  883. return;
  884. }
  885. UIEvent::StatusEvent(StatusEvent::DisplayMessage(ref msg)) => {
  886. self.display_messages.push(DisplayMessage {
  887. timestamp: melib::datetime::now(),
  888. msg: msg.clone(),
  889. });
  890. self.display_messages_active = true;
  891. self.display_messages_expiration_start = None;
  892. self.display_messages_pos = self.display_messages.len() - 1;
  893. self.redraw();
  894. }
  895. UIEvent::FinishedUIDialog(ref id, ref mut results)
  896. if self.overlay.iter().any(|c| c.id() == *id) =>
  897. {
  898. if let Some(Some(ref mut action)) = results.downcast_mut::<Option<Action>>() {
  899. self.exec_command(std::mem::replace(action, Action::ToggleThreadSnooze));
  900. let pos = self.overlay.iter().position(|c| c.id() == *id).unwrap();
  901. self.overlay.remove(pos);
  902. return;
  903. }
  904. }
  905. UIEvent::GlobalUIDialog(dialog) => {
  906. self.overlay.push(dialog);
  907. return;
  908. }
  909. _ => {}
  910. }
  911. let Self {
  912. ref mut components,
  913. ref mut context,
  914. ref mut overlay,
  915. ..
  916. } = self;
  917. /* inform each component */
  918. for c in overlay.iter_mut().chain(components.iter_mut()) {
  919. if c.process_event(&mut event, context) {
  920. break;
  921. }
  922. }
  923. if !self.context.replies.is_empty() {
  924. let replies: smallvec::SmallVec<[UIEvent; 8]> =
  925. self.context.replies.drain(0..).collect();
  926. // Pass replies to self and call count on the map iterator to force evaluation
  927. replies.into_iter().map(|r| self.rcv_event(r)).count();
  928. }
  929. }
  930. pub fn try_wait_on_child(&mut self) -> Option<bool> {
  931. let should_return_flag = match self.child {
  932. Some(ForkType::NewDraft(_, ref mut c)) => {
  933. let w = c.try_wait();
  934. match w {
  935. Ok(Some(_)) => true,
  936. Ok(None) => false,
  937. Err(e) => {
  938. log(
  939. format!("Failed to wait on editor process: {}", e.to_string()),
  940. ERROR,
  941. );
  942. return None;
  943. }
  944. }
  945. }
  946. Some(ForkType::Generic(ref mut c)) => {
  947. let w = c.try_wait();
  948. match w {
  949. Ok(Some(_)) => true,
  950. Ok(None) => false,
  951. Err(e) => {
  952. log(
  953. format!("Failed to wait on child process: {}", e.to_string()),
  954. ERROR,
  955. );
  956. return None;
  957. }
  958. }
  959. }
  960. Some(ForkType::Finished) => {
  961. /* Fork has already finished */
  962. std::mem::replace(&mut self.child, None);
  963. return None;
  964. }
  965. _ => {
  966. return None;
  967. }
  968. };
  969. if should_return_flag {
  970. return Some(true);
  971. }
  972. Some(false)
  973. }
  974. fn flush(&mut self) {
  975. if let Some(s) = self.stdout.as_mut() {
  976. s.flush().unwrap();
  977. }
  978. }
  979. fn stdout(&mut self) -> &mut StateStdout {
  980. self.stdout.as_mut().unwrap()
  981. }
  982. pub fn check_accounts(&mut self) {
  983. let mut ctr = 0;
  984. for i in 0..self.context.accounts.len() {
  985. if self.context.is_online(i).is_ok() {
  986. ctr += 1;
  987. }
  988. }
  989. if ctr != self.context.accounts.len() {
  990. self.timer.thread().unpark();
  991. }
  992. }
  993. }