From d641f6211696cbd550e68b21be1218fe4d937c87 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Tue, 20 Oct 2026 16:42:12 +0800 Subject: [PATCH] feat: build a resizable native developer workspace with console and network inspection --- README.md | 54 +- src/README.md | 17 +- src/activity.rs | 90 ++ src/api.rs | 173 +++- src/app.rs | 172 +++- src/developer_tools.rs | 1674 ++++++++++++++++++++++++++++++++------ src/display_list.rs | 2 + src/endor_host.rs | 38 + src/main.rs | 7 +- src/scene.rs | 14 +- src/software_renderer.rs | 49 +- src/sources.rs | 53 ++ 12 files changed, 2042 insertions(+), 301 deletions(-) create mode 100644 src/activity.rs create mode 100644 src/sources.rs diff --git a/README.md b/README.md index ef03fad..af29e2d 100644 --- a/README.md +++ b/README.md @@ -169,11 +169,55 @@ source budgets and VM instruction limits are not a complete untrusted-code sandb ## Developer tools -Toggle the sidebar with Command-Option-I or F12 on macOS, Control-Shift-I or F12 -on Windows/Linux. It displays Aster AST functions, bindings, calls and expressions. -Selection shows their ranges in the exact submitted source. Tessera does not -maintain a second language AST. Source lines and tree labels are fitted to the -available measured width; truncation preserves Unicode grapheme clusters. +Toggle developer tools with Command-Option-I or F12 on macOS, Control-Shift-I or +F12 on Windows/Linux. The compact Console, Sources, Network and Settings tabs +share a draggable dock edge. Console's editor boundary, the Sources tree/source +boundary and Network's request/details boundary can also be dragged. Each content +area has independent vertical and horizontal scrolling, draggable scrollbar thumbs, +and trackpad support. Shift-wheel scrolls horizontally. Layout uses logical pixels +and the actual display scale; resize clamps pane sizes to keep controls reachable. + +Console is the default execution transcript. Type an expression, press Enter to +run, or Shift-Enter for a newline. Switch to Script mode to PUT a **complete source +replacement** that renders a page. Arrow keys, Home/End, grapheme-safe deletion, +selection of all input, macOS copy/cut/paste and IME composition are supported. +Up/Down recall single-line history; Command/Control-Up/Down also recall history in +multiline input. Clicking the editor positions the caret. HTTP requests from other +clients appear in the same transcript with input, result, error and diagnostics. +Clear hides the displayed transcript; history stays in memory for this window. +Transport failures are shown beside the editor and restore an otherwise empty draft. + +Expression mode sends `POST /v1/namespaces/app.main/evaluate` as `text/plain`. +It accepts exactly one Aster expression and returns JSON with `value`, +`execution: "isolated-expression"` and `persistent: false`. It uses a disposable VM, +without `ui` or previous bindings, and never changes the page or committed revision. +For example, `"Hello Endor"` and `42` return values. Language operations unsupported +by the pinned Aster compiler (currently including numeric arithmetic bytecode) +produce actual diagnostics. Evaluation shares the eight-entry execution queue. +**Persistent REPL sessions are not connected.** Console history is a transcript, +not VM state; Tessera never replays old input to simulate persistence. + +Sources shows the full last successful source snapshot with line numbers, Aster's +AST and selected source ranges. Selecting an AST node scrolls to its location while +keeping the entire file available. Cloud files has a separate file navigator and +source viewer, initially disconnected. The `CloudSourceProvider` boundary in +`src/sources.rs` supplies file identities/paths and full source on open; there is no +cloud backend, fake file listing or source persistence in this release. + +Network observes only HTTP requests handled by this Tessera process on +`127.0.0.1:4737`, including pending requests, method, path, status, server duration, +request/response headers and bodies. Filter matches method, path or status. Clear +clears the Network view without changing the document or Console transcript. A bounded +ring retains 80 requests with explicitly marked 32 KiB body previews. Request +headers are allowlisted to Content-Type and Content-Length; credentials and cookies +are not captured. No external browser or operating-system traffic is represented. +Console and Network share the bounded capture ring and have independent clear +markers. Clicking a Console record opens its Network details and restores that view. + +Settings applies six accent presets or a custom six-digit hex color immediately. +Very bright custom colors are darkened to keep accents visible on white. Execution +separators, selected tabs and focus indicators use the accent, while text keeps its +readable neutral/error/success colors. Settings and source remain in memory only. ## Validation diff --git a/src/README.md b/src/README.md index 1708d04..cd6a0af 100644 --- a/src/README.md +++ b/src/README.md @@ -3,7 +3,8 @@ | Module | Responsibility | | --- | --- | | main.rs | Native window event loop, namespace state and API startup | -| api.rs | Code CRUD, eight-entry execution queue, worker, submission ordering and diagnostics | +| api.rs | Code CRUD, isolated expression endpoint, eight-entry worker queue, request observation and diagnostics | +| activity.rs | Bounded in-memory HTTP exchanges with marked previews and allowlisted request headers | | endor_host.rs | Aster compilation, fresh candidate VM, bounded script/module execution, root cleanup and AST developer tree | | endor_script.rs | Batch complete inputs for Aster's Interactive parser/compiler, retain Module entry, and rebase Aster spans to the original snapshot | | ui_bridge.rs | Tessera UI/page payloads and bound render methods, preallocated node/page pools and native snapshot extraction | @@ -11,10 +12,11 @@ | document.rs | Published source/AST/UI snapshot, revisions, invalidation, frame validation and display commands | | app.rs | Window events, redraw and developer-tools input | | scene.rs | Page and developer-tools display-list composition | -| developer_tools.rs | Aster AST tree selection and corresponding source display | +| developer_tools.rs | Console input/transcript, full Sources, Network inspector, theme, pane/scroll geometry and focus | +| sources.rs | Disconnected cloud workspace and provider boundary for listing/opening complete source files | | display_list.rs | Rendering primitives and color representation | | geometry.rs | Native points and rectangles | -| software_renderer.rs | Software rasterization of the display list | +| software_renderer.rs | Software rasterization and nested rectangular clipping for independently scrolling panes | | text.rs | Shared system font discovery, shaping, real measurements, antialiased glyphs and bounded caches | | README.md | Module map | @@ -44,3 +46,12 @@ antialiasing and transparency. A process-wide mutex keeps font discovery, shapin and glyph caches shared between the worker's layout and window redraw. The 256-string/512-KiB source cache and 4096-glyph/32-MiB image cache are discarded when their budgets are exceeded. See the [project guide](../README.md) for public behavior. + +The expression endpoint deliberately uses Aster's Expression entry in a fresh VM; +it has no host UI, no history replay and no published document. API observation +notifies the window for accepted and completed requests, including failures. The +worker still owns source compilation and snapshot publication. Console sends real +loopback HTTP requests on a separate client thread and reports transport failures +through the native event loop. CloudSourceProvider is an optional host-side adapter, +not a cloud service. A future network adapter should deliver cached/asynchronous +results to the workspace rather than block the native event loop during I/O. diff --git a/src/activity.rs b/src/activity.rs new file mode 100644 index 0000000..3774fca --- /dev/null +++ b/src/activity.rs @@ -0,0 +1,90 @@ +//! Bounded observation of this process's local HTTP API, never external traffic. +use std::{ + collections::VecDeque, + sync::{Arc, Mutex}, + time::{Instant, SystemTime, UNIX_EPOCH}, +}; + +pub type Activity = Arc>; +pub const BODY_PREVIEW: usize = 32 * 1024; +const MAX_RECORDS: usize = 80; + +#[derive(Clone, Debug)] +pub struct Exchange { + pub id: u64, + pub method: String, + pub path: String, + pub origin: String, + pub timestamp: String, + pub request: String, + pub response: String, + pub status: Option, + pub elapsed_ms: u128, + pub request_headers: String, + pub response_headers: String, + started: Instant, +} + +#[derive(Debug, Default)] +pub struct ActivityLog { + pub records: VecDeque, + next_id: u64, +} +impl ActivityLog { + pub fn begin(&mut self, method: String, path: String, origin: String, headers: String) -> u64 { + self.next_id += 1; + let id = self.next_id; + let seconds = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs() + % 86400; + self.records.push_back(Exchange { + id, + method, + path: preview(&path), + origin, + timestamp: format!( + "{:02}:{:02}:{:02} UTC", + seconds / 3600, + seconds / 60 % 60, + seconds % 60 + ), + request: String::new(), + response: String::new(), + status: None, + elapsed_ms: 0, + request_headers: preview(&headers), + response_headers: String::new(), + started: Instant::now(), + }); + while self.records.len() > MAX_RECORDS { + self.records.pop_front(); + } + id + } + pub fn body(&mut self, id: u64, body: &str) { + if let Some(record) = self.records.iter_mut().find(|r| r.id == id) { + record.request = preview(body); + } + } + pub fn finish(&mut self, id: u64, status: u16, body: &str, headers: String) { + if let Some(record) = self.records.iter_mut().find(|r| r.id == id) { + record.status = Some(status); + record.response = preview(body); + record.elapsed_ms = record.started.elapsed().as_millis(); + record.response_headers = preview(&headers); + } + } +} + +pub fn preview(value: &str) -> String { + if value.len() <= BODY_PREVIEW { + return value.to_owned(); + } + let mut end = BODY_PREVIEW; + while !value.is_char_boundary(end) { + end -= 1; + } + format!("{}\n[preview truncated at 32 KiB]", &value[..end]) +} diff --git a/src/api.rs b/src/api.rs index 7ad96dc..cebdbbc 100644 --- a/src/api.rs +++ b/src/api.rs @@ -1,6 +1,8 @@ use std::{ io::Read, + ops::{Deref, DerefMut}, panic::{AssertUnwindSafe, catch_unwind}, + sync::Mutex, sync::{ Arc, RwLock, mpsc::{SyncSender, TrySendError, sync_channel}, @@ -12,14 +14,20 @@ use anyhow::{Context as _, Result}; use tiny_http::{Header, Method, Request, Response, Server, StatusCode}; use winit::event_loop::EventLoopProxy; -use crate::{app::AppEvent, document::NamespaceState, endor_host}; +use crate::{ + activity::{Activity, ActivityLog}, + app::AppEvent, + document::NamespaceState, + endor_host, +}; pub const API_ADDRESS: &str = "127.0.0.1:4737"; const MAX_CODE_SIZE: u64 = endor_host::MAX_SOURCE_BYTES as u64; type Notify = Arc; struct BuildRequest { - request: Request, + request: ObservedRequest, + evaluate: bool, source: String, namespace: String, submission: u64, @@ -28,21 +36,45 @@ struct BuildRequest { pub fn start( namespace: Arc>, proxy: EventLoopProxy, -) -> Result<()> { +) -> Result { let server = Server::http(API_ADDRESS) .map_err(|error| anyhow::anyhow!(error)) .with_context(|| format!("bind Tessera API to {API_ADDRESS}"))?; let notify: Notify = Arc::new(move || { let _ = proxy.send_event(AppEvent::DocumentUpdated); }); - start_server(Arc::new(server), namespace, notify)?; - Ok(()) + let activity = Arc::new(Mutex::new(ActivityLog::default())); + start_server_observed( + Arc::new(server), + namespace, + notify.clone(), + activity.clone(), + notify, + )?; + Ok(activity) } +#[cfg(test)] fn start_server( server: Arc, namespace: Arc>, notify: Notify, +) -> Result> { + start_server_observed( + server, + namespace, + notify, + Arc::new(Mutex::new(ActivityLog::default())), + Arc::new(|| {}), + ) +} + +fn start_server_observed( + server: Arc, + namespace: Arc>, + notify: Notify, + activity: Activity, + observer_notify: Notify, ) -> Result> { let (sender, receiver) = sync_channel::(8); let worker_namespace = namespace.clone(); @@ -60,18 +92,104 @@ fn start_server( .name("tessera-agent-api".to_owned()) .spawn(move || { for request in server.incoming_requests() { - handle(request, &namespace, ¬ify, &sender); + handle( + request, + &namespace, + ¬ify, + &sender, + &activity, + &observer_notify, + ); } }) .context("start Tessera agent API thread") } +// Capture only allowlisted headers: credentials and cookies never enter the inspector. +struct ObservedRequest { + inner: Request, + activity: Activity, + id: u64, + notify: Notify, +} +impl ObservedRequest { + fn new(inner: Request, activity: Activity, notify: Notify) -> Self { + let headers = inner + .headers() + .iter() + .filter(|h| h.field.equiv("Content-Type") || h.field.equiv("Content-Length")) + .map(ToString::to_string) + .collect::>() + .join("\n"); + let origin = if inner + .headers() + .iter() + .any(|h| h.field.equiv("X-Tessera-Origin") && h.value.as_str() == "console") + { + "Console" + } else { + "HTTP" + } + .to_owned(); + let id = activity.lock().unwrap().begin( + inner.method().to_string(), + inner.url().to_owned(), + origin, + headers, + ); + notify(); + Self { + inner, + activity, + id, + notify, + } + } + fn record_body(&self, body: &str) { + self.activity.lock().unwrap().body(self.id, body); + (self.notify)(); + } + fn respond(self, response: Response>>) -> std::io::Result<()> { + let status = response.status_code(); + let headers = response.headers().to_vec(); + let length = response.data_length(); + let reader = response.into_reader(); + self.activity.lock().unwrap().finish( + self.id, + status.0, + &String::from_utf8_lossy(reader.get_ref()), + headers + .iter() + .map(ToString::to_string) + .collect::>() + .join("\n"), + ); + (self.notify)(); + self.inner + .respond(Response::new(status, headers, reader, length, None)) + } +} +impl Deref for ObservedRequest { + type Target = Request; + fn deref(&self) -> &Request { + &self.inner + } +} +impl DerefMut for ObservedRequest { + fn deref_mut(&mut self) -> &mut Request { + &mut self.inner + } +} + fn handle( request: Request, namespace: &Arc>, notify: &Notify, sender: &SyncSender, + activity: &Activity, + observer_notify: &Notify, ) { + let request = ObservedRequest::new(request, activity.clone(), observer_notify.clone()); let method = request.method().clone(); let path = request .url() @@ -80,10 +198,16 @@ fn handle( .unwrap_or(request.url()) .to_owned(); - if method == Method::Put + let evaluation = path + .strip_suffix("/evaluate") + .and_then(|prefix| prefix.strip_prefix("/v1/namespaces/")); + if (method == Method::Put || method == Method::Post) && let Some(addressed) = namespace_from_path(&path) + .filter(|_| method == Method::Put) + .or(evaluation + .filter(|name| method == Method::Post && !name.is_empty() && !name.contains('/'))) { - submit(request, addressed, namespace, sender); + submit(request, addressed, namespace, sender, evaluation.is_some()); return; } let response = if method == Method::Get && path == "/agent" { @@ -162,10 +286,11 @@ fn code_request( } fn submit( - mut request: Request, + mut request: ObservedRequest, addressed: &str, namespace: &Arc>, sender: &SyncSender, + evaluate: bool, ) { let source = match read_code(&mut request) { Ok(source) => source, @@ -174,6 +299,7 @@ fn submit( return; } }; + request.record_body(&source); let Ok(mut current) = namespace.write() else { let _ = request.respond(error_response( StatusCode(500), @@ -194,6 +320,7 @@ fn submit( }; let job = BuildRequest { request, + evaluate, source, namespace: addressed.into(), submission, @@ -201,7 +328,11 @@ fn submit( match sender.try_send(job) { // A rejected queue entry never invalidates accepted work. The worker // uses this same lock when committing, so publication is atomic. - Ok(()) => current.submission = submission, + Ok(()) => { + if !evaluate { + current.submission = submission; + } + } Err(TrySendError::Full(job)) => { let _ = job .request @@ -221,6 +352,16 @@ fn build( namespace: &Arc>, notify: &Notify, ) -> Response>> { + if job.evaluate { + return match catch_unwind(AssertUnwindSafe(|| endor_host::evaluate(&job.source))) { + Ok(Ok(value)) => json( + StatusCode(200), + serde_json::json!({"ok":true,"value":value,"execution":"isolated-expression","persistent":false}), + ), + Ok(Err(error)) => compile_error(error), + Err(_) => error_response(StatusCode(500), "expression execution failed internally"), + }; + } match namespace.read() { Ok(current) if current.submission != job.submission => return superseded(job.submission), Err(_) => return error_response(StatusCode(500), "namespace lock is poisoned"), @@ -315,6 +456,14 @@ Send PUT bodies as `text/plain; charset=utf-8`. ```endor {example}``` +## Isolated expression evaluation + +`POST http://{address}/v1/namespaces/{name}/evaluate` accepts one Endor expression +as text/plain and returns its value. It uses a fresh VM without ui or prior bindings, +does not publish a page or change the revision, and shares the bounded worker queue. +Persistent REPL sessions are not available. The Console is an activity transcript, +not a persistent VM; history is never replayed. PUT remains a complete source replacement. + ## UI host object Positional arguments only: @@ -400,12 +549,12 @@ fn text(status: StatusCode, value: &str, content_type: &str) -> Response>) -> Self { + pub fn new( + namespace: Arc>, + activity: Activity, + proxy: EventLoopProxy, + ) -> Self { Self { window: None, context: None, surface: None, namespace, - developer_tools: DeveloperToolsState::default(), + developer_tools: { + let mut state = DeveloperToolsState::default(); + state.proxy = Some(proxy); + state + }, layout: SceneLayout::default(), pointer: Point::default(), modifiers: ModifiersState::default(), + activity, } } @@ -72,7 +84,7 @@ impl TesseraApp { } fn handle_keyboard(&mut self, event: &winit::event::KeyEvent) { - if event.state != ElementState::Pressed || event.repeat { + if event.state != ElementState::Pressed { return; } let is_f12 = matches!(event.logical_key, Key::Named(NamedKey::F12)); @@ -81,15 +93,62 @@ impl TesseraApp { let mac_shortcut = self.modifiers.super_key() && self.modifiers.alt_key() && is_i; let other_shortcut = self.modifiers.control_key() && self.modifiers.shift_key() && is_i; if is_f12 || mac_shortcut || other_shortcut { - self.toggle_developer_tools(); - } - } - - fn handle_click(&mut self) { - let Some(node_id) = self.layout.developer_tools.node_at(self.pointer) else { + if !event.repeat { + self.toggle_developer_tools(); + } return; - }; - self.developer_tools.selected_node_id = Some(node_id.to_owned()); + } + if !self.developer_tools.open || self.developer_tools.focus.is_none() { + return; + } + let command = self.modifiers.super_key() || self.modifiers.control_key(); + if command && let Key::Character(value) = &event.logical_key { + match value.to_lowercase().as_str() { + "a" => self.developer_tools.selection = true, + "v" => { + #[cfg(target_os = "macos")] + if let Ok(output) = std::process::Command::new("pbpaste").output() + && output.status.success() + { + self.developer_tools + .insert(&String::from_utf8_lossy(&output.stdout)); + } + } + "c" | "x" => { + #[cfg(target_os = "macos")] + { + use std::io::Write; + let selected = self.developer_tools.selected_text(); + if !selected.is_empty() + && let Ok(mut child) = std::process::Command::new("pbcopy") + .stdin(std::process::Stdio::piped()) + .spawn() + { + if let Some(mut stdin) = child.stdin.take() { + let _ = stdin.write_all(selected.as_bytes()); + } + let _ = child.wait(); + if value.eq_ignore_ascii_case("x") { + self.developer_tools.insert(""); + } + } + } + } + _ => {} + } + } else if let Key::Named(key) = &event.logical_key { + if !self.developer_tools.preedit.is_empty() { + return; + } + self.developer_tools + .key(key, self.modifiers.shift_key(), command); + } else if !command + && self.developer_tools.preedit.is_empty() + && let Some(text) = &event.text + { + let text: String = text.chars().filter(|c| !c.is_control()).collect(); + self.developer_tools.insert(&text); + } self.request_redraw(); } @@ -112,10 +171,18 @@ impl TesseraApp { size.height, window.scale_factor() as f32, &namespace.document, - &self.developer_tools, + &mut self.developer_tools, + &self.activity, ); drop(namespace); self.layout = scene.layout; + let ime = self + .developer_tools + .ime_position(&self.layout.developer_tools); + window.set_ime_cursor_area( + LogicalPosition::new(ime.x as f64, ime.y as f64), + LogicalSize::new(1.0, 19.0), + ); surface .resize(width, height) @@ -145,6 +212,7 @@ impl ApplicationHandler for TesseraApp { let surface = Surface::new(&context, window.clone()).expect("create software-rendering surface"); + window.set_ime_allowed(true); self.window = Some(window.clone()); self.context = Some(context); self.surface = Some(surface); @@ -154,6 +222,14 @@ impl ApplicationHandler for TesseraApp { fn user_event(&mut self, _event_loop: &ActiveEventLoop, event: AppEvent) { match event { AppEvent::DocumentUpdated => self.document_updated(), + AppEvent::ConsoleFailed { message, source } => { + self.developer_tools.input_error = format!("Request failed: {message}"); + if self.developer_tools.input.is_empty() { + self.developer_tools.input = source; + self.developer_tools.cursor = self.developer_tools.input.len(); + } + self.request_redraw(); + } } } @@ -178,12 +254,72 @@ impl ApplicationHandler for TesseraApp { WindowEvent::CursorMoved { position: PhysicalPosition { x, y }, .. - } => self.pointer = Point::new(x as f32, y as f32), + } => { + let scale = window.scale_factor() as f32; + let next = Point::new(x as f32 / scale, y as f32 / scale); + let delta = Point::new(next.x - self.pointer.x, next.y - self.pointer.y); + self.pointer = next; + self.developer_tools.move_pointer( + next, + delta, + &self.layout.developer_tools, + window.inner_size().width as f32 / scale, + ); + window.set_cursor( + self.developer_tools + .cursor_kind(&self.layout.developer_tools, next), + ); + window.request_redraw(); + } WindowEvent::MouseInput { - state: ElementState::Released, + state, button: MouseButton::Left, .. - } => self.handle_click(), + } => { + if state == ElementState::Pressed { + self.developer_tools.press( + &self.layout.developer_tools, + self.pointer, + &self.activity, + ); + } else { + self.developer_tools.release(); + } + window.request_redraw(); + } + WindowEvent::MouseWheel { delta, .. } => { + let (mut dx, mut dy) = match delta { + MouseScrollDelta::LineDelta(x, y) => (x * 38.0, y * 38.0), + MouseScrollDelta::PixelDelta(p) => ( + p.x as f32 / window.scale_factor() as f32, + p.y as f32 / window.scale_factor() as f32, + ), + }; + if self.modifiers.shift_key() && dx.abs() < 0.1 { + dx = dy; + dy = 0.0; + } + self.developer_tools + .wheel(&self.layout.developer_tools, self.pointer, dx, dy); + window.request_redraw(); + } + WindowEvent::Ime(Ime::Preedit(value, _)) => { + self.developer_tools.preedit = value; + window.request_redraw(); + } + WindowEvent::Ime(Ime::Commit(value)) => { + self.developer_tools.preedit.clear(); + if self.developer_tools.open { + self.developer_tools.insert(&value); + } + window.request_redraw(); + } + WindowEvent::Focused(false) => { + self.developer_tools.release(); + self.developer_tools.focus = None; + self.developer_tools.preedit.clear(); + self.modifiers = ModifiersState::default(); + } WindowEvent::ModifiersChanged(modifiers) => self.modifiers = modifiers.state(), WindowEvent::KeyboardInput { event, .. } => self.handle_keyboard(&event), WindowEvent::RedrawRequested => self.redraw(), diff --git a/src/developer_tools.rs b/src/developer_tools.rs index 08157db..e0092a7 100644 --- a/src/developer_tools.rs +++ b/src/developer_tools.rs @@ -1,288 +1,1456 @@ +//! Native developer workspace. Coordinates and scroll offsets are logical pixels. use crate::{ + activity::{Activity, Exchange}, + app::AppEvent, display_list::{Color, DisplayList, DrawCommand}, document::{CodeNode, RenderDocument}, geometry::{Point, Rect}, - text::{self as typography, TextStyle}, + sources::SourceWorkspace, + text::{self, TextStyle}, }; +use std::{ + io::{Read, Write}, + net::TcpStream, + thread, + time::Duration, +}; +use unicode_segmentation::UnicodeSegmentation; -const PANEL: Color = Color::rgb(247, 247, 245); -const PANEL_ALT: Color = Color::rgb(238, 238, 235); -const BORDER: Color = Color::rgb(214, 214, 209); -const TEXT: Color = Color::rgb(36, 36, 34); -const MUTED: Color = Color::rgb(112, 112, 107); -const SELECTED: Color = Color::rgb(224, 229, 247); +const BG: Color = Color::rgb(255, 255, 255); +const BAR: Color = Color::rgb(243, 245, 248); +const BORDER: Color = Color::rgb(214, 220, 229); +const TEXT: Color = Color::rgb(35, 42, 53); +const MUTED: Color = Color::rgb(103, 114, 130); +const ERROR: Color = Color::rgb(175, 42, 49); +const OK: Color = Color::rgb(31, 121, 80); +const ROW: f32 = 19.0; +const PALETTE: [Color; 6] = [ + Color::rgb(22, 113, 213), + Color::rgb(0, 132, 143), + Color::rgb(115, 76, 189), + Color::rgb(180, 68, 115), + Color::rgb(168, 94, 24), + Color::rgb(52, 123, 78), +]; -#[derive(Debug, Default)] -pub struct DeveloperToolsState { - pub open: bool, - pub selected_node_id: Option, +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub enum Tab { + #[default] + Console, + Sources, + Network, + Settings, +} +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Region { + Transcript = 0, + Input, + Tree, + Source, + Requests, + Details, +} +#[derive(Clone, Copy, Debug, Default)] +struct Scroll { + x: f32, + y: f32, +} +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Focus { + Input, + Filter, + Custom, +} +#[derive(Clone, Debug)] +pub enum Action { + Tab(Tab), + Close, + ClearConsole, + ClearNetwork, + Follow, + Mode, + Submit, + Focus(Focus), + Snapshot, + Cloud, + CloudRefresh, + CloudOpen(String), + Node(String, usize), + Request(u64), + Theme(usize), +} +#[derive(Clone, Copy, Debug)] +pub enum Split { + Dock, + Editor, + Tree, + Network, +} +#[derive(Clone, Copy, Debug)] +enum Drag { + Split(Split), + Scroll(Region, bool, f32), } -impl DeveloperToolsState { - pub fn toggle(&mut self, document: &RenderDocument) { - self.open = !self.open; - self.ensure_selection(document); - } - - pub fn document_updated(&mut self, document: &RenderDocument) { - self.ensure_selection(document); - } - - fn ensure_selection(&mut self, document: &RenderDocument) { - let selection_exists = self - .selected_node_id - .as_deref() - .is_some_and(|id| document.node(id).is_some()); - if !selection_exists { - self.selected_node_id = document.root.as_ref().map(|node| node.id.clone()); +#[derive(Debug)] +pub struct DeveloperToolsState { + pub open: bool, + pub proxy: Option>, + pub cloud_sources: SourceWorkspace, + pub tab: Tab, + pub selected_node_id: Option, + pub focus: Option, + pub input: String, + pub cursor: usize, + pub selection: bool, + pub preedit: String, + pub filter: String, + pub custom: String, + pub accent: Color, + pub input_error: String, + panel_width: f32, + editor_height: f32, + tree_width: f32, + network_fraction: f32, + scroll: [Scroll; 6], + widths: [Option<(u64, f32)>; 6], + drag: Option, + script: bool, + cloud: bool, + follow: bool, + selected_request: Option, + console_after: u64, + network_after: u64, + history: Vec, + history_index: Option, + draft: String, +} +impl Default for DeveloperToolsState { + fn default() -> Self { + Self { + open: false, + proxy: None, + cloud_sources: SourceWorkspace::default(), + tab: Tab::Console, + selected_node_id: None, + focus: None, + input: String::new(), + cursor: 0, + selection: false, + preedit: String::new(), + filter: String::new(), + custom: "#1671D5".into(), + accent: PALETTE[0], + input_error: String::new(), + panel_width: 660.0, + editor_height: 180.0, + tree_width: 190.0, + network_fraction: 0.42, + scroll: [Scroll::default(); 6], + widths: [None; 6], + drag: None, + script: false, + cloud: false, + follow: true, + selected_request: None, + console_after: 0, + network_after: 0, + history: Vec::new(), + history_index: None, + draft: String::new(), } } } - #[derive(Clone, Debug, Default)] pub struct DeveloperToolsLayout { - rows: Vec, + pub panel: Rect, + pub actions: Vec<(Rect, Action)>, + splits: Vec<(Rect, Split)>, + regions: Vec<(Rect, Region, f32, f32)>, + thumbs: Vec<(Rect, Region, bool, f32)>, } - -impl DeveloperToolsLayout { - pub fn node_at(&self, point: Point) -> Option<&str> { - self.rows +impl DeveloperToolsState { + pub fn toggle(&mut self, doc: &RenderDocument) { + self.open = !self.open; + self.focus = None; + self.drag = None; + self.document_updated(doc); + } + pub fn document_updated(&mut self, doc: &RenderDocument) { + if self + .selected_node_id + .as_deref() + .is_none_or(|id| doc.node(id).is_none()) + { + self.selected_node_id = doc.root.as_ref().map(|n| n.id.clone()); + } + } + pub fn cursor_kind( + &self, + layout: &DeveloperToolsLayout, + point: Point, + ) -> winit::window::CursorIcon { + use winit::window::CursorIcon; + if let Some((_, split)) = layout.splits.iter().find(|(r, _)| r.contains(point)) { + return match split { + Split::Dock | Split::Tree => CursorIcon::ColResize, + _ => CursorIcon::RowResize, + }; + } + if layout + .actions .iter() - .find(|row| row.rect.contains(point)) - .map(|row| row.node_id.as_str()) + .any(|(r, a)| r.contains(point) && matches!(a, Action::Focus(_))) + { + CursorIcon::Text + } else { + CursorIcon::Default + } + } + pub fn press(&mut self, layout: &DeveloperToolsLayout, p: Point, activity: &Activity) { + if !self.open { + return; + } + self.preedit.clear(); + if let Some((_, split)) = layout.splits.iter().find(|(r, _)| r.contains(p)) { + self.drag = Some(Drag::Split(*split)); + self.focus = None; + return; + } + if let Some((_, region, horizontal, ratio)) = + layout.thumbs.iter().find(|(r, _, _, _)| r.contains(p)) + { + self.drag = Some(Drag::Scroll(*region, *horizontal, *ratio)); + return; + } + let action = layout + .actions + .iter() + .rev() + .find(|(r, _)| r.contains(p)) + .map(|(_, a)| a.clone()); + self.focus = None; + match action { + Some(Action::Tab(t)) => { + self.tab = t; + } + Some(Action::Close) => { + self.open = false; + } + Some(Action::Focus(f)) => { + self.focus = Some(f); + self.selection = false; + if f == Focus::Input + && let Some((area, _, _, _)) = layout + .regions + .iter() + .find(|(_, r, _, _)| *r == Region::Input) + { + let scroll = self.scroll[Region::Input as usize]; + let row = ((p.y - area.y - 5.0 + scroll.y) / ROW).floor().max(0.0) as usize; + let mut start = 0; + let line = self + .input + .split('\n') + .enumerate() + .find_map(|(i, line)| { + if i == row { + Some(line) + } else { + start += line.len() + 1; + None + } + }) + .unwrap_or(""); + let target = (p.x - area.x - 8.0 + scroll.x).max(0.0); + let mut offset = line.len(); + for (i, part) in line.grapheme_indices(true) { + let advance = + text::measure(&line[..i + part.len()], TextStyle::code()).width; + if advance >= target { + offset = i; + break; + } + } + self.cursor = (start + offset).min(self.input.len()); + } + } + Some(Action::ClearConsole) => { + self.console_after = activity.lock().unwrap().records.back().map_or(0, |r| r.id); + } + Some(Action::ClearNetwork) => { + self.network_after = activity.lock().unwrap().records.back().map_or(0, |r| r.id); + self.selected_request = None; + } + Some(Action::Follow) => { + self.follow = !self.follow; + } + Some(Action::Mode) => { + self.script = !self.script; + } + Some(Action::Submit) => self.submit(), + Some(Action::Snapshot) => self.cloud = false, + Some(Action::Cloud) => self.cloud = true, + Some(Action::CloudRefresh) => self.cloud_sources.refresh(), + Some(Action::CloudOpen(id)) => { + self.cloud_sources.open(&id); + self.scroll[Region::Source as usize] = Scroll::default(); + } + Some(Action::Node(id, line)) => { + self.selected_node_id = Some(id); + self.scroll[Region::Source as usize].x = 0.0; + self.scroll[Region::Source as usize].y = line.saturating_sub(1) as f32 * ROW; + } + Some(Action::Request(id)) => { + self.selected_request = Some(id); + if self.tab == Tab::Console { + self.tab = Tab::Network; + self.network_after = 0; + self.filter.clear(); + } + self.scroll[Region::Details as usize] = Scroll::default(); + } + Some(Action::Theme(i)) => { + self.accent = PALETTE[i]; + self.custom = format!( + "#{:02X}{:02X}{:02X}", + self.accent.red, self.accent.green, self.accent.blue + ); + } + None => {} + } + } + pub fn release(&mut self) { + self.drag = None; + } + pub fn move_pointer( + &mut self, + p: Point, + delta: Point, + layout: &DeveloperToolsLayout, + window_width: f32, + ) { + match self.drag { + Some(Drag::Split(Split::Dock)) => { + self.panel_width = + (window_width - p.x).clamp(360.0, (window_width - 100.0).max(360.0)) + } + Some(Drag::Split(Split::Editor)) => { + self.editor_height = (layout.panel.height - p.y - 22.0) + .clamp(100.0, (layout.panel.height - 170.0).max(100.0)) + } + Some(Drag::Split(Split::Tree)) => { + self.tree_width = + (p.x - layout.panel.x).clamp(120.0, (layout.panel.width - 180.0).max(120.0)) + } + Some(Drag::Split(Split::Network)) => { + self.network_fraction = + ((p.y - 92.0) / (layout.panel.height - 114.0).max(1.0)).clamp(0.2, 0.8) + } + Some(Drag::Scroll(r, h, ratio)) => { + let s = &mut self.scroll[r as usize]; + if h { + s.x = (s.x + delta.x * ratio).max(0.0); + } else { + s.y = (s.y + delta.y * ratio).max(0.0); + } + if r == Region::Transcript { + self.follow = false; + } + } + None => {} + } + } + pub fn wheel(&mut self, layout: &DeveloperToolsLayout, p: Point, dx: f32, dy: f32) { + if let Some((_, r, _, _)) = layout + .regions + .iter() + .rev() + .find(|(area, _, _, _)| area.contains(p)) + { + let s = &mut self.scroll[*r as usize]; + s.x = (s.x - dx).max(0.0); + s.y = (s.y - dy).max(0.0); + if *r == Region::Transcript { + self.follow = false; + } + } + } + pub fn insert(&mut self, value: &str) { + match self.focus { + Some(Focus::Input) => { + if self.input.len() + value.len() > 1_048_576 { + self.input_error = "Input exceeds 1 MiB".into(); + return; + } + if self.selection { + self.input.clear(); + self.cursor = 0; + self.selection = false; + } + self.input.insert_str(self.cursor, value); + self.cursor += value.len(); + self.history_index = None; + self.reveal_cursor(); + } + Some(Focus::Filter) => { + if self.selection { + self.filter.clear(); + self.selection = false; + } + self.filter + .extend(value.chars().filter(|c| !c.is_control()).take(200)); + self.scroll[Region::Requests as usize].y = 0.0; + } + Some(Focus::Custom) => { + if self.selection { + self.custom.clear(); + self.selection = false; + } + self.custom.extend( + value + .chars() + .filter(|c| c.is_ascii_hexdigit() || *c == '#') + .take(7), + ); + } + None => {} + } + } + fn reveal_cursor(&mut self) { + let before = &self.input[..self.cursor]; + let line = before.matches('\n').count() as f32; + let y = line * ROW; + let s = &mut self.scroll[Region::Input as usize]; + if y < s.y { + s.y = y; + } + if y > s.y + self.editor_height - 100.0 { + s.y = (y - self.editor_height + 100.0).max(0.0); + } + let column = before.rsplit('\n').next().unwrap_or(""); + let x = text::measure(column, TextStyle::code()).width; + if x < s.x { + s.x = x; + } + if x > s.x + self.panel_width - 100.0 { + s.x = (x - self.panel_width + 100.0).max(0.0); + } + } + pub fn ime_position(&self, layout: &DeveloperToolsLayout) -> Point { + if let Some((area, _, _, _)) = layout + .regions + .iter() + .find(|(_, r, _, _)| *r == Region::Input) + { + let before = &self.input[..self.cursor]; + let row = before.matches('\n').count() as f32; + let col = before.rsplit('\n').next().unwrap_or(""); + let scroll = self.scroll[Region::Input as usize]; + return Point::new( + (area.x + 8.0 + text::measure(col, TextStyle::code()).width - scroll.x) + .clamp(area.x, area.x + area.width), + (area.y + 5.0 + row * ROW - scroll.y).clamp(area.y, area.y + area.height), + ); + } + Point::new(layout.panel.x + 20.0, 60.0) + } + pub fn selected_text(&self) -> String { + if !self.selection { + return String::new(); + } + match self.focus { + Some(Focus::Input) => self.input.clone(), + Some(Focus::Filter) => self.filter.clone(), + Some(Focus::Custom) => self.custom.clone(), + None => String::new(), + } + } + pub fn key(&mut self, key: &winit::keyboard::NamedKey, shift: bool, command: bool) { + use winit::keyboard::NamedKey::*; + if self.focus == Some(Focus::Custom) && *key == Enter { + let hex = self.custom.trim_start_matches('#'); + if hex.len() == 6 + && let Ok(v) = u32::from_str_radix(hex, 16) + { + self.accent = readable_accent(Color::rgb((v >> 16) as u8, (v >> 8) as u8, v as u8)); + self.input_error.clear(); + } else { + self.input_error = "Use a six-digit hex color, e.g. #1671D5".into(); + } + return; + } + if self.focus != Some(Focus::Input) { + if *key == Backspace { + match self.focus { + Some(Focus::Filter) => { + if self.selection { + self.filter.clear(); + } else { + self.filter.pop(); + } + } + Some(Focus::Custom) => { + if self.selection { + self.custom.clear(); + } else { + self.custom.pop(); + } + } + _ => {} + } + self.selection = false; + } + return; + } + match key { + Enter if !shift => self.submit(), + Enter => self.insert("\n"), + Tab => self.insert(" "), + Space => self.insert(" "), + Backspace | Delete => { + if self.selection { + self.input.clear(); + self.cursor = 0; + self.selection = false; + } else if *key == Backspace && self.cursor > 0 { + let n = self.input[..self.cursor] + .grapheme_indices(true) + .next_back() + .map_or(0, |(i, _)| i); + self.input.replace_range(n..self.cursor, ""); + self.cursor = n; + } else if *key == Delete && self.cursor < self.input.len() { + let len = self.input[self.cursor..] + .graphemes(true) + .next() + .unwrap() + .len(); + self.input.replace_range(self.cursor..self.cursor + len, ""); + } + } + ArrowLeft => { + self.cursor = if command { + 0 + } else { + self.input[..self.cursor] + .grapheme_indices(true) + .next_back() + .map_or(0, |(i, _)| i) + }; + self.selection = false; + } + ArrowRight => { + self.cursor = if command { + self.input.len() + } else { + self.cursor + + self.input[self.cursor..] + .graphemes(true) + .next() + .map_or(0, str::len) + }; + self.selection = false; + } + Home => { + self.cursor = if command { + 0 + } else { + self.input[..self.cursor].rfind('\n').map_or(0, |i| i + 1) + }; + self.selection = false; + } + End => { + self.cursor = if command { + self.input.len() + } else { + self.input[self.cursor..] + .find('\n') + .map_or(self.input.len(), |i| self.cursor + i) + }; + self.selection = false; + } + ArrowUp | ArrowDown if command || !self.input.contains('\n') => { + if self.history.is_empty() { + return; + } + if self.history_index.is_none() { + self.draft = self.input.clone(); + } + let current = self.history_index.unwrap_or(self.history.len()); + let index = if *key == ArrowUp { + current.saturating_sub(1) + } else { + (current + 1).min(self.history.len()) + }; + self.history_index = (index < self.history.len()).then_some(index); + self.input = self + .history_index + .map_or_else(|| self.draft.clone(), |i| self.history[i].clone()); + self.cursor = self.input.len(); + } + ArrowUp | ArrowDown => { + let start = self.input[..self.cursor].rfind('\n').map_or(0, |i| i + 1); + let col = self.input[start..self.cursor].graphemes(true).count(); + let target = if *key == ArrowUp { + if start == 0 { + 0 + } else { + self.input[..start - 1].rfind('\n').map_or(0, |i| i + 1) + } + } else { + self.input[self.cursor..] + .find('\n') + .map_or(self.input.len(), |i| self.cursor + i + 1) + }; + let end = self.input[target..] + .find('\n') + .map_or(self.input.len(), |i| target + i); + self.cursor = target + + self.input[target..end] + .graphemes(true) + .take(col) + .map(str::len) + .sum::(); + self.selection = false; + } + Escape => { + self.focus = None; + self.preedit.clear(); + } + _ => {} + } + self.reveal_cursor(); + } + fn submit(&mut self) { + if self.input.trim().is_empty() { + return; + } + let source = self.input.clone(); + let script = self.script; + let proxy = self.proxy.clone(); + // A real loopback request keeps Console and external integrations on the same API path. + match thread::Builder::new().name("tessera-console-client".into()).spawn(move || { + let send=|| -> std::io::Result<()> { + let mut stream=TcpStream::connect_timeout(&"127.0.0.1:4737".parse().unwrap(),Duration::from_secs(2))?; + stream.set_read_timeout(Some(Duration::from_secs(120)))?;stream.set_write_timeout(Some(Duration::from_secs(10)))?; + let (method,path)=if script {("PUT","code")}else{("POST","evaluate")}; + write!(stream,"{method} /v1/namespaces/app.main/{path} HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\nContent-Type: text/plain; charset=utf-8\r\nX-Tessera-Origin: console\r\nContent-Length: {}\r\n\r\n{}",source.len(),source)?; + let mut response=String::new();stream.read_to_string(&mut response)?;Ok(()) + }; + if let Err(error)=send() && let Some(proxy)=proxy {let _=proxy.send_event(AppEvent::ConsoleFailed {message:error.to_string(),source});} + }) { Ok(_)=> {self.history.push(self.input.clone()); if self.history.len()>80{self.history.remove(0);}self.input.clear();self.cursor=0;self.history_index=None;self.scroll[Region::Input as usize]=Scroll::default();self.follow=true;self.input_error.clear();},Err(e)=>self.input_error=e.to_string() } } } -#[derive(Clone, Debug)] -struct TreeRowHit { - rect: Rect, - node_id: String, +struct Painter { + list: DisplayList, + layout: DeveloperToolsLayout, + accent: Color, +} +impl Painter { + fn fill(&mut self, r: Rect, c: Color) { + self.list.push(DrawCommand::FillRoundedRect { + rect: r, + radius: 0.0, + color: c, + }); + } + fn label(&mut self, x: f32, y: f32, value: &str, c: Color, code: bool) { + self.list.push(DrawCommand::Text { + origin: Point::new(x, y), + value: value.into(), + style: if code { + TextStyle::code() + } else { + TextStyle { + font_size: 12.0, + line_height: 18.0, + ..TextStyle::ui(1) + } + }, + color: c, + }); + } + fn button(&mut self, r: Rect, label: &str, action: Action, active: bool) { + if active { + self.fill(r, tint(self.accent)); + } + self.label(r.x + 10.0, r.y + 6.0, label, TEXT, false); + self.layout.actions.push((r, action)); + } + fn split(&mut self, r: Rect, kind: Split) { + self.fill(r, BORDER); + self.layout.splits.push(( + Rect::new(r.x - 2.0, r.y - 2.0, r.width + 4.0, r.height + 4.0), + kind, + )); + } + fn lines( + &mut self, + area: Rect, + region: Region, + lines: &[Line], + state: &mut DeveloperToolsState, + follow: bool, + ) { + let content_h = lines.len() as f32 * ROW + 12.0; + use std::hash::{Hash, Hasher}; + let mut hash = std::collections::hash_map::DefaultHasher::new(); + for line in lines { + line.value.hash(&mut hash); + } + let fingerprint = hash.finish(); + let cache = &mut state.widths[region as usize]; + let content_w = match *cache { + Some((previous, width)) if previous == fingerprint => width, + _ => { + let width = lines + .iter() + .map(|line| text::measure(&line.value, TextStyle::code()).width + 20.0) + .fold(0.0_f32, f32::max); + *cache = Some((fingerprint, width)); + width + } + }; + let s = &mut state.scroll[region as usize]; + s.y = if follow { + (content_h - area.height + 12.0).max(0.0) + } else { + s.y.clamp(0.0, (content_h - area.height + 12.0).max(0.0)) + }; + s.x = s.x.clamp(0.0, (content_w - area.width + 12.0).max(0.0)); + self.list.push(DrawCommand::PushClip(Rect::new( + area.x, + area.y, + (area.width - 9.0).max(0.0), + (area.height - 9.0).max(0.0), + ))); + let first = (s.y / ROW).floor() as usize; + let count = (area.height / ROW).ceil() as usize + 2; + for (i, line) in lines.iter().enumerate().skip(first).take(count) { + let y = area.y + 5.0 + i as f32 * ROW - s.y; + if line.divider { + self.fill(Rect::new(area.x, y, area.width, 1.0), self.accent); + } + if line.selected { + self.fill(Rect::new(area.x, y, area.width, ROW), tint(self.accent)); + } + self.label(area.x + 8.0 - s.x, y, &line.value, line.color, true); + if let Some(action) = &line.action { + let top = y.max(area.y); + let bottom = (y + ROW).min(area.y + area.height - 9.0); + if bottom > top { + self.layout.actions.push(( + Rect::new(area.x, top, area.width - 9.0, bottom - top), + action.clone(), + )); + } + } + } + self.list.push(DrawCommand::PopClip); + self.layout + .regions + .push((area, region, content_w, content_h)); + self.scrollbar(area, region, false, s.y, content_h); + self.scrollbar(area, region, true, s.x, content_w); + } + fn scrollbar(&mut self, r: Rect, region: Region, h: bool, offset: f32, content: f32) { + let viewport = if h { r.width } else { r.height } - 10.0; + if content <= viewport || viewport <= 0.0 { + return; + } + let length = (viewport * viewport / content).max(24.0).min(viewport); + let travel = (viewport - length).max(1.0); + let maximum = (content - viewport).max(1.0); + let position = (offset / maximum).clamp(0.0, 1.0) * travel; + let track = if h { + Rect::new(r.x, r.y + r.height - 8.0, viewport, 8.0) + } else { + Rect::new(r.x + r.width - 8.0, r.y, 8.0, viewport) + }; + self.fill(track, BAR); + let thumb = if h { + Rect::new(track.x + position, track.y + 1.0, length, 6.0) + } else { + Rect::new(track.x + 1.0, track.y + position, 6.0, length) + }; + self.fill(thumb, Color::rgb(161, 173, 190)); + self.layout + .thumbs + .push((thumb, region, h, maximum / travel)); + } +} +#[derive(Clone)] +struct Line { + value: String, + color: Color, + divider: bool, + selected: bool, + action: Option, +} +impl Line { + fn new(value: impl Into, color: Color) -> Self { + Self { + value: value.into(), + color, + divider: false, + selected: false, + action: None, + } + } +} +fn readable_accent(mut c: Color) -> Color { + // Keep an accent visible on white while retaining the chosen hue. + while (c.red as u32 * 299 + c.green as u32 * 587 + c.blue as u32 * 114) / 1000 > 155 { + c = Color::rgb( + (c.red as f32 * 0.94) as u8, + (c.green as f32 * 0.94) as u8, + (c.blue as f32 * 0.94) as u8, + ); + } + c +} +fn tint(c: Color) -> Color { + Color::rgb(232 + c.red / 12, 232 + c.green / 12, 232 + c.blue / 12) +} +fn multiline(out: &mut Vec, value: &str, color: Color) { + out.extend( + value + .replace('\t', " ") + .split('\n') + .map(|s| Line::new(s, color)), + ); +} +fn console_result(out: &mut Vec, body: &str, color: Color) { + if let Ok(value) = serde_json::from_str::(body) { + if let Some(result) = value["value"].as_str() { + multiline(out, result, color); + return; + } + if let Some(diagnostics) = value["diagnostics"].as_array() + && !diagnostics.is_empty() + { + for d in diagnostics { + if let Some(line) = d["line"].as_u64() { + out.push(Line::new( + format!("Error · line {line}, column {}", d["column"]), + color, + )); + } + multiline( + out, + d["message"].as_str().unwrap_or("Execution failed"), + color, + ); + } + return; + } + if let Some(error) = value["error"].as_str() { + multiline(out, error, color); + return; + } + if let Some(revision) = value["revision"].as_u64() { + out.push(Line::new(format!("Committed revision {revision}"), color)); + return; + } + } + multiline(out, body, color); +} +fn flatten<'a>(node: &'a CodeNode, depth: usize, out: &mut Vec<(usize, &'a CodeNode)>) { + out.push((depth, node)); + for child in &node.children { + flatten(child, depth + 1, out); + } } pub fn build( width: u32, height: u32, scale: f32, - document: &RenderDocument, - state: &DeveloperToolsState, + doc: &RenderDocument, + state: &mut DeveloperToolsState, + activity: &Activity, ) -> (DisplayList, DeveloperToolsLayout) { if !state.open { - return (DisplayList::default(), DeveloperToolsLayout::default()); + return (Default::default(), Default::default()); } - - let mut list = DisplayList::default(); - let width = width as f32; - let height = height as f32; - let panel_width = (430.0 * scale).min(width * 0.52); - let panel_x = width - panel_width; - let header_height = 44.0 * scale; - let tree_height = ((height - header_height) * 0.42).max(150.0 * scale); - let code_y = header_height + tree_height; - - fill( - &mut list, - Rect::new(panel_x, 0.0, panel_width, height), - 0.0, - PANEL, + let width = width as f32 / scale; + let height = height as f32 / scale; + let w = state + .panel_width + .clamp(360.0, (width - 100.0).max(360.0)) + .min(width); + let x = width - w; + let panel = Rect::new(x, 0.0, w, height); + let mut p = Painter { + list: DisplayList::default(), + layout: DeveloperToolsLayout { + panel, + ..Default::default() + }, + accent: state.accent, + }; + p.fill(panel, BG); + p.list.push(DrawCommand::PushClip(panel)); + p.fill(Rect::new(x, 0.0, w, 31.0), BAR); + p.split(Rect::new(x, 0.0, 1.0, height), Split::Dock); + for (i, (label, tab)) in [ + ("Console", Tab::Console), + ("Sources", Tab::Sources), + ("Network", Tab::Network), + ("Settings", Tab::Settings), + ] + .iter() + .enumerate() + { + let r = Rect::new(x + 5.0 + i as f32 * 75.0, 0.0, 75.0, 30.0); + p.button(r, label, Action::Tab(*tab), state.tab == *tab); + if state.tab == *tab { + p.fill(Rect::new(r.x, 29.0, r.width, 2.0), state.accent); + } + } + p.button( + Rect::new(width - 32.0, 0.0, 31.0, 30.0), + "×", + Action::Close, + false, ); - fill( - &mut list, - Rect::new(panel_x, 0.0, 1.0 * scale, height), - 0.0, - BORDER, + let records = activity + .lock() + .unwrap() + .records + .iter() + .cloned() + .collect::>(); + let bottom = height - 22.0; + match state.tab { + Tab::Console => { + p.fill(Rect::new(x, 32.0, w, 30.0), BAR); + p.button( + Rect::new(x + 3.0, 32.0, 62.0, 29.0), + "Clear", + Action::ClearConsole, + false, + ); + p.button( + Rect::new(x + 68.0, 32.0, 106.0, 29.0), + if state.follow { + "Follow: on" + } else { + "Follow: off" + }, + Action::Follow, + state.follow, + ); + p.label( + x + 184.0, + 39.0, + "app.main · execution transcript", + MUTED, + false, + ); + let editor = state + .editor_height + .clamp(100.0, (height - 170.0).max(100.0)); + let split_y = bottom - editor; + let mut lines = Vec::new(); + for r in records.iter().filter(|r| { + r.id > state.console_after + && (r.method == "PUT" || r.method == "POST" || r.method == "DELETE") + }) { + let kind = if r.path.ends_with("/evaluate") { + "EXPRESSION · fresh VM" + } else if r.method == "PUT" { + "SCRIPT · replace snapshot" + } else { + "CLEAR DOCUMENT" + }; + let mut title = Line::new( + format!("#{} {} {} {}", r.id, r.timestamp, r.origin, kind), + MUTED, + ); + title.divider = true; + title.action = Some(Action::Request(r.id)); + lines.push(title); + multiline(&mut lines, &format!("› {}", r.request), TEXT); + let color = if r.status.is_some_and(|s| s >= 400) { + ERROR + } else { + OK + }; + if let Some(status) = r.status { + lines.push(Line::new( + format!("‹ {status} · {} ms", r.elapsed_ms), + color, + )); + console_result(&mut lines, &r.response, color); + } else { + lines.push(Line::new(" Executing…", MUTED)); + } + lines.push(Line::new("", MUTED)); + } + if lines.is_empty() { + multiline( + &mut lines, + "Console\n\nEvaluate an expression, or submit a complete UI script.\nExternal HTTP executions appear here as they happen.\n\nEach request starts a fresh VM. Bindings do not persist.\nPersistent REPL sessions are not connected.\nNo history is replayed.", + MUTED, + ); + } + let follow = state.follow; + p.lines( + Rect::new(x + 1.0, 63.0, w - 2.0, split_y - 63.0), + Region::Transcript, + &lines, + state, + follow, + ); + p.split(Rect::new(x + 1.0, split_y, w - 2.0, 1.0), Split::Editor); + p.fill(Rect::new(x + 1.0, split_y + 1.0, w - 2.0, 32.0), BAR); + p.button( + Rect::new(x + 5.0, split_y + 2.0, 190.0, 30.0), + if state.script { + "Script · replace page ⇄" + } else { + "Expression · fresh VM ⇄" + }, + Action::Mode, + true, + ); + p.button( + Rect::new(width - 95.0, split_y + 2.0, 89.0, 30.0), + "Run ↵", + Action::Submit, + false, + ); + let input_area = Rect::new(x + 3.0, split_y + 35.0, w - 6.0, (editor - 62.0).max(24.0)); + p.layout + .actions + .push((input_area, Action::Focus(Focus::Input))); + if state.selection && state.focus == Some(Focus::Input) { + p.fill(input_area, tint(state.accent)); + } + if state.focus == Some(Focus::Input) { + p.fill( + Rect::new(x + 2.0, split_y + 35.0, 2.0, input_area.height), + state.accent, + ); + } + let mut input = state.input.clone(); + if state.focus == Some(Focus::Input) { + input.insert_str(state.cursor, &format!("{}│", state.preedit)); + } + if input.is_empty() { + input = if state.script { + "// Complete script; must render a page" + } else { + "// Try \"Hello Endor\"" + } + .into(); + } + let mut input_lines = Vec::new(); + multiline(&mut input_lines, &input, TEXT); + p.lines(input_area, Region::Input, &input_lines, state, false); + p.label( + x + 10.0, + bottom - 23.0, + if state.input_error.is_empty() { + "Enter: run · Shift+Enter: newline · ⌘/Ctrl+↑↓: history" + } else { + &state.input_error + }, + if state.input_error.is_empty() { + MUTED + } else { + ERROR + }, + false, + ); + } + Tab::Sources => { + p.fill(Rect::new(x, 32.0, w, 30.0), BAR); + p.button( + Rect::new(x + 3.0, 32.0, 139.0, 29.0), + "Current snapshot", + Action::Snapshot, + !state.cloud, + ); + p.button( + Rect::new(x + 145.0, 32.0, 107.0, 29.0), + "Cloud files", + Action::Cloud, + state.cloud, + ); + if state.cloud { + p.button( + Rect::new(width - 92.0, 32.0, 88.0, 29.0), + "Refresh", + Action::CloudRefresh, + false, + ); + let tree = state.tree_width.clamp(120.0, (w - 180.0).max(120.0)); + let code_x = x + tree + 2.0; + p.label(x + 10.0, 69.0, "CLOUD FILES", MUTED, false); + let file_lines = state + .cloud_sources + .files + .iter() + .map(|file| { + let mut l = Line::new(&file.path, TEXT); + l.action = Some(Action::CloudOpen(file.id.clone())); + l + }) + .collect::>(); + p.lines( + Rect::new(x + 1.0, 92.0, tree - 1.0, bottom - 92.0), + Region::Tree, + &file_lines, + state, + false, + ); + p.split(Rect::new(x + tree, 63.0, 1.0, bottom - 63.0), Split::Tree); + let mut source_lines = Vec::new(); + if let Some(source) = &state.cloud_sources.opened { + p.label(code_x + 10.0, 69.0, &source.path, MUTED, false); + for (i, line) in source.code.split('\n').enumerate() { + source_lines.push(Line::new(format!("{:>5} {}", i + 1, line), TEXT)); + } + } else { + multiline( + &mut source_lines, + "No cloud file open\n\nNo provider connected.\nCloud files will open here as full source.\nCurrent snapshot contains your last successful script.", + MUTED, + ); + } + if !state.cloud_sources.error.is_empty() { + source_lines.push(Line::new(&state.cloud_sources.error, ERROR)); + } + p.lines( + Rect::new(code_x, 92.0, width - code_x, bottom - 92.0), + Region::Source, + &source_lines, + state, + false, + ); + } else { + let tree = state.tree_width.clamp(120.0, (w - 180.0).max(120.0)); + let code_x = x + tree + 2.0; + p.label(x + 10.0, 69.0, "ASTER AST", MUTED, false); + p.label( + code_x + 10.0, + 69.0, + &format!( + "app.main.endor · {} lines · read only", + doc.source.split('\n').count() + ), + MUTED, + false, + ); + let mut tree_lines = Vec::new(); + if let Some(root) = &doc.root { + let mut flat = Vec::new(); + flatten(root, 0, &mut flat); + for (depth, n) in flat { + let mut l = + Line::new(format!("{}{} {}", " ".repeat(depth), n.kind, n.name), TEXT); + l.selected = state.selected_node_id.as_deref() == Some(&n.id); + l.action = Some(Action::Node(n.id.clone(), n.start_line)); + tree_lines.push(l); + } + } else { + tree_lines.push(Line::new("No submitted source", MUTED)); + } + p.lines( + Rect::new(x + 1.0, 92.0, tree - 1.0, bottom - 92.0), + Region::Tree, + &tree_lines, + state, + false, + ); + p.split(Rect::new(x + tree, 63.0, 1.0, bottom - 63.0), Split::Tree); + let selected = state + .selected_node_id + .as_deref() + .and_then(|id| doc.node(id)); + let code_lines = doc + .source + .replace("\r\n", "\n") + .split('\n') + .enumerate() + .map(|(i, s)| { + let mut l = + Line::new(format!("{:>5} {}", i + 1, s.replace('\t', " ")), TEXT); + l.selected = + selected.is_some_and(|n| i + 1 >= n.start_line && i < n.end_line); + l + }) + .collect::>(); + p.lines( + Rect::new(code_x, 92.0, width - code_x, bottom - 92.0), + Region::Source, + &code_lines, + state, + false, + ); + } + } + Tab::Network => { + p.fill(Rect::new(x, 32.0, w, 30.0), BAR); + p.button( + Rect::new(x + 3.0, 32.0, 62.0, 29.0), + "Clear", + Action::ClearNetwork, + false, + ); + let filter_area = Rect::new(x + 72.0, 35.0, (w - 85.0).max(100.0), 24.0); + p.fill( + filter_area, + if state.focus == Some(Focus::Filter) { + tint(state.accent) + } else { + BG + }, + ); + p.label( + filter_area.x + 7.0, + filter_area.y + 3.0, + &format!( + "Filter: {}{}", + state.filter, + if state.focus == Some(Focus::Filter) { + "│" + } else { + "" + } + ), + MUTED, + false, + ); + p.layout + .actions + .push((filter_area, Action::Focus(Focus::Filter))); + p.label( + x + 10.0, + 69.0, + "METHOD STATUS TIME PATH", + MUTED, + true, + ); + let divider = 92.0 + (bottom - 92.0) * state.network_fraction; + let filter = state.filter.to_lowercase(); + let visible = records + .iter() + .filter(|r| r.id > state.network_after) + .filter(|r| { + format!( + "{} {} {}", + r.method, + r.path, + r.status.map_or("pending".into(), |s| s.to_string()) + ) + .to_lowercase() + .contains(&filter) + }) + .collect::>(); + let mut lines = Vec::new(); + for r in &visible { + let mut l = Line::new( + format!( + "{:<7} {:<6} {:>5} ms {}", + r.method, + r.status.map_or("…".into(), |s| s.to_string()), + r.elapsed_ms, + r.path + ), + if r.status.is_some_and(|s| s >= 400) { + ERROR + } else { + TEXT + }, + ); + l.selected = state.selected_request == Some(r.id); + l.action = Some(Action::Request(r.id)); + lines.push(l); + } + if lines.is_empty() { + lines.push(Line::new( + "No matching requests. Listening to Tessera's local API.", + MUTED, + )); + } + p.lines( + Rect::new(x + 1.0, 92.0, w - 2.0, divider - 92.0), + Region::Requests, + &lines, + state, + false, + ); + p.split(Rect::new(x + 1.0, divider, w - 2.0, 1.0), Split::Network); + let selected = records + .iter() + .find(|r| Some(r.id) == state.selected_request); + let mut details = Vec::new(); + if let Some(r) = selected { + request_details(&mut details, r); + } else { + multiline( + &mut details, + "Select a request to inspect headers and bodies.\n\nCapture scope: 127.0.0.1:4737 in this Tessera process.\n80 most recent requests; body previews up to 32 KiB.\nOnly Content-Type and Content-Length request headers are recorded.\nExternal browser / OS traffic is not captured.", + MUTED, + ); + } + p.lines( + Rect::new(x + 1.0, divider + 5.0, w - 2.0, bottom - divider - 5.0), + Region::Details, + &details, + state, + false, + ); + } + Tab::Settings => { + p.label(x + 24.0, 62.0, "Appearance", TEXT, false); + p.label( + x + 24.0, + 90.0, + "Accent color · tabs, focus and execution separators", + MUTED, + false, + ); + for (i, color) in PALETTE.iter().enumerate() { + let r = Rect::new(x + 24.0 + i as f32 * 44.0, 122.0, 32.0, 32.0); + p.fill(r, *color); + if *color == state.accent { + p.label(r.x + 10.0, r.y + 6.0, "✓", BG, false); + } + p.layout.actions.push((r, Action::Theme(i))); + } + p.label( + x + 24.0, + 176.0, + "Custom hex · Enter to apply (bright colors adjusted)", + MUTED, + false, + ); + let custom = Rect::new(x + 24.0, 204.0, 200.0, 32.0); + p.fill(custom, BAR); + p.label( + custom.x + 10.0, + custom.y + 6.0, + &format!( + "{}{}", + state.custom, + if state.focus == Some(Focus::Custom) { + "│" + } else { + "" + } + ), + TEXT, + true, + ); + p.layout + .actions + .push((custom, Action::Focus(Focus::Custom))); + if !state.input_error.is_empty() { + p.label(x + 24.0, 245.0, &state.input_error, ERROR, false); + } + p.fill(Rect::new(x + 24.0, 285.0, w - 48.0, 1.0), BORDER); + p.label(x + 24.0, 305.0, "Theme preview", TEXT, false); + p.fill(Rect::new(x + 24.0, 340.0, w - 48.0, 2.0), state.accent); + p.label(x + 32.0, 353.0, "› \"Hello\"", TEXT, true); + p.label(x + 32.0, 380.0, "‹ \"Hello\"", OK, true); + p.label( + x + 24.0, + 430.0, + "Settings last for this window session. Source is not persisted.", + MUTED, + false, + ); + } + } + p.fill(Rect::new(x + 1.0, bottom, w - 1.0, 22.0), BAR); + p.label( + x + 9.0, + bottom + 3.0, + &text::fit( + &format!( + "● 127.0.0.1:4737 · {} captured · F12 / ⌘⌥I", + records + .iter() + .filter(|r| r.id > state.network_after) + .count() + ), + w - 20.0, + TextStyle::code(), + ), + MUTED, + false, ); - fill( - &mut list, - Rect::new(panel_x, header_height - scale, panel_width, scale), - 0.0, - BORDER, - ); - fill( - &mut list, - Rect::new(panel_x, code_y, panel_width, height - code_y), - 0.0, - PANEL_ALT, - ); - fill( - &mut list, - Rect::new(panel_x, code_y, panel_width, scale), - 0.0, - BORDER, - ); - - text( - &mut list, - panel_x + 14.0 * scale, - 15.0 * scale, - "DEVELOPER", - scale, + p.list.push(DrawCommand::PopClip); + let mut scaled = DisplayList::default(); + for cmd in p.list.commands() { + let rect = + |r: &Rect| Rect::new(r.x * scale, r.y * scale, r.width * scale, r.height * scale); + scaled.push(match cmd { + DrawCommand::FillRoundedRect { + rect: r, + radius, + color, + } => DrawCommand::FillRoundedRect { + rect: rect(r), + radius: radius * scale, + color: *color, + }, + DrawCommand::Text { + origin, + value, + style, + color, + } => DrawCommand::Text { + origin: Point::new(origin.x * scale, origin.y * scale), + value: value.clone(), + style: style.scaled(scale), + color: *color, + }, + DrawCommand::PushClip(r) => DrawCommand::PushClip(rect(r)), + other => other.clone(), + }); + } + (scaled, p.layout) +} +fn request_details(out: &mut Vec, r: &Exchange) { + multiline( + out, + &format!( + "#{} {} {}\n{} · {} · {} ms\nStatus: {}", + r.id, + r.method, + r.path, + r.timestamp, + r.origin, + r.elapsed_ms, + r.status.map_or("pending".into(), |s| s.to_string()) + ), TEXT, ); - text( - &mut list, - width - 116.0 * scale, - 15.0 * scale, - "F12 TOGGLE", - scale, - MUTED, - ); - - text( - &mut list, - panel_x + 14.0 * scale, - header_height + 13.0 * scale, - "ARCHITECTURE", - scale, - MUTED, - ); - - let mut layout = DeveloperToolsLayout::default(); - if let Some(root) = &document.root { - let mut flattened = Vec::new(); - flatten(root, 0, &mut flattened); - let row_height = 24.0 * scale; - let first_y = header_height + 34.0 * scale; - let maximum_rows = ((tree_height - 40.0 * scale) / row_height).max(0.0) as usize; - - for (index, (depth, node)) in flattened.into_iter().take(maximum_rows).enumerate() { - let y = first_y + index as f32 * row_height; - let row = Rect::new( - panel_x + 7.0 * scale, - y, - panel_width - 14.0 * scale, - row_height, - ); - if state.selected_node_id.as_deref() == Some(node.id.as_str()) { - fill(&mut list, row, 5.0 * scale, SELECTED); - } - let text_x = row.x + (9.0 + depth as f32 * 14.0) * scale; - let label = typography::fit( - &format!("{} {}", node.kind, node.name), - (width - 14.0 * scale - text_x).max(0.0), - TextStyle::code().scaled(scale), - ); - text(&mut list, text_x, row.y + 3.0 * scale, &label, scale, TEXT); - layout.rows.push(TreeRowHit { - rect: row, - node_id: node.id.clone(), - }); - } - } else { - text( - &mut list, - panel_x + 14.0 * scale, - header_height + 48.0 * scale, - "NO RENDER TREE", - scale, - MUTED, - ); - } - - text( - &mut list, - panel_x + 14.0 * scale, - code_y + 16.0 * scale, - "SOURCE", - scale, - MUTED, - ); - draw_source( - &mut list, - Rect::new(panel_x, code_y, panel_width, height - code_y), - scale, - document, - state.selected_node_id.as_deref(), - ); - - (list, layout) -} - -fn draw_source( - list: &mut DisplayList, - area: Rect, - scale: f32, - document: &RenderDocument, - selected_id: Option<&str>, -) { - if document.source.is_empty() { - text( - list, - area.x + 14.0 * scale, - area.y + 50.0 * scale, - "NO SOURCE LOADED", - scale, - MUTED, - ); - return; - } - - let normalized_source = document.source.replace("\r\n", "\n").replace('\r', "\n"); - let all_lines: Vec<_> = normalized_source.lines().collect(); - let selected = selected_id.and_then(|id| document.node(id)); - let start = selected - .map(|node| node.start_line.saturating_sub(1)) - .unwrap_or(0) - .min(all_lines.len()); - let declared_end = selected - .map(|node| node.end_line) - .unwrap_or(all_lines.len()); - let end = if declared_end == 0 { - all_lines.len() - } else { - declared_end.min(all_lines.len()) - }; - let line_height = 18.0 * scale; - let first_y = area.y + 42.0 * scale; - let maximum_lines = - ((area.y + area.height - first_y - 10.0 * scale) / line_height).max(0.0) as usize; - let source_width = (area.width - 65.0 * scale).max(0.0); - - for (offset, source_line) in all_lines[start..end].iter().take(maximum_lines).enumerate() { - let line_number = start + offset + 1; - let y = first_y + offset as f32 * line_height; - text( - list, - area.x + 12.0 * scale, - y, - &format!("{:>4}", line_number), - scale, - MUTED, - ); - text( - list, - area.x + 55.0 * scale, - y, - &typography::fit( - &source_line.replace('\t', " "), - source_width, - TextStyle::code().scaled(scale), - ), - scale, - TEXT, + for (title, body) in [ + ("REQUEST HEADERS", &r.request_headers), + ("REQUEST BODY", &r.request), + ("RESPONSE HEADERS", &r.response_headers), + ("RESPONSE BODY", &r.response), + ] { + out.push(Line::new("", MUTED)); + let mut l = Line::new(title, MUTED); + l.divider = true; + out.push(l); + multiline( + out, + if body.is_empty() { "(empty)" } else { body }, + if title == "RESPONSE BODY" && r.status.is_some_and(|s| s >= 400) { + ERROR + } else { + TEXT + }, ); } } - -fn flatten<'a>(node: &'a CodeNode, depth: usize, output: &mut Vec<(usize, &'a CodeNode)>) { - output.push((depth, node)); - for child in &node.children { - flatten(child, depth + 1, output); - } -} - -fn fill(list: &mut DisplayList, rect: Rect, radius: f32, color: Color) { - list.push(DrawCommand::FillRoundedRect { - rect, - radius, - color, - }); -} - -fn text(list: &mut DisplayList, x: f32, y: f32, value: &str, scale: f32, color: Color) { - list.push(DrawCommand::Text { - origin: Point::new(x, y), - value: value.to_owned(), - style: TextStyle::code().scaled(scale), - color, - }); -} diff --git a/src/display_list.rs b/src/display_list.rs index 4b48879..a4727c5 100644 --- a/src/display_list.rs +++ b/src/display_list.rs @@ -32,6 +32,8 @@ impl Color { #[derive(Clone, Debug)] pub enum DrawCommand { Clear(Color), + PushClip(Rect), + PopClip, FillRoundedRect { rect: Rect, radius: f32, diff --git a/src/endor_host.rs b/src/endor_host.rs index 0d635c9..f70439c 100644 --- a/src/endor_host.rs +++ b/src/endor_host.rs @@ -101,6 +101,44 @@ pub fn compile(source: &str, namespace: &str, submission: u64) -> Result Result { + if source.len() > MAX_SOURCE_BYTES { + bail!("expression exceeds the 1 MiB limit"); + } + let source = EndorReader::from_text("console expression", source); + let ast = frontend::parse_source_ast(&source, frontend::ParseMode::Expression)?; + AstBudget::default().visit_ast_root(&ast)?; + let compiled = compiler::compile_ast(&ast, &source, &compiler::CompileOptions::default()) + .map_err(|error| source.annotate(error))?; + let mut candidate = Candidate::new()?; + let result = (|| { + let globals = candidate.vm.new_dict()?; + candidate.globals = Some(globals); + candidate.roots.push(globals); + let code = compiled.load(&mut candidate.vm)?; + candidate.roots.push(code); + let value = candidate + .vm + .execute_with_limits(code, globals, LIMITS) + .map_err(|error| runtime_error(&candidate.vm, error))?; + let rendered = match &value { + Value::Nil => "nil".to_owned(), + Value::Bool(v) => v.to_string(), + Value::Text(v) => format!("{v:?}"), + Value::Number(v) => v.to_string(), + Value::Object(v) => candidate.vm.repr(*v)?, + }; + candidate.vm.release_value(value)?; + Ok(rendered) + })(); + let cleanup = candidate.close(); + match (result, cleanup) { + (Ok(value), Ok(())) => Ok(value), + (Err(e), _) | (_, Err(e)) => Err(e), + } +} + fn compile_plan(source: &SourceUnit, plan: &SourcePlan) -> Result> { let mut globals = BTreeSet::from(["ui".to_owned()]); // Match Aster module behavior for function forward references. Bindings are diff --git a/src/main.rs b/src/main.rs index 87b2804..fff12f9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,4 @@ +mod activity; mod api; mod app; mod developer_tools; @@ -9,6 +10,7 @@ mod geometry; mod layout; mod scene; mod software_renderer; +mod sources; mod text; mod ui_bridge; @@ -23,7 +25,8 @@ fn main() -> Result<()> { let event_loop = EventLoop::::with_user_event().build()?; event_loop.set_control_flow(ControlFlow::Wait); let namespace = Arc::new(RwLock::new(NamespaceState::default())); - api::start(namespace.clone(), event_loop.create_proxy())?; - event_loop.run_app(&mut TesseraApp::new(namespace))?; + let activity = api::start(namespace.clone(), event_loop.create_proxy())?; + let mut app = TesseraApp::new(namespace, activity, event_loop.create_proxy()); + event_loop.run_app(&mut app)?; Ok(()) } diff --git a/src/scene.rs b/src/scene.rs index 40fefab..1333b3f 100644 --- a/src/scene.rs +++ b/src/scene.rs @@ -1,4 +1,5 @@ use crate::{ + activity::Activity, developer_tools::{self, DeveloperToolsLayout, DeveloperToolsState}, display_list::DisplayList, document::RenderDocument, @@ -14,15 +15,22 @@ pub fn build_scene( height: u32, scale: f32, document: &RenderDocument, - developer_tools_state: &DeveloperToolsState, + developer_tools_state: &mut DeveloperToolsState, + activity: &Activity, ) -> DisplayScene { let mut display_list = document.display_list(scale).unwrap_or_else(|_| { RenderDocument::default() .display_list(scale) .expect("default document is valid") }); - let (developer_list, developer_layout) = - developer_tools::build(width, height, scale, document, developer_tools_state); + let (developer_list, developer_layout) = developer_tools::build( + width, + height, + scale, + document, + developer_tools_state, + activity, + ); display_list.extend(developer_list); DisplayScene { diff --git a/src/software_renderer.rs b/src/software_renderer.rs index 4e7d967..49ac39a 100644 --- a/src/software_renderer.rs +++ b/src/software_renderer.rs @@ -12,10 +12,34 @@ impl SoftwareRenderer { pixels: target, width, height, + clip: Rect::new(0.0, 0.0, width as f32, height as f32), }; + let mut clips = Vec::new(); for command in list.commands() { match command { + DrawCommand::PushClip(rect) => { + clips.push(canvas.clip); + let x = canvas.clip.x.max(rect.x); + let y = canvas.clip.y.max(rect.y); + canvas.clip = Rect::new( + x, + y, + (canvas.clip.x + canvas.clip.width) + .min(rect.x + rect.width) + .max(x) + - x, + (canvas.clip.y + canvas.clip.height) + .min(rect.y + rect.height) + .max(y) + - y, + ); + } + DrawCommand::PopClip => { + if let Some(clip) = clips.pop() { + canvas.clip = clip; + } + } DrawCommand::Clear(color) => canvas.clear(*color), DrawCommand::FillRoundedRect { rect, @@ -43,6 +67,7 @@ struct Canvas<'a> { pixels: &'a mut [u32], width: u32, height: u32, + clip: Rect, } impl Canvas<'_> { @@ -97,15 +122,29 @@ impl Canvas<'_> { fn clamped_bounds(&self, rect: Rect) -> (i32, i32, i32, i32) { ( - rect.x.max(0.0).floor() as i32, - rect.y.max(0.0).floor() as i32, - (rect.x + rect.width).min(self.width as f32).ceil() as i32, - (rect.y + rect.height).min(self.height as f32).ceil() as i32, + rect.x.max(self.clip.x).max(0.0).floor() as i32, + rect.y.max(self.clip.y).max(0.0).floor() as i32, + (rect.x + rect.width) + .min(self.clip.x + self.clip.width) + .min(self.width as f32) + .ceil() as i32, + (rect.y + rect.height) + .min(self.clip.y + self.clip.height) + .min(self.height as f32) + .ceil() as i32, ) } fn blend_pixel(&mut self, x: i32, y: i32, source: Color) { - if x < 0 || y < 0 || x >= self.width as i32 || y >= self.height as i32 || source.alpha == 0 + if x < 0 + || y < 0 + || x >= self.width as i32 + || y >= self.height as i32 + || source.alpha == 0 + || (x as f32) < self.clip.x + || (y as f32) < self.clip.y + || (x as f32) >= self.clip.x + self.clip.width + || (y as f32) >= self.clip.y + self.clip.height { return; } diff --git a/src/sources.rs b/src/sources.rs new file mode 100644 index 0000000..be4e127 --- /dev/null +++ b/src/sources.rs @@ -0,0 +1,53 @@ +//! Cloud source integration seam. The host installs a provider when one exists; +//! the default workspace stays disconnected and never fabricates or stores files. +use anyhow::Result; + +#[derive(Clone, Debug)] +pub struct SourceFile { + pub id: String, + pub path: String, +} +#[derive(Clone, Debug)] +pub struct OpenedSource { + pub path: String, + pub code: String, +} + +pub trait CloudSourceProvider: std::fmt::Debug + Send { + fn list_files(&mut self) -> Result>; + fn open_file(&mut self, id: &str) -> Result; +} +#[derive(Debug, Default)] +pub struct SourceWorkspace { + pub provider: Option>, + pub files: Vec, + pub opened: Option, + pub error: String, +} +impl SourceWorkspace { + pub fn refresh(&mut self) { + let Some(provider) = &mut self.provider else { + self.error = "No cloud file provider configured".into(); + return; + }; + match provider.list_files() { + Ok(files) => { + self.files = files; + self.error.clear(); + } + Err(error) => self.error = error.to_string(), + } + } + pub fn open(&mut self, id: &str) { + let Some(provider) = &mut self.provider else { + return; + }; + match provider.open_file(id) { + Ok(source) => { + self.opened = Some(source); + self.error.clear(); + } + Err(error) => self.error = error.to_string(), + } + } +}