mirror of
https://github.com/storytold/AniCraft.git
synced 2026-11-24 11:32:15 +01:00
Merge outside PR #216: feat(control): live control port and MCP bridge (ADR 0104) (M8)
# Conflicts: # CHANGELOG.md # docs/roadmap.md # src/main.rs
This commit is contained in:
commit
6f1adc4ea2
17 files changed
+1303
-20
No files matched your search
+10
@@ -340,6 +340,9 @@ impl PolyStarOptions {
|
||||
pub struct App {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) updates: crate::updates::Updates,
|
||||
/// The live control port, with `--control` (ADR 0104).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) remote: Option<crate::remote::Remote>,
|
||||
pub s: Session,
|
||||
pub tool: Tool,
|
||||
pub view: StageView,
|
||||
@@ -669,6 +672,8 @@ impl App {
|
||||
let mut app = App {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
updates: Default::default(),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
remote: None,
|
||||
s: session,
|
||||
tool: Tool::Select,
|
||||
view: StageView { zoom: 1.0, pan: egui::Vec2::ZERO, fit: true, fitted: None, clip_to_stage: false },
|
||||
@@ -3769,6 +3774,8 @@ impl eframe::App for App {
|
||||
self.recovery.finish(&self.s, clean);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
self.updates.finish();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
crate::remote::finish(self);
|
||||
}
|
||||
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
@@ -3790,6 +3797,9 @@ impl App {
|
||||
}
|
||||
}
|
||||
self.handle_screenshot(&ctx);
|
||||
// An assistant's edits (ADR 0104), before anything draws: they show in this frame.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
crate::remote::poll(self, &ctx);
|
||||
self.poll_font_scan(&ctx);
|
||||
self.follow_system_look(&ctx);
|
||||
if let Some(p) = platform::picked_file() {
|
||||
|
||||
+33
-4
@@ -152,7 +152,7 @@ struct Look {
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn run(attempt: startup::Attempt, file: Option<&Path>, shot: Option<PathBuf>, open: Option<String>, look: Look) -> eframe::Result {
|
||||
fn run(attempt: startup::Attempt, file: Option<&Path>, shot: Option<PathBuf>, open: Option<String>, look: Look, control: Option<u16>) -> eframe::Result {
|
||||
let options = attempt.options(eframe::NativeOptions {
|
||||
viewport: platform::viewport(egui::ViewportBuilder::default().with_title("AniCraft").with_inner_size([1600.0, 940.0]).with_min_inner_size([960.0, 600.0])),
|
||||
..Default::default()
|
||||
@@ -184,6 +184,10 @@ fn run(attempt: startup::Attempt, file: Option<&Path>, shot: Option<PathBuf>, op
|
||||
start::open(&mut a);
|
||||
}
|
||||
a.preview_look(&cc.egui_ctx, look.theme, look.scale);
|
||||
// `--control`: an assistant can edit this window live (ADR 0104).
|
||||
if let Some(port) = control {
|
||||
remote::start(&mut a, &cc.egui_ctx, port);
|
||||
}
|
||||
a.open_panel(open.as_deref());
|
||||
match report {
|
||||
// An imported document says what came across, as opening it from the menu does.
|
||||
@@ -214,6 +218,8 @@ struct Args {
|
||||
open: Option<String>,
|
||||
renderer: Option<String>,
|
||||
look: Look,
|
||||
/// `--control <port>`: the live control port (ADR 0104).
|
||||
control: Option<u16>,
|
||||
/// `--version` / `--help`: print and leave.
|
||||
print: Option<Print>,
|
||||
}
|
||||
@@ -234,6 +240,8 @@ fn parse_args(args: impl IntoIterator<Item = String>) -> Result<Args, String> {
|
||||
match a.as_str() {
|
||||
"--screenshot" => out.shot = Some(PathBuf::from(args.next().ok_or("--screenshot needs a file name")?)), // i18n-exempt: a console message
|
||||
"--open" => out.open = args.next(),
|
||||
// i18n-exempt: a console message
|
||||
"--control" => out.control = Some(anicraft_cli::control::parse_port(&args.next().unwrap_or_default()).map_err(|e| format!("--control: {e}"))?),
|
||||
"--renderer" => out.renderer = args.next(),
|
||||
"--shot-width" => match args.next().and_then(|s| s.parse::<u32>().ok()) {
|
||||
Some(w) if (64..=8192).contains(&w) => out.look.shot_width = Some(w),
|
||||
@@ -270,7 +278,7 @@ fn parse_args(args: impl IntoIterator<Item = String>) -> Result<Args, String> {
|
||||
/// `--help` (the console's text, in English).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
// i18n-exempt: the --help console text
|
||||
const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width <px>]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme graphite|high-contrast] [--scale <percent>] [--lang <code>|auto|pseudo] [--open palette|shortcuts|helpbone|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|rulers|editguides|editgrid|symboledit|groups|combine|nineslice|nineslicedit|brush|brushing|polystar|paintinside|drawingedit|shapeenvelope|brushlibrary|brushcurve|paintbrush|eraser|erasing|erasemerge|tiltbrush|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|bones|springbones|shapebones|shapeweights|layerdepth|layerdepthview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|ease|easepreset|plugineases|pluginexport|pluginexportwindow|library|librarymenu|libraryfolders|colour|layerprops|frameview|layercolour|timelinepolish|dock|dockicons|floattabs|docknarrow|workspaces|animator|designer|gradient|gradientbucket|swatches|swatchpanel]\n\
|
||||
const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width <px>]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme graphite|high-contrast] [--scale <percent>] [--lang <code>|auto|pseudo] [--control <port>] [--open palette|shortcuts|helpbone|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|rulers|editguides|editgrid|symboledit|groups|combine|nineslice|nineslicedit|brush|brushing|polystar|paintinside|drawingedit|shapeenvelope|brushlibrary|brushcurve|paintbrush|eraser|erasing|erasemerge|tiltbrush|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|bones|springbones|shapebones|shapeweights|layerdepth|layerdepthview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|ease|easepreset|plugineases|pluginexport|pluginexportwindow|library|librarymenu|libraryfolders|colour|layerprops|frameview|layercolour|timelinepolish|dock|dockicons|floattabs|docknarrow|workspaces|animator|designer|gradient|gradientbucket|swatches|swatchpanel]\n\
|
||||
--renderer the window's graphics (also ANICRAFT_RENDERER); default automatic, falling back to OpenGL\n\
|
||||
--open shows a panel at start (handy with --screenshot for visual checks)\n\
|
||||
--shot-width scales the screenshot down to this width (the user guide's pictures)\n\
|
||||
@@ -278,6 +286,8 @@ const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--sc
|
||||
--theme the interface palette for this run (not saved)\n\
|
||||
--scale the interface scale for this run, 75 to 200 (not saved)\n\
|
||||
--lang the interface language for this run (not saved); pseudo tests the layout\n\
|
||||
--control lets an assistant edit this window live through a port on this computer\n\
|
||||
(also ANICRAFT_CONTROL_PORT; 9878 by convention; see docs/control-protocol.md)\n\
|
||||
Headless use: anicraft-cli --help";
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -307,7 +317,21 @@ fn main() -> eframe::Result {
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
let Args { shot, file, open, renderer, look, .. } = args;
|
||||
let Args { shot, file, open, renderer, look, control, .. } = args;
|
||||
// ANICRAFT_CONTROL_PORT when there is no --control; a bad port stops here, before a window.
|
||||
let control = match control {
|
||||
Some(p) => Some(p),
|
||||
None => match std::env::var(anicraft_cli::control::PORT_ENV).ok().filter(|v| !v.trim().is_empty()) {
|
||||
Some(v) => match anicraft_cli::control::parse_port(&v) {
|
||||
Ok(p) => Some(p),
|
||||
Err(e) => {
|
||||
eprintln!("{}: {e}", anicraft_cli::control::PORT_ENV);
|
||||
std::process::exit(2);
|
||||
}
|
||||
},
|
||||
None => None,
|
||||
},
|
||||
};
|
||||
// macOS hands documents over as Apple Events, the one that launched the app included: listen
|
||||
// from before the event loop starts until it ends (ADR 0062).
|
||||
let _documents = platform::listen_for_documents();
|
||||
@@ -326,7 +350,7 @@ fn main() -> eframe::Result {
|
||||
let attempts = startup::plan(platform::forced_backend(renderer.as_deref()), prefs::Prefs::load().window_backend, &platform::window_attempts(platform::OS), &last);
|
||||
for (n, attempt) in attempts.iter().enumerate() {
|
||||
startup::trying(attempt, n + 1, attempts.len());
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(*attempt, file.as_deref(), shot.clone(), open.clone(), look.clone())));
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(*attempt, file.as_deref(), shot.clone(), open.clone(), look.clone(), control)));
|
||||
why = match result {
|
||||
Ok(Ok(())) => {
|
||||
// The window's graphics device was lost mid-session (ADR 0092): it closed
|
||||
@@ -393,6 +417,11 @@ mod args_tests {
|
||||
assert_eq!(parse(&["--screenshot", "a.png", "--shot-width", "1200"]).look.shot_width, Some(1200));
|
||||
assert!(parse_args(["--shot-width".to_string(), "9".to_string()]).is_err());
|
||||
assert_eq!(parse(&["--version"]).print, Some(Print::Version));
|
||||
// `--control <port>` (ADR 0104): a port from 1 to 65535, or an error before any window.
|
||||
assert_eq!(parse(&["--control", "9878"]).control, Some(9878));
|
||||
for bad in [&["--control"][..], &["--control", "0"], &["--control", "99999"], &["--control", "port"]] {
|
||||
assert!(parse_args(bad.iter().map(|a| a.to_string())).is_err(), "{bad:?}");
|
||||
}
|
||||
// And the file opens: the session starts with it, not the sample.
|
||||
let dir = std::env::temp_dir().join(format!("anicraft-shell-args-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
|
||||
@@ -363,6 +363,13 @@ pub fn status_bar(app: &mut App, ui: &mut egui::Ui) {
|
||||
let small = |t: String| text(Type::Data, t).color(T.text_faint);
|
||||
ui.label(small(tr!("undo {steps} · {size} MB", steps = app.s.history().undo_len(), size = format!("{:.1}", app.s.history().bytes() as f32 / (1024.0 * 1024.0)))));
|
||||
ui.add_space(12.0);
|
||||
// An assistant can edit this window (ADR 0104): always in view while that is so.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(port) = crate::remote::port(app) {
|
||||
ui.label(text(Type::Label, tr!("Remote control on (port {port})", port = port)).color(T.text_faint))
|
||||
.on_hover_text(tr!("An assistant can edit this document through a control port on this computer. Its edits appear here at once and undo like your own. Started with --control; close AniCraft to turn it off."));
|
||||
ui.add_space(12.0);
|
||||
}
|
||||
if let Some(a) = crate::autosave::status(app, now) {
|
||||
ui.label(small(a)).on_hover_text(tr!("A recovery copy of your unsaved work. If AniCraft closes unexpectedly, the next start offers it back."));
|
||||
ui.add_space(12.0);
|
||||
|
||||
@@ -412,6 +412,31 @@ pub fn recovery_dir() -> Option<PathBuf> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes a file only this user may read (the control port's token, ADR 0104), making its folder
|
||||
/// first. On Windows the settings folder (%APPDATA%) is already private to the user; elsewhere
|
||||
/// the file is made owner-only (0600).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn write_private_file(path: &std::path::Path, contents: &[u8]) -> std::io::Result<()> {
|
||||
use std::io::Write;
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
let mut options = std::fs::OpenOptions::new();
|
||||
options.write(true).create(true).truncate(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
|
||||
options.mode(0o600);
|
||||
// An older file keeps its mode when opened: tighten it first.
|
||||
if path.exists() {
|
||||
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
|
||||
}
|
||||
}
|
||||
let mut f = options.open(path)?;
|
||||
f.write_all(contents)?;
|
||||
f.sync_all()
|
||||
}
|
||||
|
||||
/// Whether the recovery folder was chosen explicitly (screenshot runs only touch it then).
|
||||
pub fn recovery_dir_overridden() -> bool {
|
||||
std::env::var_os("ANICRAFT_RECOVERY_DIR").is_some_and(|v| !v.is_empty())
|
||||
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
//! Remote control (ADR 0104, `docs/control-protocol.md`): `anicraft --control <port>` opens a
|
||||
//! control port on this computer, and an assistant (through `anicraft-cli mcp --bridge`) edits
|
||||
//! the open document live. The port, its threads and the tools are `anicraft_cli::control`'s;
|
||||
//! this module runs each call on the window's session at the start of a frame, writes the
|
||||
//! run's token to `control.json` in the settings folder, and removes it on exit.
|
||||
//!
|
||||
//! A call that edits waits while the person is dragging (or a plug-in dialog has its preview
|
||||
//! open), so the two never share an undo step. Typing in a field doesn't hold it back: the
|
||||
//! person's typed change is committed as its own step first, as clicking elsewhere would.
|
||||
|
||||
use crate::app::{App, Drag};
|
||||
use crate::platform;
|
||||
use anicraft_cli::{control, mcp};
|
||||
use anicraft_engine::Session;
|
||||
use serde_json::Value;
|
||||
use std::collections::VecDeque;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// An open control port.
|
||||
pub struct Remote {
|
||||
server: control::Server,
|
||||
/// Calls in arrival order; the first one that edits holds the rest back during a drag.
|
||||
waiting: VecDeque<control::Request>,
|
||||
token: String,
|
||||
/// `control.json`, when it could be written.
|
||||
file: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// Opens the control port; failures go to the status bar (the window still opens).
|
||||
pub fn start(app: &mut App, ctx: &egui::Context, port: u16) {
|
||||
let token = match control::token_from_env().map_or_else(control::new_token, Ok) {
|
||||
Ok(t) => t,
|
||||
Err(e) => {
|
||||
app.status_err(tr!("Remote control is off: {reason}", reason = e));
|
||||
return;
|
||||
}
|
||||
};
|
||||
let wake_ctx = ctx.clone();
|
||||
let server = match control::listen(port, token.clone(), Arc::new(move || wake_ctx.request_repaint())) {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
app.status_err(tr!("Remote control is off: port {port} is in use or not allowed ({reason}). Is another AniCraft already open with remote control?", port = port, reason = e));
|
||||
return;
|
||||
}
|
||||
};
|
||||
let file = control::control_file();
|
||||
let written = file.as_ref().map(|path| {
|
||||
let contents = control::ControlFile { port: server.port, token: token.clone(), pid: std::process::id(), version: env!("CARGO_PKG_VERSION").to_string() };
|
||||
platform::write_private_file(path, contents.to_json().to_string().as_bytes())
|
||||
});
|
||||
if let Some(Err(e)) = &written {
|
||||
// The port works with ANICRAFT_CONTROL_TOKEN; without the file a bridge can't find it.
|
||||
app.status_err(tr!("Remote control is on, but its token could not be saved ({reason}); set ANICRAFT_CONTROL_TOKEN for the assistant.", reason = e));
|
||||
}
|
||||
let file = if matches!(written, Some(Ok(()))) { file } else { None };
|
||||
app.remote = Some(Remote { server, waiting: VecDeque::new(), token, file });
|
||||
}
|
||||
|
||||
/// The port, while remote control is on (the status bar shows it).
|
||||
pub fn port(app: &App) -> Option<u16> {
|
||||
app.remote.as_ref().map(|r| r.server.port)
|
||||
}
|
||||
|
||||
/// Whether the person is in the middle of an edit a remote one must not join.
|
||||
fn person_is_dragging(app: &App, ctx: &egui::Context) -> bool {
|
||||
app.drag != Drag::None || app.plugin_dialog.is_some() || (app.s.in_gesture() && ctx.egui_is_using_pointer())
|
||||
}
|
||||
|
||||
/// Runs the waiting calls: at the start of a frame, so their edits draw in this one.
|
||||
pub fn poll(app: &mut App, ctx: &egui::Context) {
|
||||
let Some(r) = app.remote.as_mut() else { return };
|
||||
while let Some(req) = r.server.try_recv() {
|
||||
r.waiting.push_back(req);
|
||||
}
|
||||
loop {
|
||||
let dragging = person_is_dragging(app, ctx);
|
||||
let Some(r) = app.remote.as_mut() else { return };
|
||||
let Some(next) = r.waiting.front() else { return };
|
||||
if next.changes_document() && dragging && !next.expired() {
|
||||
// Look again shortly: the drag ends without a remote wake-up.
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(50));
|
||||
return;
|
||||
}
|
||||
let Some(req) = r.waiting.pop_front() else { return };
|
||||
// (An expired call is refused without running: it leaves the person's gesture alone.)
|
||||
if req.changes_document() && !req.expired() && !dragging && app.s.in_gesture() {
|
||||
// A typed property change still open: it becomes its own undo step first.
|
||||
app.s.end_gesture();
|
||||
}
|
||||
req.run(&mut Live(app));
|
||||
}
|
||||
}
|
||||
|
||||
/// On exit: calls still waiting are told so, and `control.json` goes (if it is still ours).
|
||||
pub fn finish(app: &mut App) {
|
||||
let Some(mut r) = app.remote.take() else { return };
|
||||
for req in r.waiting.drain(..) {
|
||||
// i18n-exempt: the protocol's English, read by the assistant (as MCP)
|
||||
req.refuse("AniCraft is closing");
|
||||
}
|
||||
if let Some(path) = &r.file {
|
||||
let ours = std::fs::read_to_string(path).ok().and_then(|t| control::ControlFile::parse(&t).ok()).is_some_and(|c| c.token == r.token);
|
||||
if ours {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The window as the tools' host: commands run with the follow-up the person's own get (the
|
||||
/// status line, the view a new document resets, Open Recent).
|
||||
struct Live<'a>(&'a mut App);
|
||||
|
||||
impl mcp::Host for Live<'_> {
|
||||
fn session(&self) -> &Session {
|
||||
&self.0.s
|
||||
}
|
||||
fn execute(&mut self, id: &str, params: &Value) -> Result<Value, String> {
|
||||
let selected = self.0.s.selection.len();
|
||||
let revision = self.0.s.revision;
|
||||
let v = self.0.s.execute(id, params).map_err(|e| e.to_string())?;
|
||||
// An edit to the document behind the start screen: show the document, so the person
|
||||
// sees it land (ADR 0059's start screen otherwise covers the workspace).
|
||||
if self.0.s.revision != revision {
|
||||
self.0.start = None;
|
||||
}
|
||||
self.0.announce(id, &v, selected);
|
||||
Ok(v)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::platform;
|
||||
|
||||
/// The CLI finds `control.json` with its own copy of the settings-folder rule (it can't use
|
||||
/// the shell); they must agree, or the bridge looks in the wrong place.
|
||||
#[test]
|
||||
fn the_bridge_looks_for_the_token_in_the_settings_folder() {
|
||||
assert_eq!(anicraft_cli::control::settings_dir(), platform::config_dir());
|
||||
assert_eq!(anicraft_cli::control::control_file(), platform::config_dir().map(|d| d.join("control.json")));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user