output.rs 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  1. use crate::{
  2. serve::{ansi_buffer::AnsiStringLine, ServeUpdate, WebServer},
  3. BuildStage, BuilderUpdate, Platform, TraceContent, TraceMsg, TraceSrc,
  4. };
  5. use crossterm::{
  6. cursor::{Hide, Show},
  7. event::{
  8. DisableBracketedPaste, DisableFocusChange, EnableBracketedPaste, EnableFocusChange, Event,
  9. EventStream, KeyCode, KeyEvent, KeyEventKind, KeyModifiers,
  10. },
  11. terminal::{disable_raw_mode, enable_raw_mode, Clear, ClearType},
  12. ExecutableCommand,
  13. };
  14. use ratatui::{
  15. prelude::*,
  16. widgets::{Block, BorderType, Borders, LineGauge, Paragraph},
  17. TerminalOptions, Viewport,
  18. };
  19. use std::{
  20. cell::RefCell,
  21. collections::VecDeque,
  22. io::{self, stdout},
  23. rc::Rc,
  24. time::Duration,
  25. };
  26. use tracing::Level;
  27. use super::AppServer;
  28. const TICK_RATE_MS: u64 = 100;
  29. const VIEWPORT_MAX_WIDTH: u16 = 100;
  30. const VIEWPORT_HEIGHT_SMALL: u16 = 5;
  31. const VIEWPORT_HEIGHT_BIG: u16 = 13;
  32. /// The TUI that drives the console output.
  33. ///
  34. /// We try not to store too much state about the world here, just the state about the tui itself.
  35. /// This is to prevent out-of-sync issues with the rest of the build engine and to use the components
  36. /// of the serve engine as the source of truth.
  37. ///
  38. /// Please please, do not add state here that does not belong here. We should only be storing state
  39. /// here that is used to change how we display *other* state. Things like throbbers, modals, etc.
  40. pub struct Output {
  41. term: Rc<RefCell<Option<Terminal<CrosstermBackend<io::Stdout>>>>>,
  42. events: Option<EventStream>,
  43. // A list of all messages from build, dev, app, and more.
  44. more_modal_open: bool,
  45. interactive: bool,
  46. // Whether to show verbose logs or not
  47. // We automatically hide "debug" logs if verbose is false (only showing "info" / "warn" / "error")
  48. verbose: bool,
  49. trace: bool,
  50. // Pending logs
  51. pending_logs: VecDeque<TraceMsg>,
  52. dx_version: String,
  53. tick_animation: bool,
  54. tick_interval: tokio::time::Interval,
  55. // ! needs to be wrapped in an &mut since `render stateful widget` requires &mut... but our
  56. // "render" method only borrows &self (for no particular reason at all...)
  57. throbber: RefCell<throbber_widgets_tui::ThrobberState>,
  58. }
  59. #[derive(Clone, Copy)]
  60. struct RenderState<'a> {
  61. runner: &'a AppServer,
  62. server: &'a WebServer,
  63. }
  64. impl Output {
  65. pub(crate) async fn start(interactive: bool) -> crate::Result<Self> {
  66. let mut output = Self {
  67. interactive,
  68. term: Rc::new(RefCell::new(None)),
  69. dx_version: format!(
  70. "{}-{}",
  71. env!("CARGO_PKG_VERSION"),
  72. crate::dx_build_info::GIT_COMMIT_HASH_SHORT.unwrap_or("main")
  73. ),
  74. events: None,
  75. more_modal_open: false,
  76. pending_logs: VecDeque::new(),
  77. throbber: RefCell::new(throbber_widgets_tui::ThrobberState::default()),
  78. trace: crate::logging::VERBOSITY.get().unwrap().trace,
  79. verbose: crate::logging::VERBOSITY.get().unwrap().verbose,
  80. tick_animation: false,
  81. tick_interval: {
  82. let mut interval = tokio::time::interval(Duration::from_millis(TICK_RATE_MS));
  83. interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
  84. interval
  85. },
  86. };
  87. output.startup()?;
  88. Ok(output)
  89. }
  90. /// Call the startup functions that might mess with the terminal settings.
  91. /// This is meant to be paired with "shutdown" to restore the terminal to its original state.
  92. fn startup(&mut self) -> io::Result<()> {
  93. if self.interactive {
  94. // Check if writing the terminal is going to block infinitely.
  95. // If it does, we should disable interactive mode. This ensures we work with programs like `bg`
  96. // which suspend the process and cause us to block when writing output.
  97. if Self::enable_raw_mode().is_err() {
  98. self.term.take();
  99. self.interactive = false;
  100. return Ok(());
  101. }
  102. self.term.replace(
  103. Terminal::with_options(
  104. CrosstermBackend::new(stdout()),
  105. TerminalOptions {
  106. viewport: Viewport::Inline(VIEWPORT_HEIGHT_SMALL),
  107. },
  108. )
  109. .ok(),
  110. );
  111. // Initialize the event stream here - this is optional because an EvenStream in a non-interactive
  112. // terminal will cause a panic instead of simply doing nothing.
  113. // https://github.com/crossterm-rs/crossterm/issues/659
  114. self.events = Some(EventStream::new());
  115. }
  116. Ok(())
  117. }
  118. /// Enable raw mode, but don't let it block forever.
  119. ///
  120. /// This lets us check if writing to tty is going to block forever and then recover, allowing
  121. /// interopability with programs like `bg`.
  122. fn enable_raw_mode() -> io::Result<()> {
  123. #[cfg(unix)]
  124. {
  125. use tokio::signal::unix::{signal, SignalKind};
  126. // Ignore SIGTSTP, SIGTTIN, and SIGTTOU
  127. _ = signal(SignalKind::from_raw(20))?; // SIGTSTP
  128. _ = signal(SignalKind::from_raw(21))?; // SIGTTIN
  129. _ = signal(SignalKind::from_raw(22))?; // SIGTTOU
  130. }
  131. use std::io::IsTerminal;
  132. if !stdout().is_terminal() {
  133. return io::Result::Err(io::Error::new(io::ErrorKind::Other, "Not a terminal"));
  134. }
  135. enable_raw_mode()?;
  136. stdout()
  137. .execute(Hide)?
  138. .execute(EnableFocusChange)?
  139. .execute(EnableBracketedPaste)?;
  140. Ok(())
  141. }
  142. /// Call the shutdown functions that might mess with the terminal settings - see the related code
  143. /// in "startup" for more details about what we need to unset
  144. pub(crate) fn shutdown(&self) -> io::Result<()> {
  145. Self::remote_shutdown(self.interactive)?;
  146. Ok(())
  147. }
  148. pub(crate) fn remote_shutdown(interactive: bool) -> io::Result<()> {
  149. if interactive {
  150. stdout()
  151. .execute(Show)?
  152. .execute(DisableFocusChange)?
  153. .execute(DisableBracketedPaste)?;
  154. disable_raw_mode()?;
  155. // print a line to force the cursor down (no tearing)
  156. println!();
  157. }
  158. Ok(())
  159. }
  160. pub(crate) async fn wait(&mut self) -> ServeUpdate {
  161. use futures_util::future::OptionFuture;
  162. use futures_util::StreamExt;
  163. if !self.interactive {
  164. return std::future::pending().await;
  165. }
  166. // Wait for the next user event or animation tick
  167. loop {
  168. let next = OptionFuture::from(self.events.as_mut().map(|f| f.next()));
  169. let event = tokio::select! {
  170. biased; // Always choose the event over the animation tick to not lose the event
  171. Some(Some(Ok(event))) = next => event,
  172. _ = self.tick_interval.tick(), if self.tick_animation => {
  173. self.throbber.borrow_mut().calc_next();
  174. return ServeUpdate::Redraw
  175. },
  176. else => futures_util::future::pending().await
  177. };
  178. match self.handle_input(event) {
  179. Ok(Some(update)) => return update,
  180. Err(ee) => {
  181. return ServeUpdate::Exit {
  182. error: Some(Box::new(ee)),
  183. }
  184. }
  185. Ok(None) => {}
  186. }
  187. }
  188. }
  189. /// Handle an input event, returning `true` if the event should cause the program to restart.
  190. fn handle_input(&mut self, input: Event) -> io::Result<Option<ServeUpdate>> {
  191. // handle ctrlc
  192. if let Event::Key(key) = input {
  193. if let KeyCode::Char('c') = key.code {
  194. if key.modifiers.contains(KeyModifiers::CONTROL) {
  195. return Ok(Some(ServeUpdate::Exit { error: None }));
  196. }
  197. }
  198. }
  199. match input {
  200. Event::Key(key) if key.kind == KeyEventKind::Press => self.handle_keypress(key),
  201. _ => Ok(Some(ServeUpdate::Redraw)),
  202. }
  203. }
  204. fn handle_keypress(&mut self, key: KeyEvent) -> io::Result<Option<ServeUpdate>> {
  205. match key.code {
  206. KeyCode::Char('r') => return Ok(Some(ServeUpdate::RequestRebuild)),
  207. KeyCode::Char('o') => return Ok(Some(ServeUpdate::OpenApp)),
  208. KeyCode::Char('p') => return Ok(Some(ServeUpdate::ToggleShouldRebuild)),
  209. KeyCode::Char('v') => {
  210. self.verbose = !self.verbose;
  211. tracing::info!(
  212. "Verbose logging is now {}",
  213. if self.verbose { "on" } else { "off" }
  214. );
  215. }
  216. KeyCode::Char('t') => {
  217. self.trace = !self.trace;
  218. tracing::info!("Tracing is now {}", if self.trace { "on" } else { "off" });
  219. }
  220. KeyCode::Char('c') => {
  221. stdout()
  222. .execute(Clear(ClearType::All))?
  223. .execute(Clear(ClearType::Purge))?;
  224. // Clear the terminal and push the frame to the bottom
  225. _ = self.term.borrow_mut().as_mut().map(|t| {
  226. let frame_rect = t.get_frame().area();
  227. let term_size = t.size().unwrap();
  228. let remaining_space = term_size
  229. .height
  230. .saturating_sub(frame_rect.y + frame_rect.height);
  231. t.insert_before(remaining_space, |_| {})
  232. });
  233. }
  234. // Toggle the more modal by swapping the the terminal with a new one
  235. // This is a bit of a hack since crossterm doesn't technically support changing the
  236. // size of an inline viewport.
  237. KeyCode::Char('/') => {
  238. if let Some(terminal) = self.term.borrow_mut().as_mut() {
  239. // Toggle the more modal, which will change our current viewport height
  240. self.more_modal_open = !self.more_modal_open;
  241. // Clear the terminal before resizing it, such that it doesn't tear
  242. terminal.clear()?;
  243. // And then set the new viewport, which essentially mimics a resize
  244. *terminal = Terminal::with_options(
  245. CrosstermBackend::new(stdout()),
  246. TerminalOptions {
  247. viewport: Viewport::Inline(self.viewport_current_height()),
  248. },
  249. )?;
  250. }
  251. }
  252. _ => {}
  253. }
  254. // Out of safety, we always redraw, since it's relatively cheap operation
  255. Ok(Some(ServeUpdate::Redraw))
  256. }
  257. /// Push a TraceMsg to be printed on the next render
  258. pub fn push_log(&mut self, message: TraceMsg) {
  259. self.pending_logs.push_front(message);
  260. }
  261. pub fn push_cargo_log(&mut self, message: cargo_metadata::CompilerMessage) {
  262. use cargo_metadata::diagnostic::DiagnosticLevel;
  263. if self.trace || !matches!(message.message.level, DiagnosticLevel::Note) {
  264. self.push_log(TraceMsg::cargo(message));
  265. }
  266. }
  267. /// Add a message from stderr to the logs
  268. /// This will queue the stderr message as a TraceMsg and print it on the next render
  269. /// We'll use the `App` TraceSrc for the msg, and whatever level is provided
  270. pub fn push_stdio(&mut self, platform: Platform, msg: String, level: Level) {
  271. self.push_log(TraceMsg::text(TraceSrc::App(platform), level, msg));
  272. }
  273. /// Push a message from the websocket to the logs
  274. pub fn push_ws_message(&mut self, platform: Platform, message: &axum::extract::ws::Message) {
  275. use dioxus_devtools_types::ClientMsg;
  276. // We can only handle text messages from the websocket...
  277. let axum::extract::ws::Message::Text(text) = message else {
  278. return;
  279. };
  280. // ...and then decode them into a ClientMsg
  281. let res = serde_json::from_str::<ClientMsg>(text.as_str());
  282. // Client logs being errors aren't fatal, but we should still report them them
  283. let msg = match res {
  284. Ok(msg) => msg,
  285. Err(err) => {
  286. tracing::error!(dx_src = ?TraceSrc::Dev, "Error parsing message from {}: {} -> {:?}", platform, err, text.as_str());
  287. return;
  288. }
  289. };
  290. let ClientMsg::Log { level, messages } = msg else {
  291. return;
  292. };
  293. // FIXME(jon): why are we pulling only the first message here?
  294. let content = messages.first().unwrap_or(&String::new()).clone();
  295. let level = match level.as_str() {
  296. "trace" => Level::TRACE,
  297. "debug" => Level::DEBUG,
  298. "info" => Level::INFO,
  299. "warn" => Level::WARN,
  300. "error" => Level::ERROR,
  301. _ => Level::INFO,
  302. };
  303. // We don't care about logging the app's message so we directly push it instead of using tracing.
  304. self.push_log(TraceMsg::text(TraceSrc::App(platform), level, content));
  305. }
  306. /// Change internal state based on the build engine's update
  307. ///
  308. /// We want to keep internal state as limited as possible, so currently we're only setting our
  309. /// animation tick. We could, in theory, just leave animation running and have no internal state,
  310. /// but that seems a bit wasteful. We might eventually change this to be more of a "requestAnimationFrame"
  311. /// approach, but then we'd need to do that *everywhere* instead of simply performing a react-like
  312. /// re-render when external state changes. Ratatui will diff the intermediate buffer, so we at least
  313. /// we won't be drawing it.
  314. pub(crate) fn new_build_update(&mut self, update: &BuilderUpdate) {
  315. match update {
  316. BuilderUpdate::Progress {
  317. stage: BuildStage::Starting { .. },
  318. } => self.tick_animation = true,
  319. BuilderUpdate::BuildReady { .. } => self.tick_animation = false,
  320. BuilderUpdate::BuildFailed { .. } => self.tick_animation = false,
  321. _ => {}
  322. }
  323. }
  324. /// Render the current state of everything to the console screen
  325. pub fn render(&mut self, runner: &AppServer, server: &WebServer) {
  326. if !self.interactive {
  327. return;
  328. }
  329. // Get a handle to the terminal with a different lifetime so we can continue to call &self methods
  330. let owned_term = self.term.clone();
  331. let mut term = owned_term.borrow_mut();
  332. let Some(term) = term.as_mut() else {
  333. return;
  334. };
  335. // First, dequeue any logs that have built up from event handling
  336. _ = self.drain_logs(term);
  337. // Then, draw the frame, passing along all the state of the TUI so we can render it properly
  338. _ = term.draw(|frame| {
  339. self.render_frame(frame, RenderState { runner, server });
  340. });
  341. }
  342. fn render_frame(&self, frame: &mut Frame, state: RenderState) {
  343. // Use the max size of the viewport, but shrunk to a sensible max width
  344. let mut area = frame.area();
  345. area.width = area.width.clamp(0, VIEWPORT_MAX_WIDTH);
  346. let [_top, body, _bottom] = Layout::vertical([
  347. Constraint::Length(1),
  348. Constraint::Fill(1),
  349. Constraint::Length(1),
  350. ])
  351. .horizontal_margin(1)
  352. .areas(area);
  353. self.render_borders(frame, area);
  354. self.render_body(frame, body, state);
  355. self.render_body_title(frame, _top, state);
  356. }
  357. fn render_body_title(&self, frame: &mut Frame<'_>, area: Rect, _state: RenderState) {
  358. frame.render_widget(
  359. Line::from(vec![
  360. " ".dark_gray(),
  361. match self.more_modal_open {
  362. true => "/:more".light_yellow(),
  363. false => "/:more".dark_gray(),
  364. },
  365. " ".dark_gray(),
  366. ])
  367. .right_aligned(),
  368. area,
  369. );
  370. }
  371. fn render_body(&self, frame: &mut Frame<'_>, area: Rect, state: RenderState) {
  372. let [_title, body, more, _foot] = Layout::vertical([
  373. Constraint::Length(0),
  374. Constraint::Length(VIEWPORT_HEIGHT_SMALL - 2),
  375. Constraint::Fill(1),
  376. Constraint::Length(0),
  377. ])
  378. .horizontal_margin(1)
  379. .areas(area);
  380. let [col1, col2] = Layout::horizontal([Constraint::Length(50), Constraint::Fill(1)])
  381. .horizontal_margin(1)
  382. .areas(body);
  383. self.render_gauges(frame, col1, state);
  384. self.render_stats(frame, col2, state);
  385. if self.more_modal_open {
  386. self.render_more_modal(frame, more, state);
  387. }
  388. }
  389. fn render_gauges(&self, frame: &mut Frame<'_>, area: Rect, state: RenderState) {
  390. let [gauge_area, _margin] =
  391. Layout::horizontal([Constraint::Fill(1), Constraint::Length(3)]).areas(area);
  392. let [app_progress, second_progress, status_line]: [_; 3] = Layout::vertical([
  393. Constraint::Length(1),
  394. Constraint::Length(1),
  395. Constraint::Length(1),
  396. ])
  397. .areas(gauge_area);
  398. let client = &state.runner.client();
  399. self.render_single_gauge(
  400. frame,
  401. app_progress,
  402. client.compile_progress(),
  403. "App: ",
  404. state,
  405. client.compile_duration(),
  406. );
  407. if state.runner.is_fullstack() {
  408. self.render_single_gauge(
  409. frame,
  410. second_progress,
  411. state.runner.server_compile_progress(),
  412. "Server: ",
  413. state,
  414. client.compile_duration(),
  415. );
  416. } else {
  417. self.render_single_gauge(
  418. frame,
  419. second_progress,
  420. client.bundle_progress(),
  421. "Bundle: ",
  422. state,
  423. client.bundle_duration(),
  424. );
  425. }
  426. let mut lines = vec!["Status: ".white()];
  427. match &client.stage {
  428. BuildStage::Initializing => lines.push("Initializing".yellow()),
  429. BuildStage::Starting { patch, .. } => {
  430. if *patch {
  431. lines.push("Hot-patching...".yellow())
  432. } else {
  433. lines.push("Starting build".yellow())
  434. }
  435. }
  436. BuildStage::InstallingTooling => lines.push("Installing tooling".yellow()),
  437. BuildStage::Compiling {
  438. current,
  439. total,
  440. krate,
  441. ..
  442. } => {
  443. lines.push("Compiling ".yellow());
  444. lines.push(format!("{current}/{total} ").gray());
  445. lines.push(krate.as_str().dark_gray())
  446. }
  447. BuildStage::OptimizingWasm => lines.push("Optimizing wasm".yellow()),
  448. BuildStage::SplittingBundle => lines.push("Splitting bundle".yellow()),
  449. BuildStage::CompressingAssets => lines.push("Compressing assets".yellow()),
  450. BuildStage::RunningBindgen => lines.push("Running wasm-bindgen".yellow()),
  451. BuildStage::RunningGradle => lines.push("Running gradle assemble".yellow()),
  452. BuildStage::Bundling => lines.push("Bundling app".yellow()),
  453. BuildStage::CopyingAssets {
  454. current,
  455. total,
  456. path,
  457. } => {
  458. lines.push("Copying asset ".yellow());
  459. lines.push(format!("{current}/{total} ").gray());
  460. if let Some(name) = path.file_name().and_then(|f| f.to_str()) {
  461. lines.push(name.dark_gray())
  462. }
  463. }
  464. BuildStage::Success => {
  465. lines.push("Serving ".yellow());
  466. lines.push(client.build.executable_name().white());
  467. lines.push(" 🚀 ".green());
  468. if let Some(comp_time) = client.total_build_time() {
  469. lines.push(format!("{:.1}s", comp_time.as_secs_f32()).dark_gray());
  470. }
  471. }
  472. BuildStage::Failed => lines.push("Failed".red()),
  473. BuildStage::Aborted => lines.push("Aborted".red()),
  474. BuildStage::Restarting => lines.push("Restarting".yellow()),
  475. BuildStage::Linking => lines.push("Linking".yellow()),
  476. BuildStage::Hotpatching => lines.push("Hot-patching...".yellow()),
  477. BuildStage::ExtractingAssets => lines.push("Extracting assets".yellow()),
  478. _ => {}
  479. };
  480. frame.render_widget(Line::from(lines), status_line);
  481. }
  482. fn render_single_gauge(
  483. &self,
  484. frame: &mut Frame<'_>,
  485. area: Rect,
  486. value: f64,
  487. label: &str,
  488. state: RenderState,
  489. time_taken: Option<Duration>,
  490. ) {
  491. let failed = state.runner.client.stage == BuildStage::Failed;
  492. let value = if failed { 1.0 } else { value.clamp(0.0, 1.0) };
  493. let [gauge_row, _, icon] = Layout::horizontal([
  494. Constraint::Fill(1),
  495. Constraint::Length(2),
  496. Constraint::Length(10),
  497. ])
  498. .areas(area);
  499. frame.render_widget(
  500. LineGauge::default()
  501. .filled_style(Style::default().fg(match value {
  502. 1.0 if failed => Color::Red,
  503. 1.0 => Color::Green,
  504. _ => Color::Yellow,
  505. }))
  506. .unfilled_style(Style::default().fg(Color::DarkGray))
  507. .label(label.gray())
  508. .line_set(symbols::line::THICK)
  509. .ratio(if !failed { value } else { 1.0 }),
  510. gauge_row,
  511. );
  512. let [throbber_frame, time_frame] = Layout::default()
  513. .direction(Direction::Horizontal)
  514. .constraints([Constraint::Length(3), Constraint::Fill(1)])
  515. .areas(icon);
  516. if value != 1.0 {
  517. let throb = throbber_widgets_tui::Throbber::default()
  518. .style(ratatui::style::Style::default().fg(ratatui::style::Color::Cyan))
  519. .throbber_style(
  520. ratatui::style::Style::default()
  521. .fg(ratatui::style::Color::White)
  522. .add_modifier(ratatui::style::Modifier::BOLD),
  523. )
  524. .throbber_set(throbber_widgets_tui::BLACK_CIRCLE)
  525. .use_type(throbber_widgets_tui::WhichUse::Spin);
  526. frame.render_stateful_widget(throb, throbber_frame, &mut self.throbber.borrow_mut());
  527. } else {
  528. frame.render_widget(
  529. Line::from(vec![if failed {
  530. "❌ ".white()
  531. } else {
  532. "🎉 ".white()
  533. }])
  534. .left_aligned(),
  535. throbber_frame,
  536. );
  537. }
  538. if let Some(time_taken) = time_taken {
  539. if !failed {
  540. frame.render_widget(
  541. Line::from(vec![format!("{:.1}s", time_taken.as_secs_f32()).dark_gray()])
  542. .left_aligned(),
  543. time_frame,
  544. );
  545. }
  546. }
  547. }
  548. fn render_stats(&self, frame: &mut Frame<'_>, area: Rect, state: RenderState) {
  549. let [current_platform, app_features, serve_address]: [_; 3] = Layout::vertical([
  550. Constraint::Length(1),
  551. Constraint::Length(1),
  552. Constraint::Length(1),
  553. ])
  554. .areas(area);
  555. let client = &state.runner.client();
  556. frame.render_widget(
  557. Paragraph::new(Line::from(vec![
  558. "Platform: ".gray(),
  559. client.build.platform.expected_name().yellow(),
  560. if state.runner.is_fullstack() {
  561. " + fullstack".yellow()
  562. } else {
  563. " ".dark_gray()
  564. },
  565. ])),
  566. current_platform,
  567. );
  568. self.render_feature_list(frame, app_features, state);
  569. // todo(jon) should we write https ?
  570. let address = match state.server.displayed_address() {
  571. Some(address) => format!("http://{}", address).blue(),
  572. None => "no server address".dark_gray(),
  573. };
  574. frame.render_widget_ref(
  575. Paragraph::new(Line::from(vec![
  576. if client.build.platform == Platform::Web {
  577. "Serving at: ".gray()
  578. } else {
  579. "ServerFns at: ".gray()
  580. },
  581. address,
  582. ])),
  583. serve_address,
  584. );
  585. }
  586. fn render_feature_list(&self, frame: &mut Frame<'_>, area: Rect, state: RenderState) {
  587. frame.render_widget(
  588. Paragraph::new(Line::from({
  589. let mut lines = vec!["App features: ".gray(), "[".yellow()];
  590. let feature_list: Vec<String> = state.runner.client().build.all_target_features();
  591. let num_features = feature_list.len();
  592. for (idx, feature) in feature_list.into_iter().enumerate() {
  593. lines.push("\"".yellow());
  594. lines.push(feature.yellow());
  595. lines.push("\"".yellow());
  596. if idx != num_features - 1 {
  597. lines.push(", ".dark_gray());
  598. }
  599. }
  600. lines.push("]".yellow());
  601. lines
  602. })),
  603. area,
  604. );
  605. }
  606. fn render_more_modal(&self, frame: &mut Frame<'_>, area: Rect, state: RenderState) {
  607. let [col1, col2] =
  608. Layout::horizontal([Constraint::Length(50), Constraint::Fill(1)]).areas(area);
  609. let [top, bottom] = Layout::vertical([Constraint::Fill(1), Constraint::Length(2)])
  610. .horizontal_margin(1)
  611. .areas(col1);
  612. let meta_list: [_; 6] = Layout::vertical([
  613. Constraint::Length(1), // spacing
  614. Constraint::Length(1), // item 1
  615. Constraint::Length(1), // item 2
  616. Constraint::Length(1), // item 3
  617. Constraint::Length(1), // item 4
  618. Constraint::Length(1), // Spacing
  619. ])
  620. .areas(top);
  621. frame.render_widget(
  622. Paragraph::new(Line::from(vec![
  623. "dx version: ".gray(),
  624. self.dx_version.as_str().yellow(),
  625. ])),
  626. meta_list[1],
  627. );
  628. frame.render_widget(
  629. Paragraph::new(Line::from(vec![
  630. "rustc: ".gray(),
  631. state.runner.workspace.rustc_version.as_str().yellow(),
  632. ])),
  633. meta_list[2],
  634. );
  635. frame.render_widget(
  636. Paragraph::new(Line::from(vec![
  637. "Hotreload: ".gray(),
  638. "rsx and assets".yellow(),
  639. ])),
  640. meta_list[3],
  641. );
  642. let server_address = match state.server.server_address() {
  643. Some(address) => format!("http://{}", address).yellow(),
  644. None => "no address".dark_gray(),
  645. };
  646. frame.render_widget(
  647. Paragraph::new(Line::from(vec!["Network: ".gray(), server_address])),
  648. meta_list[4],
  649. );
  650. let links_list: [_; 2] =
  651. Layout::vertical([Constraint::Length(1), Constraint::Length(1)]).areas(bottom);
  652. frame.render_widget(
  653. Paragraph::new(Line::from(vec![
  654. "Read the docs: ".gray(),
  655. "https://dioxuslabs.com/0.6/docs".blue(),
  656. ])),
  657. links_list[0],
  658. );
  659. frame.render_widget(
  660. Paragraph::new(Line::from(vec![
  661. "Video tutorials: ".gray(),
  662. "https://youtube.com/@DioxusLabs".blue(),
  663. ])),
  664. links_list[1],
  665. );
  666. let cmds = [
  667. "",
  668. "r: rebuild the app",
  669. "o: open the app",
  670. "p: pause rebuilds",
  671. "v: toggle verbose logs",
  672. "t: toggle tracing logs ",
  673. "c: clear the screen",
  674. "/: toggle more commands",
  675. ];
  676. let layout: [_; 8] = Layout::vertical(cmds.iter().map(|_| Constraint::Length(1)))
  677. .horizontal_margin(1)
  678. .areas(col2);
  679. for (idx, cmd) in cmds.iter().enumerate() {
  680. if cmd.is_empty() {
  681. continue;
  682. }
  683. let (cmd, detail) = cmd.split_once(": ").unwrap_or((cmd, ""));
  684. frame.render_widget(
  685. Paragraph::new(Line::from(vec![
  686. cmd.gray(),
  687. ": ".gray(),
  688. detail.dark_gray(),
  689. ])),
  690. layout[idx],
  691. );
  692. }
  693. }
  694. /// Render borders around the terminal, forcing an inner clear while we're at it
  695. fn render_borders(&self, frame: &mut Frame, area: Rect) {
  696. frame.render_widget(ratatui::widgets::Clear, area);
  697. frame.render_widget(
  698. Block::default()
  699. .borders(Borders::ALL)
  700. .border_type(BorderType::Rounded)
  701. .border_style(Style::default().fg(Color::DarkGray)),
  702. area,
  703. );
  704. }
  705. /// Print logs to the terminal as close to a regular "println!()" as possible.
  706. ///
  707. /// We don't want alternate screens or other terminal tricks because we want these logs to be as
  708. /// close to real as possible. Once the log is printed, it is lost, so we need to be very careful
  709. /// here to not print it incorrectly.
  710. ///
  711. /// This method works by printing lines at the top of the viewport frame, and then scrolling up
  712. /// the viewport accordingly, such that our final call to "clear" will cause the terminal the viewport
  713. /// to be comlpetely erased and rewritten. This is slower since we're going around ratatui's diff
  714. /// logic, but it's the only way to do this that gives us "true println!" semantics.
  715. ///
  716. /// In the future, Ratatui's insert_before method will get scroll regions, which will make this logic
  717. /// much simpler. In that future, we'll simply insert a line into the scrollregion which should automatically
  718. /// force that portion of the terminal to scroll up.
  719. ///
  720. /// TODO(jon): we could look into implementing scroll regions ourselves, but I think insert_before will
  721. /// land in a reasonable amount of time.
  722. #[deny(clippy::manual_saturating_arithmetic)]
  723. fn drain_logs(
  724. &mut self,
  725. terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
  726. ) -> io::Result<()> {
  727. use unicode_segmentation::UnicodeSegmentation;
  728. let Some(log) = self.pending_logs.pop_back() else {
  729. return Ok(());
  730. };
  731. // Only show debug logs if verbose is enabled
  732. if log.level == Level::DEBUG && !self.verbose {
  733. return Ok(());
  734. }
  735. if log.level == Level::TRACE && !self.trace {
  736. return Ok(());
  737. }
  738. // Grab out the size and location of the terminal and its viewport before we start messing with it
  739. let frame_rect = terminal.get_frame().area();
  740. let term_size = terminal.size().unwrap();
  741. // Render the log into an ansi string
  742. // We're going to add some metadata to it like the timestamp and source and then dump it to the raw ansi sequences we need to send to crossterm
  743. let lines = Self::tracemsg_to_ansi_string(log);
  744. // Get the lines of the output sequence and their overflow
  745. let lines_printed = lines
  746. .iter()
  747. .map(|line| {
  748. // Very important to strip ansi codes before counting graphemes - the ansi codes count as multiple graphemes!
  749. let grapheme_count = console::strip_ansi_codes(line).graphemes(true).count();
  750. grapheme_count.max(1).div_ceil(term_size.width as usize) as u16
  751. })
  752. .sum::<u16>();
  753. // The viewport might be clipped, but the math still needs to work out.
  754. let actual_vh_height = self.viewport_current_height().min(term_size.height);
  755. // Move the terminal's cursor down to the number of lines printed
  756. let remaining_space = term_size
  757. .height
  758. .saturating_sub(frame_rect.y + frame_rect.height);
  759. // Calculate how many lines we need to push back
  760. // - padding equals lines_printed when the frame is at the bottom
  761. // - padding is zero when the remaining space is greater/equal than the scrollback (the frame will get pushed naturally)
  762. // Determine what extra padding is remaining after we've shifted the terminal down
  763. // this will be the distance between the final line and the top of the frame, only if the
  764. // final line has extended into the frame
  765. let final_line = frame_rect.y + lines_printed;
  766. let max_frame_top = term_size.height - actual_vh_height;
  767. let padding = final_line
  768. .saturating_sub(max_frame_top)
  769. .clamp(0, actual_vh_height - 1);
  770. // The only reliable way we can force the terminal downards is through "insert_before".
  771. //
  772. // If we need to push the terminal down, we'll use this method with the number of lines
  773. // Ratatui will handle this rest.
  774. //
  775. // This also calls `.clear()` so we don't need to call clear at the end of this function.
  776. //
  777. // FIXME(jon): eventually insert_before will get scroll regions, breaking this, but making the logic here simpler
  778. terminal.insert_before(remaining_space.min(lines_printed), |_| {})?;
  779. // Wipe the viewport clean so it doesn't tear
  780. crossterm::queue!(
  781. std::io::stdout(),
  782. crossterm::cursor::MoveTo(0, frame_rect.y),
  783. crossterm::terminal::Clear(ClearType::FromCursorDown),
  784. )?;
  785. // Start printing the log by writing on top of the topmost line
  786. for (idx, line) in lines.into_iter().enumerate() {
  787. // Move the cursor to the correct line offset but don't go past the bottom of the terminal
  788. let start = frame_rect.y + idx as u16;
  789. let start = start.min(term_size.height - 1);
  790. crossterm::queue!(
  791. std::io::stdout(),
  792. crossterm::cursor::MoveTo(0, start),
  793. crossterm::style::Print(line),
  794. crossterm::style::Print("\n"),
  795. )?;
  796. }
  797. // Scroll the terminal if we need to
  798. for _ in 0..padding {
  799. crossterm::queue!(
  800. std::io::stdout(),
  801. crossterm::cursor::MoveTo(0, term_size.height - 1),
  802. crossterm::style::Print("\n"),
  803. )?;
  804. }
  805. Ok(())
  806. }
  807. fn viewport_current_height(&self) -> u16 {
  808. match self.more_modal_open {
  809. true => VIEWPORT_HEIGHT_BIG,
  810. false => VIEWPORT_HEIGHT_SMALL,
  811. }
  812. }
  813. fn tracemsg_to_ansi_string(log: TraceMsg) -> Vec<String> {
  814. use ansi_to_tui::IntoText;
  815. use chrono::Timelike;
  816. let rendered = match log.content {
  817. TraceContent::Cargo(msg) => msg.message.rendered.unwrap_or_default(),
  818. TraceContent::Text(text) => text,
  819. };
  820. let mut lines = vec![];
  821. for (idx, raw_line) in rendered.lines().enumerate() {
  822. let line_as_text = raw_line.into_text().unwrap();
  823. let is_pretending_to_be_frame = !raw_line.is_empty()
  824. && raw_line
  825. .chars()
  826. .all(|c| c == '=' || c == '-' || c == ' ' || c == '─');
  827. for (subline_idx, mut line) in line_as_text.lines.into_iter().enumerate() {
  828. if idx == 0 && subline_idx == 0 {
  829. let mut formatted_line = Line::default();
  830. formatted_line.push_span(
  831. Span::raw(format!(
  832. "{:02}:{:02}:{:02} ",
  833. log.timestamp.hour(),
  834. log.timestamp.minute(),
  835. log.timestamp.second()
  836. ))
  837. .dark_gray(),
  838. );
  839. formatted_line.push_span(
  840. Span::raw(format!(
  841. "[{src}] {padding}",
  842. src = log.source,
  843. padding =
  844. " ".repeat(3usize.saturating_sub(log.source.to_string().len()))
  845. ))
  846. .style(match log.source {
  847. TraceSrc::App(_platform) => Style::new().blue(),
  848. TraceSrc::Dev => Style::new().magenta(),
  849. TraceSrc::Build => Style::new().yellow(),
  850. TraceSrc::Bundle => Style::new().magenta(),
  851. TraceSrc::Cargo => Style::new().yellow(),
  852. TraceSrc::Unknown => Style::new().gray(),
  853. }),
  854. );
  855. for span in line.spans {
  856. formatted_line.push_span(span);
  857. }
  858. line = formatted_line;
  859. }
  860. if is_pretending_to_be_frame {
  861. line = line.dark_gray();
  862. }
  863. // Create the ansi -> raw string line with a width of either the viewport width or the max width
  864. let line_length = line.styled_graphemes(Style::default()).count();
  865. if line_length < u16::MAX as usize {
  866. lines.push(AnsiStringLine::new(line_length as _).render(&line));
  867. } else {
  868. lines.push(line.to_string())
  869. }
  870. }
  871. }
  872. lines
  873. }
  874. }