feat: build a resizable native developer workspace with console and network inspection
Verify Tessera GUI / verify (push) Failing after 7m12s
Verify Tessera GUI / verify (push) Failing after 7m12s
This commit is contained in:
@@ -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
|
||||
|
||||
|
||||
+14
-3
@@ -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.
|
||||
|
||||
@@ -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<Mutex<ActivityLog>>;
|
||||
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<u16>,
|
||||
pub elapsed_ms: u128,
|
||||
pub request_headers: String,
|
||||
pub response_headers: String,
|
||||
started: Instant,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct ActivityLog {
|
||||
pub records: VecDeque<Exchange>,
|
||||
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])
|
||||
}
|
||||
+161
-12
@@ -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<dyn Fn() + Send + Sync>;
|
||||
|
||||
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<RwLock<NamespaceState>>,
|
||||
proxy: EventLoopProxy<AppEvent>,
|
||||
) -> Result<()> {
|
||||
) -> Result<Activity> {
|
||||
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<Server>,
|
||||
namespace: Arc<RwLock<NamespaceState>>,
|
||||
notify: Notify,
|
||||
) -> Result<thread::JoinHandle<()>> {
|
||||
start_server_observed(
|
||||
server,
|
||||
namespace,
|
||||
notify,
|
||||
Arc::new(Mutex::new(ActivityLog::default())),
|
||||
Arc::new(|| {}),
|
||||
)
|
||||
}
|
||||
|
||||
fn start_server_observed(
|
||||
server: Arc<Server>,
|
||||
namespace: Arc<RwLock<NamespaceState>>,
|
||||
notify: Notify,
|
||||
activity: Activity,
|
||||
observer_notify: Notify,
|
||||
) -> Result<thread::JoinHandle<()>> {
|
||||
let (sender, receiver) = sync_channel::<BuildRequest>(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::<Vec<_>>()
|
||||
.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::Cursor<Vec<u8>>>) -> 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::<Vec<_>>()
|
||||
.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<RwLock<NamespaceState>>,
|
||||
notify: &Notify,
|
||||
sender: &SyncSender<BuildRequest>,
|
||||
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<RwLock<NamespaceState>>,
|
||||
sender: &SyncSender<BuildRequest>,
|
||||
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<RwLock<NamespaceState>>,
|
||||
notify: &Notify,
|
||||
) -> Response<std::io::Cursor<Vec<u8>>> {
|
||||
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<std::io
|
||||
add_header(
|
||||
&mut response,
|
||||
"Access-Control-Allow-Methods",
|
||||
"GET, PUT, DELETE, OPTIONS",
|
||||
"GET, PUT, POST, DELETE, OPTIONS",
|
||||
);
|
||||
add_header(
|
||||
&mut response,
|
||||
"Access-Control-Allow-Headers",
|
||||
"Content-Type",
|
||||
"Content-Type, X-Tessera-Origin",
|
||||
);
|
||||
response
|
||||
}
|
||||
|
||||
+154
-18
@@ -6,14 +6,15 @@ use std::{
|
||||
use softbuffer::{Context, Surface};
|
||||
use winit::{
|
||||
application::ApplicationHandler,
|
||||
dpi::{LogicalSize, PhysicalPosition},
|
||||
event::{ElementState, MouseButton, WindowEvent},
|
||||
event_loop::ActiveEventLoop,
|
||||
dpi::{LogicalPosition, LogicalSize, PhysicalPosition},
|
||||
event::{ElementState, Ime, MouseButton, MouseScrollDelta, WindowEvent},
|
||||
event_loop::{ActiveEventLoop, EventLoopProxy},
|
||||
keyboard::{Key, ModifiersState, NamedKey},
|
||||
window::{Window, WindowAttributes, WindowId},
|
||||
};
|
||||
|
||||
use crate::{
|
||||
activity::Activity,
|
||||
developer_tools::DeveloperToolsState,
|
||||
document::NamespaceState,
|
||||
geometry::Point,
|
||||
@@ -24,6 +25,7 @@ use crate::{
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum AppEvent {
|
||||
DocumentUpdated,
|
||||
ConsoleFailed { message: String, source: String },
|
||||
}
|
||||
|
||||
pub struct TesseraApp {
|
||||
@@ -35,19 +37,29 @@ pub struct TesseraApp {
|
||||
layout: SceneLayout,
|
||||
pointer: Point,
|
||||
modifiers: ModifiersState,
|
||||
activity: Activity,
|
||||
}
|
||||
|
||||
impl TesseraApp {
|
||||
pub fn new(namespace: Arc<RwLock<NamespaceState>>) -> Self {
|
||||
pub fn new(
|
||||
namespace: Arc<RwLock<NamespaceState>>,
|
||||
activity: Activity,
|
||||
proxy: EventLoopProxy<AppEvent>,
|
||||
) -> 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<AppEvent> 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<AppEvent> 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<AppEvent> 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(),
|
||||
|
||||
+1421
-253
File diff suppressed because it is too large
Load Diff
@@ -32,6 +32,8 @@ impl Color {
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum DrawCommand {
|
||||
Clear(Color),
|
||||
PushClip(Rect),
|
||||
PopClip,
|
||||
FillRoundedRect {
|
||||
rect: Rect,
|
||||
radius: f32,
|
||||
|
||||
@@ -101,6 +101,44 @@ pub fn compile(source: &str, namespace: &str, submission: u64) -> Result<RenderD
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluate exactly one expression in a disposable VM; never touch the published page.
|
||||
pub fn evaluate(source: &str) -> Result<String> {
|
||||
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<Vec<compiler::CompiledCode>> {
|
||||
let mut globals = BTreeSet::from(["ui".to_owned()]);
|
||||
// Match Aster module behavior for function forward references. Bindings are
|
||||
|
||||
+5
-2
@@ -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::<AppEvent>::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(())
|
||||
}
|
||||
|
||||
+11
-3
@@ -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 {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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<Vec<SourceFile>>;
|
||||
fn open_file(&mut self, id: &str) -> Result<OpenedSource>;
|
||||
}
|
||||
#[derive(Debug, Default)]
|
||||
pub struct SourceWorkspace {
|
||||
pub provider: Option<Box<dyn CloudSourceProvider>>,
|
||||
pub files: Vec<SourceFile>,
|
||||
pub opened: Option<OpenedSource>,
|
||||
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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user