mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-10 20:29:33 -06:00
Merge main into #1911
This commit is contained in:
+2
-1
File diff suppressed because one or more lines are too long
@@ -118,7 +118,7 @@ fn a_file_shared_online_is_joined_by_its_codes() {
|
||||
});
|
||||
for guest in [&b, &c] {
|
||||
assert!(guest.message.as_deref().unwrap_or_default().contains("Sharing was stopped"), "{:?}", guest.message);
|
||||
assert_eq!(guest.live().status, Status::Off, "over, not failed: nothing retries");
|
||||
assert!(guest.live().rejoinable() && !guest.live().status.active(), "over: nothing retries, and the tab says so");
|
||||
}
|
||||
assert_eq!(layers(&b), before + 2, "Bo keeps the copy");
|
||||
let folder = dir.path().join("files").join(&p.file);
|
||||
|
||||
@@ -160,7 +160,7 @@ fn revoked_links_stop_working_at_once() {
|
||||
assert_eq!((files.len(), files[0].people), (1, 3));
|
||||
// Revoked: Cy is out at once, the others stay.
|
||||
assert_eq!(ask(Admin::Revoke { file: file.clone(), link: review.link.id.clone() }), AdminReply::Done);
|
||||
pump(&mut [&mut a, &mut b, &mut c], "Cy out", |s| s[2].live().status == Status::Off && s[0].live().peers.len() == 1);
|
||||
pump(&mut [&mut a, &mut b, &mut c], "Cy out", |s| s[2].live().rejoinable() && s[0].live().peers.len() == 1);
|
||||
// Told as when a host stops: the session is over for Cy, whose copy stays open (no retries).
|
||||
assert!(c.message.as_deref().unwrap_or_default().contains("Sharing was stopped"), "{:?}", c.message);
|
||||
assert!(live(&b));
|
||||
|
||||
@@ -28,7 +28,7 @@ use crate::invite::Endpoint;
|
||||
use crate::join::{GuestConfig, Next, Outcome, Resuming, Seen, Taken, after, ask, closed, hello, resolved, take, too_large, unresolved};
|
||||
use crate::limits::NetLimits;
|
||||
use crate::requests::Publish;
|
||||
use crate::throttle::{PRESENCE_INTERVAL, Throttle, earliest};
|
||||
use crate::throttle::{PRESENCE_INTERVAL, Paced, Throttle, earliest};
|
||||
|
||||
/// A WebSocket the driver opens, writes and closes; what it receives comes back through the
|
||||
/// driver's event methods.
|
||||
@@ -79,6 +79,8 @@ pub(crate) struct Driver<S: Socket> {
|
||||
/// Your latest presence while not welcomed (sent with the welcome).
|
||||
pending: Option<Presence>,
|
||||
throttle: Throttle<Presence>,
|
||||
/// Sync messages waiting their turn (a long queue from while offline).
|
||||
paced: Paced<ClientMsg>,
|
||||
reconnect_at: Option<Instant>,
|
||||
/// What this connection asks a server (a managing one), and what follows its answers.
|
||||
asking: Option<(Box<Exchange>, Then)>,
|
||||
@@ -86,7 +88,7 @@ pub(crate) struct Driver<S: Socket> {
|
||||
}
|
||||
|
||||
impl<S: Socket> Driver<S> {
|
||||
fn new(sock: S, cfg: GuestConfig, inbox: Inbox) -> Self {
|
||||
fn new(sock: S, cfg: GuestConfig, inbox: Inbox, now: Instant) -> Self {
|
||||
Self {
|
||||
sock,
|
||||
cfg,
|
||||
@@ -97,6 +99,7 @@ impl<S: Socket> Driver<S> {
|
||||
resume: Resuming::default(),
|
||||
pending: None,
|
||||
throttle: Throttle::new(PRESENCE_INTERVAL),
|
||||
paced: Paced::new(now),
|
||||
reconnect_at: None,
|
||||
asking: None,
|
||||
done: false,
|
||||
@@ -105,7 +108,7 @@ impl<S: Socket> Driver<S> {
|
||||
|
||||
/// Start joining (progress arrives in `inbox`).
|
||||
pub(crate) fn start(sock: S, cfg: GuestConfig, inbox: Inbox, now: Instant) -> Self {
|
||||
let mut d = Self::new(sock, cfg, inbox);
|
||||
let mut d = Self::new(sock, cfg, inbox, now);
|
||||
d.inbox.push(Event::Status(Status::Connecting));
|
||||
d.connect(now);
|
||||
d
|
||||
@@ -114,7 +117,7 @@ impl<S: Socket> Driver<S> {
|
||||
/// Start with what `next` asks a server (a background request): the events it ends in go to
|
||||
/// `inbox`, then the join it ends in, if any, as `cfg` says.
|
||||
pub(crate) fn asking(sock: S, cfg: GuestConfig, next: exchange::Next, inbox: Inbox, now: Instant) -> Self {
|
||||
let mut d = Self::new(sock, cfg, inbox);
|
||||
let mut d = Self::new(sock, cfg, inbox, now);
|
||||
d.follow(next, now);
|
||||
d
|
||||
}
|
||||
@@ -159,6 +162,8 @@ impl<S: Socket> Driver<S> {
|
||||
|
||||
fn connect(&mut self, now: Instant) {
|
||||
self.reconnect_at = None;
|
||||
// A server counts per connection, and these were made for the last one.
|
||||
self.paced = Paced::new(now);
|
||||
self.conn = Some(Conn::new(now));
|
||||
if let Err(e) = self.sock.open(&self.server().url()) {
|
||||
self.dropped(e, now);
|
||||
@@ -303,13 +308,35 @@ impl<S: Socket> Driver<S> {
|
||||
if !self.conn.as_ref().is_some_and(|c| c.welcomed) {
|
||||
return;
|
||||
}
|
||||
if !self.write(&msg) {
|
||||
self.paced.push(msg);
|
||||
if !self.send_paced(now) {
|
||||
self.end(Outcome::Retry("the connection dropped".into()), now);
|
||||
}
|
||||
}
|
||||
|
||||
/// Send the sync messages whose turn has come; false when one couldn't go.
|
||||
fn send_paced(&mut self, now: Instant) -> bool {
|
||||
while let Some(msg) = self.paced.take_due(now) {
|
||||
if !self.write(&msg) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Reconnect now, if it is waiting to: the pauses grow from the beginning again.
|
||||
pub(crate) fn retry(&mut self, now: Instant) {
|
||||
if !self.done && self.reconnect_at.is_some() {
|
||||
self.attempt = 0;
|
||||
self.connect(now);
|
||||
}
|
||||
}
|
||||
|
||||
/// Leave the session.
|
||||
pub(crate) fn leave(&mut self, now: Instant) {
|
||||
// What may go now still reaches the others. The rest would get the connection refused, and
|
||||
// a page can't wait: the sync client says so when you leave.
|
||||
let _ = self.send_paced(now);
|
||||
self.end(Outcome::Left, now);
|
||||
}
|
||||
|
||||
@@ -327,7 +354,7 @@ impl<S: Socket> Driver<S> {
|
||||
[Some(c.last_ping + l.keepalive), Some(c.last_heard + c.silence_limit(l)), if c.welcomed { self.throttle.due() } else { None }]
|
||||
}
|
||||
});
|
||||
earliest(conn.into_iter().flatten().chain([self.reconnect_at]))
|
||||
earliest(conn.into_iter().flatten().chain([self.reconnect_at, self.paced.due()]))
|
||||
}
|
||||
|
||||
/// Do what's due at `now`: reconnect, send held presence or a ping, give up on a connection
|
||||
@@ -357,7 +384,7 @@ impl<S: Socket> Driver<S> {
|
||||
if now >= last_heard + silence {
|
||||
return self.end(Outcome::Retry("the host stopped answering".into()), now);
|
||||
}
|
||||
let ok = self.throttle.take_due(now).is_none_or(|p| self.write(&ClientMsg::Presence(p)));
|
||||
let ok = self.send_paced(now) && self.throttle.take_due(now).is_none_or(|p| self.write(&ClientMsg::Presence(p)));
|
||||
let ok = ok && (now < last_ping + l.keepalive || self.ping(now));
|
||||
if !ok {
|
||||
self.end(Outcome::Retry("the connection dropped".into()), now);
|
||||
@@ -388,6 +415,8 @@ impl<S: Socket> Driver<S> {
|
||||
self.sock.close();
|
||||
}
|
||||
self.throttle = Throttle::new(PRESENCE_INTERVAL);
|
||||
// Made for this connection: the sync client sends again what the server didn't get.
|
||||
self.paced = Paced::new(now);
|
||||
match after(outcome, &self.cfg, self.was_live, &mut self.attempt, &self.inbox) {
|
||||
Next::Stop(e) => {
|
||||
if let Some(e) = e {
|
||||
|
||||
@@ -252,7 +252,7 @@ fn a_silent_host_counts_as_dropped_and_the_client_reconnects() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconnects_back_off_then_give_up() {
|
||||
fn a_live_connection_reconnects_in_rounds_and_never_gives_up() {
|
||||
let t0 = Instant::now();
|
||||
let (mut d, inbox) = start(Script::default(), t0);
|
||||
d.opened(t0);
|
||||
@@ -260,7 +260,7 @@ fn reconnects_back_off_then_give_up() {
|
||||
let mut now = t0;
|
||||
let mut pauses = Vec::new();
|
||||
d.closed(1006, "", now);
|
||||
while !d.done() {
|
||||
for _ in 0..26 {
|
||||
let next = d.deadline().unwrap();
|
||||
pauses.push(next - now);
|
||||
now = next;
|
||||
@@ -269,11 +269,183 @@ fn reconnects_back_off_then_give_up() {
|
||||
d.closed(1006, "", now);
|
||||
}
|
||||
let secs: Vec<f64> = pauses.iter().map(Duration::as_secs_f64).collect();
|
||||
assert_eq!(secs, [0.5, 1.0, 2.0, 4.0, 8.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0]);
|
||||
let round = [1.0, 2.0, 4.0, 8.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0];
|
||||
assert_eq!(secs[0], 0.5);
|
||||
assert_eq!(secs[1..12], round);
|
||||
assert_eq!(secs[12], 60.0, "a longer pause after a round");
|
||||
assert_eq!(secs[13..24], round, "then as many again");
|
||||
assert_eq!(secs[24], 60.0);
|
||||
assert!(!d.done());
|
||||
let st = statuses(&inbox.drain());
|
||||
assert_eq!(st.len(), 14, "connecting, 12 reconnects, then failed");
|
||||
assert!(matches!(st.last(), Some(Status::Failed { reason }) if reason.starts_with("Lost the connection to the host")), "{st:?}");
|
||||
assert_eq!(d.deadline(), None);
|
||||
assert!(!st.iter().any(|s| matches!(s, Status::Failed { .. })), "{st:?}");
|
||||
assert!(matches!(st.last(), Some(Status::Reconnecting { attempt: 27 })), "{st:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_now_skips_the_pause_and_starts_the_round_over() {
|
||||
let t0 = Instant::now();
|
||||
let (mut d, inbox) = start(Script::default(), t0);
|
||||
d.opened(t0);
|
||||
d.message(&welcome(), t0);
|
||||
d.closed(1006, "", t0);
|
||||
let mut now = t0;
|
||||
for _ in 0..12 {
|
||||
now = d.deadline().unwrap();
|
||||
d.tick(now);
|
||||
d.closed(1006, "", now);
|
||||
}
|
||||
assert_eq!(d.deadline().unwrap() - now, Duration::from_secs(60));
|
||||
let opened = d.sock.opened.len();
|
||||
d.retry(now);
|
||||
assert_eq!(d.sock.opened.len(), opened + 1, "connects at once");
|
||||
inbox.drain();
|
||||
d.closed(1006, "", now);
|
||||
assert_eq!(statuses(&inbox.drain()), vec![Status::Reconnecting { attempt: 1 }]);
|
||||
assert_eq!(d.deadline().unwrap() - now, ms(500), "the pauses grow from the beginning again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_that_was_live_only_stops_for_a_refusal_that_is_for_good() {
|
||||
let t0 = Instant::now();
|
||||
// The words servers turn a session away with for now.
|
||||
for reason in [
|
||||
"too many messages",
|
||||
"the server is busy: try again in a moment",
|
||||
"the session is full",
|
||||
"no hello in time",
|
||||
"this file can't be opened on the server (its data is damaged); tell the server's owner",
|
||||
"too many connections from your address lately: wait a minute and try again",
|
||||
] {
|
||||
for frame in [false, true] {
|
||||
let (mut d, inbox) = start(Script::default(), t0);
|
||||
d.opened(t0);
|
||||
d.message(&welcome(), t0);
|
||||
inbox.drain();
|
||||
if frame {
|
||||
d.closed(1008, reason, t0);
|
||||
} else {
|
||||
d.message(&encode(&ServerMsg::Refused { reason: reason.into() }), t0);
|
||||
}
|
||||
assert!(!d.done(), "{reason}");
|
||||
assert_eq!(statuses(&inbox.drain()), vec![Status::Reconnecting { attempt: 1 }], "{reason}");
|
||||
}
|
||||
}
|
||||
// And the words for good.
|
||||
for reason in [
|
||||
"this link isn't valid (it may have been revoked)",
|
||||
"this file isn't on the server (it may have been removed)",
|
||||
"this file was removed from the server",
|
||||
"you were removed from this session",
|
||||
"this server no longer accepts connections from your address",
|
||||
"this server doesn't accept connections from your address",
|
||||
"wrong session token",
|
||||
"protocol 9 isn't supported",
|
||||
"message too large: this server takes at most 64 MiB at once (a change that big can't be kept here)",
|
||||
] {
|
||||
let (mut d, inbox) = start(Script::default(), t0);
|
||||
d.opened(t0);
|
||||
d.message(&welcome(), t0);
|
||||
d.closed(1008, reason, t0);
|
||||
assert!(d.done(), "{reason}");
|
||||
assert!(matches!(statuses(&inbox.drain()).last(), Some(Status::Failed { reason: r }) if r.contains(reason)), "{reason}");
|
||||
}
|
||||
// What this end finds it can't talk to: a text frame, or a message it can't read.
|
||||
for text in [true, false] {
|
||||
let (mut d, inbox) = start(Script::default(), t0);
|
||||
d.opened(t0);
|
||||
d.message(&welcome(), t0);
|
||||
if text {
|
||||
d.text(t0);
|
||||
} else {
|
||||
d.message(&[0xFF, 1, 2, 3], t0);
|
||||
}
|
||||
assert!(d.done(), "text: {text}");
|
||||
assert!(matches!(statuses(&inbox.drain()).last(), Some(Status::Failed { .. })));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_queue_goes_out_paced_and_in_order() {
|
||||
let t0 = Instant::now();
|
||||
let (mut d, _inbox) = start(Script::default(), t0);
|
||||
d.opened(t0);
|
||||
d.message(&welcome(), t0);
|
||||
let before = d.sock.sent.len();
|
||||
for seq in 0..500 {
|
||||
d.send(ClientMsg::Ack { seq }, t0);
|
||||
}
|
||||
let at_once = d.sock.sent.len() - before;
|
||||
assert!((1..=200).contains(&at_once), "{at_once} at once: a server drops a connection past 400");
|
||||
let mut now = t0;
|
||||
while d.sock.sent.iter().filter(|m| matches!(m, ClientMsg::Ack { .. })).count() < 500 {
|
||||
now = d.deadline().unwrap();
|
||||
d.tick(now);
|
||||
}
|
||||
let seqs: Vec<u64> = d.sock.sent.iter().filter_map(|m| if let ClientMsg::Ack { seq } = m { Some(*seq) } else { None }).collect();
|
||||
assert_eq!(seqs, (0..500).collect::<Vec<u64>>());
|
||||
assert!(now - t0 >= Duration::from_secs(4), "the rest take their time: {:?}", now - t0);
|
||||
// Unsent ones were made for this connection: the sync client sends them again.
|
||||
for seq in 0..500 {
|
||||
d.send(ClientMsg::Ack { seq }, now);
|
||||
}
|
||||
d.closed(1006, "", now);
|
||||
assert_eq!(d.deadline().unwrap() - now, ms(500), "nothing left to send but the reconnect");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn messages_held_up_by_a_stall_dont_leave_together() {
|
||||
let t0 = Instant::now();
|
||||
let (mut d, _inbox) = start(Script::default(), t0);
|
||||
d.opened(t0);
|
||||
d.message(&welcome(), t0);
|
||||
for seq in 0..700 {
|
||||
d.send(ClientMsg::Ack { seq }, t0);
|
||||
}
|
||||
let acks = |d: &Driver<Script>| d.sock.sent.iter().filter(|m| matches!(m, ClientMsg::Ack { .. })).count();
|
||||
let first = acks(&d);
|
||||
// Nothing ran for 8 s.
|
||||
d.tick(t0 + Duration::from_secs(8));
|
||||
assert!(acks(&d) - first <= 200, "{} at once: a server drops a connection past 400", acks(&d) - first);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_connection_starts_with_a_fresh_pace() {
|
||||
let t0 = Instant::now();
|
||||
let (mut d, _inbox) = start(Script::default(), t0);
|
||||
d.opened(t0);
|
||||
d.message(&welcome(), t0);
|
||||
for seq in 0..500 {
|
||||
d.send(ClientMsg::Ack { seq }, t0);
|
||||
}
|
||||
d.closed(1006, "", t0);
|
||||
let back = d.deadline().unwrap();
|
||||
d.tick(back);
|
||||
d.opened(back);
|
||||
d.message(&welcome(), back);
|
||||
d.send(ClientMsg::Ack { seq: 900 }, back);
|
||||
assert!(d.sock.sent.iter().any(|m| matches!(m, ClientMsg::Ack { seq: 900 })), "sent at once");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaving_sends_what_may_go_at_its_pace() {
|
||||
let t0 = Instant::now();
|
||||
let (mut d, _inbox) = start(Script::default(), t0);
|
||||
d.opened(t0);
|
||||
d.message(&welcome(), t0);
|
||||
for seq in 0..150 {
|
||||
d.send(ClientMsg::Ack { seq }, t0);
|
||||
}
|
||||
let later = t0 + Duration::from_secs(1);
|
||||
for seq in 150..600 {
|
||||
d.send(ClientMsg::Ack { seq }, later);
|
||||
}
|
||||
let before = d.sock.sent.iter().filter(|m| matches!(m, ClientMsg::Ack { .. })).count();
|
||||
d.leave(later + Duration::from_secs(1));
|
||||
let seqs: Vec<u64> = d.sock.sent.iter().filter_map(|m| if let ClientMsg::Ack { seq } = m { Some(*seq) } else { None }).collect();
|
||||
assert!(seqs.len() > before, "more goes on leaving");
|
||||
assert!(seqs.len() - before <= 200, "{} at once: a server drops a connection past 400", seqs.len() - before);
|
||||
assert_eq!(seqs, (0..seqs.len() as u64).collect::<Vec<u64>>(), "in order");
|
||||
assert!(d.done());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -31,7 +31,7 @@ use crate::manage;
|
||||
use crate::net::{Duplex, NetLimits, config, open, shutdown};
|
||||
use crate::requests;
|
||||
pub use crate::requests::Publish;
|
||||
use crate::throttle::{PRESENCE_INTERVAL, Throttle, earliest};
|
||||
use crate::throttle::{PRESENCE_INTERVAL, Paced, Throttle, earliest};
|
||||
|
||||
/// A joined (or joining) session. Dropping it leaves.
|
||||
pub struct Guest {
|
||||
@@ -44,6 +44,8 @@ enum Cmd {
|
||||
/// For the server, in order (document changes).
|
||||
Send(ClientMsg),
|
||||
Leave,
|
||||
/// Try now rather than after the pause under way (reconnecting).
|
||||
Retry,
|
||||
/// The reader of connection `epoch` got its welcome.
|
||||
Welcomed(u64),
|
||||
/// Connection `epoch` ended.
|
||||
@@ -133,6 +135,11 @@ impl Guest {
|
||||
let _ = self.cmd.send(Cmd::Send(msg));
|
||||
}
|
||||
|
||||
/// Reconnect now, if it is waiting to.
|
||||
pub fn retry(&self) {
|
||||
let _ = self.cmd.send(Cmd::Retry);
|
||||
}
|
||||
|
||||
/// Leave (returns at once: a connection attempt in progress ends on its own).
|
||||
pub fn leave(&mut self) {
|
||||
let _ = self.cmd.send(Cmd::Leave);
|
||||
@@ -155,6 +162,9 @@ impl Drop for Guest {
|
||||
}
|
||||
}
|
||||
|
||||
/// How long leaving keeps sending what was waiting its turn.
|
||||
const LEAVE_DRAIN: Duration = Duration::from_secs(10);
|
||||
|
||||
/// A connected socket: reader and writer ends.
|
||||
struct Conn {
|
||||
reader: WebSocket<Duplex>,
|
||||
@@ -227,6 +237,11 @@ fn supervise(cfg: &GuestConfig, inbox: &Inbox, rx: &Receiver<Cmd>, me: &Sender<C
|
||||
match rx.recv_timeout(until.saturating_duration_since(Instant::now())) {
|
||||
Ok(Cmd::Leave) | Err(RecvTimeoutError::Disconnected) => return,
|
||||
Ok(Cmd::Presence(p)) => pending = Some(p),
|
||||
// A fresh start: the pauses grow from the beginning again.
|
||||
Ok(Cmd::Retry) => {
|
||||
attempt = 0;
|
||||
break;
|
||||
}
|
||||
// From the old connection's client: the next welcome starts over.
|
||||
Ok(_) => {}
|
||||
Err(RecvTimeoutError::Timeout) => break,
|
||||
@@ -267,14 +282,15 @@ fn session(
|
||||
let hello = hello(cfg, resume);
|
||||
let mut welcomed = false;
|
||||
let mut throttle = Throttle::new(PRESENCE_INTERVAL);
|
||||
// Sync messages waiting their turn (a long queue from while offline).
|
||||
let mut paced: Paced<ClientMsg> = Paced::new(Instant::now());
|
||||
let outcome = if send(&mut writer, &hello) {
|
||||
loop {
|
||||
let ping_at = last_ping + cfg.limits.keepalive;
|
||||
let wake = earliest([throttle.due(), Some(ping_at)]).unwrap_or(ping_at);
|
||||
let wake = earliest([throttle.due(), Some(ping_at), paced.due()]).unwrap_or(ping_at);
|
||||
let mut out = None;
|
||||
let mut now_send = Vec::new();
|
||||
match rx.recv_timeout(wake.saturating_duration_since(Instant::now())) {
|
||||
Ok(Cmd::Send(m)) if welcomed => now_send.push(m),
|
||||
Ok(Cmd::Send(m)) if welcomed => paced.push(m),
|
||||
// Made for the previous connection (the sync client sends again what the server
|
||||
// didn't get once it has caught up with this connection's welcome).
|
||||
Ok(Cmd::Send(_)) => {}
|
||||
@@ -288,17 +304,22 @@ fn session(
|
||||
}
|
||||
Ok(Cmd::Lost(e, o)) if e == epoch => break o,
|
||||
Ok(Cmd::Leave) | Err(RecvTimeoutError::Disconnected) => {
|
||||
leave_paced(&mut writer, &mut paced);
|
||||
let _ = writer.close(Some(CloseFrame { code: CloseCode::Normal, reason: "".into() }));
|
||||
break Outcome::Left;
|
||||
}
|
||||
// From an earlier connection.
|
||||
Ok(Cmd::Welcomed(_) | Cmd::Lost(..)) => {}
|
||||
Ok(Cmd::Welcomed(_) | Cmd::Lost(..) | Cmd::Retry) => {}
|
||||
Err(RecvTimeoutError::Timeout) => {}
|
||||
}
|
||||
if !now_send.iter().all(|m| send(&mut writer, m)) {
|
||||
let now = Instant::now();
|
||||
let mut sent = true;
|
||||
while sent && let Some(m) = paced.take_due(now) {
|
||||
sent = send(&mut writer, &m);
|
||||
}
|
||||
if !sent {
|
||||
break Outcome::Retry("the connection dropped".into());
|
||||
}
|
||||
let now = Instant::now();
|
||||
let out = out.or_else(|| throttle.take_due(now));
|
||||
let ok = out.is_none_or(|p| send(&mut writer, &ClientMsg::Presence(p)));
|
||||
let ok = ok
|
||||
@@ -318,6 +339,28 @@ fn session(
|
||||
outcome
|
||||
}
|
||||
|
||||
/// Send what was waiting its turn before leaving, at its pace, for at most [`LEAVE_DRAIN`]: nothing
|
||||
/// waits for this thread (the app has moved on), and going faster would get the rest refused. What
|
||||
/// doesn't go is left to the sync client, which says so when you leave.
|
||||
fn leave_paced(writer: &mut WebSocket<Duplex>, paced: &mut Paced<ClientMsg>) {
|
||||
let give_up = Instant::now() + LEAVE_DRAIN;
|
||||
loop {
|
||||
let now = Instant::now();
|
||||
if now >= give_up {
|
||||
return;
|
||||
}
|
||||
if let Some(m) = paced.take_due(now) {
|
||||
if !send(writer, &m) {
|
||||
return;
|
||||
}
|
||||
} else if let Some(at) = paced.due().filter(|at| *at < give_up) {
|
||||
std::thread::sleep(at.saturating_duration_since(now));
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Send one message; false when the connection is gone.
|
||||
fn send(ws: &mut WebSocket<Duplex>, msg: &ClientMsg) -> bool {
|
||||
message::encode(msg).is_ok_and(|b| ws.send(Message::Binary(Bytes::from(b))).is_ok())
|
||||
|
||||
@@ -51,6 +51,12 @@ fn health_check(stream: &mut TcpStream, until: Instant) -> bool {
|
||||
let mut req = Vec::new();
|
||||
let mut chunk = [0u8; 1024];
|
||||
while !req.windows(4).any(|w| w == b"\r\n\r\n") && req.len() < 16 << 10 {
|
||||
// The same deadline as the request line: a peer dripping header bytes would otherwise
|
||||
// hold this thread and its connection slot for as long as it liked.
|
||||
let left = until.saturating_duration_since(Instant::now());
|
||||
if left.is_zero() || stream.set_read_timeout(Some(left)).is_err() {
|
||||
break;
|
||||
}
|
||||
match stream.read(&mut chunk) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(n) => req.extend_from_slice(chunk.get(..n).unwrap_or_default()),
|
||||
@@ -409,3 +415,31 @@ fn linger(ws: &mut WebSocket<Duplex>) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod health_check_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_health_check_dripping_headers_ends_at_the_deadline() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let client = std::thread::spawn(move || {
|
||||
let mut c = TcpStream::connect(addr).unwrap();
|
||||
c.write_all(b"GET /healthz HTTP/1.1\r\n").unwrap();
|
||||
// One header byte every 20 ms, far past the deadline, until the server hangs up.
|
||||
for _ in 0..200 {
|
||||
if c.write_all(b"X").is_err() {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
});
|
||||
let (mut stream, _) = listener.accept().unwrap();
|
||||
let start = Instant::now();
|
||||
assert!(health_check(&mut stream, start + Duration::from_millis(300)));
|
||||
assert!(start.elapsed() < Duration::from_secs(2), "{:?}", start.elapsed());
|
||||
drop(stream);
|
||||
client.join().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,8 +39,10 @@ pub struct GuestConfig {
|
||||
/// The pause before the first reconnect; it doubles each time up to `max_backoff`.
|
||||
pub backoff: Duration,
|
||||
pub max_backoff: Duration,
|
||||
/// Reconnect attempts before giving up.
|
||||
/// Reconnect attempts in a row before the longer pause (`round_pause`), after which it tries
|
||||
/// as many again: a connection that was live is never given up on by itself.
|
||||
pub attempts: u32,
|
||||
pub round_pause: Duration,
|
||||
/// Join as the client you were (an app that starts over after a crash): the first hello
|
||||
/// carries it, and a server that still knows the id gives it back.
|
||||
pub resume: Option<Resume>,
|
||||
@@ -57,6 +59,7 @@ impl GuestConfig {
|
||||
backoff: Duration::from_millis(500),
|
||||
max_backoff: Duration::from_secs(10),
|
||||
attempts: 12,
|
||||
round_pause: Duration::from_secs(60),
|
||||
resume: None,
|
||||
}
|
||||
}
|
||||
@@ -65,6 +68,14 @@ impl GuestConfig {
|
||||
pub(crate) fn backoff(&self, attempt: u32) -> Duration {
|
||||
self.backoff.saturating_mul(1u32 << attempt.saturating_sub(1).min(16)).min(self.max_backoff)
|
||||
}
|
||||
|
||||
/// The pause before reconnect attempt `attempt` (from 1): growing within a round of
|
||||
/// [`attempts`](Self::attempts), and [`round_pause`](Self::round_pause) between rounds.
|
||||
pub(crate) fn pause(&self, attempt: u32) -> Duration {
|
||||
let round = self.attempts.max(1);
|
||||
let into_round = attempt.saturating_sub(1) % round;
|
||||
if into_round == 0 && attempt > round { self.round_pause } else { self.backoff(into_round + 1) }
|
||||
}
|
||||
}
|
||||
|
||||
/// How a connection ended.
|
||||
@@ -144,11 +155,39 @@ pub(crate) enum Next {
|
||||
Reconnect(Duration),
|
||||
}
|
||||
|
||||
/// After `outcome`: a refusal or the end of the session is final, and so is a first join that
|
||||
/// can't reach the host; a live connection that dropped tries again with growing pauses until the
|
||||
/// attempts run out.
|
||||
/// What a server refuses for good, whenever you ask: the link, the file or your place in it is
|
||||
/// gone, or the two versions can't talk. Anything else a server refuses a session with (it is
|
||||
/// busy, a limit was hit, the file couldn't be read just now) may pass, and servers of any version
|
||||
/// say so in these words, so a reason not listed here means try again.
|
||||
const FINAL_REFUSALS: [&str; 12] = [
|
||||
"isn't valid",
|
||||
"isn't on the server",
|
||||
"was removed from the server",
|
||||
"were removed from this session",
|
||||
"no longer accepts connections",
|
||||
"doesn't accept connections",
|
||||
"wrong session token",
|
||||
"isn't supported",
|
||||
"couldn't be read",
|
||||
"message too large",
|
||||
"this version can't read",
|
||||
"sent a text message",
|
||||
];
|
||||
|
||||
/// Whether `reason`, from a server refusing a session that was live, is for good.
|
||||
pub(crate) fn final_refusal(reason: &str) -> bool {
|
||||
FINAL_REFUSALS.iter().any(|f| reason.contains(f))
|
||||
}
|
||||
|
||||
/// After `outcome`: the end of the session is final, and so are a refusal for good and a first
|
||||
/// join that can't reach the host. A live connection that dropped or was turned away for now tries
|
||||
/// again until you leave: with growing pauses, and a longer one between rounds.
|
||||
pub(crate) fn after(outcome: Outcome, cfg: &GuestConfig, was_live: bool, attempt: &mut u32, inbox: &Inbox) -> Next {
|
||||
let failed = |reason: String| Next::Stop(Some(Box::new(Event::Status(Status::Failed { reason }))));
|
||||
let outcome = match outcome {
|
||||
Outcome::Refused(why) if was_live && !final_refusal(&why) => Outcome::Retry(why),
|
||||
o => o,
|
||||
};
|
||||
match outcome {
|
||||
Outcome::Left => Next::Stop(None),
|
||||
Outcome::Refused(why) => failed(format!("The host refused: {why}")),
|
||||
@@ -156,13 +195,10 @@ pub(crate) fn after(outcome: Outcome, cfg: &GuestConfig, was_live: bool, attempt
|
||||
Outcome::Ended(reason) => Next::Stop(Some(Box::new(Event::Ended { reason }))),
|
||||
Outcome::Retry(why) if !was_live => failed(format!("Couldn't join the live session: {why}")),
|
||||
Outcome::Retry(why) => {
|
||||
*attempt += 1;
|
||||
if *attempt > cfg.attempts {
|
||||
return failed(format!("Lost the connection to the host ({why})"));
|
||||
}
|
||||
*attempt = attempt.saturating_add(1);
|
||||
log::info!("live session: connection lost ({why}); reconnecting, attempt {attempt}");
|
||||
inbox.push(Event::Status(Status::Reconnecting { attempt: *attempt }));
|
||||
Next::Reconnect(cfg.backoff(*attempt))
|
||||
Next::Reconnect(cfg.pause(*attempt))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -308,6 +308,12 @@ impl LiveLink for NetLink {
|
||||
}
|
||||
}
|
||||
|
||||
fn retry(&mut self, session: SessionId) {
|
||||
if let Some(Active::Guest(g)) = self.sessions.get(session) {
|
||||
g.retry();
|
||||
}
|
||||
}
|
||||
|
||||
fn presence(&mut self, session: SessionId, p: &Presence) {
|
||||
match self.sessions.get(session) {
|
||||
Some(Active::Host(h)) => h.presence(p.clone()),
|
||||
|
||||
@@ -124,8 +124,9 @@ fn following_a_viewport_until_you_move() {
|
||||
fn the_host_stopping_ends_the_session_for_guests() {
|
||||
let (mut host, mut guest, _, _) = host_and_join();
|
||||
host.execute("collab.stop", &json!({})).unwrap();
|
||||
pump(&mut host, &mut guest, "the end", |_, g| g.live().status == Status::Off);
|
||||
assert!(guest.live().peers.is_empty());
|
||||
pump(&mut host, &mut guest, "the end", |_, g| g.live().rejoinable());
|
||||
assert!(guest.live().peers.is_empty() && !guest.live().syncing());
|
||||
assert!(guest.live().disconnected(), "the tab says so");
|
||||
assert_eq!(guest.message.as_deref(), Some(crate::host::ENDED));
|
||||
}
|
||||
|
||||
|
||||
@@ -158,8 +158,8 @@ fn two_files_are_hosted_and_joined_independently() {
|
||||
assert!(host.live_of(hb).presence.get(&ada(&host, hb)).is_none_or(|p| p.cursor.is_none()), "no cursor in the file that isn't in front");
|
||||
// The host closes B: its session ends for everyone, A's goes on.
|
||||
host.execute("file.close", &json!({"index": 1, "force": true})).unwrap();
|
||||
pump(&mut [&mut host, &mut guest], "B's session ending", |s| s[0].live.iter().count() == 1 && s[1].live.iter().count() == 1);
|
||||
assert_eq!(guest.live_of(gb).status, Status::Off);
|
||||
pump(&mut [&mut host, &mut guest], "B's session ending", |s| s[0].live.iter().count() == 1 && s[1].live_of(gb).rejoinable());
|
||||
assert!(guest.live_of(gb).disconnected(), "the guest's tab says so");
|
||||
assert_eq!(guest.docs.len(), 3, "the guest keeps its copy of B");
|
||||
assert_eq!((host.live_of(ha).status.clone(), host.live_of(ha).peers.len()), (Status::Live, 1));
|
||||
assert_eq!(guest.live_of(ga).status, Status::Live);
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! (replacing any older waiting value) until the interval has passed, so the last one is never
|
||||
//! lost. Used for presence on both ends (about 30 updates a second).
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::time::Duration;
|
||||
|
||||
// `std::time::Instant` on native builds; the browser's clock in the web build.
|
||||
@@ -10,6 +11,54 @@ use web_time::Instant;
|
||||
/// How often presence goes out at most.
|
||||
pub const PRESENCE_INTERVAL: Duration = Duration::from_millis(33);
|
||||
|
||||
/// How many messages other than presence go out at once, and per second after that: with presence
|
||||
/// and pings that stays under what a server takes from a connection before it drops it.
|
||||
const PACE_BURST: f64 = 200.0;
|
||||
const PACE_RATE: f64 = 60.0;
|
||||
|
||||
/// Messages that must all go out, in order, at a pace (everything queued while offline leaves at
|
||||
/// once when the connection comes back). The pace is counted when they go, so messages held up by
|
||||
/// a stalled connection don't leave together afterwards.
|
||||
#[derive(Debug)]
|
||||
pub struct Paced<T> {
|
||||
tokens: f64,
|
||||
last: Instant,
|
||||
queue: VecDeque<T>,
|
||||
}
|
||||
|
||||
impl<T> Paced<T> {
|
||||
pub fn new(now: Instant) -> Self {
|
||||
Self { tokens: PACE_BURST, last: now, queue: VecDeque::new() }
|
||||
}
|
||||
|
||||
pub fn push(&mut self, v: T) {
|
||||
self.queue.push_back(v);
|
||||
}
|
||||
|
||||
/// The next message, if its turn has come at `now`.
|
||||
pub fn take_due(&mut self, now: Instant) -> Option<T> {
|
||||
if self.queue.is_empty() {
|
||||
return None;
|
||||
}
|
||||
self.tokens = (self.tokens + now.saturating_duration_since(self.last).as_secs_f64() * PACE_RATE).min(PACE_BURST);
|
||||
self.last = now;
|
||||
// Within rounding of a whole turn counts as one: the time `due` gave has come.
|
||||
if self.tokens < 1.0 - 1e-6 {
|
||||
return None;
|
||||
}
|
||||
self.tokens -= 1.0;
|
||||
self.queue.pop_front()
|
||||
}
|
||||
|
||||
/// When the next message's turn comes (`None`: there's none).
|
||||
pub fn due(&self) -> Option<Instant> {
|
||||
self.queue.front()?;
|
||||
// Rounded up to whole microseconds, so a timer set for this always finds the turn come.
|
||||
let wait = ((1.0 - self.tokens).max(0.0) / PACE_RATE * 1e6).ceil() as u64;
|
||||
Some(self.last + Duration::from_micros(wait))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Throttle<T> {
|
||||
interval: Duration,
|
||||
|
||||
@@ -242,6 +242,10 @@ impl LiveLink for NetLink {
|
||||
}
|
||||
}
|
||||
|
||||
fn retry(&mut self, session: SessionId) {
|
||||
self.with(session, |d, now| d.retry(now));
|
||||
}
|
||||
|
||||
fn presence(&mut self, session: SessionId, p: &Presence) {
|
||||
self.with(session, |d, now| d.presence(p.clone(), now));
|
||||
}
|
||||
|
||||
@@ -72,6 +72,12 @@ pub fn attached_sides(from: RouteEnd, to: RouteEnd) -> (Option<Side>, Option<Sid
|
||||
(attach(from, to.centre()).1, attach(to, from.centre()).1)
|
||||
}
|
||||
|
||||
/// Where a connector's ends attach, as routed now: the points [`ConnectorPath::Runs`] is measured
|
||||
/// from the middle of.
|
||||
pub fn attach_points(from: RouteEnd, to: RouteEnd) -> (Point, Point) {
|
||||
(attach(from, to.centre()).0, attach(to, from.centre()).0)
|
||||
}
|
||||
|
||||
/// The route's path handles: one for each run of an elbow and one for a curve, with the portion
|
||||
/// of the path each moves and where it sits.
|
||||
pub fn path_handles(pts: &[Point], routing: Routing) -> Vec<(usize, Point)> {
|
||||
@@ -96,8 +102,9 @@ pub fn reshaped(from: RouteEnd, to: RouteEnd, routing: Routing, path: Option<&Co
|
||||
}
|
||||
}
|
||||
|
||||
/// A path of more runs than this can't be made by hand: [`reshaped`] refuses another.
|
||||
const MAX_RUNS: usize = 64;
|
||||
/// A path of more runs than this can't be made by hand: [`reshaped`] refuses another, and an
|
||||
/// importer leaves a saved one to the router.
|
||||
pub const MAX_RUNS: usize = 64;
|
||||
|
||||
/// The runs of the right-angled route `pts` with run `portion` moved to `p`.
|
||||
fn reshaped_runs(pts: &[Point], portion: usize, p: Point) -> Option<ConnectorPath> {
|
||||
|
||||
@@ -27,7 +27,7 @@ pub mod vector_faces;
|
||||
pub mod vector_regions;
|
||||
|
||||
pub use board::*;
|
||||
pub use board_route::{END_GAP, RouteEnd, attached_sides, path_handles, reshaped, route_along, route_points};
|
||||
pub use board_route::{END_GAP, MAX_RUNS, RouteEnd, attach_points, attached_sides, path_handles, reshaped, route_along, route_points};
|
||||
pub use colors::*;
|
||||
pub use comments::*;
|
||||
pub use facilitation::*;
|
||||
|
||||
+22
-6
@@ -948,8 +948,12 @@ impl Node {
|
||||
if self.stroke.cap_start.is_arrow() || self.stroke.cap_end.is_arrow() || point_arrows { w.max(self.stroke.weight) * 3.0 } else { w };
|
||||
// Right-angled or smooth outlines (boxes, whole ellipses) end their mitres on the grown
|
||||
// box; an arc's corners don't.
|
||||
let miter = if self.grows_by_exactly_its_spread() { 1.0 } else { self.stroke.miter_limit.clamp(1.0, 4.0) };
|
||||
base.max(if matches!(self.kind, NodeKind::Line | NodeKind::Vector { .. }) { caps } else { 0.0 }) * miter
|
||||
let miter = if self.outline_mitres_end_on_its_box() { 1.0 } else { self.stroke.miter_limit.clamp(1.0, 4.0) };
|
||||
// A dash's square end stands out along the path as far as the band does across it:
|
||||
// its corners reach √2 times as far from the path, past the box round a curve.
|
||||
let square_dashes = !self.stroke.dashes.is_empty() && self.stroke.band_caps().contains(&StrokeCap::Square);
|
||||
let corners = if square_dashes { miter.max(std::f64::consts::SQRT_2) } else { miter };
|
||||
base.max(if matches!(self.kind, NodeKind::Line | NodeKind::Vector { .. }) { caps } else { 0.0 }) * corners
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
@@ -964,9 +968,10 @@ impl Node {
|
||||
!(matches!(self.kind, NodeKind::Group) || (matches!(self.kind, NodeKind::Text(_)) && self.has_visible_stroke()))
|
||||
}
|
||||
|
||||
/// Whether a spread grows this node's outline by exactly the spread (no sharp corners). An arc
|
||||
/// (an ellipse that doesn't go all the way round) has corners where its ends meet its sides.
|
||||
fn grows_by_exactly_its_spread(&self) -> bool {
|
||||
/// Whether this node's outline has no sharp corners (right-angled ones aside), so mitres along
|
||||
/// it end on its box grown by as much: a box or a whole ellipse. An arc (an ellipse that doesn't
|
||||
/// go all the way round) has corners where its ends meet its sides.
|
||||
fn outline_mitres_end_on_its_box(&self) -> bool {
|
||||
match self.kind {
|
||||
NodeKind::Rectangle | NodeKind::Section { .. } => true,
|
||||
NodeKind::Ellipse { sweep, .. } => figcraft_geom::full_sweep(sweep),
|
||||
@@ -974,9 +979,20 @@ impl Node {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a spread grows this node by exactly the spread: its outline mitres end on its box
|
||||
/// (see [`Node::outline_mitres_end_on_its_box`]), and so does its stroke. A dashed stroke is
|
||||
/// cut into dashes with corners wherever they fall round the outline, and a width profile or a
|
||||
/// brush can give the stroke corners of its own, which the spread mitres out.
|
||||
fn grows_by_exactly_its_spread(&self) -> bool {
|
||||
let s = &self.stroke;
|
||||
let cornered = self.has_visible_stroke() && (!s.dashes.is_empty() || s.profile().is_some() || s.brush.is_some());
|
||||
!cornered && self.outline_mitres_end_on_its_box()
|
||||
}
|
||||
|
||||
/// How much further than its spread a drop shadow can reach at the outline's sharp corners:
|
||||
/// spread moves the edges out in parallel and they meet in a mitre (see
|
||||
/// [`SPREAD_MITER_LIMIT`]). Rectangles, frames and whole ellipses grow by exactly the spread.
|
||||
/// [`SPREAD_MITER_LIMIT`]). Rectangles, frames and whole ellipses grow by exactly the spread,
|
||||
/// unless their stroke has corners (see [`Node::grows_by_exactly_its_spread`]).
|
||||
fn spread_miter_reach(&self) -> f64 {
|
||||
if self.grows_by_exactly_its_spread() {
|
||||
return 0.0;
|
||||
|
||||
+11
-4
@@ -146,10 +146,16 @@ impl Brush {
|
||||
}
|
||||
}
|
||||
|
||||
/// How much wider than the stroke weight the brush can paint (larger copies, strays).
|
||||
pub fn reach_factor(&self) -> f64 {
|
||||
/// The farthest a built-in brush shape reaches from the path, in stroke weights: the ink
|
||||
/// brush's ragged edges stand a little past half the weight.
|
||||
pub const SHAPE_REACH: f64 = 0.54;
|
||||
|
||||
/// How much wider than the stroke weight the brush can paint where a width profile scales it
|
||||
/// at most `scale`: its shapes' edges and larger copies, which the profile scales, and strays,
|
||||
/// which it doesn't.
|
||||
pub fn reach_factor(&self, scale: f64) -> f64 {
|
||||
let b = self.sanitized();
|
||||
1.0 + b.size_jitter + 2.0 * b.scatter
|
||||
2.0 * Self::SHAPE_REACH * (1.0 + b.size_jitter) * scale + 2.0 * b.scatter
|
||||
}
|
||||
}
|
||||
|
||||
@@ -188,7 +194,8 @@ impl StrokeProps {
|
||||
/// The widest the stroke gets anywhere along the path (the weight, scaled by a width profile
|
||||
/// and widened by a brush's reach).
|
||||
pub fn max_weight(&self) -> f64 {
|
||||
self.profile().map_or(self.weight, |p| self.weight * p.max_scale()) * self.brush.as_ref().map_or(1.0, Brush::reach_factor)
|
||||
let scale = self.profile().map_or(1.0, WidthProfile::max_scale);
|
||||
self.weight * self.brush.as_ref().map_or(scale, |b| b.reach_factor(scale))
|
||||
}
|
||||
|
||||
/// The miter limit as the angle (degrees) below which joins bevel: limit = 1 / sin(angle / 2),
|
||||
|
||||
@@ -223,6 +223,7 @@ fn text_case() {
|
||||
assert_eq!(style_weight("Semi Bold Italic"), 600);
|
||||
assert_eq!(style_weight("Black"), 900);
|
||||
assert_eq!(style_weight("Regular"), 400);
|
||||
assert_eq!(style_weight("Hairline"), 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -439,8 +439,9 @@ pub fn style_weight(style: &str) -> u16 {
|
||||
{
|
||||
return n;
|
||||
}
|
||||
let table: [(&str, u16); 10] = [
|
||||
let table: [(&str, u16); 11] = [
|
||||
("thin", 100),
|
||||
("hairline", 100),
|
||||
("extralight", 200),
|
||||
("ultralight", 200),
|
||||
("light", 300),
|
||||
@@ -567,7 +568,7 @@ impl TextPath {
|
||||
|
||||
/// The path (empty when `d` doesn't parse).
|
||||
pub fn path(&self) -> figcraft_geom::BezPath {
|
||||
figcraft_geom::BezPath::from_svg(&self.d).unwrap_or_default()
|
||||
figcraft_geom::svg_path(&self.d).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The start offset clamped into 0..1 (NaN: 0).
|
||||
|
||||
@@ -300,6 +300,12 @@ pub fn open(path: impl AsRef<Path>) -> Result<std::fs::File> {
|
||||
std::fs::File::open(allow(path, Access::Read)?).map_err(io(path))
|
||||
}
|
||||
|
||||
/// What the file system says about `path` itself (a link is not followed).
|
||||
pub fn link_metadata(path: impl AsRef<Path>) -> Result<std::fs::Metadata> {
|
||||
let path = path.as_ref();
|
||||
std::fs::symlink_metadata(allow(path, Access::Read)?).map_err(io(path))
|
||||
}
|
||||
|
||||
/// What the file system says about `path` (links followed).
|
||||
pub fn metadata(path: impl AsRef<Path>) -> Result<std::fs::Metadata> {
|
||||
let path = path.as_ref();
|
||||
|
||||
@@ -107,3 +107,45 @@ fn the_pencil_records_pressure_and_its_brush() {
|
||||
let last = doc.nodes().filter(|n| matches!(n.kind, NodeKind::Vector { .. })).max_by_key(|n| n.id).unwrap();
|
||||
assert!(last.stroke.profile().is_none() && last.stroke.brush.is_none());
|
||||
}
|
||||
|
||||
/// The Pencil draws black on a light page and white on a dark page or inside a dark frame, the
|
||||
/// rule new text follows (#1741; Figma: "in black, unless you're sketching on a dark canvas or
|
||||
/// frame"), and the stroke in progress previews in that colour.
|
||||
#[test]
|
||||
fn the_pencil_draws_white_on_a_dark_background() {
|
||||
use figcraft_color::Color;
|
||||
let mut s = Session::new();
|
||||
s.execute("tool.set", &json!({"tool": "pencil"})).unwrap();
|
||||
// A stroke from (x, y); its colour, and the preview colour the overlay carried while drawing.
|
||||
let stroke = |s: &mut Session, x: f64, y: f64| {
|
||||
s.pointer(&PointerEvent::at(PointerKind::Down, x, y, 1.0)).unwrap();
|
||||
s.pointer(&PointerEvent::at(PointerKind::Move, x + 40.0, y + 10.0, 1.0)).unwrap();
|
||||
let preview = s.tool.overlay.pen_color;
|
||||
s.pointer(&PointerEvent::at(PointerKind::Move, x + 80.0, y, 1.0)).unwrap();
|
||||
s.pointer(&PointerEvent::at(PointerKind::Up, x + 80.0, y, 1.0)).unwrap();
|
||||
assert!(s.tool.overlay.pen_color.is_none(), "no preview colour after the stroke");
|
||||
let doc = s.doc().unwrap();
|
||||
let last = doc.nodes().filter(|n| matches!(n.kind, NodeKind::Vector { .. })).max_by_key(|n| n.id).unwrap();
|
||||
(last.strokes.first().and_then(|p| p.solid_color()).unwrap(), preview)
|
||||
};
|
||||
assert_eq!(stroke(&mut s, 0.0, 0.0), (Color::BLACK, Some(Color::BLACK)), "a light page");
|
||||
s.execute("page.setBackground", &json!({"color": "#1E1E1E"})).unwrap();
|
||||
assert_eq!(stroke(&mut s, 0.0, 100.0), (Color::WHITE, Some(Color::WHITE)), "a dark page");
|
||||
// A dark frame on a light page, and a light frame on a dark page.
|
||||
s.execute("page.setBackground", &json!({"color": "#F5F5F5"})).unwrap();
|
||||
s.execute("node.create", &json!({"type": "frame", "x": 300, "y": 300, "width": 200, "height": 200, "props": {"fills": ["#202020"]}})).unwrap();
|
||||
assert_eq!(stroke(&mut s, 320.0, 320.0), (Color::WHITE, Some(Color::WHITE)), "inside a dark frame");
|
||||
s.execute("page.setBackground", &json!({"color": "#1E1E1E"})).unwrap();
|
||||
s.execute("node.create", &json!({"type": "frame", "x": 600, "y": 300, "width": 200, "height": 200, "props": {"fills": ["#FFFFFF"]}})).unwrap();
|
||||
assert_eq!(stroke(&mut s, 620.0, 320.0), (Color::BLACK, Some(Color::BLACK)), "inside a light frame on a dark page");
|
||||
// A frame without a fill, or with a see-through one, is looked through to what is behind it.
|
||||
s.execute("node.create", &json!({"type": "frame", "x": 900, "y": 300, "width": 200, "height": 200, "props": {"fills": []}})).unwrap();
|
||||
assert_eq!(stroke(&mut s, 920.0, 320.0), (Color::WHITE, Some(Color::WHITE)), "a frame without a fill on a dark page");
|
||||
s.execute("node.create", &json!({"type": "frame", "x": 1200, "y": 300, "width": 200, "height": 200, "props": {"fills": ["#FFFFFF40"]}})).unwrap();
|
||||
assert_eq!(stroke(&mut s, 1220.0, 320.0), (Color::WHITE, Some(Color::WHITE)), "a mostly transparent light frame on a dark page");
|
||||
// The threshold is Color::is_dark: white reads better than black from #757575 down.
|
||||
for (bg, want) in [("#767676", Color::BLACK), ("#757575", Color::WHITE)] {
|
||||
s.execute("page.setBackground", &json!({"color": bg})).unwrap();
|
||||
assert_eq!(stroke(&mut s, 0.0, 600.0).0, want, "on {bg}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -328,6 +328,9 @@ pub struct Overlay {
|
||||
pub cursor: Cursor,
|
||||
/// Pen tool: the in-progress path's anchor points and the rubber band to the pointer.
|
||||
pub pen: Vec<[f64; 2]>,
|
||||
/// Pencil: the colour of the stroke in progress, for its preview (white over a dark page or
|
||||
/// frame); None outside a Pencil stroke.
|
||||
pub pen_color: Option<figcraft_color::Color>,
|
||||
pub rubber: Option<[f64; 4]>,
|
||||
/// Pen tool: the handles shaping the segments at the pen (anchor x, y, handle x, y): the last
|
||||
/// anchor's in and out handles and the one before's out handle.
|
||||
|
||||
@@ -237,6 +237,7 @@ impl Session {
|
||||
}
|
||||
Gesture::Pencil { mut points, mut pressure } => {
|
||||
self.tool.overlay.pen.clear();
|
||||
self.tool.overlay.pen_color = None;
|
||||
// The stroke ends where the button came up, even without a move to get there.
|
||||
if points.last().is_none_or(|l| (*l - ev.p()).hypot() > 0.5 / ev.zoom.max(1e-6)) {
|
||||
points.push(ev.p());
|
||||
|
||||
@@ -36,16 +36,33 @@ pub fn anchor_name(a: (u8, u8)) -> &'static str {
|
||||
ANCHORS.get(usize::from(a.1.min(2)) * 3 + usize::from(a.0.min(2))).copied().unwrap_or("tl")
|
||||
}
|
||||
|
||||
/// Whether what is drawn in `parent` sits on a dark background: the nearest layer from `parent`
|
||||
/// out whose top visible fill is a mostly opaque (alpha 0.5 or more) solid colour, else the page
|
||||
/// (#362); a frame without such a fill is looked through to what is behind it. Dark means white
|
||||
/// reads better on it than black (`Color::is_dark`: `#757575` is dark, `#767676` is light).
|
||||
pub(crate) fn on_dark_background(doc: &Document, parent: NodeId) -> bool {
|
||||
std::iter::once(parent)
|
||||
.chain(doc.ancestors(parent))
|
||||
.filter_map(|id| doc.node(id))
|
||||
.find_map(|n| match &n.kind {
|
||||
NodeKind::Page { background, .. } => Some(background.is_dark()),
|
||||
_ => n.fills.iter().rev().find(|p| p.visible).and_then(|p| p.solid_color()).filter(|c| c.a >= 0.5).map(|c| c.is_dark()),
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// The fill new text takes to be readable where it is drawn, in `parent`: white on a dark
|
||||
/// background (None: the model's default, black). The background is the nearest layer from `parent`
|
||||
/// out whose top visible fill is a mostly opaque solid colour, else the page (#362). For text made
|
||||
/// in the app: by the Text tool, or by a command that names no fill while the interface is up.
|
||||
/// background (None: the model's default, black). For text made in the app: by the Text tool, or
|
||||
/// by a command that names no fill while the interface is up.
|
||||
pub(crate) fn readable_text_fills(doc: &Document, parent: NodeId) -> Option<Vec<figcraft_color::Paint>> {
|
||||
let dark = std::iter::once(parent).chain(doc.ancestors(parent)).filter_map(|id| doc.node(id)).find_map(|n| match &n.kind {
|
||||
NodeKind::Page { background, .. } => Some(background.is_dark()),
|
||||
_ => n.fills.iter().rev().find(|p| p.visible).and_then(|p| p.solid_color()).filter(|c| c.a >= 0.5).map(|c| c.is_dark()),
|
||||
});
|
||||
dark.unwrap_or(false).then(|| vec![figcraft_color::Paint::solid(figcraft_color::Color::WHITE)])
|
||||
on_dark_background(doc, parent).then(|| vec![figcraft_color::Paint::solid(figcraft_color::Color::WHITE)])
|
||||
}
|
||||
|
||||
/// The colour the Pencil draws with in `parent`: [`PENCIL_STROKE`]'s black, or white on a dark
|
||||
/// background by the rule text follows (#1741; "in black, unless you're sketching on a dark canvas
|
||||
/// or frame").
|
||||
pub(crate) fn pencil_color(doc: &Document, parent: NodeId) -> figcraft_color::Color {
|
||||
if on_dark_background(doc, parent) { figcraft_color::Color::WHITE } else { PENCIL_STROKE.0 }
|
||||
}
|
||||
|
||||
const ANCHORS: [&str; 9] = ["tl", "t", "tr", "l", "c", "r", "bl", "b", "br"];
|
||||
|
||||
@@ -333,7 +333,9 @@ impl Session {
|
||||
let mut local = fitted.clone();
|
||||
local.apply_affine(pw.inverse());
|
||||
let _ = d;
|
||||
let (color, weight) = PENCIL_STROKE;
|
||||
// Black, or white on a dark page or frame (#1741).
|
||||
let (_, weight) = PENCIL_STROKE;
|
||||
let color = super::handles::pencil_color(self.doc()?, parent);
|
||||
let mut props = json!({"fills": [], "strokes": [color.to_css_hex()], "strokeWeight": weight, "strokeCap": "round", "strokeJoin": "round", "strokeAlign": "center"});
|
||||
// Pen pressure becomes the stroke's width profile (brushes follow it too).
|
||||
if let Some(points) = pressure_profile(points, pressure) {
|
||||
@@ -348,4 +350,13 @@ impl Session {
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The colour a Pencil stroke starting at `p` will have: it goes into the frame under `p`
|
||||
/// (else the page), and is white when that is dark (`pencil_color`).
|
||||
pub(super) fn pencil_color_at(&self, p: figcraft_geom::Point) -> Result<figcraft_color::Color> {
|
||||
let page = self.page()?;
|
||||
let doc = self.doc()?;
|
||||
let parent = frame_at(doc, page, p, &[]).unwrap_or(page);
|
||||
Ok(super::handles::pencil_color(doc, parent))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,6 +160,8 @@ impl Session {
|
||||
ToolId::TextOnPath => self.text_on_path_down(ev),
|
||||
ToolId::Pen => self.pen_down(ev),
|
||||
ToolId::Pencil => {
|
||||
// The preview draws in the colour the stroke will have (#1741).
|
||||
self.tool.overlay.pen_color = self.pencil_color_at(ev.p()).ok();
|
||||
self.tool.gesture = Gesture::Pencil { points: vec![ev.p()], pressure: vec![ev.pressure] };
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1261,6 +1261,20 @@ pub fn paint_all(doc: &mut Document, id: NodeId, pts: &[Point]) -> Result<bool>
|
||||
Ok(filled)
|
||||
}
|
||||
|
||||
/// The fills the Fill section shows for layer `id` while regions of it are selected in edit
|
||||
/// mode: the stack those regions share (their own, else the layer's), `Some(None)` when they
|
||||
/// differ (mixed), `None` when no region of that layer is selected (the layer's fills show). The
|
||||
/// fill commands edit the same regions then (#1875).
|
||||
pub fn selected_region_fills(s: &Session, id: NodeId) -> Option<Option<Vec<figcraft_color::Paint>>> {
|
||||
let ve = s.ds().ok()?.vector_edit.as_ref().filter(|ve| ve.id == id && !ve.regions.is_empty())?;
|
||||
let doc = s.doc().ok()?;
|
||||
let node = doc.node(id)?;
|
||||
let net = network(doc, id)?;
|
||||
let mut stacks = ve.regions.iter().filter_map(|r| net.regions.get(*r)).map(|r| r.fills.clone().unwrap_or_else(|| node.fills.clone()));
|
||||
let first = stacks.next()?;
|
||||
Some(stacks.all(|st| st == first).then_some(first))
|
||||
}
|
||||
|
||||
/// Add points `vs` of edited layer `id` to its selection.
|
||||
pub(crate) fn add_points(ve: &mut VectorEdit, id: NodeId, vs: &[usize]) {
|
||||
let list = if id == ve.id { Some(&mut ve.vertices) } else { ve.others.iter_mut().find(|o| o.id == id).map(|o| &mut o.vertices) };
|
||||
|
||||
@@ -6,6 +6,7 @@ use figcraft_geom::{Affine, Point, Rect, Vec2};
|
||||
use serde_json::json;
|
||||
|
||||
use super::regions::*;
|
||||
use super::selected_region_fills;
|
||||
use super::tests::{ex, net, ve};
|
||||
use crate::Session;
|
||||
use crate::tools::{PointerEvent, PointerKind};
|
||||
@@ -540,3 +541,85 @@ fn hovered_and_selected_is_hatched_once_and_regions_share_one_pattern() {
|
||||
assert!(!part.is_empty() && part.len() < all.len());
|
||||
assert!(part.iter().all(|x| all.iter().any(|y| (x - y).abs() < 1e-6)));
|
||||
}
|
||||
|
||||
/// Each closed region of a vector network has its own fill (#1875): with regions selected in edit mode, the fill
|
||||
/// commands edit those regions' own fills and leave the layer's; `regions` names them outright.
|
||||
#[test]
|
||||
fn the_fill_commands_edit_the_selected_regions() {
|
||||
let mut s = Session::new();
|
||||
let id = editing_vector(&mut s, overlapping());
|
||||
let fills_of = |s: &Session, r: usize| net(s, id).regions[r].fills.clone();
|
||||
let layer = |s: &Session| s.doc().unwrap().node(id).unwrap().fills.clone();
|
||||
let colour = |s: &Session, r: usize, i: usize| fills_of(s, r).unwrap()[i].solid_color().unwrap().to_css_hex().to_ascii_uppercase();
|
||||
let before = layer(&s);
|
||||
ex(&mut s, "vector.edit.select", json!({"regions": [1]}));
|
||||
ex(&mut s, "fill.set", json!({"ids": [id], "color": "#FF0000"}));
|
||||
assert_eq!(fills_of(&s, 1).map(|f| f.len()), Some(1));
|
||||
assert_eq!(colour(&s, 1, 0), "#FF0000");
|
||||
assert_eq!(fills_of(&s, 0), None, "the other region still inherits");
|
||||
assert_eq!(layer(&s), before, "the layer's fills are untouched");
|
||||
// The section's list for the layer is the region's own stack.
|
||||
assert_eq!(selected_region_fills(&s, id).and_then(|l| l).map(|l| l.len()), Some(1));
|
||||
ex(&mut s, "fill.add", json!({"ids": [id], "color": "#00FF00"}));
|
||||
assert_eq!(fills_of(&s, 1).unwrap().len(), 2);
|
||||
ex(&mut s, "fill.move", json!({"ids": [id], "from": 0, "to": 1}));
|
||||
assert_eq!((colour(&s, 1, 0), colour(&s, 1, 1)), ("#00FF00".to_string(), "#FF0000".to_string()));
|
||||
ex(&mut s, "fill.remove", json!({"ids": [id], "index": 0}));
|
||||
assert_eq!(fills_of(&s, 1).unwrap().len(), 1);
|
||||
assert_eq!(colour(&s, 1, 0), "#FF0000");
|
||||
assert_eq!(layer(&s), before);
|
||||
// Both regions selected with different fills: the section shows mixed content.
|
||||
ex(&mut s, "vector.edit.select", json!({"regions": [0, 1]}));
|
||||
assert_eq!(selected_region_fills(&s, id), Some(None));
|
||||
// Named outright, with no selection; junk is refused.
|
||||
ex(&mut s, "vector.edit.select", json!({}));
|
||||
ex(&mut s, "fill.set", json!({"ids": [id], "regions": [0], "color": "#0000FF"}));
|
||||
assert_eq!(colour(&s, 0, 0), "#0000FF");
|
||||
assert!(s.execute("fill.set", &json!({"ids": [id], "regions": [9], "color": "#0000FF"})).is_err());
|
||||
assert!(s.execute("fill.set", &json!({"ids": [id], "regions": "all", "color": "#0000FF"})).is_err());
|
||||
assert!(s.execute("fill.set", &json!({"ids": [id], "regions": [], "color": "#0000FF"})).is_err());
|
||||
// Nothing selected: the layer's fills, as before; the regions keep their own.
|
||||
ex(&mut s, "fill.set", json!({"ids": [id], "color": "#123456"}));
|
||||
assert_ne!(layer(&s), before);
|
||||
assert_eq!(colour(&s, 1, 0), "#FF0000");
|
||||
assert_eq!(selected_region_fills(&s, id), None);
|
||||
s.undo().unwrap();
|
||||
assert_eq!(layer(&s), before, "one undo step per command");
|
||||
}
|
||||
|
||||
/// Region fill edits from review: a region named twice is edited once; an edit that changes
|
||||
/// nothing leaves an inheriting region inheriting; Copy fill reads the selected region's fill.
|
||||
#[test]
|
||||
fn region_fill_edits_apply_once_skip_no_ops_and_copy_the_region() {
|
||||
let mut s = Session::new();
|
||||
let id = editing_vector(&mut s, overlapping());
|
||||
let fills_of = |s: &Session, r: usize| net(s, id).regions[r].fills.clone();
|
||||
ex(&mut s, "vector.edit.select", json!({"regions": [1]}));
|
||||
ex(&mut s, "fill.move", json!({"ids": [id], "from": 0, "to": 0}));
|
||||
assert_eq!(fills_of(&s, 1), None, "moving a paint onto itself leaves the region inheriting");
|
||||
ex(&mut s, "fill.remove", json!({"ids": [id], "index": 5}));
|
||||
assert_eq!(fills_of(&s, 1), None, "removing a paint that isn't there leaves it inheriting");
|
||||
ex(&mut s, "fill.add", json!({"ids": [id], "regions": [0, 0], "color": "#00FF00"}));
|
||||
assert_eq!(fills_of(&s, 0).map(|f| f.len()), Some(2), "the layer's fill and one added, once");
|
||||
// Copy fill takes the selected region's own paint, not the layer's.
|
||||
ex(&mut s, "fill.set", json!({"ids": [id], "color": "#FF0000"}));
|
||||
ex(&mut s, "fill.copy", json!({"ids": [id], "index": 0}));
|
||||
let copied = s.clipboard.paint.clone().map(|(_, p)| p.solid_color().unwrap().to_css_hex().to_ascii_uppercase());
|
||||
assert_eq!(copied.as_deref(), Some("#FF0000"));
|
||||
// Regions whose fills differ have no one paint to copy.
|
||||
ex(&mut s, "vector.edit.select", json!({"regions": [0, 1]}));
|
||||
assert!(s.execute("fill.copy", &json!({"ids": [id], "index": 0})).is_err());
|
||||
}
|
||||
|
||||
/// `fill.pattern` sets the layer's fill, as its spec says, also while regions are selected.
|
||||
#[test]
|
||||
fn fill_pattern_sets_the_layers_fill_with_regions_selected() {
|
||||
let mut s = Session::new();
|
||||
let src = crate::params::id_of(&ex(&mut s, "shape.rectangle", json!({"x": 400, "y": 0, "width": 20, "height": 20}))["id"]).unwrap();
|
||||
let id = editing_vector(&mut s, overlapping());
|
||||
ex(&mut s, "vector.edit.select", json!({"regions": [1]}));
|
||||
ex(&mut s, "fill.pattern", json!({"ids": [id], "source": src}));
|
||||
assert_eq!(net(&s, id).regions[1].fills, None, "the region still inherits");
|
||||
let top = s.doc().unwrap().node(id).unwrap().fills.last().cloned().unwrap();
|
||||
assert!(matches!(top.kind, figcraft_color::PaintKind::Pattern(_)), "{top:?}");
|
||||
}
|
||||
|
||||
@@ -194,7 +194,7 @@ fn create_kind(s: &mut Session, p: &Value, t: &str) -> Result<Value> {
|
||||
|
||||
/// Parse SVG path data (`M L H V C S Q T A Z`, absolute and relative) into a bezier path.
|
||||
pub fn parse_path_data(d: &str) -> Option<figcraft_geom::BezPath> {
|
||||
figcraft_geom::BezPath::from_svg(d).ok()
|
||||
figcraft_geom::svg_path(d).ok()
|
||||
}
|
||||
|
||||
/// A vector's geometry made from SVG path data (see [`path_network`]).
|
||||
@@ -213,7 +213,9 @@ pub(crate) struct PathShape {
|
||||
pub(crate) fn path_network(cmd: &str, d: &str, width: Option<f64>, height: Option<f64>) -> Result<PathShape> {
|
||||
use figcraft_geom::Shape;
|
||||
let empty = || bad(cmd, "`path` draws nothing: a vector needs a visible line or area");
|
||||
let mut path = parse_path_data(d).ok_or_else(|| bad(cmd, "`path` is not valid SVG path data"))?;
|
||||
let mut path = figcraft_geom::svg_path(d).map_err(|e| {
|
||||
if e.contains("too large") { bad(cmd, "`path` has coordinates too large to draw") } else { bad(cmd, "`path` is not valid SVG path data") }
|
||||
})?;
|
||||
let bb = path.bounding_box();
|
||||
if !(bb.x0.is_finite() && bb.y0.is_finite() && bb.width().is_finite() && bb.height().is_finite()) {
|
||||
return Err(bad(cmd, "`path` has coordinates too large to draw"));
|
||||
|
||||
@@ -15,6 +15,7 @@ use crate::{BatchStep, EngineError, Result, Session, bad, spec};
|
||||
|
||||
mod clipboard;
|
||||
mod props;
|
||||
pub(crate) use props::{edit_region_fills, fill_regions};
|
||||
mod select;
|
||||
|
||||
pub(crate) use clipboard::apply_copied_props;
|
||||
@@ -345,14 +346,28 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
s.doc_mut()?.reorder(i, idx)?;
|
||||
ok()
|
||||
}),
|
||||
spec!("fill.add", "Add fill", "{ids?, paint? | color? (default #D9D9D9 or white for frames)}", true, |s, p| paint_list(s, p, true, true)),
|
||||
spec!(
|
||||
"fill.add",
|
||||
"Add fill",
|
||||
"{ids?, paint? | color? (default #D9D9D9 or white for frames), regions? (a vector's regions by index: their own fills, as the regions selected in edit mode)}",
|
||||
true,
|
||||
|s, p| paint_list(s, p, true, true)
|
||||
),
|
||||
spec!("stroke.add", "Add stroke", "{ids?, paint? | color? (default black)}", true, |s, p| paint_list(s, p, false, true)),
|
||||
spec!("fill.remove", "Remove fill", "{ids?, index}", true, |s, p| paint_list(s, p, true, false)),
|
||||
spec!("fill.remove", "Remove fill", "{ids?, index, regions?}", true, |s, p| paint_list(s, p, true, false)),
|
||||
spec!("stroke.remove", "Remove stroke", "{ids?, index}", true, |s, p| paint_list(s, p, false, false)),
|
||||
spec!("fill.set", "Set fill", "{ids?, index?, paint | color, opacity?, visible?, blend?}", true, |s, p| paint_set(s, p, true)),
|
||||
spec!(
|
||||
"fill.set",
|
||||
"Set fill",
|
||||
"{ids?, index?, paint | color, opacity?, visible?, blend?, regions? (a vector's regions by index: their own fills, as the regions selected in edit mode)}",
|
||||
true,
|
||||
|s, p| paint_set(s, p, true)
|
||||
),
|
||||
spec!("stroke.set", "Set stroke", "{ids?, index?, paint | color, opacity?, visible?, blend?}", true, |s, p| paint_set(s, p, false)),
|
||||
spec!("fill.copy", "Copy fill", "{id?, index? (default the top fill)}", false, |s, p| paint_copy(s, p, true)),
|
||||
spec!("fill.paste", "Paste fill", "{ids?, index? (replace the fill there; without: add one)}", true, |s, p| paint_paste(s, p, true)),
|
||||
spec!("fill.paste", "Paste fill", "{ids?, index? (replace the fill there; without: add one), regions?}", true, |s, p| paint_paste(
|
||||
s, p, true
|
||||
)),
|
||||
spec!(
|
||||
"stroke.copy",
|
||||
"Copy stroke",
|
||||
|
||||
@@ -260,10 +260,92 @@ pub(super) fn reparent(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// The regions of a vector whose own fill stacks a fill command edits instead of the layer's: the
|
||||
/// `regions` named (with one target, a vector; indices into its network's regions), else the
|
||||
/// regions selected in vector edit mode when the one target is the layer being edited (#1875).
|
||||
/// None: the layer's.
|
||||
pub(crate) fn fill_regions(s: &Session, cmd: &str, p: &Value, ids: &[NodeId]) -> Result<Option<(NodeId, Vec<usize>)>> {
|
||||
let doc = s.doc()?;
|
||||
let region_count = |id: NodeId| match doc.node(id).map(|n| &n.kind) {
|
||||
Some(NodeKind::Vector { network }) => Some(network.regions.len()),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(list) = get(p, "regions") {
|
||||
let [id] = ids else { return Err(bad(cmd, "`regions` goes with one vector layer")) };
|
||||
let Some(count) = region_count(*id) else { return Err(bad(cmd, "`regions` goes with a vector layer")) };
|
||||
let mut regions = list
|
||||
.as_array()
|
||||
.ok_or_else(|| bad(cmd, "regions: [index, ...]"))?
|
||||
.iter()
|
||||
.map(|v| {
|
||||
v.as_u64()
|
||||
.and_then(|i| usize::try_from(i).ok())
|
||||
.filter(|i| *i < count)
|
||||
.ok_or_else(|| bad(cmd, format!("regions: indices below {count}")))
|
||||
})
|
||||
.collect::<Result<Vec<usize>>>()?;
|
||||
// A region named twice is edited once.
|
||||
regions.sort_unstable();
|
||||
regions.dedup();
|
||||
if regions.is_empty() {
|
||||
return Err(bad(cmd, "regions: at least one"));
|
||||
}
|
||||
return Ok(Some((*id, regions)));
|
||||
}
|
||||
let [id] = ids else { return Ok(None) };
|
||||
let Some(ve) = s.ds()?.vector_edit.as_ref().filter(|ve| ve.id == *id && !ve.regions.is_empty()) else { return Ok(None) };
|
||||
let count = region_count(*id).unwrap_or(0);
|
||||
let mut regions: Vec<usize> = ve.regions.iter().copied().filter(|r| *r < count).collect();
|
||||
regions.sort_unstable();
|
||||
regions.dedup();
|
||||
Ok((!regions.is_empty()).then_some((*id, regions)))
|
||||
}
|
||||
|
||||
/// Runs `f` on the own fill stack of each of `regions` of vector `id` (a region without one
|
||||
/// starts from the layer's fills, which stay as they are). A region that inherits the layer's
|
||||
/// fills keeps inheriting when `f` leaves the stack as it was, so later edits of the layer's
|
||||
/// fills still reach it; a region's own stack is only replaced once `f` succeeds.
|
||||
pub(crate) fn edit_region_fills(
|
||||
doc: &mut figcraft_doc::Document,
|
||||
id: NodeId,
|
||||
regions: &[usize],
|
||||
mut f: impl FnMut(&mut Vec<figcraft_color::Paint>) -> Result<()>,
|
||||
) -> Result<()> {
|
||||
let inherited = doc.get(id)?.fills.clone();
|
||||
let NodeKind::Vector { network } = &mut doc.get_mut(id)?.kind else { return Err(bad("fill", "not a vector layer")) };
|
||||
for &r in regions {
|
||||
let Some(region) = network.regions.get_mut(r) else { continue };
|
||||
let mut list = region.fills.clone().unwrap_or_else(|| inherited.clone());
|
||||
f(&mut list)?;
|
||||
if region.fills.is_some() || list != inherited {
|
||||
region.fills = Some(list);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn paint_list(s: &mut Session, p: &Value, fills: bool, add: bool) -> Result<Value> {
|
||||
let cmd = if fills { "fill" } else { "stroke" };
|
||||
let ids = req_targets(cmd, s, p)?;
|
||||
let index = if add || get(p, "index").is_none() { None } else { Some(req_index(cmd, p, "index")?) };
|
||||
if let Some((id, regions)) = fill_regions(s, cmd, p, &ids)?.filter(|_| fills) {
|
||||
let paint = match get(p, "paint").or_else(|| get(p, "color")) {
|
||||
Some(v) => Some(paint_of(v).ok_or_else(|| bad(cmd, "invalid paint"))?),
|
||||
None => None,
|
||||
};
|
||||
edit_region_fills(s.doc_mut()?, id, ®ions, |list| {
|
||||
if add {
|
||||
list.push(paint.clone().unwrap_or_else(|| figcraft_color::Paint::solid(figcraft_color::Color::DEFAULT_SHAPE)));
|
||||
} else {
|
||||
let idx = index.unwrap_or(list.len().saturating_sub(1));
|
||||
if idx < list.len() {
|
||||
let _ = list.remove(idx);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
return ok();
|
||||
}
|
||||
let doc = s.doc_mut()?;
|
||||
for i in ids {
|
||||
let n = doc.get_mut(i)?;
|
||||
@@ -299,6 +381,12 @@ pub(super) fn paint_list(s: &mut Session, p: &Value, fills: bool, add: bool) ->
|
||||
}
|
||||
|
||||
pub(super) fn paint_set(s: &mut Session, p: &Value, fills: bool) -> Result<Value> {
|
||||
paint_set_in(s, p, fills, true)
|
||||
}
|
||||
|
||||
/// [`paint_set`]; `to_regions`: whether the regions selected (or named) on a vector take the
|
||||
/// edit in their own fills (#1875), as for `fill.set`; `fill.pattern` always sets the layer's.
|
||||
fn paint_set_in(s: &mut Session, p: &Value, fills: bool, to_regions: bool) -> Result<Value> {
|
||||
let cmd = if fills { "fill.set" } else { "stroke.set" };
|
||||
let ids = req_targets(cmd, s, p)?;
|
||||
let idx = opt_index(cmd, p, "index")?;
|
||||
@@ -307,19 +395,8 @@ pub(super) fn paint_set(s: &mut Session, p: &Value, fills: bool) -> Result<Value
|
||||
None => None,
|
||||
};
|
||||
let col = color(p, "color");
|
||||
let doc = s.doc_mut()?;
|
||||
for i in ids {
|
||||
let n = doc.get_mut(i)?;
|
||||
if fills {
|
||||
crate::cmd::lists::take_character_fills(n);
|
||||
}
|
||||
let list = if fills { &mut n.fills } else { &mut n.strokes };
|
||||
let at = idx.unwrap_or(list.len().saturating_sub(1));
|
||||
if list.is_empty() {
|
||||
list.push(figcraft_color::Paint::solid(if fills { figcraft_color::Color::DEFAULT_SHAPE } else { figcraft_color::Color::BLACK }));
|
||||
}
|
||||
let Some(slot) = list.get_mut(at) else { return Err(bad(cmd, format!("no paint at index {at}"))) };
|
||||
let old = slot.clone();
|
||||
// The edit of one paint slot, the same for a layer's list and a region's.
|
||||
let edit_slot = |slot: &mut figcraft_color::Paint| {
|
||||
if let Some(np) = &new_paint {
|
||||
*slot = np.clone();
|
||||
}
|
||||
@@ -340,6 +417,33 @@ pub(super) fn paint_set(s: &mut Session, p: &Value, fills: bool) -> Result<Value
|
||||
if let Some(b) = blend(p, "blend") {
|
||||
slot.blend = b;
|
||||
}
|
||||
};
|
||||
if let Some((id, regions)) = fill_regions(s, cmd, p, &ids)?.filter(|_| fills && to_regions) {
|
||||
edit_region_fills(s.doc_mut()?, id, ®ions, |list| {
|
||||
if list.is_empty() {
|
||||
list.push(figcraft_color::Paint::solid(figcraft_color::Color::DEFAULT_SHAPE));
|
||||
}
|
||||
let at = idx.unwrap_or(list.len().saturating_sub(1));
|
||||
let Some(slot) = list.get_mut(at) else { return Err(bad(cmd, format!("no paint at index {at}"))) };
|
||||
edit_slot(slot);
|
||||
Ok(())
|
||||
})?;
|
||||
return ok();
|
||||
}
|
||||
let doc = s.doc_mut()?;
|
||||
for i in ids {
|
||||
let n = doc.get_mut(i)?;
|
||||
if fills {
|
||||
crate::cmd::lists::take_character_fills(n);
|
||||
}
|
||||
let list = if fills { &mut n.fills } else { &mut n.strokes };
|
||||
let at = idx.unwrap_or(list.len().saturating_sub(1));
|
||||
if list.is_empty() {
|
||||
list.push(figcraft_color::Paint::solid(if fills { figcraft_color::Color::DEFAULT_SHAPE } else { figcraft_color::Color::BLACK }));
|
||||
}
|
||||
let Some(slot) = list.get_mut(at) else { return Err(bad(cmd, format!("no paint at index {at}"))) };
|
||||
let old = slot.clone();
|
||||
edit_slot(slot);
|
||||
crate::cmd::lists::rebind_edited_paint(n, fills, at, &old);
|
||||
if fills {
|
||||
n.styles.fill = None;
|
||||
@@ -359,8 +463,15 @@ pub(super) fn paint_copy(s: &mut Session, p: &Value, fills: bool) -> Result<Valu
|
||||
let (paint, stroke) = {
|
||||
let doc = s.doc()?;
|
||||
let n = doc.get(id)?;
|
||||
// A text's fills are what its characters show (the list the Design panel's rows are).
|
||||
let list = if fills { crate::cmd::lists::character_fills(n).unwrap_or_default() } else { n.strokes.clone() };
|
||||
// Regions selected in vector edit mode: their own fills, as the Fill section lists them
|
||||
// (#1875); a text's fills are what its characters show (#1856).
|
||||
let regions = if fills { crate::vectoredit::selected_region_fills(s, id) } else { None };
|
||||
let list: Vec<figcraft_color::Paint> = match regions {
|
||||
Some(Some(list)) => list,
|
||||
Some(None) => return Err(bad(cmd, "the selected regions' fills differ")),
|
||||
None if fills => crate::cmd::lists::character_fills(n).unwrap_or_default(),
|
||||
None => n.strokes.clone(),
|
||||
};
|
||||
let at = at.unwrap_or(list.len().saturating_sub(1));
|
||||
let paint = list.get(at).cloned().ok_or_else(|| bad(cmd, format!("no {} at index {at}", if fills { "fill" } else { "stroke" })))?;
|
||||
(paint, (!fills).then(|| n.stroke.clone()))
|
||||
@@ -429,6 +540,9 @@ pub(super) fn paint_paste(s: &mut Session, p: &Value, fills: bool) -> Result<Val
|
||||
}
|
||||
}
|
||||
let mut q = json!({"ids": ids, "paint": serde_json::to_value(paint).map_err(|e| bad(cmd, e.to_string()))?});
|
||||
if let Some(regions) = get(p, "regions") {
|
||||
q["regions"] = regions.clone();
|
||||
}
|
||||
let out = match opt_index(cmd, p, "index")? {
|
||||
Some(at) => {
|
||||
q["index"] = json!(at);
|
||||
@@ -464,7 +578,7 @@ pub(super) fn pattern_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
q["paint"] =
|
||||
serde_json::to_value(figcraft_color::Paint { kind: figcraft_color::PaintKind::Pattern(pt), ..figcraft_color::Paint::pattern(src.0) })
|
||||
.map_err(|e| bad(CMD, e.to_string()))?;
|
||||
paint_set(s, &q, true)
|
||||
paint_set_in(s, &q, true, false)
|
||||
}
|
||||
|
||||
pub(super) fn effect_add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -194,7 +194,7 @@ fn with(p: &Value, keys: &[&str], mut base: Value) -> Value {
|
||||
}
|
||||
|
||||
/// An enabled library of the active document (`library` param), read from its file.
|
||||
fn library(s: &mut Session, cmd: &str, p: &Value) -> Result<(LibraryLink, Arc<PublishedLibrary>)> {
|
||||
pub(crate) fn library(s: &mut Session, cmd: &str, p: &Value) -> Result<(LibraryLink, Arc<PublishedLibrary>)> {
|
||||
let key = req_string(cmd, p, "library")?;
|
||||
let link = find_link(s.doc()?, &key)
|
||||
.cloned()
|
||||
|
||||
@@ -15,7 +15,7 @@ use crate::{Result, Session, spec};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
spec!("fill.move", "Move fill", "{ids?, from, to} (indices in the fill list, bottom first)", true, |s, p| {
|
||||
spec!("fill.move", "Move fill", "{ids?, from, to, regions?} (indices in the fill list, bottom first)", true, |s, p| {
|
||||
move_item(s, p, "fill.move", BoundList::Fills)
|
||||
}),
|
||||
spec!("stroke.move", "Move stroke", "{ids?, from, to} (indices in the stroke list, bottom first)", true, |s, p| {
|
||||
@@ -295,7 +295,20 @@ fn reorder<T>(v: &mut Vec<T>, from: usize, to: usize) -> bool {
|
||||
fn move_item(s: &mut Session, p: &Value, cmd: &str, list: BoundList) -> Result<Value> {
|
||||
let from = req_index(cmd, p, "from")?;
|
||||
let to = req_index(cmd, p, "to")?;
|
||||
for id in req_targets(cmd, s, p)? {
|
||||
let ids = req_targets(cmd, s, p)?;
|
||||
// Fills of the regions selected (or named) in a vector: their own stacks move (#1875).
|
||||
if matches!(list, BoundList::Fills)
|
||||
&& let Some((id, regions)) = crate::cmd::edit::fill_regions(s, cmd, p, &ids)?
|
||||
{
|
||||
crate::cmd::edit::edit_region_fills(s.doc_mut()?, id, ®ions, |fills| {
|
||||
if from < fills.len() && to < fills.len() {
|
||||
reorder(fills, from, to);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
return ok();
|
||||
}
|
||||
for id in ids {
|
||||
// A text's characters' shared fills are the list the Design panel shows and reorders.
|
||||
let len = s
|
||||
.doc()?
|
||||
|
||||
@@ -10,6 +10,8 @@ use serde_json::{Value, json};
|
||||
|
||||
use super::edit::{roots, z_sorted};
|
||||
use super::{CommandSpec, ok};
|
||||
|
||||
mod suggest;
|
||||
use crate::params::{f64_of, get, id_of, num_or, req_id, req_index, req_num, req_targets, string, targets};
|
||||
use crate::{EngineError, Result, Session, bad, spec};
|
||||
|
||||
@@ -109,7 +111,13 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
Ok(json!({"removed": removed}))
|
||||
}
|
||||
),
|
||||
spec!("layout.suggest", "Suggest auto layout", "{ids?, direction? (horizontal|vertical|grid)}", true, layout_add),
|
||||
spec!(
|
||||
"layout.suggest",
|
||||
"Suggest auto layout",
|
||||
"{ids?, direction? (horizontal|vertical|grid)} splits each frame's layers into rows or columns by the gaps between them, wraps every band of several layers in a frame without fill that hugs it and does the same inside, so the layers keep their place where the gaps are even and the bands start at the same offset across the flow; the frame keeps its size, and the result carries `warnings` for gaps that differ, bands that start at different offsets (they line up at the smallest and some move) and layers that overlap. Instances and the layers inside them are refused. `direction` sets the top level's direction (nested frames follow the gaps); grid lays the layers out in one grid. A group is converted to a frame and several layers are wrapped in one, as Add auto layout does",
|
||||
true,
|
||||
suggest::layout_suggest
|
||||
),
|
||||
spec!("object.moveToPage", "Move to page", "{ids?, page}", true, move_to_page),
|
||||
spec!("object.setThumbnail", "Set as thumbnail", "{id?}", true, |s, p| {
|
||||
let id = targets(s, p).first().copied().ok_or_else(|| bad("object.setThumbnail", "select a frame"))?;
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
//! Suggest auto layout (#1823): split a frame's layers into rows or columns by the gaps between
|
||||
//! them, wrap each band that holds several layers in a frame of its own and do the same inside
|
||||
//! it, so the design gets as many auto layout frames as it needs and keeps its placement.
|
||||
|
||||
use figcraft_doc::{AutoLayout, Document, LayoutMode, NodeId, NodeKind, Sizing};
|
||||
use figcraft_geom::Rect;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{Wrap, convert, infer_layout, sort_layout_children, wrap};
|
||||
use crate::params::{id_of, req_targets, string};
|
||||
use crate::{EngineError, Result, Session, bad};
|
||||
|
||||
/// How deep nested band frames go before a frame is laid out as a single list.
|
||||
const MAX_DEPTH: usize = 16;
|
||||
/// The most layers analysed in one frame; past this the frame is laid out as a single list.
|
||||
const MAX_CHILDREN: usize = 1000;
|
||||
/// Gaps that differ by more than this are reported.
|
||||
const GAP_TOLERANCE: f64 = 0.5;
|
||||
/// Edges closer than this count as touching.
|
||||
const EDGE_EPS: f64 = 1e-6;
|
||||
|
||||
/// One row or column: the layers in it and the span it covers along both axes.
|
||||
struct Band {
|
||||
members: Vec<(NodeId, Rect)>,
|
||||
/// Start and end along the split axis.
|
||||
lo: f64,
|
||||
hi: f64,
|
||||
/// Start and end along the other axis.
|
||||
cross_lo: f64,
|
||||
cross_hi: f64,
|
||||
}
|
||||
|
||||
fn span(r: &Rect, vertical: bool) -> (f64, f64, f64, f64) {
|
||||
if vertical { (r.y0, r.y1, r.x0, r.x1) } else { (r.x0, r.x1, r.y0, r.y1) }
|
||||
}
|
||||
|
||||
/// Split the layers into bands along one axis: sorted by their start, a layer joins the current
|
||||
/// band while it starts before the band ends, and opens a new band when there is a gap or it
|
||||
/// only touches. Layers starting together always share a band.
|
||||
fn bands(boxes: &[(NodeId, Rect)], vertical: bool) -> Vec<Band> {
|
||||
let mut sorted = boxes.to_vec();
|
||||
sorted.sort_by(|a, b| span(&a.1, vertical).0.total_cmp(&span(&b.1, vertical).0));
|
||||
let mut out: Vec<Band> = Vec::new();
|
||||
for item in sorted {
|
||||
let (lo, hi, cross_lo, cross_hi) = span(&item.1, vertical);
|
||||
match out.last_mut() {
|
||||
Some(b) if lo < b.hi - EDGE_EPS || lo - b.lo < EDGE_EPS => {
|
||||
b.hi = b.hi.max(hi);
|
||||
b.cross_lo = b.cross_lo.min(cross_lo);
|
||||
b.cross_hi = b.cross_hi.max(cross_hi);
|
||||
b.members.push(item);
|
||||
}
|
||||
_ => out.push(Band { members: vec![item], lo, hi, cross_lo, cross_hi }),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The layers a frame lays out, with their boxes in the frame's own space. `None` when a box
|
||||
/// isn't a finite number.
|
||||
fn flow_boxes(doc: &Document, frame: NodeId) -> Option<Vec<(NodeId, Rect)>> {
|
||||
let mut out = Vec::new();
|
||||
for c in figcraft_layout::flow_children(doc, frame) {
|
||||
let n = doc.node(c)?;
|
||||
let r = figcraft_geom::transform_rect_bbox(n.transform, n.local_rect());
|
||||
if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
out.push((c, r));
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
fn finite_or_zero(v: f64) -> f64 {
|
||||
if v.is_finite() { (v * 1000.0).round() / 1000.0 } else { 0.0 }
|
||||
}
|
||||
|
||||
fn mode_from(direction: &str) -> LayoutMode {
|
||||
match direction.to_ascii_lowercase().as_str() {
|
||||
"vertical" | "column" => LayoutMode::Vertical,
|
||||
"grid" => LayoutMode::Grid,
|
||||
_ => LayoutMode::Horizontal,
|
||||
}
|
||||
}
|
||||
|
||||
/// The auto layout that places `bands` where they are: the gap between them, the room before the
|
||||
/// first and after the last, and on the other axis the smallest offset from each edge.
|
||||
fn layout_for(bands: &[Band], vertical: bool, frame_w: f64, frame_h: f64, name: &str, warnings: &mut Vec<String>) -> AutoLayout {
|
||||
let gaps: Vec<f64> = bands.windows(2).filter_map(|w| Some((w.get(1)?.lo - w.first()?.hi).max(0.0))).collect();
|
||||
let smallest = gaps.iter().copied().fold(f64::INFINITY, f64::min);
|
||||
let largest = gaps.iter().copied().fold(0.0, f64::max);
|
||||
if largest - smallest > GAP_TOLERANCE {
|
||||
let what = if vertical { "rows" } else { "columns" };
|
||||
warnings.push(format!(
|
||||
"\"{name}\": the gaps between the {what} differ ({} to {}), so the smallest is used and later {what} move",
|
||||
finite_or_zero(smallest),
|
||||
finite_or_zero(largest)
|
||||
));
|
||||
}
|
||||
let (main_size, cross_size) = if vertical { (frame_h, frame_w) } else { (frame_w, frame_h) };
|
||||
let main_start = bands.first().map_or(0.0, |b| b.lo).max(0.0);
|
||||
let main_end = (main_size - bands.last().map_or(0.0, |b| b.hi)).max(0.0);
|
||||
let cross_start = bands.iter().map(|b| b.cross_lo).fold(f64::INFINITY, f64::min).max(0.0);
|
||||
let cross_end = bands.iter().map(|b| cross_size - b.cross_hi).fold(f64::INFINITY, f64::min).max(0.0);
|
||||
// Every band is lined up at the start across the flow, so one that starts further in (a
|
||||
// centred title above a card) moves to the smallest offset.
|
||||
let widest_start = bands.iter().map(|b| b.cross_lo).fold(f64::NEG_INFINITY, f64::max);
|
||||
let smallest_start = bands.iter().map(|b| b.cross_lo).fold(f64::INFINITY, f64::min);
|
||||
if widest_start - smallest_start > GAP_TOLERANCE {
|
||||
let what = if vertical { "rows" } else { "columns" };
|
||||
warnings.push(format!(
|
||||
"\"{name}\": the {what} start at different offsets ({} to {}), so they are lined up at the smallest and some move",
|
||||
finite_or_zero(smallest_start),
|
||||
finite_or_zero(widest_start)
|
||||
));
|
||||
}
|
||||
let [ms, me, cs, ce] = [main_start, main_end, cross_start, cross_end].map(finite_or_zero);
|
||||
AutoLayout {
|
||||
mode: if vertical { LayoutMode::Vertical } else { LayoutMode::Horizontal },
|
||||
gap: finite_or_zero(smallest),
|
||||
// Top, right, bottom, left.
|
||||
padding: if vertical { [ms, ce, me, cs] } else { [cs, me, ce, ms] },
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Lay a frame out as one list the way "Add auto layout" does: the direction is inferred, or
|
||||
/// `direction` forces it.
|
||||
fn flat_layout(s: &mut Session, frame: NodeId, direction: Option<&str>) -> Result<()> {
|
||||
let doc = s.doc_mut()?;
|
||||
let mut al = infer_layout(doc, frame);
|
||||
if let Some(d) = direction {
|
||||
al.mode = mode_from(d);
|
||||
}
|
||||
let mut kids = doc.get(frame)?.children.clone();
|
||||
sort_layout_children(doc, &mut kids, al.mode == LayoutMode::Vertical);
|
||||
let n = doc.get_mut(frame)?;
|
||||
n.children = kids;
|
||||
n.layout = Some(al);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Turn the frame's layers into bands and give the frame, and every band frame made on the way,
|
||||
/// the auto layout that keeps them where they are. Returns whether the frame got auto layout.
|
||||
fn split(s: &mut Session, frame: NodeId, depth: usize, direction: Option<&str>, warnings: &mut Vec<String>) -> Result<bool> {
|
||||
let doc = s.doc()?;
|
||||
let name = doc.get(frame)?.name.clone();
|
||||
let (frame_w, frame_h) = (doc.get(frame)?.width, doc.get(frame)?.height);
|
||||
let any_mask = doc.get(frame)?.children.iter().filter_map(|c| doc.node(*c)).any(|c| c.is_mask);
|
||||
let Some(boxes) = flow_boxes(doc, frame) else {
|
||||
warnings.push(format!("\"{name}\": a layer has no usable position, so no auto layout was added"));
|
||||
return Ok(false);
|
||||
};
|
||||
if boxes.len() < 2 {
|
||||
flat_layout(s, frame, direction)?;
|
||||
return Ok(true);
|
||||
}
|
||||
if depth >= MAX_DEPTH || boxes.len() > MAX_CHILDREN || any_mask {
|
||||
let why = if any_mask {
|
||||
"it has a mask"
|
||||
} else if depth >= MAX_DEPTH {
|
||||
"the frames are nested too deep"
|
||||
} else {
|
||||
"it has too many layers to analyse"
|
||||
};
|
||||
warnings.push(format!("\"{name}\": {why}, so its layers are laid out in one list"));
|
||||
flat_layout(s, frame, direction)?;
|
||||
return Ok(true);
|
||||
}
|
||||
// The direction asked for decides the axis of the top level; nested frames follow the gaps.
|
||||
let forced = direction.map(mode_from);
|
||||
let (vertical, found) = match forced {
|
||||
Some(LayoutMode::Vertical) => (true, bands(&boxes, true)),
|
||||
Some(LayoutMode::Horizontal) => (false, bands(&boxes, false)),
|
||||
Some(_) => (true, Vec::new()),
|
||||
None => {
|
||||
let rows = bands(&boxes, true);
|
||||
if rows.len() >= 2 { (true, rows) } else { (false, bands(&boxes, false)) }
|
||||
}
|
||||
};
|
||||
if found.len() < 2 {
|
||||
if forced.is_some() {
|
||||
if forced != Some(LayoutMode::Grid) {
|
||||
warnings.push(format!("\"{name}\": its layers don't separate along the direction asked for, so they are laid out in one list"));
|
||||
}
|
||||
flat_layout(s, frame, direction)?;
|
||||
return Ok(true);
|
||||
}
|
||||
warnings.push(format!("\"{name}\": its layers overlap along both axes, so no auto layout was added"));
|
||||
return Ok(false);
|
||||
}
|
||||
let al = layout_for(&found, vertical, frame_w, frame_h, &name, warnings);
|
||||
// Band frames first, while the layers are still where they were.
|
||||
let mut made = Vec::new();
|
||||
for band in &found {
|
||||
if band.members.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
let ids: Vec<NodeId> = band.members.iter().map(|(id, _)| *id).collect();
|
||||
let r = wrap(s, &json!({"ids": ids}), "layout.suggest", Wrap::Frame)?;
|
||||
let fid = id_of(&r["id"]).ok_or_else(|| EngineError::Other("wrap failed".into()))?;
|
||||
let f = s.doc_mut()?.get_mut(fid)?;
|
||||
f.fills.clear();
|
||||
f.clip = false;
|
||||
made.push(fid);
|
||||
}
|
||||
let doc = s.doc_mut()?;
|
||||
let mut kids = doc.get(frame)?.children.clone();
|
||||
sort_layout_children(doc, &mut kids, vertical);
|
||||
let n = doc.get_mut(frame)?;
|
||||
n.children = kids;
|
||||
n.layout = Some(al);
|
||||
for fid in made {
|
||||
if split(s, fid, depth + 1, None, warnings)? {
|
||||
// A band frame that got auto layout is as big as what is in it (one that did not stays Fixed).
|
||||
let f = s.doc_mut()?.get_mut(fid)?;
|
||||
f.child_layout.sizing_h = Sizing::Hug;
|
||||
f.child_layout.sizing_v = Sizing::Hug;
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Add auto layout to the frames, group or layers asked for the way "Add auto layout" finds its
|
||||
/// targets, then split each into nested rows and columns by the gaps between its layers.
|
||||
pub(super) fn layout_suggest(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = req_targets("layout.suggest", s, p)?;
|
||||
let direction = string(p, "direction");
|
||||
let doc = s.doc()?;
|
||||
// An instance's layers come from its main component: nothing is added to them. Checked
|
||||
// before anything changes, with the words Convert to group uses.
|
||||
for i in &ids {
|
||||
let n = doc.get(*i)?;
|
||||
if matches!(n.kind, NodeKind::Instance { .. }) {
|
||||
return Err(bad("layout.suggest", format!("\"{}\" is an instance: its layers come from its main component (detach it first)", n.name)));
|
||||
}
|
||||
if crate::components::owning_instance(doc, *i).is_some() {
|
||||
return Err(bad("layout.suggest", format!("\"{}\" is inside an instance: edit its main component, or detach the instance", n.name)));
|
||||
}
|
||||
}
|
||||
let all_frames = ids.iter().all(|i| doc.node(*i).is_some_and(|n| n.kind.is_frame_like() && n.layout.is_none()));
|
||||
let single_group = ids.len() == 1 && ids.first().and_then(|i| doc.node(*i)).is_some_and(|n| matches!(n.kind, NodeKind::Group));
|
||||
// A frame with auto layout already is wrapped, like a layer, and so are several layers.
|
||||
let (targets, own_size) = if all_frames {
|
||||
(ids, true)
|
||||
} else if single_group {
|
||||
// The group's layers are laid out directly, not inside a wrapper.
|
||||
convert(s, &json!({"ids": ids}), "layout.suggest", true)?;
|
||||
(ids, false)
|
||||
} else {
|
||||
let r = wrap(s, &json!({"ids": ids}), "layout.suggest", Wrap::Frame)?;
|
||||
let fid = id_of(&r["id"]).ok_or_else(|| EngineError::Other("wrap failed".into()))?;
|
||||
let f = s.doc_mut()?.get_mut(fid)?;
|
||||
f.fills.clear();
|
||||
f.clip = false;
|
||||
(vec![fid], false)
|
||||
};
|
||||
let mut warnings = Vec::new();
|
||||
for f in &targets {
|
||||
// A frame keeps its size; a wrapper or a converted group has none of its own and hugs.
|
||||
let got_layout = split(s, *f, 0, direction.as_deref(), &mut warnings)?;
|
||||
if got_layout && !own_size {
|
||||
let n = s.doc_mut()?.get_mut(*f)?;
|
||||
if !single_group || n.child_layout.sizing_h != Sizing::Fill {
|
||||
n.child_layout.sizing_h = Sizing::Hug;
|
||||
}
|
||||
if !single_group || n.child_layout.sizing_v != Sizing::Fill {
|
||||
n.child_layout.sizing_v = Sizing::Hug;
|
||||
}
|
||||
}
|
||||
}
|
||||
s.set_selection(targets.clone());
|
||||
let mut out = json!({"ids": targets});
|
||||
if !warnings.is_empty() {
|
||||
out["warnings"] = json!(warnings);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -129,11 +129,138 @@ fn toggle_italic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Hiragino's weight names: "W3" is 300.
|
||||
fn w_number(word: &str) -> Option<u16> {
|
||||
let n = word.strip_prefix('w')?.parse::<u16>().ok()?;
|
||||
(1..=9).contains(&n).then_some(n * 100)
|
||||
}
|
||||
|
||||
/// A weight number as some families name styles ("Condensed 600"). Below 100 it is something else
|
||||
/// (a width grade, an optical size: "Condensed 2", "Caption 12").
|
||||
fn number_weight(word: &str) -> Option<u16> {
|
||||
let n = word.parse::<u16>().ok().filter(|_| word.bytes().all(|b| b.is_ascii_digit()))?;
|
||||
(100..=1000).contains(&n).then_some(n)
|
||||
}
|
||||
|
||||
/// Style-name words that give a weight or a slant.
|
||||
const WEIGHT_WORDS: [&str; 25] = [
|
||||
"thin",
|
||||
"hairline",
|
||||
"extralight",
|
||||
"ultralight",
|
||||
"light",
|
||||
"semilight",
|
||||
"demilight",
|
||||
"regular",
|
||||
"normal",
|
||||
"roman",
|
||||
"book",
|
||||
"medium",
|
||||
"semibold",
|
||||
"demibold",
|
||||
"bold",
|
||||
"extrabold",
|
||||
"ultrabold",
|
||||
"black",
|
||||
"extrablack",
|
||||
"ultrablack",
|
||||
"heavy",
|
||||
"italic",
|
||||
"oblique",
|
||||
"plain",
|
||||
"standard",
|
||||
];
|
||||
|
||||
/// Words that grade the weight word after them ("Extra Bold") but a width otherwise ("Extra Condensed").
|
||||
const GRADES: [&str; 4] = ["extra", "ultra", "semi", "demi"];
|
||||
|
||||
/// The width a Univers number leading a style name gives, as Univers, Frutiger and Helvetica Neue
|
||||
/// LT name styles ("45 Light", "55 Roman", "57 Condensed", "67 Bold Condensed"): the first digit
|
||||
/// grades the weight, the second the width (3 or 4 extended, 5 or 6 normal, 7 or 8 condensed, 9
|
||||
/// ultra condensed; even is italic, which the name says too). Only before weight, slant and width
|
||||
/// words, so another leading number ("12 Regular", "55 Rounded") stays part of the width.
|
||||
fn univers_width(words: &[&str]) -> Option<u8> {
|
||||
const WIDTHS: [&str; 6] = ["condensed", "compressed", "narrow", "extended", "expanded", "wide"];
|
||||
let (code, rest) = words.split_first()?;
|
||||
let &[b'1'..=b'9', d @ b'3'..=b'9'] = code.as_bytes() else { return None };
|
||||
let known = |w: &&str| WEIGHT_WORDS.contains(w) || GRADES.contains(w) || WIDTHS.contains(w);
|
||||
(!rest.is_empty() && rest.iter().all(known)).then_some((d - b'1') / 2)
|
||||
}
|
||||
|
||||
/// What a style name says besides its weight and slant ("Narrow Bold Italic" → "narrow",
|
||||
/// "Extra Condensed Bold" → "extra condensed", "67 Bold Condensed" → its Univers width and "condensed").
|
||||
fn style_rest(style: &str) -> String {
|
||||
let s = style.to_ascii_lowercase().replace('-', " ");
|
||||
let words: Vec<&str> = s.split_whitespace().collect();
|
||||
let weight = |w: &str| WEIGHT_WORDS.contains(&w) || w_number(w).or_else(|| number_weight(w)).is_some();
|
||||
let rest = words.iter().enumerate().filter(|(i, w)| {
|
||||
let graded = GRADES.contains(w) && words.get(i + 1).is_some_and(|next| weight(next) && !matches!(*next, "italic" | "oblique"));
|
||||
!weight(w) && !graded
|
||||
});
|
||||
let univers = univers_width(&words).map(|d| format!("univers width {d}"));
|
||||
// The Univers number (the first word kept) gives way to its width.
|
||||
let rest = rest.map(|(_, w)| *w).skip(usize::from(univers.is_some()));
|
||||
univers.as_deref().into_iter().chain(rest).collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
/// A style name that slants: italic, or oblique as some families name it.
|
||||
fn slanted(style: &str) -> bool {
|
||||
let s = style.to_ascii_lowercase();
|
||||
s.contains("italic") || s.contains("oblique")
|
||||
}
|
||||
|
||||
/// The weight a style name says ("W3", "W6 Italic", "Condensed W7", "Condensed 600" and "45 Light" too).
|
||||
pub(crate) fn name_weight(style: &str) -> u16 {
|
||||
let s = style.to_ascii_lowercase().replace('-', " ");
|
||||
let words: Vec<&str> = s.split_whitespace().collect();
|
||||
// A Univers number's weight digit has no fixed CSS weight ("65" is Medium in Helvetica Neue,
|
||||
// Bold in Univers): the words after it say it.
|
||||
if let Some((_, rest)) = words.split_first().filter(|_| univers_width(&words).is_some()) {
|
||||
return figcraft_doc::style_weight(&rest.join(" "));
|
||||
}
|
||||
words.iter().find_map(|w| w_number(w).or_else(|| number_weight(w))).unwrap_or_else(|| figcraft_doc::style_weight(style))
|
||||
}
|
||||
|
||||
/// The next heavier (`up`) or lighter style of `styles` (a family's with the weight each is listed
|
||||
/// by, lightest first, as the style menu lists them) after the chars' style, with the same slant
|
||||
/// and width. The chars' style is found in the list by name and its neighbour taken; a style the
|
||||
/// family doesn't have, or a custom weight axis value, goes to the listed style of nearest weight
|
||||
/// that way. None when the family has nothing further.
|
||||
pub(crate) fn next_style(styles: &[(String, u16)], st: &TextStyle, up: bool) -> Option<String> {
|
||||
let italic = st.italic() || slanted(&st.font_style);
|
||||
let rest = style_rest(&st.font_style);
|
||||
let mut same: Vec<&(String, u16)> = styles.iter().filter(|(x, _)| slanted(x) == italic && style_rest(x) == rest).collect();
|
||||
let norm = |s: &str| s.to_lowercase().replace([' ', '-', '_'], "");
|
||||
let here = same.iter().position(|(x, _)| norm(x) == norm(&st.font_style));
|
||||
let axis = st.variations.contains_key("wght");
|
||||
if let Some(i) = here.filter(|_| !axis) {
|
||||
let next = if up { i.checked_add(1) } else { i.checked_sub(1) };
|
||||
return next.and_then(|n| same.get(n)).map(|(x, _)| x.clone());
|
||||
}
|
||||
let w = i32::from(if axis { st.weight() } else { name_weight(&st.font_style) });
|
||||
// Of equal weights, the one nearest in the family's order: the first going up, the last going down.
|
||||
if !up {
|
||||
same.reverse();
|
||||
}
|
||||
same.into_iter()
|
||||
.map(|(x, xw)| (i32::from(*xw) - w, x))
|
||||
.filter(|(d, _)| if up { *d > 0 } else { *d < 0 })
|
||||
.min_by_key(|(d, _)| d.abs())
|
||||
.map(|(_, x)| x.clone())
|
||||
}
|
||||
|
||||
/// `text.weightUp` / `text.weightDown`: each targeted run moves to the next style of its family.
|
||||
fn step_weight(s: &mut Session, p: &Value, up: bool) -> Result<Value> {
|
||||
style(s, p, |st| {
|
||||
let w = (i32::from(st.weight()) + if up { 100 } else { -100 }).clamp(100, 900) as u16;
|
||||
let italic = st.italic();
|
||||
st.set_font_style(styled_name(weight_name(w), italic));
|
||||
let styles = figcraft_text::family_style_weights(&st.font_family);
|
||||
if styles.is_empty() {
|
||||
// A family that isn't installed: step the weight by 100 under its canonical name.
|
||||
let w = (i32::from(st.weight()) + if up { 100 } else { -100 }).clamp(100, 900) as u16;
|
||||
let italic = st.italic();
|
||||
st.set_font_style(styled_name(weight_name(w), italic));
|
||||
} else if let Some(next) = next_style(&styles, st, up) {
|
||||
st.set_font_style(next);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -318,6 +318,129 @@ fn a_dropped_connection_keeps_editing_and_catches_up() {
|
||||
assert_eq!((doc.node(r).unwrap().name.as_str(), doc.node(f).unwrap().name.as_str()), ("Sent", "Offline"));
|
||||
}
|
||||
|
||||
impl Room {
|
||||
/// Person `i` has been told to join again: the server takes them as someone new.
|
||||
fn welcome_anew(&mut self, i: usize) {
|
||||
let ClientMsg::Hello(h) = Client::hello("f", "t", "Person", "") else { panic!("not a hello") };
|
||||
let (id, out) = self.server.join(h).unwrap();
|
||||
let w = welcome_of(&out, id);
|
||||
let p = &mut self.people[i];
|
||||
p.id = id;
|
||||
p.online = true;
|
||||
p.script.lock().unwrap().events.extend([Event::Welcome { info: info(Role::Guest, id), peers: vec![] }, Event::Sync(w)]);
|
||||
p.s.live_poll();
|
||||
}
|
||||
|
||||
fn event(&mut self, i: usize, e: Event) {
|
||||
let p = &mut self.people[i];
|
||||
p.script.lock().unwrap().events.push(e);
|
||||
p.s.live_poll();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconnecting_can_be_told_to_try_now_and_shows_as_disconnected() {
|
||||
let mut room = Room::new(base(), 1, 7);
|
||||
assert!(!room.s(0).live().disconnected());
|
||||
assert!(room.s(0).execute("collab.reconnect", &json!({})).is_err(), "nothing was lost");
|
||||
room.disconnect(0);
|
||||
assert!(room.s(0).live().disconnected());
|
||||
assert_eq!(room.s(0).execute("collab.reconnect", &json!({})).unwrap()["status"], "reconnecting");
|
||||
let session = room.s(0).live().id;
|
||||
assert_eq!(room.people[0].script.lock().unwrap().retried, [session]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_that_cant_go_on_stays_on_its_tab_and_joins_again_there() {
|
||||
let mut room = Room::new(base(), 2, 7);
|
||||
let (f, r) = frame_and_rect(room.server.document());
|
||||
let uid = room.s(0).ds().unwrap().uid;
|
||||
let tabs = room.s(0).docs.len();
|
||||
room.disconnect(0);
|
||||
room.s(0).execute("node.set", &json!({"id": r, "props": {"name": "Offline"}})).unwrap();
|
||||
room.event(0, Event::Status(Status::Failed { reason: "The host refused: this link isn't valid".into() }));
|
||||
// The tab says so, and is yours to go on working in.
|
||||
let live = room.s(0).live();
|
||||
assert!(live.disconnected() && live.rejoinable() && live.doc_uid == Some(uid));
|
||||
assert!(room.s(0).live_read_only(uid).is_none());
|
||||
room.s(0).execute("node.set", &json!({"id": f, "props": {"name": "Offline too"}})).unwrap();
|
||||
// A try that fails leaves it just as it was.
|
||||
assert_eq!(room.s(0).execute("collab.reconnect", &json!({})).unwrap()["status"], "connecting");
|
||||
assert!(room.s(0).live().disconnected() && !room.s(0).live().rejoinable());
|
||||
assert!(room.s(0).live_read_only(uid).is_none(), "it can still be edited while it tries");
|
||||
room.event(0, Event::Status(Status::Failed { reason: "Couldn't join the live session: no answer".into() }));
|
||||
assert!(room.s(0).live().rejoinable());
|
||||
// Someone else's edit lands meanwhile.
|
||||
room.s(1).execute("transform.move", &json!({"ids": [r], "dx": 5, "dy": 5})).unwrap();
|
||||
room.settle();
|
||||
// The next try joins in the same tab, and what was done offline opens beside it.
|
||||
room.s(0).execute("collab.reconnect", &json!({})).unwrap();
|
||||
room.welcome_anew(0);
|
||||
let s = room.s(0);
|
||||
assert_eq!(s.live().status, Status::Live);
|
||||
assert!(!s.live().disconnected());
|
||||
assert_eq!(s.docs.len(), tabs + 1, "the copy's is the only new tab");
|
||||
let (tab, copy) = (s.docs.iter().find(|d| d.uid == uid).unwrap(), s.docs.last().unwrap());
|
||||
assert_eq!(s.live().doc_uid, Some(uid));
|
||||
assert_ne!(tab.doc.node(r).unwrap().name, "Offline", "the session's tab shows the server's version");
|
||||
assert_eq!(copy.doc.name, format!("{} (offline copy)", tab.doc.name));
|
||||
assert_eq!(copy.doc.node(r).unwrap().name, "Offline");
|
||||
assert_eq!(copy.doc.node(f).unwrap().name, "Offline too");
|
||||
assert!(copy.is_dirty(), "closing the copy asks first");
|
||||
assert!(s.message.as_deref().is_some_and(|m| m.contains("offline copy")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn joining_again_with_nothing_changed_opens_no_copy() {
|
||||
let mut room = Room::new(base(), 1, 7);
|
||||
let tabs = room.s(0).docs.len();
|
||||
room.disconnect(0);
|
||||
room.event(0, Event::Ended { reason: "Sharing was stopped".into() });
|
||||
assert!(room.s(0).live().rejoinable(), "the end of a session you were in shows on its tab too");
|
||||
assert_eq!(room.s(0).message.as_deref(), Some("Sharing was stopped"));
|
||||
room.s(0).execute("collab.reconnect", &json!({})).unwrap();
|
||||
room.welcome_anew(0);
|
||||
assert_eq!(room.s(0).docs.len(), tabs);
|
||||
assert_eq!(room.s(0).live().status, Status::Live);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_out_of_step_joins_again_by_itself() {
|
||||
let mut room = Room::new(base(), 1, 7);
|
||||
let joins = room.people[0].script.lock().unwrap().joined.len();
|
||||
let tabs = room.s(0).docs.len();
|
||||
// A batch from far in the future: it can't be applied.
|
||||
room.event(0, Event::Sync(ServerMsg::Changes(figcraft_collab::Accepted { seq: 999, author: 42, batch_id: 1, changes: vec![] })));
|
||||
assert_eq!(room.s(0).live().status, Status::Connecting);
|
||||
assert!(room.s(0).live().disconnected());
|
||||
assert_eq!(room.people[0].script.lock().unwrap().joined.len(), joins + 1);
|
||||
room.welcome_anew(0);
|
||||
assert_eq!(room.s(0).live().status, Status::Live);
|
||||
assert_eq!(room.s(0).docs.len(), tabs);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaving_with_changes_unconfirmed_says_so() {
|
||||
let mut room = Room::new(base(), 1, 7);
|
||||
let (_, r) = frame_and_rect(room.server.document());
|
||||
room.s(0).execute("collab.leave", &json!({})).unwrap();
|
||||
assert_eq!(room.s(0).message.as_deref(), Some("You left the session; your copy stays open here"));
|
||||
let mut room = Room::new(base(), 1, 7);
|
||||
room.s(0).execute("node.set", &json!({"id": r, "props": {"name": "Unconfirmed"}})).unwrap();
|
||||
room.s(0).execute("collab.leave", &json!({})).unwrap();
|
||||
assert!(room.s(0).message.as_deref().is_some_and(|m| m.contains("before your last changes were confirmed")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaving_a_lost_session_makes_the_tab_a_plain_copy() {
|
||||
let mut room = Room::new(base(), 1, 7);
|
||||
room.disconnect(0);
|
||||
room.event(0, Event::Status(Status::Failed { reason: "gone".into() }));
|
||||
room.s(0).execute("collab.leave", &json!({})).unwrap();
|
||||
assert_eq!(room.s(0).live().status, Status::Off);
|
||||
assert!(!room.s(0).live().disconnected());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_commands_with_undo_and_drops_converge_through_the_engine() {
|
||||
for seed in 0..6 {
|
||||
|
||||
@@ -46,3 +46,37 @@ fn a_plugin_gets_names_but_no_paths() {
|
||||
assert!(out.contains("Front"), "{out}");
|
||||
assert!(!out.contains(SECRET) && !out.contains("path"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plugin_gets_library_names_but_not_their_links() {
|
||||
const LINK: &str = "ws://tracker.example:9/?file=f&token=per-file-secret";
|
||||
let mut s = Session::new();
|
||||
s.doc_mut().unwrap().libraries_mut().enabled.push(figcraft_doc::LibraryLink {
|
||||
id: "lib".into(),
|
||||
name: "Kit".into(),
|
||||
path: LINK.into(),
|
||||
version: 3,
|
||||
});
|
||||
let tail = "(call $set_output (i32.const 40000) (call $reply_read (i32.const 40000) (i32.const 20000))) (return (i32.const 0))";
|
||||
install(&mut s, manifest("org.test.libs", "read", &[]), &script(&[("library.list", json!({}))], OnRefusal::Fail, tail));
|
||||
let out = ex(&mut s, "plugin.run", json!({"id": "org.test.libs"}))["output"].to_string();
|
||||
assert!(out.contains("Kit"), "{out}");
|
||||
assert!(!out.contains("per-file-secret") && !out.contains("\\\"path\\\""), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plugin_gets_a_fixed_message_for_library_update_failures() {
|
||||
const LINK: &str = "/home/someone/private/kits/kit.figcraft";
|
||||
let mut s = Session::new();
|
||||
s.doc_mut().unwrap().libraries_mut().enabled.push(figcraft_doc::LibraryLink {
|
||||
id: "lib".into(),
|
||||
name: "Kit".into(),
|
||||
path: LINK.into(),
|
||||
version: 3,
|
||||
});
|
||||
let tail = "(call $set_output (i32.const 40000) (call $reply_read (i32.const 40000) (i32.const 20000))) (return (i32.const 0))";
|
||||
install(&mut s, manifest("org.test.upd", "read", &[]), &script(&[("library.updates", json!({}))], OnRefusal::Fail, tail));
|
||||
let out = ex(&mut s, "plugin.run", json!({"id": "org.test.upd"}))["output"].to_string();
|
||||
assert!(out.contains("could not be read"), "{out}");
|
||||
assert!(!out.contains("someone") && !out.contains("private"), "{out}");
|
||||
}
|
||||
|
||||
@@ -231,12 +231,23 @@ fn bundle_from_disk(cmd: &str, path: &str) -> Result<Bundle> {
|
||||
let wasm = module_file(&file, &m)?;
|
||||
let mut assets = Vec::new();
|
||||
let dir = file.parent().map(|d| d.join(ASSETS));
|
||||
// Links are not followed: a folder handed to the publisher could otherwise put any file the
|
||||
// publisher can read (a key, a token) in the bundle the directory then serves to everyone.
|
||||
let linked = |p: &std::path::Path| crate::file_access::link_metadata(p).is_ok_and(|m| m.is_symlink());
|
||||
if dir.as_ref().is_some_and(|d| linked(d)) {
|
||||
return Err(bad(cmd, format!("the {ASSETS} folder is a link: only files inside the plugin's folder are published")));
|
||||
}
|
||||
if let Some(entries) = dir.as_ref().and_then(|d| crate::file_access::read_dir(d).ok()) {
|
||||
let mut names: Vec<(String, std::path::PathBuf)> = entries
|
||||
.into_iter()
|
||||
.filter(|p| crate::file_access::metadata(p).is_ok_and(|m| m.is_file()))
|
||||
.map(|p| (p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(), p))
|
||||
.collect();
|
||||
let mut names: Vec<(String, std::path::PathBuf)> = Vec::new();
|
||||
for p in entries {
|
||||
let name = p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
if linked(&p) {
|
||||
return Err(bad(cmd, format!("{ASSETS}/{name} is a link: only files inside the plugin's folder are published")));
|
||||
}
|
||||
if crate::file_access::link_metadata(&p).is_ok_and(|m| m.is_file()) {
|
||||
names.push((name, p));
|
||||
}
|
||||
}
|
||||
names.sort();
|
||||
if names.len() > MAX_ASSETS {
|
||||
return Err(bad(cmd, format!("a plugin's assets folder holds at most {MAX_ASSETS} files")));
|
||||
|
||||
@@ -180,12 +180,21 @@ fn refusal(m: &Manifest, command: &str, params: &Value) -> Option<String> {
|
||||
if command == "variable.import" && get(params, "variables").and_then(Value::as_str).is_some_and(|t| !t.trim_start().starts_with('{')) {
|
||||
return Some("plugins can't read files: pass the variables JSON itself".into());
|
||||
}
|
||||
// A saved version is the file's history, which plugins can't read (`version.` is denied).
|
||||
if command == "dev.compare" && get(params, "version").is_some_and(|v| !v.is_null()) {
|
||||
return Some("plugins can't read saved versions: leave out `version`".into());
|
||||
}
|
||||
if !m.permissions.allows(command) {
|
||||
return Some(format!("`{command}` isn't in the commands {} asked permission for", m.name));
|
||||
}
|
||||
if m.permissions.access == Access::Read && find_command(command).is_some_and(|c| c.history) {
|
||||
return Some(format!("`{command}` edits the document, and {} may only read it", m.name));
|
||||
}
|
||||
// Branches live beside the document (not in its undo history or its `Arc`), so the write
|
||||
// checks below don't see them change.
|
||||
if m.permissions.access == Access::Read && matches!(command, "branch.create" | "branch.updateFromMain" | "branch.merge" | "branch.archive") {
|
||||
return Some(format!("`{command}` changes the file's branches, and {} may only read it", m.name));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
@@ -263,10 +272,23 @@ impl figcraft_plugin::Host for EngineHost<'_> {
|
||||
Ok(v)
|
||||
});
|
||||
r.map(|mut v| {
|
||||
// A plugin gets the open files' names, not where they are on disk (#1117).
|
||||
if command == "doc.list" {
|
||||
for e in v.as_array_mut().into_iter().flatten().filter_map(Value::as_object_mut) {
|
||||
// A plugin gets the open files' and libraries' names, not where they are on disk or
|
||||
// the share links (with their tokens) that reach them (#1117).
|
||||
if matches!(command, "doc.list" | "library.list" | "library.updates") {
|
||||
// `doc.list` is a list; `library.list` keeps its list under `libraries`, and
|
||||
// `library.updates` its failures under `errors`.
|
||||
let list = match command {
|
||||
"library.list" => v.get_mut("libraries"),
|
||||
"library.updates" => v.get_mut("errors"),
|
||||
_ => Some(&mut v),
|
||||
};
|
||||
for e in list.and_then(Value::as_array_mut).into_iter().flatten().filter_map(Value::as_object_mut) {
|
||||
e.remove("path");
|
||||
// A failure's text may quote the path, a token or another form of it: the
|
||||
// plugin gets a fixed message.
|
||||
if let Some(err) = e.get_mut("error").filter(|v| v.is_string()) {
|
||||
*err = json!("the library could not be read");
|
||||
}
|
||||
}
|
||||
}
|
||||
v.to_string()
|
||||
@@ -708,6 +730,23 @@ mod refusal_tests {
|
||||
let r = refusal(&m, "library.publishToServer", &json!({}));
|
||||
assert!(r.is_some(), "library.publishToServer uploads the document and must be refused");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_only_plugin_cannot_change_branches() {
|
||||
let m = Manifest::parse(r#"{"id":"x.y","name":"X","main":"plugin.wasm"}"#).unwrap();
|
||||
for cmd in ["branch.archive", "branch.updateFromMain", "branch.merge", "branch.create"] {
|
||||
assert!(refusal(&m, cmd, &json!({})).is_some(), "{cmd} changes persisted branch state");
|
||||
}
|
||||
assert!(refusal(&m, "branch.list", &json!({})).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugins_cannot_compare_against_a_saved_version() {
|
||||
let m = Manifest::parse(r#"{"id":"x.y","name":"X","main":"plugin.wasm","permissions":{"access":"write"}}"#).unwrap();
|
||||
assert!(refusal(&m, "dev.compare", &json!({"version": "v1"})).is_some());
|
||||
assert!(refusal(&m, "dev.compare", &json!({"version": null})).is_none());
|
||||
assert!(refusal(&m, "dev.compare", &json!({})).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
//! Suggest auto layout (#1823): a frame's layers are split into rows or columns by the gaps between
|
||||
//! them, each band of several layers gets a frame of its own, and the design keeps its placement.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Session;
|
||||
use crate::params::id_of;
|
||||
use figcraft_doc::{LayoutMode, NodeId, NodeKind, Sizing};
|
||||
|
||||
fn id(v: &Value) -> NodeId {
|
||||
id_of(&v["id"]).unwrap()
|
||||
}
|
||||
|
||||
fn ex(s: &mut Session, cmd: &str, p: Value) -> Value {
|
||||
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd} {p}: {e}"))
|
||||
}
|
||||
|
||||
fn frame(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
|
||||
id(&ex(s, "frame.create", json!({"x": x, "y": y, "width": w, "height": h})))
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, parent: NodeId, x: f64, y: f64, w: f64, h: f64) -> NodeId {
|
||||
id(&ex(s, "shape.rectangle", json!({"parent": parent, "x": x, "y": y, "width": w, "height": h})))
|
||||
}
|
||||
|
||||
/// A layer's box on the page: `[x0, y0, x1, y1]`, rounded.
|
||||
fn page_box(s: &Session, n: NodeId) -> [f64; 4] {
|
||||
let b = s.doc().unwrap().world_bounds(n).unwrap();
|
||||
[b.x0, b.y0, b.x1, b.y1].map(|v| (v * 1000.0).round() / 1000.0)
|
||||
}
|
||||
|
||||
fn boxes(s: &Session, ns: &[NodeId]) -> Vec<[f64; 4]> {
|
||||
ns.iter().map(|n| page_box(s, *n)).collect()
|
||||
}
|
||||
|
||||
fn kids(s: &Session, n: NodeId) -> Vec<NodeId> {
|
||||
s.doc().unwrap().node(n).unwrap().children.clone()
|
||||
}
|
||||
|
||||
fn mode(s: &Session, n: NodeId) -> Option<LayoutMode> {
|
||||
s.doc().unwrap().node(n).unwrap().layout.as_ref().map(|l| l.mode)
|
||||
}
|
||||
|
||||
/// A frame made by Suggest auto layout: no fill, no clipping, hugging what is in it.
|
||||
fn assert_band(s: &Session, n: NodeId, m: LayoutMode) {
|
||||
let node = s.doc().unwrap().node(n).unwrap();
|
||||
assert!(matches!(node.kind, NodeKind::Frame), "a band is a frame");
|
||||
assert!(node.fills.is_empty() && !node.clip, "a band has no fill and does not clip");
|
||||
assert_eq!(mode(s, n), Some(m));
|
||||
assert_eq!((node.child_layout.sizing_h, node.child_layout.sizing_v), (Sizing::Hug, Sizing::Hug));
|
||||
}
|
||||
|
||||
fn warnings(r: &Value) -> Vec<String> {
|
||||
r["warnings"].as_array().map(|a| a.iter().filter_map(|w| w.as_str().map(String::from)).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The issue's design: four 50 x 50 squares in a 200 x 200 frame, two rows of two.
|
||||
fn squares() -> (Session, NodeId, [NodeId; 4]) {
|
||||
let mut s = Session::new();
|
||||
let f = frame(&mut s, 100.0, 50.0, 200.0, 200.0);
|
||||
let sq = [(0.0, 0.0), (60.0, 0.0), (0.0, 60.0), (60.0, 60.0)].map(|(x, y)| rect(&mut s, f, x, y, 50.0, 50.0));
|
||||
(s, f, sq)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_rows_of_two_squares_become_a_vertical_frame_of_two_horizontal_rows() {
|
||||
let (mut s, f, sq) = squares();
|
||||
let before_frame = page_box(&s, f);
|
||||
let before = boxes(&s, &sq);
|
||||
let result = ex(&mut s, "layout.suggest", json!({"ids": [f]}));
|
||||
assert_eq!(result["ids"], json!([f]));
|
||||
assert!(warnings(&result).is_empty(), "{result}");
|
||||
assert_eq!(mode(&s, f), Some(LayoutMode::Vertical));
|
||||
let rows = kids(&s, f);
|
||||
assert_eq!(rows.len(), 2, "two rows");
|
||||
for (row, pair) in rows.iter().zip([[sq[0], sq[1]], [sq[2], sq[3]]]) {
|
||||
assert_band(&s, *row, LayoutMode::Horizontal);
|
||||
assert_eq!(kids(&s, *row), pair);
|
||||
}
|
||||
let node = s.doc().unwrap().node(f).unwrap();
|
||||
assert_eq!(node.child_layout.sizing_h, Sizing::Fixed, "the frame keeps its size");
|
||||
assert_eq!(node.child_layout.sizing_v, Sizing::Fixed);
|
||||
assert_eq!(page_box(&s, f), before_frame);
|
||||
assert_eq!(boxes(&s, &sq), before, "every square stays where it was");
|
||||
assert_eq!(s.selection(), vec![f]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suggesting_auto_layout_is_one_undo_step() {
|
||||
let (mut s, f, sq) = squares();
|
||||
let rows_before = kids(&s, f);
|
||||
let steps = s.ds().unwrap().history.undo.len();
|
||||
ex(&mut s, "layout.suggest", json!({"ids": [f]}));
|
||||
assert_eq!(s.ds().unwrap().history.undo.len(), steps + 1);
|
||||
let rows = kids(&s, f);
|
||||
s.undo().unwrap();
|
||||
assert_eq!(kids(&s, f), rows_before);
|
||||
assert_eq!(mode(&s, f), None);
|
||||
assert!(rows.iter().all(|r| s.doc().unwrap().node(*r).is_none()), "the band frames are gone");
|
||||
assert_eq!(
|
||||
boxes(&s, &sq),
|
||||
[[100.0, 50.0, 150.0, 100.0], [160.0, 50.0, 210.0, 100.0], [100.0, 110.0, 150.0, 160.0], [160.0, 110.0, 210.0, 160.0]]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_squares_in_a_row_get_one_horizontal_layout_without_nesting() {
|
||||
let mut s = Session::new();
|
||||
let f = frame(&mut s, 20.0, 30.0, 200.0, 100.0);
|
||||
let sq = [0.0, 70.0, 140.0].map(|x| rect(&mut s, f, x, 25.0, 50.0, 50.0));
|
||||
let before = boxes(&s, &sq);
|
||||
let result = ex(&mut s, "layout.suggest", json!({"ids": [f]}));
|
||||
assert!(warnings(&result).is_empty(), "{result}");
|
||||
assert_eq!(mode(&s, f), Some(LayoutMode::Horizontal));
|
||||
assert_eq!(kids(&s, f), sq, "the squares are the frame's own layers");
|
||||
assert_eq!(boxes(&s, &sq), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_squares_in_a_column_get_one_vertical_layout_without_nesting() {
|
||||
let mut s = Session::new();
|
||||
let f = frame(&mut s, 20.0, 30.0, 100.0, 200.0);
|
||||
let sq = [0.0, 70.0, 140.0].map(|y| rect(&mut s, f, 25.0, y, 50.0, 50.0));
|
||||
let before = boxes(&s, &sq);
|
||||
let result = ex(&mut s, "layout.suggest", json!({"ids": [f]}));
|
||||
assert!(warnings(&result).is_empty(), "{result}");
|
||||
assert_eq!(mode(&s, f), Some(LayoutMode::Vertical));
|
||||
assert_eq!(kids(&s, f), sq);
|
||||
assert_eq!(boxes(&s, &sq), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_above_two_columns_of_squares_gives_a_row_per_line() {
|
||||
let mut s = Session::new();
|
||||
let f = frame(&mut s, 0.0, 0.0, 200.0, 200.0);
|
||||
let header = rect(&mut s, f, 0.0, 0.0, 200.0, 50.0);
|
||||
let sq = [(0.0, 60.0), (0.0, 120.0), (110.0, 60.0), (110.0, 120.0)].map(|(x, y)| rect(&mut s, f, x, y, 50.0, 50.0));
|
||||
let all = [vec![header], sq.to_vec()].concat();
|
||||
let before = boxes(&s, &all);
|
||||
let result = ex(&mut s, "layout.suggest", json!({"ids": [f]}));
|
||||
assert!(warnings(&result).is_empty(), "{result}");
|
||||
// The squares line up in two rows, so the gaps between rows win over the gap between columns.
|
||||
assert_eq!(mode(&s, f), Some(LayoutMode::Vertical));
|
||||
let top = kids(&s, f);
|
||||
assert_eq!(top.len(), 3);
|
||||
assert_eq!(top.first(), Some(&header));
|
||||
assert_band(&s, top[1], LayoutMode::Horizontal);
|
||||
assert_eq!(kids(&s, top[1]), vec![sq[0], sq[2]]);
|
||||
assert_band(&s, top[2], LayoutMode::Horizontal);
|
||||
assert_eq!(kids(&s, top[2]), vec![sq[1], sq[3]]);
|
||||
assert_eq!(boxes(&s, &all), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_above_a_tall_layer_beside_a_column_nests_three_levels() {
|
||||
let mut s = Session::new();
|
||||
let f = frame(&mut s, 40.0, 10.0, 200.0, 200.0);
|
||||
let header = rect(&mut s, f, 0.0, 0.0, 200.0, 40.0);
|
||||
let tall = rect(&mut s, f, 0.0, 60.0, 50.0, 110.0);
|
||||
let sq = [60.0, 120.0].map(|y| rect(&mut s, f, 110.0, y, 50.0, 50.0));
|
||||
let all = [header, tall, sq[0], sq[1]];
|
||||
let before = boxes(&s, &all);
|
||||
let result = ex(&mut s, "layout.suggest", json!({"ids": [f]}));
|
||||
assert!(warnings(&result).is_empty(), "{result}");
|
||||
assert_eq!(mode(&s, f), Some(LayoutMode::Vertical));
|
||||
let top = kids(&s, f);
|
||||
assert_eq!(top.len(), 2);
|
||||
assert_eq!(top.first(), Some(&header));
|
||||
let band = top[1];
|
||||
assert_band(&s, band, LayoutMode::Horizontal);
|
||||
let cols = kids(&s, band);
|
||||
assert_eq!(cols.len(), 2);
|
||||
assert_eq!(cols.first(), Some(&tall));
|
||||
assert_band(&s, cols[1], LayoutMode::Vertical);
|
||||
assert_eq!(kids(&s, cols[1]), sq);
|
||||
assert_eq!(boxes(&s, &all), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unequal_gaps_use_the_smallest_and_say_so() {
|
||||
let mut s = Session::new();
|
||||
let f = frame(&mut s, 0.0, 0.0, 300.0, 100.0);
|
||||
let sq = [0.0, 60.0, 130.0].map(|x| rect(&mut s, f, x, 10.0, 50.0, 50.0));
|
||||
let result = ex(&mut s, "layout.suggest", json!({"ids": [f]}));
|
||||
assert_eq!(mode(&s, f), Some(LayoutMode::Horizontal));
|
||||
let w = warnings(&result);
|
||||
assert_eq!(w.len(), 1, "{result}");
|
||||
assert!(w[0].contains("gaps"), "{}", w[0]);
|
||||
let b = boxes(&s, &sq);
|
||||
assert_eq!(b[0], [0.0, 10.0, 50.0, 60.0]);
|
||||
assert_eq!(b[1], [60.0, 10.0, 110.0, 60.0]);
|
||||
assert_eq!(b[2], [120.0, 10.0, 170.0, 60.0], "the last square moves along the row only");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_layers_leave_the_frame_without_auto_layout_and_say_so() {
|
||||
let mut s = Session::new();
|
||||
let f = frame(&mut s, 0.0, 0.0, 200.0, 200.0);
|
||||
let a = rect(&mut s, f, 0.0, 0.0, 100.0, 100.0);
|
||||
let b = rect(&mut s, f, 50.0, 50.0, 100.0, 100.0);
|
||||
let result = ex(&mut s, "layout.suggest", json!({"ids": [f]}));
|
||||
assert_eq!(mode(&s, f), None);
|
||||
assert_eq!(kids(&s, f), vec![a, b]);
|
||||
assert_eq!(warnings(&result).len(), 1, "{result}");
|
||||
assert_eq!(boxes(&s, &[a, b]), vec![[0.0, 0.0, 100.0, 100.0], [50.0, 50.0, 150.0, 150.0]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_becomes_a_frame_in_place_and_follows_the_rules() {
|
||||
let mut s = Session::new();
|
||||
let page = s.page().unwrap();
|
||||
let (a, b, c, d) = (
|
||||
rect(&mut s, page, 10.0, 20.0, 40.0, 40.0),
|
||||
rect(&mut s, page, 70.0, 20.0, 40.0, 40.0),
|
||||
rect(&mut s, page, 10.0, 80.0, 40.0, 40.0),
|
||||
rect(&mut s, page, 70.0, 80.0, 40.0, 40.0),
|
||||
);
|
||||
let group = id(&ex(&mut s, "object.group", json!({"ids": [a, b, c, d]})));
|
||||
let before = boxes(&s, &[group, a, b, c, d]);
|
||||
let result = ex(&mut s, "layout.suggest", json!({"ids": [group]}));
|
||||
assert_eq!(result["ids"], json!([group]), "the group keeps its identity");
|
||||
assert!(matches!(s.doc().unwrap().node(group).unwrap().kind, NodeKind::Frame));
|
||||
assert_eq!(mode(&s, group), Some(LayoutMode::Vertical));
|
||||
let rows = kids(&s, group);
|
||||
assert_eq!(rows.len(), 2);
|
||||
assert_band(&s, rows[0], LayoutMode::Horizontal);
|
||||
assert_eq!(kids(&s, rows[0]), vec![a, b]);
|
||||
assert_eq!(kids(&s, rows[1]), vec![c, d]);
|
||||
assert_eq!(boxes(&s, &[group, a, b, c, d]), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_layers_are_wrapped_in_a_frame_that_is_then_split() {
|
||||
let mut s = Session::new();
|
||||
let page = s.page().unwrap();
|
||||
let sq = [(0.0, 0.0), (80.0, 0.0), (0.0, 80.0), (80.0, 80.0)].map(|(x, y)| rect(&mut s, page, x, y, 50.0, 50.0));
|
||||
let before = boxes(&s, &sq);
|
||||
let result = ex(&mut s, "layout.suggest", json!({"ids": sq}));
|
||||
let wrapper = id_of(&result["ids"][0]).unwrap();
|
||||
assert!(s.doc().unwrap().node(wrapper).unwrap().fills.is_empty());
|
||||
assert_eq!(mode(&s, wrapper), Some(LayoutMode::Vertical));
|
||||
assert_eq!(kids(&s, wrapper).len(), 2);
|
||||
assert_eq!(boxes(&s, &sq), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_direction_forces_the_top_level_and_nested_frames_follow_the_gaps() {
|
||||
let (mut s, f, sq) = squares();
|
||||
let before = boxes(&s, &sq);
|
||||
let result = ex(&mut s, "layout.suggest", json!({"ids": [f], "direction": "horizontal"}));
|
||||
assert!(warnings(&result).is_empty(), "{result}");
|
||||
assert_eq!(mode(&s, f), Some(LayoutMode::Horizontal));
|
||||
let cols = kids(&s, f);
|
||||
assert_eq!(cols.len(), 2, "two columns");
|
||||
assert_band(&s, cols[0], LayoutMode::Vertical);
|
||||
assert_eq!(kids(&s, cols[0]), vec![sq[0], sq[2]]);
|
||||
assert_band(&s, cols[1], LayoutMode::Vertical);
|
||||
assert_eq!(kids(&s, cols[1]), vec![sq[1], sq[3]]);
|
||||
assert_eq!(boxes(&s, &sq), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_frame_with_one_layer_is_laid_out_like_add_auto_layout() {
|
||||
let mut s = Session::new();
|
||||
let f = frame(&mut s, 0.0, 0.0, 200.0, 100.0);
|
||||
let a = rect(&mut s, f, 20.0, 20.0, 60.0, 40.0);
|
||||
let result = ex(&mut s, "layout.suggest", json!({"ids": [f]}));
|
||||
assert!(warnings(&result).is_empty(), "{result}");
|
||||
assert_eq!(mode(&s, f), Some(LayoutMode::Horizontal));
|
||||
assert_eq!(kids(&s, f), vec![a]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_auto_layout_still_makes_a_single_row() {
|
||||
let (mut s, f, sq) = squares();
|
||||
ex(&mut s, "layout.add", json!({"ids": [f]}));
|
||||
let mut got = kids(&s, f);
|
||||
got.sort();
|
||||
assert_eq!(got, sq.to_vec(), "no nested frames");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_centred_title_above_a_card_is_lined_up_at_the_card_edge_with_a_warning() {
|
||||
let mut s = Session::new();
|
||||
let f = frame(&mut s, 0.0, 0.0, 200.0, 200.0);
|
||||
let title = rect(&mut s, f, 60.0, 0.0, 80.0, 30.0);
|
||||
let card = rect(&mut s, f, 0.0, 40.0, 200.0, 100.0);
|
||||
let result = ex(&mut s, "layout.suggest", json!({"ids": [f]}));
|
||||
assert_eq!(mode(&s, f), Some(LayoutMode::Vertical));
|
||||
assert_eq!(kids(&s, f), vec![title, card]);
|
||||
let w = warnings(&result);
|
||||
assert_eq!(w.len(), 1, "{result}");
|
||||
assert!(w[0].contains("different offsets"), "{}", w[0]);
|
||||
assert_eq!(page_box(&s, title), [0.0, 0.0, 80.0, 30.0], "the title's left edge is the card's now");
|
||||
assert_eq!(page_box(&s, card), [0.0, 40.0, 200.0, 140.0], "the rest stays");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instances_and_layers_inside_them_are_refused_and_a_main_component_works() {
|
||||
let mut s = Session::new();
|
||||
let f = frame(&mut s, 0.0, 0.0, 200.0, 200.0);
|
||||
rect(&mut s, f, 0.0, 0.0, 50.0, 50.0);
|
||||
rect(&mut s, f, 0.0, 60.0, 50.0, 30.0);
|
||||
let nested = id(&ex(&mut s, "frame.create", json!({"parent": f, "x": 0, "y": 100, "width": 100, "height": 50})));
|
||||
rect(&mut s, nested, 0.0, 0.0, 20.0, 20.0);
|
||||
rect(&mut s, nested, 40.0, 0.0, 20.0, 20.0);
|
||||
let comp = id(&ex(&mut s, "component.create", json!({"ids": [f]})));
|
||||
let inst = id(&ex(&mut s, "instance.create", json!({"component": comp, "x": 400, "y": 0})));
|
||||
let inside: Vec<NodeId> = kids(&s, inst).into_iter().filter(|k| matches!(s.doc().unwrap().node(*k).unwrap().kind, NodeKind::Frame)).collect();
|
||||
assert!(!inside.is_empty(), "the instance has a frame of its own");
|
||||
let page = s.page().unwrap();
|
||||
let snapshot = |s: &Session| (kids(s, page), kids(s, inst), kids(s, inside[0]));
|
||||
let before = snapshot(&s);
|
||||
let steps = s.ds().unwrap().history.undo.len();
|
||||
for target in [inst, inside[0]] {
|
||||
let e = s.execute("layout.suggest", &json!({"ids": [target]})).unwrap_err().to_string();
|
||||
assert!(e.contains("instance"), "{e}");
|
||||
}
|
||||
assert_eq!(snapshot(&s), before, "nothing changed");
|
||||
assert_eq!(s.ds().unwrap().history.undo.len(), steps, "no history step");
|
||||
assert!(s.doc().unwrap().node(inst).unwrap().layout.is_none());
|
||||
// The main component is a frame and works.
|
||||
let result = ex(&mut s, "layout.suggest", json!({"ids": [comp]}));
|
||||
assert_eq!(result["ids"], json!([comp]));
|
||||
}
|
||||
@@ -393,6 +393,8 @@ mod jpg_export_tests;
|
||||
#[cfg(test)]
|
||||
mod keymap_tests;
|
||||
#[cfg(test)]
|
||||
mod layout_suggest_tests;
|
||||
#[cfg(test)]
|
||||
mod library_beacon_tests;
|
||||
#[cfg(test)]
|
||||
mod library_path_tests;
|
||||
@@ -589,6 +591,8 @@ mod text_style_picker_tests;
|
||||
#[cfg(test)]
|
||||
mod text_tail_tests;
|
||||
#[cfg(test)]
|
||||
mod text_weight_step_tests;
|
||||
#[cfg(test)]
|
||||
mod textfit_tests;
|
||||
#[cfg(test)]
|
||||
mod theme_pages_tests;
|
||||
|
||||
@@ -17,7 +17,9 @@ pub(crate) struct Script {
|
||||
pub(crate) events: Vec<Event>,
|
||||
pub(crate) sent: Vec<Presence>,
|
||||
pub(crate) hosted: Vec<HostOptions>,
|
||||
joined: Vec<String>,
|
||||
pub(crate) joined: Vec<String>,
|
||||
/// The sessions told to reconnect now, in order.
|
||||
pub(crate) retried: Vec<u64>,
|
||||
pub(crate) left: usize,
|
||||
pub(crate) msgs: Vec<ClientMsg>,
|
||||
pub(crate) published: Vec<PublishOptions>,
|
||||
@@ -46,6 +48,10 @@ impl LiveLink for Mock {
|
||||
i.url = format!("ws://{}/?file=f&token=t", i.address);
|
||||
Ok(i)
|
||||
}
|
||||
fn retry(&mut self, session: u64) {
|
||||
self.0.lock().unwrap().retried.push(session);
|
||||
}
|
||||
|
||||
fn join(&mut self, session: u64, link: &str, _: &str) -> Result<(), String> {
|
||||
if !link.starts_with("figcraft://") {
|
||||
return Err("not an invite".into());
|
||||
@@ -231,7 +237,7 @@ fn events_build_who_is_here() {
|
||||
assert_eq!(s.live_summary()["attempt"], 1);
|
||||
push(&script, vec![Event::Status(Status::Failed { reason: "Lost the connection".into() })]);
|
||||
s.live_poll();
|
||||
assert!(s.live().info.is_none());
|
||||
assert!(s.live().peers.is_empty() && !s.live().syncing());
|
||||
assert_eq!(s.live_summary()["reason"], "Lost the connection");
|
||||
assert_eq!(s.message.as_deref(), Some("Lost the connection"));
|
||||
assert!(!s.live_poll(), "nothing new");
|
||||
|
||||
@@ -592,4 +592,7 @@ fn same_server_ignores_the_default_port_before_a_path() {
|
||||
assert!(same_server("wss://share.example:443/figcraft/", "wss://share.example/figcraft/"));
|
||||
assert!(same_server("ws://host:80/x", "ws://host/x"));
|
||||
assert!(!same_server("wss://share.example:8443/figcraft/", "wss://share.example/figcraft/"));
|
||||
// The path is a route: owner tokens for /Team/ must never be sent to /team/.
|
||||
assert!(same_server("WSS://Share.Example/team/", "wss://share.example/team"));
|
||||
assert!(!same_server("wss://share.example/Team/", "wss://share.example/team/"));
|
||||
}
|
||||
|
||||
@@ -253,6 +253,31 @@ fn publishing_sends_a_checked_folder() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn publishing_refuses_a_linked_asset_instead_of_bundling_what_it_points_at() {
|
||||
let (mut s, d) = session();
|
||||
let dir = temp("publish-link");
|
||||
std::fs::create_dir_all(dir.join("build")).unwrap();
|
||||
std::fs::create_dir_all(dir.join("assets")).unwrap();
|
||||
std::fs::write(dir.join("build").join("tiny.wasm"), wasm()).unwrap();
|
||||
std::fs::write(dir.join("figcraft-plugin.json"), json!({"id": ID, "name": "Tiny", "version": "1.0.0", "main": "build/tiny.wasm"}).to_string())
|
||||
.unwrap();
|
||||
// A private file outside the plugin folder, reached through a link in its assets.
|
||||
let secret = temp("publish-link-secret").join("token.txt");
|
||||
std::fs::write(&secret, b"per-user-secret").unwrap();
|
||||
std::os::unix::fs::symlink(&secret, dir.join("assets").join("notes.txt")).unwrap();
|
||||
let e = s.execute("plugin.directory.publish", &json!({"path": dir.to_string_lossy(), "server": "ws://h:1/"})).unwrap_err().to_string();
|
||||
assert!(e.contains("link"), "{e}");
|
||||
assert!(d.lock().unwrap().plugins.is_empty(), "nothing was sent");
|
||||
// The whole assets folder as a link is refused the same way.
|
||||
std::fs::remove_file(dir.join("assets").join("notes.txt")).unwrap();
|
||||
std::fs::remove_dir(dir.join("assets")).unwrap();
|
||||
std::os::unix::fs::symlink(secret.parent().unwrap(), dir.join("assets")).unwrap();
|
||||
let e = s.execute("plugin.directory.publish", &json!({"path": dir.to_string_lossy(), "server": "ws://h:1/"})).unwrap_err().to_string();
|
||||
assert!(e.contains("link"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bundle_asking_for_more_than_the_directory_showed_is_not_installed() {
|
||||
let (mut s, d) = session();
|
||||
|
||||
@@ -5,14 +5,14 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use figcraft_color::{Paint, PaintKind};
|
||||
use figcraft_doc::{Document, NodeId, NodeKind, StyleKind, VariableType, VariableValue};
|
||||
use figcraft_doc::{Document, NodeId, NodeKind, Style, StyleKind, VariableId, VariableType, VariableValue};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::cmd::lists::{BoundList, list_binding, rebind_edited_paint};
|
||||
use crate::cmd::styles::{rebind_paint_alpha, unbind_slot};
|
||||
use crate::params::{get, paint_of, parse, req_string, targets};
|
||||
use crate::{CommandSpec, Result, Session, bad, spec};
|
||||
use crate::params::{get, paint_of, parse, req_string, string, targets};
|
||||
use crate::{CommandSpec, EngineError, Result, Session, bad, spec};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
@@ -127,10 +127,17 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
spec!(
|
||||
"selection.applyColorStyle",
|
||||
"Apply selection color style",
|
||||
"{targets, style}; applies the color style to matching fill/stroke lists (text ranges keep typography)",
|
||||
"{targets, style (id or name), library? (an enabled library: id, name or path; the style is then one it publishes, copied in linked and read-only)}; applies the color style to matching fill/stroke lists (text ranges keep typography)",
|
||||
true,
|
||||
apply_style
|
||||
),
|
||||
spec!(
|
||||
"selection.createColorStyle",
|
||||
"Create selection color style",
|
||||
"{targets, name, description?} → {id}; makes a color style of the paint the targets share and applies it to them as selection.applyColorStyle does, keeping the variables bound to the paint; a name another style has, a target whose list holds other paints, or targets bound to different variables are refused",
|
||||
true,
|
||||
create_style
|
||||
),
|
||||
spec!(
|
||||
"selection.bindColorVariable",
|
||||
"Apply selection color variable",
|
||||
@@ -205,15 +212,96 @@ fn apply_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "selection.applyColorStyle";
|
||||
let targets = checked_targets(s, p, CMD)?;
|
||||
let name = req_string(CMD, p, "style")?;
|
||||
let name = if get(p, "library").is_some() { import_library_style(s, CMD, p, &name)? } else { name };
|
||||
let style = s.doc()?.style(&name).cloned().ok_or_else(|| bad(CMD, "no such color style"))?;
|
||||
if !matches!(style.kind, StyleKind::Paint { .. }) {
|
||||
return Err(bad(CMD, "a color style is required"));
|
||||
}
|
||||
for target in &targets {
|
||||
link_style(s, &targets, &style)?;
|
||||
Ok(json!({"ok": true}))
|
||||
}
|
||||
|
||||
/// Copy the color style `key` (id, else name) that the enabled library `library` publishes into the
|
||||
/// document, linked and read-only, and return the copy's id.
|
||||
fn import_library_style(s: &mut Session, cmd: &str, p: &Value, key: &str) -> Result<String> {
|
||||
let (link, lib) = crate::cmd::library::library(s, cmd, p)?;
|
||||
let published = |st: &&Style| lib.manifest.style(&st.id).is_some_and(|x| x.published);
|
||||
let styles = || lib.doc.styles.iter().filter(published);
|
||||
let style = styles()
|
||||
.find(|st| st.id == key)
|
||||
.or_else(|| styles().find(|st| st.name == key))
|
||||
.ok_or_else(|| bad(cmd, format!("\"{}\" publishes no style `{key}`", link.name)))?;
|
||||
if !matches!(style.kind, StyleKind::Paint { .. }) {
|
||||
return Err(bad(cmd, "a color style is required"));
|
||||
}
|
||||
let keys = BTreeSet::from([style.id.clone()]);
|
||||
crate::library::import_styles(s.doc_mut()?, &lib, &keys, false)
|
||||
.into_values()
|
||||
.next()
|
||||
.ok_or_else(|| EngineError::Other("the style didn't import".into()))
|
||||
}
|
||||
|
||||
fn create_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "selection.createColorStyle";
|
||||
let targets = checked_targets(s, p, CMD)?;
|
||||
let doc = s.doc()?;
|
||||
let paint = targets.first().and_then(|t| t.paint(doc)).ok_or_else(|| bad(CMD, "a selection color target no longer exists"))?;
|
||||
if !matches!(paint.kind, PaintKind::Solid { .. } | PaintKind::Gradient(_)) {
|
||||
return Err(bad(CMD, "a solid or gradient paint is required"));
|
||||
}
|
||||
if targets.iter().any(|t| t.paint(doc).as_ref() != Some(&paint)) {
|
||||
return Err(bad(CMD, "the targets no longer share one paint"));
|
||||
}
|
||||
if let Some(why) = create_refusal(doc, &targets) {
|
||||
return Err(bad(CMD, why));
|
||||
}
|
||||
let name = crate::cmd::variables::clean_name(&req_string(CMD, p, "name")?).ok_or_else(|| bad(CMD, "name can't be empty"))?;
|
||||
if doc.styles.iter().any(|st| st.name == name) {
|
||||
return Err(bad(CMD, format!("a style named `{name}` already exists")));
|
||||
}
|
||||
let kind = StyleKind::Paint { paints: vec![paint] };
|
||||
let bound = targets.first().map(|t| target_bindings(doc, t, &kind)).unwrap_or_default();
|
||||
let doc = s.doc_mut()?;
|
||||
let id = doc.new_style_id();
|
||||
let style = Style { id: id.clone(), name, description: string(p, "description").unwrap_or_default(), kind, bound };
|
||||
doc.styles.push(style.clone());
|
||||
link_style(s, &targets, &style)?;
|
||||
Ok(json!({"id": id}))
|
||||
}
|
||||
|
||||
/// Why a color style can't be made from `targets` (`selection.createColorStyle`), if it can't: a
|
||||
/// linked style replaces the whole fill or stroke list, so a target whose list holds other paints
|
||||
/// would lose them. The new style takes over the variables bound to the paint, so targets bound to
|
||||
/// different variables are refused too. The Selection colors menu leaves Create style out for such rows.
|
||||
pub fn create_refusal(doc: &Document, targets: &[PaintTarget]) -> Option<&'static str> {
|
||||
if targets.iter().any(|t| t.paints(doc).is_none_or(|paints| paints.len() != 1)) {
|
||||
return Some("a style can only be made from a fill or stroke list that holds this one paint");
|
||||
}
|
||||
let paint = targets.first().and_then(|t| t.paint(doc))?;
|
||||
let kind = StyleKind::Paint { paints: vec![paint] };
|
||||
let mut bindings = targets.iter().map(|t| target_bindings(doc, t, &kind));
|
||||
let first = bindings.next()?;
|
||||
bindings.any(|b| b != first).then_some("the targets are bound to different variables")
|
||||
}
|
||||
|
||||
/// The variable bindings a paint style of `kind` made from `target` takes over: those on the fill or
|
||||
/// stroke list the target stands for. A text range with fills of its own holds none.
|
||||
fn target_bindings(doc: &Document, target: &PaintTarget, kind: &StyleKind) -> BTreeMap<String, VariableId> {
|
||||
if list_field(doc, target).is_none() {
|
||||
return BTreeMap::new();
|
||||
}
|
||||
let field = if target.fills { "fillStyle" } else { "strokeStyle" };
|
||||
doc.node(target.id).map(|n| crate::style_vars::from_layer(n, field, kind)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Apply paint style `style` to every target: a fill or stroke list is linked to it; a text range
|
||||
/// takes its resolved paints and keeps its typography.
|
||||
fn link_style(s: &mut Session, targets: &[PaintTarget], style: &Style) -> Result<()> {
|
||||
for target in targets {
|
||||
if let Some((start, end)) = target.range {
|
||||
// Text ranges have typography-style links, not paint-style links. Copy resolved paint
|
||||
// values just as an explicit range fill does; never replace its font or size.
|
||||
let StyleKind::Paint { paints } = crate::style_vars::kind_for(s.doc()?, &style, target.id).into_owned() else { continue };
|
||||
let StyleKind::Paint { paints } = crate::style_vars::kind_for(s.doc()?, style, target.id).into_owned() else { continue };
|
||||
let n = s.doc_mut()?.get_mut(target.id)?;
|
||||
if let NodeKind::Text(t) = &mut n.kind {
|
||||
t.restyle(start, end, |st| st.fills = Some(paints.clone()));
|
||||
@@ -222,7 +310,7 @@ fn apply_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
crate::cmd::styles::apply_style_ref(s.doc_mut()?, target.id, if target.fills { "fillStyle" } else { "strokeStyle" }, Some(&style.id))?;
|
||||
}
|
||||
}
|
||||
Ok(json!({"ok": true}))
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The binding key (`fills/<i>/color` or `strokes/<i>/color`) of the slot a target stands for, when the
|
||||
|
||||
@@ -140,6 +140,18 @@ pub struct Live {
|
||||
/// The branches of the session's file made or last updated from main in this session: every
|
||||
/// layer of their base was in it (see [`crate::branches`]).
|
||||
branch_bases: BTreeSet<String>,
|
||||
/// You were in this session and aren't now: what joining it again takes (`collab.reconnect`).
|
||||
stranded: Option<Stranded>,
|
||||
}
|
||||
|
||||
/// What's kept of a session you joined once it can't go on by itself. The tab stays yours to work
|
||||
/// in, and says so.
|
||||
#[derive(Clone)]
|
||||
struct Stranded {
|
||||
/// The invite link you joined with (it holds the token: never shown).
|
||||
link: String,
|
||||
/// The server's state when it stopped: what's different from it in the tab is your own work.
|
||||
confirmed: Box<figcraft_collab::Replica>,
|
||||
}
|
||||
|
||||
impl Live {
|
||||
@@ -170,6 +182,41 @@ impl Live {
|
||||
*self = Live { id: self.id, tab: self.tab, ..Live::default() };
|
||||
}
|
||||
|
||||
/// Keep this session on its tab for joining again (see [`Stranded`]): a session you joined, or
|
||||
/// one that already is; any other goes back to no session.
|
||||
fn strand(&mut self) {
|
||||
let joined = self.info.as_ref().filter(|i| i.role == Role::Guest && !i.link.is_empty());
|
||||
let held = self.stranded.take().or_else(|| {
|
||||
let (client, info) = (self.client.as_ref()?, joined?);
|
||||
Some(Stranded { link: info.link.clone(), confirmed: Box::new(client.confirmed().clone()) })
|
||||
});
|
||||
if held.is_none() {
|
||||
return self.reset();
|
||||
}
|
||||
*self = Live {
|
||||
id: self.id,
|
||||
tab: self.tab,
|
||||
doc_uid: self.doc_uid,
|
||||
info: self.info.take(),
|
||||
server: std::mem::take(&mut self.server),
|
||||
published: self.published.take(),
|
||||
share: self.share.take(),
|
||||
stranded: held,
|
||||
..Live::default()
|
||||
};
|
||||
}
|
||||
|
||||
/// You were in this session and aren't now: the connection dropped and it is trying again, or
|
||||
/// it can't go on by itself. What you do in its tab isn't reaching anyone.
|
||||
pub fn disconnected(&self) -> bool {
|
||||
matches!(self.status, Status::Reconnecting { .. }) || self.stranded.is_some()
|
||||
}
|
||||
|
||||
/// The session can be joined again in its tab (`collab.reconnect`).
|
||||
pub fn rejoinable(&self) -> bool {
|
||||
self.stranded.is_some() && !self.status.active()
|
||||
}
|
||||
|
||||
/// The document sync client (once the welcome arrived): peers, pending batches, the user's
|
||||
/// undo history.
|
||||
pub fn client(&self) -> Option<&Client> {
|
||||
|
||||
@@ -214,8 +214,15 @@ impl Session {
|
||||
// order.
|
||||
Event::Sync(msg) => live.deferred.push(msg),
|
||||
Event::Ended { reason } => {
|
||||
self.message = Some(if behind.is_empty() { reason } else { format!("{}: {reason}", behind.trim_start()) });
|
||||
self.live.end(id);
|
||||
let joined = live.syncing() && live.role() == Some(Role::Guest);
|
||||
let text = if behind.is_empty() { reason.clone() } else { format!("{}: {reason}", behind.trim_start()) };
|
||||
if joined {
|
||||
// The tab says so and stays yours: it doesn't pass for a file of your own.
|
||||
self.live_fail(id, reason);
|
||||
} else {
|
||||
self.live.end(id);
|
||||
}
|
||||
self.message = Some(text);
|
||||
}
|
||||
Event::Published(p) => {
|
||||
// Shared with a code: the popover shows it, nothing more to say.
|
||||
@@ -389,6 +396,7 @@ impl Session {
|
||||
}
|
||||
(Some(Role::Guest), Some(uid)) => {
|
||||
// Joining again in this tab, or the file you published arriving from the server.
|
||||
self.live_keep_offline_work(id, uid);
|
||||
let doc = Arc::new(client.document().clone());
|
||||
let was_dirty = self.docs.iter().find(|d| d.uid == uid).is_some_and(DocState::is_dirty);
|
||||
self.apply_remote(uid, doc.clone());
|
||||
@@ -435,15 +443,53 @@ impl Session {
|
||||
live.synced = synced;
|
||||
live.client = Some(client);
|
||||
live.deferred.clear();
|
||||
live.stranded = None;
|
||||
}
|
||||
|
||||
/// Session `id` is over with a message: it couldn't be joined, the connection was lost for
|
||||
/// good or sync broke. Its tab shows why.
|
||||
/// Session `id` is back on document `uid` after it couldn't go on, and the server's version is
|
||||
/// about to replace the tab's: what you did since opens beside it, unsaved, so nothing is lost.
|
||||
fn live_keep_offline_work(&mut self, id: SessionId, uid: u64) {
|
||||
let Some(held) = self.live.sessions.get(&id).and_then(|l| l.stranded.as_ref()) else { return };
|
||||
let Some(local) = self.docs.iter().find(|d| d.uid == uid).map(|d| d.doc.clone()) else { return };
|
||||
let name = local.name.clone();
|
||||
// A document that can't be compared is kept too.
|
||||
if figcraft_collab::diff(&held.confirmed, &local).is_ok_and(|d| d.changes.is_empty()) {
|
||||
self.message = Some(format!("Reconnected to {name}"));
|
||||
return;
|
||||
}
|
||||
let mut copy = DocState::new((*local).clone(), None);
|
||||
let copy_name = format!("{name} (offline copy)");
|
||||
Arc::make_mut(&mut copy.doc).name.clone_from(©_name);
|
||||
self.docs.push(copy);
|
||||
self.message = Some(format!("Reconnected to {name}. What you changed while disconnected is open beside it as “{copy_name}”"));
|
||||
}
|
||||
|
||||
/// Join session `id` again in its tab (see [`Live::strand`]), as someone new: a fresh join needs
|
||||
/// nothing from the connection that was lost.
|
||||
pub(super) fn live_rejoin(&mut self, cmd: &str, id: SessionId) -> Result<()> {
|
||||
let name = display_name(&self.prefs);
|
||||
let Some(link) = self.live.sessions.get(&id).and_then(|l| l.stranded.as_ref()).map(|s| s.link.clone()) else {
|
||||
return Err(crate::bad(cmd, "this file has no live session to join again"));
|
||||
};
|
||||
self.live.leave(id);
|
||||
if let Some(why) = crate::file_access::network_refused() {
|
||||
return Err(EngineError::Disabled(cmd.to_string(), why));
|
||||
}
|
||||
let Some(net) = self.live.link() else { return Err(super::unavailable(cmd)) };
|
||||
net.join_resuming(id, &link, &name, None).map_err(|e| crate::bad(cmd, e))?;
|
||||
if let Some(live) = self.live.sessions.get_mut(&id) {
|
||||
live.status = Status::Connecting;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Session `id` is over with a message: it couldn't be joined, it was refused or ended for
|
||||
/// good, or sync broke. Its tab shows why, and a session you were in can be joined again there.
|
||||
pub(super) fn live_fail(&mut self, id: SessionId, reason: String) {
|
||||
log::warn!("live session: {reason}");
|
||||
self.live.leave(id);
|
||||
if let Some(live) = self.live.sessions.get_mut(&id) {
|
||||
live.reset();
|
||||
live.strand();
|
||||
live.status = Status::Failed { reason: reason.clone() };
|
||||
}
|
||||
self.message = Some(reason);
|
||||
@@ -456,7 +502,7 @@ impl Session {
|
||||
let live = self.live.doc(uid)?;
|
||||
match &live.client {
|
||||
Some(c) => limited_by(c.access()),
|
||||
None if live.status.active() && live.role() != Some(Role::Host) => Some(PUBLISHING),
|
||||
None if live.status.active() && live.role() != Some(Role::Host) && !live.disconnected() => Some(PUBLISHING),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,12 +42,38 @@ fn leave(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => s.live.shown(s.tab()),
|
||||
};
|
||||
let ended = id.and_then(|id| s.live.end(id));
|
||||
if ended.as_ref().is_some_and(|l| l.syncing() && l.role() == Some(Role::Guest)) {
|
||||
s.message = Some("You left the session; your copy stays open here".into());
|
||||
if let Some(l) = ended.as_ref().filter(|l| l.syncing() && l.role() == Some(Role::Guest)) {
|
||||
// What was still on its way may be held back for what's before it (an undo waits for its edit).
|
||||
s.message = Some(if l.client().is_some_and(|c| c.pending() > 0) {
|
||||
"You left before your last changes were confirmed: others may not see them all, and your copy stays open here".into()
|
||||
} else {
|
||||
"You left the session; your copy stays open here".into()
|
||||
});
|
||||
}
|
||||
Ok(json!({"ended": ended.is_some_and(|l| l.status.active())}))
|
||||
}
|
||||
|
||||
/// Back into the open file's session now: a reconnect that is waiting tries at once, and a session
|
||||
/// that couldn't go on is joined again in its tab.
|
||||
fn reconnect(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
const CMD: &str = "collab.reconnect";
|
||||
let live = s.live();
|
||||
let (id, reconnecting, rejoinable) = (live.id, matches!(live.status, Status::Reconnecting { .. }), live.rejoinable());
|
||||
if reconnecting {
|
||||
if let Some(why) = crate::file_access::network_refused() {
|
||||
return Err(EngineError::Disabled(CMD.to_string(), why));
|
||||
}
|
||||
if let Some(net) = s.live.link() {
|
||||
net.retry(id);
|
||||
}
|
||||
} else if rejoinable {
|
||||
s.live_rejoin(CMD, id)?;
|
||||
} else {
|
||||
return Err(bad(CMD, "this file has no lost live session to reconnect"));
|
||||
}
|
||||
Ok(json!({"status": s.live().status.id()}))
|
||||
}
|
||||
|
||||
fn stop(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A file shared online stays its owner's on the server: stopping takes the others' links (and
|
||||
// their codes) away, which disconnects whoever joined with them, and the owner stays in the
|
||||
@@ -193,10 +219,17 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
false,
|
||||
join
|
||||
),
|
||||
spec!(
|
||||
"collab.reconnect",
|
||||
"Reconnect live session",
|
||||
"{} → {status}: for the open file's session when it is disconnected: a reconnect that is waiting tries now, and a session that couldn't go on (`failed`, the file open in its tab) is joined again there, what you changed since opening beside it. Refused when nothing was lost",
|
||||
false,
|
||||
reconnect
|
||||
),
|
||||
spec!(
|
||||
"collab.leave",
|
||||
"Leave live session",
|
||||
"{session? (a session's id from `collab.peers`'s `sessions`, e.g. a join still on its way; default: the open file's session)} → {ended}: the synced file stays open as a local copy",
|
||||
"{session? (a session's id from `collab.peers`'s `sessions`, e.g. a join still on its way; default: the open file's session)} → {ended}: the synced file stays open as a local copy (also how a tab stops showing a session that couldn't go on)",
|
||||
false,
|
||||
leave
|
||||
),
|
||||
|
||||
@@ -118,7 +118,14 @@ impl Session {
|
||||
for m in std::mem::take(&mut live.deferred) {
|
||||
match client.receive(m, &EngineRecompute) {
|
||||
Ok(more) => out.extend(more),
|
||||
Err(e) => return self.live_fail(id, format!("The live session got out of step ({e}); join again")),
|
||||
Err(e) => {
|
||||
self.live_fail(id, format!("The live session got out of step ({e})"));
|
||||
// A fresh join has nothing to get out of step with.
|
||||
if let Err(e) = self.live_rejoin("collab.reconnect", id) {
|
||||
log::warn!("live session: couldn't join again: {e}");
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
let doc = Arc::new(client.document().clone());
|
||||
|
||||
@@ -523,6 +523,8 @@ pub trait LiveLink: Send {
|
||||
/// End session `session` (stop hosting or leave); the others go on. Nothing for a session
|
||||
/// that is over already.
|
||||
fn leave(&mut self, session: SessionId);
|
||||
/// Session `session` is waiting to reconnect: try now.
|
||||
fn retry(&mut self, _session: SessionId) {}
|
||||
/// Your latest presence in `session` (the link throttles and coalesces).
|
||||
fn presence(&mut self, session: SessionId, p: &Presence);
|
||||
/// A message for `session`'s server (document changes), sent in order.
|
||||
|
||||
@@ -117,14 +117,17 @@ pub(crate) fn plain_server(server: &str) -> String {
|
||||
/// Two addresses name the same server (case, a closing slash and the scheme's own port aside).
|
||||
pub fn same_server(a: &str, b: &str) -> bool {
|
||||
let norm = |s: &str| {
|
||||
let s = plain_server(s).to_ascii_lowercase();
|
||||
let s = plain_server(s);
|
||||
let s = s.trim_end_matches('/');
|
||||
let port = if s.starts_with("wss://") { ":443" } else { ":80" };
|
||||
let start = s.find("://").map_or(0, |i| i + 3);
|
||||
let end = s[start..].find('/').map_or(s.len(), |i| start + i);
|
||||
match s[start..end].strip_suffix(port) {
|
||||
Some(host) => format!("{}{}{}", &s[..start], host, &s[end..]),
|
||||
None => s.to_string(),
|
||||
// The scheme and host compare without case; the path routes (a proxy may send
|
||||
// `/Team/` and `/team/` to different servers), so it keeps its case.
|
||||
let head = s[..end].to_ascii_lowercase();
|
||||
let port = if head.starts_with("wss://") { ":443" } else { ":80" };
|
||||
match head[start..].strip_suffix(port) {
|
||||
Some(host) => format!("{}{}{}", &head[..start], host, &s[end..]),
|
||||
None => format!("{head}{}", &s[end..]),
|
||||
}
|
||||
};
|
||||
norm(a) == norm(b)
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
//! Increase and decrease font weight step through the styles the family has, by weight with the
|
||||
//! same slant and width (#1831), not by 100 to a canonical name no face provides.
|
||||
|
||||
use figcraft_doc::{NodeId, TextStyle};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::Session;
|
||||
use crate::cmd::text::{name_weight, next_style};
|
||||
|
||||
/// A family's styles listed by the weights their names say, as for faces not read yet.
|
||||
fn styles(names: &[&str]) -> Vec<(String, u16)> {
|
||||
names.iter().map(|s| ((*s).to_string(), name_weight(s))).collect()
|
||||
}
|
||||
|
||||
/// A family's styles with the faces' own weights.
|
||||
fn weighed(faces: &[(&str, u16)]) -> Vec<(String, u16)> {
|
||||
faces.iter().map(|(s, w)| ((*s).to_string(), *w)).collect()
|
||||
}
|
||||
|
||||
fn at(style: &str) -> TextStyle {
|
||||
let mut st = TextStyle::default();
|
||||
st.set_font_style(style);
|
||||
st
|
||||
}
|
||||
|
||||
/// Walk `from` heavier (`up`) or lighter until the family has nothing further.
|
||||
fn walk(family: &[(String, u16)], from: &str, up: bool) -> Vec<String> {
|
||||
let mut st = at(from);
|
||||
let mut out = Vec::new();
|
||||
while let Some(next) = next_style(family, &st, up) {
|
||||
st.set_font_style(next.clone());
|
||||
out.push(next);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_steps_follow_the_family_with_the_same_slant_and_width() {
|
||||
let arial = styles(&["Narrow", "Regular", "Italic", "Narrow Italic", "Bold", "Narrow Bold", "Bold Italic", "Narrow Bold Italic", "Black"]);
|
||||
assert_eq!(walk(&arial, "Regular", true), ["Bold", "Black"]);
|
||||
assert_eq!(walk(&arial, "Black", false), ["Bold", "Regular"]);
|
||||
assert_eq!(walk(&arial, "Italic", true), ["Bold Italic"]);
|
||||
assert_eq!(walk(&arial, "Narrow", true), ["Narrow Bold"]);
|
||||
assert_eq!(walk(&arial, "Narrow Bold Italic", false), ["Narrow Italic"]);
|
||||
let segoe = styles(&["Light", "Semilight", "Regular", "Italic", "Semibold", "Bold", "Black", "Bold Italic"]);
|
||||
assert_eq!(walk(&segoe, "Regular", true), ["Semibold", "Bold", "Black"]);
|
||||
assert_eq!(walk(&segoe, "Regular", false), ["Semilight", "Light"]);
|
||||
// A style the family doesn't have (as the old steps stored) moves to the next real one.
|
||||
assert_eq!(next_style(&segoe, &at("Medium"), true).as_deref(), Some("Semibold"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extra_and_semi_before_a_width_keep_the_width() {
|
||||
let family = styles(&["Extra Condensed Regular", "Condensed Regular", "Condensed Bold", "Extra Condensed Bold", "Semi Condensed Extra Bold"]);
|
||||
assert_eq!(walk(&family, "Extra Condensed Regular", true), ["Extra Condensed Bold"]);
|
||||
assert_eq!(walk(&family, "Condensed Bold", false), ["Condensed Regular"]);
|
||||
assert_eq!(walk(&family, "Semi Condensed Extra Bold", false), Vec::<String>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oblique_names_step_to_oblique_faces() {
|
||||
let dejavu = styles(&["Book", "Oblique", "Bold", "Bold Oblique"]);
|
||||
assert_eq!(walk(&dejavu, "Oblique", true), ["Bold Oblique"]);
|
||||
assert_eq!(walk(&dejavu, "Bold Oblique", false), ["Oblique"]);
|
||||
assert_eq!(walk(&dejavu, "Book", true), ["Bold"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hairline_and_w_numbers_are_weights() {
|
||||
let family = styles(&["Hairline", "Thin", "Regular", "Bold"]);
|
||||
assert_eq!(walk(&family, "Regular", false), ["Thin", "Hairline"]);
|
||||
// Off the list (a stored style the family lacks): by weight, the nearer of two equal ones.
|
||||
assert_eq!(next_style(&family, &at("Extra Light"), false).as_deref(), Some("Thin"));
|
||||
assert_eq!(next_style(&family, &at("Extra Light"), true).as_deref(), Some("Regular"));
|
||||
let hiragino = styles(&["W3", "W6"]);
|
||||
assert_eq!(walk(&hiragino, "W3", true), ["W6"]);
|
||||
assert_eq!(next_style(&hiragino, &at("Bold"), false).as_deref(), Some("W6"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn number_weights_count_after_a_width_but_other_numbers_dont() {
|
||||
// An off-list "Condensed 600" is 600, as "600" alone is: between Condensed 500 and 700.
|
||||
let condensed = weighed(&[("Condensed 300", 300), ("Condensed 500", 500), ("Condensed 700", 700)]);
|
||||
assert_eq!(next_style(&condensed, &at("Condensed 600"), true).as_deref(), Some("Condensed 700"));
|
||||
assert_eq!(next_style(&condensed, &at("Condensed 600"), false).as_deref(), Some("Condensed 500"));
|
||||
assert_eq!((name_weight("Condensed 600"), name_weight("600 Italic"), name_weight("Condensed 1000")), (600, 600, 1000));
|
||||
// A number that isn't a weight (a width grade, an optical size) is part of the width.
|
||||
assert_eq!((name_weight("Condensed 2"), name_weight("Caption 12 Bold"), name_weight("Condensed +600")), (400, 700, 400));
|
||||
let optical = styles(&["Caption 12 Regular", "Caption 24 Regular", "Caption 12 Bold", "Caption 24 Bold"]);
|
||||
assert_eq!(walk(&optical, "Caption 12 Regular", true), ["Caption 12 Bold"]);
|
||||
assert_eq!(walk(&optical, "Caption 24 Bold", false), ["Caption 24 Regular"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn univers_numbers_step_by_weight_within_their_width() {
|
||||
// Helvetica Neue LT, Univers, Frutiger: the first digit grades the weight, the second the width.
|
||||
let hn = weighed(&[
|
||||
("45 Light", 300),
|
||||
("46 Light Italic", 300),
|
||||
("55 Roman", 400),
|
||||
("56 Italic", 400),
|
||||
("57 Condensed", 400),
|
||||
("65 Medium", 500),
|
||||
("67 Medium Condensed", 500),
|
||||
("75 Bold", 700),
|
||||
("76 Bold Italic", 700),
|
||||
("77 Bold Condensed", 700),
|
||||
]);
|
||||
assert_eq!(walk(&hn, "55 Roman", true), ["65 Medium", "75 Bold"]);
|
||||
assert_eq!(walk(&hn, "65 Medium", false), ["55 Roman", "45 Light"]);
|
||||
assert_eq!(walk(&hn, "57 Condensed", true), ["67 Medium Condensed", "77 Bold Condensed"]);
|
||||
assert_eq!(walk(&hn, "67 Medium Condensed", false), ["57 Condensed"]);
|
||||
assert_eq!(walk(&hn, "46 Light Italic", true), ["56 Italic", "76 Bold Italic"]);
|
||||
// Faces not read yet: the words after the number give the weight.
|
||||
let univers = styles(&["45 Light", "55 Roman", "65 Bold", "75 Black", "57 Condensed", "67 Bold Condensed"]);
|
||||
assert_eq!(walk(&univers, "45 Light", true), ["55 Roman", "65 Bold", "75 Black"]);
|
||||
assert_eq!(walk(&univers, "67 Bold Condensed", false), ["57 Condensed"]);
|
||||
assert_eq!((name_weight("45 Light"), name_weight("75 Black"), name_weight("57 Condensed")), (300, 900, 400));
|
||||
// Other leading numbers stay part of the width: before another word, or not a width digit.
|
||||
let other = styles(&["12 Regular", "12 Bold", "55 Rounded", "55 Rounded Bold", "Regular", "Bold"]);
|
||||
assert_eq!(walk(&other, "12 Regular", true), ["12 Bold"]);
|
||||
assert_eq!(walk(&other, "55 Rounded", true), ["55 Rounded Bold"]);
|
||||
assert_eq!(walk(&other, "Regular", true), ["Bold"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_custom_weight_axis_value_steps_from_where_it_is() {
|
||||
let family = styles(&["Light", "Regular", "Medium", "Bold"]);
|
||||
let mut st = at("Regular");
|
||||
st.variations.insert("wght".into(), 550.0);
|
||||
assert_eq!(next_style(&family, &st, true).as_deref(), Some("Bold"));
|
||||
assert_eq!(next_style(&family, &st, false).as_deref(), Some("Medium"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn off_the_list_the_faces_own_weights_decide() {
|
||||
// From 500 between 400 and 700 faces: the neighbours, under their own names (the axis value goes).
|
||||
let family = weighed(&[("Light", 300), ("Regular", 400), ("Bold", 700)]);
|
||||
let mut st = at("Regular");
|
||||
st.variations.insert("wght".into(), 500.0);
|
||||
assert_eq!(next_style(&family, &st, true).as_deref(), Some("Bold"));
|
||||
assert_eq!(next_style(&family, &st, false).as_deref(), Some("Regular"));
|
||||
st.set_font_style("Bold");
|
||||
assert_eq!((st.weight(), st.variations.get("wght")), (700, None));
|
||||
// Segoe UI Variable's Semilight is 350, not the 300 its name says: from a `wght` of 325 it is
|
||||
// the next heavier style, and from 375 the next lighter.
|
||||
let segoe = weighed(&[("Light", 300), ("Semilight", 350), ("Regular", 400), ("Semibold", 600), ("Bold", 700)]);
|
||||
st.variations.insert("wght".into(), 325.0);
|
||||
assert_eq!(next_style(&segoe, &st, true).as_deref(), Some("Semilight"));
|
||||
assert_eq!(next_style(&segoe, &st, false).as_deref(), Some("Light"));
|
||||
st.variations.insert("wght".into(), 375.0);
|
||||
assert_eq!(next_style(&segoe, &st, false).as_deref(), Some("Semilight"));
|
||||
assert_eq!(next_style(&segoe, &st, true).as_deref(), Some("Regular"));
|
||||
// A W-numbered name with a slant after it is still that weight ("W7 Italic" is 700).
|
||||
let hiragino = weighed(&[("W3 Italic", 300), ("W6 Italic", 600), ("W8 Italic", 800)]);
|
||||
assert_eq!(next_style(&hiragino, &at("W7 Italic"), false).as_deref(), Some("W6 Italic"));
|
||||
assert_eq!(next_style(&hiragino, &at("W7 Italic"), true).as_deref(), Some("W8 Italic"));
|
||||
// And after a width ("Condensed W7 Italic" is 700 too).
|
||||
let condensed = weighed(&[("Condensed W3 Italic", 300), ("Condensed W6 Italic", 600), ("Condensed W8 Italic", 800)]);
|
||||
assert_eq!(next_style(&condensed, &at("Condensed W7 Italic"), true).as_deref(), Some("Condensed W8 Italic"));
|
||||
assert_eq!(next_style(&condensed, &at("Condensed W7 Italic"), false).as_deref(), Some("Condensed W6 Italic"));
|
||||
}
|
||||
|
||||
fn font_style(s: &Session, t: NodeId) -> String {
|
||||
s.doc().unwrap().node(t).unwrap().kind.text().unwrap().spans()[0].2.font_style.clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_commands_land_on_styles_the_family_has() {
|
||||
figcraft_text::scan_system_fonts();
|
||||
// Any installed family with a Regular face and a style the step takes it to (CI machines differ).
|
||||
let pick = figcraft_text::family_names().into_iter().find_map(|f| {
|
||||
let st = figcraft_text::family_style_weights(&f);
|
||||
let up = next_style(&st, &at("Regular"), true).filter(|_| st.iter().any(|(x, _)| x == "Regular"))?;
|
||||
Some((f, st, up))
|
||||
});
|
||||
let Some((family, styles, heavier)) = pick else { return };
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("node.create", &json!({"type": "text", "text": "Hi", "props": {"fontFamily": family, "fontStyle": "Regular"}})).unwrap();
|
||||
let t = crate::params::id_of(&r["id"]).unwrap();
|
||||
s.execute("text.weightUp", &json!({"ids": [t]})).unwrap();
|
||||
let up = font_style(&s, t);
|
||||
assert_eq!(up, heavier, "{family}: {styles:?}");
|
||||
s.execute("text.weightDown", &json!({"ids": [t]})).unwrap();
|
||||
assert_eq!(font_style(&s, t), "Regular", "{family}: {styles:?}");
|
||||
// A family that isn't installed still steps by 100 under the canonical names.
|
||||
s.execute("node.set", &json!({"ids": [t], "props": {"fontFamily": "No Such Family 7f3a", "fontStyle": "Regular"}})).unwrap();
|
||||
s.execute("text.weightUp", &json!({"ids": [t]})).unwrap();
|
||||
assert_eq!(font_style(&s, t), "Medium");
|
||||
}
|
||||
@@ -2,7 +2,7 @@ use figcraft_color::Paint;
|
||||
use figcraft_doc::NodeId;
|
||||
use figcraft_engine::{
|
||||
Session,
|
||||
selection_colors::{SelectionColor, collect},
|
||||
selection_colors::{self, SelectionColor, collect},
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -156,9 +156,14 @@ fn invalid_or_stale_targets_roll_back_atomically() {
|
||||
assert!(s.execute("selection.setPaint", &json!({"targets":red.targets,"paint":"#0000ff"})).is_err());
|
||||
assert_eq!(fill(&s, a), "FF0000");
|
||||
assert_eq!(s.undo_depth(), before);
|
||||
for command in
|
||||
["selection.setPaint", "selection.selectColor", "selection.applyColorStyle", "selection.bindColorVariable", "selection.detachColor"]
|
||||
{
|
||||
for command in [
|
||||
"selection.setPaint",
|
||||
"selection.selectColor",
|
||||
"selection.applyColorStyle",
|
||||
"selection.bindColorVariable",
|
||||
"selection.detachColor",
|
||||
"selection.createColorStyle",
|
||||
] {
|
||||
for params in [json!({}), json!({"targets":[]}), json!({"targets":[{"id":a,"fills":true,"index":0,"range":[0,1]}]})] {
|
||||
assert!(s.execute(command, ¶ms).is_err());
|
||||
}
|
||||
@@ -421,3 +426,269 @@ fn scopes_filter_the_menu_but_the_command_binds_anyway() {
|
||||
run(&mut s, "selection.bindColorVariable", json!({"targets":fill_slot,"variable":"Line"}));
|
||||
assert_eq!(fill(&s, a), "00FF00");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_style_created_from_a_row_links_its_fills_and_strokes_in_one_undo_step() {
|
||||
let mut s = Session::new();
|
||||
let a = rectangle(&mut s, "#ff0000");
|
||||
let b = rectangle(&mut s, "#0000ff");
|
||||
run(&mut s, "stroke.add", json!({"id":b,"color":"#ff0000"}));
|
||||
let red = group(&s, &[a, b], "FF0000");
|
||||
let before = s.undo_depth();
|
||||
let id = run(&mut s, "selection.createColorStyle", json!({"targets":red.targets,"name":"Brand/Red"}))["id"].clone();
|
||||
let doc = s.doc().unwrap();
|
||||
let style = doc.style(id.as_str().unwrap()).unwrap();
|
||||
assert_eq!(style.name, "Brand/Red");
|
||||
assert!(matches!(&style.kind, figcraft_doc::StyleKind::Paint { paints } if paints.len() == 1 && paints[0] == red.paint));
|
||||
assert_eq!(doc.node(a).unwrap().styles.fill.as_deref(), id.as_str());
|
||||
assert_eq!(doc.node(b).unwrap().styles.stroke.as_deref(), id.as_str());
|
||||
assert_eq!(doc.node(b).unwrap().styles.fill, None);
|
||||
assert_eq!(fill(&s, b), "0000FF");
|
||||
assert_eq!(s.undo_depth().0, before.0 + 1);
|
||||
run(&mut s, "style.update", json!({"style":id,"value":"#00ff00"}));
|
||||
assert_eq!(fill(&s, a), "00FF00");
|
||||
assert_eq!(s.doc().unwrap().node(b).unwrap().strokes[0].solid_color().unwrap().to_hex(), "00FF00");
|
||||
s.undo().unwrap();
|
||||
s.undo().unwrap();
|
||||
assert!(s.doc().unwrap().style("Brand/Red").is_none());
|
||||
assert_eq!(s.doc().unwrap().node(a).unwrap().styles.fill, None);
|
||||
assert_eq!(fill(&s, a), "FF0000");
|
||||
s.redo().unwrap();
|
||||
assert_eq!(s.doc().unwrap().node(a).unwrap().styles.fill.as_deref(), id.as_str());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_created_style_keeps_the_rows_gradient_opacity_and_blend_mode() {
|
||||
use figcraft_color::{BlendMode, Color, Gradient, GradientKind};
|
||||
let mut s = Session::new();
|
||||
let a = rectangle(&mut s, "#ff0000");
|
||||
let b = rectangle(&mut s, "#0000ff");
|
||||
let mut paint = Paint::gradient(Gradient::default_for(GradientKind::Radial, Color::BLACK));
|
||||
paint.opacity = 0.5;
|
||||
paint.blend = BlendMode::Multiply;
|
||||
for id in [a, b] {
|
||||
run(&mut s, "fill.set", json!({"id":id,"paint":paint}));
|
||||
}
|
||||
let row = collect(s.doc().unwrap(), &[a, b]).into_iter().find(|g| g.paint == paint).unwrap();
|
||||
assert_eq!(row.targets.len(), 2);
|
||||
let id = run(&mut s, "selection.createColorStyle", json!({"targets":row.targets,"name":"Shade"}))["id"].clone();
|
||||
let doc = s.doc().unwrap();
|
||||
assert!(matches!(&doc.style("Shade").unwrap().kind, figcraft_doc::StyleKind::Paint { paints } if paints == &vec![paint.clone()]));
|
||||
for n in [a, b] {
|
||||
assert_eq!(doc.node(n).unwrap().fills, vec![paint.clone()]);
|
||||
assert_eq!(doc.node(n).unwrap().styles.fill.as_deref(), id.as_str());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn creating_a_style_refuses_taken_or_empty_names_and_stale_rows_and_changes_nothing() {
|
||||
let mut s = Session::new();
|
||||
let a = rectangle(&mut s, "#ff0000");
|
||||
let b = rectangle(&mut s, "#ff0000");
|
||||
run(&mut s, "style.create", json!({"type":"paint","name":"Brand","value":"#00ff00"}));
|
||||
let red = group(&s, &[a, b], "FF0000");
|
||||
let before = s.undo_depth();
|
||||
let styles = s.doc().unwrap().styles.len();
|
||||
for name in ["Brand", " Brand ", "", " "] {
|
||||
assert!(s.execute("selection.createColorStyle", &json!({"targets":red.targets,"name":name})).is_err(), "{name:?}");
|
||||
}
|
||||
assert!(s.execute("selection.createColorStyle", &json!({"targets":red.targets})).is_err());
|
||||
// One slot of the row changed since it was listed: the row no longer stands for one paint.
|
||||
run(&mut s, "fill.set", json!({"id":b,"color":"#0000ff"}));
|
||||
let before_stale = s.undo_depth();
|
||||
assert!(s.execute("selection.createColorStyle", &json!({"targets":red.targets,"name":"Red"})).is_err());
|
||||
assert_eq!(s.undo_depth(), before_stale);
|
||||
assert_eq!(s.undo_depth().0, before.0 + 1);
|
||||
let doc = s.doc().unwrap();
|
||||
assert_eq!(doc.styles.len(), styles);
|
||||
assert_eq!(doc.node(a).unwrap().styles.fill, None);
|
||||
assert_eq!(fill(&s, a), "FF0000");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn creating_a_style_refuses_a_row_whose_list_holds_other_paints() {
|
||||
let mut s = Session::new();
|
||||
let a = rectangle(&mut s, "#ff0000");
|
||||
let b = rectangle(&mut s, "#ff0000");
|
||||
run(&mut s, "fill.add", json!({"id":a,"paint":"#0000ff"}));
|
||||
let red = group(&s, &[a, b], "FF0000");
|
||||
let before = s.undo_depth();
|
||||
let styles = s.doc().unwrap().styles.len();
|
||||
let err = s.execute("selection.createColorStyle", &json!({"targets":red.targets,"name":"Red"})).unwrap_err();
|
||||
assert!(err.to_string().contains("holds this one paint"), "{err}");
|
||||
assert!(selection_colors::create_refusal(s.doc().unwrap(), &red.targets).is_some());
|
||||
assert_eq!(s.undo_depth(), before);
|
||||
let doc = s.doc().unwrap();
|
||||
assert_eq!(doc.styles.len(), styles);
|
||||
assert_eq!(doc.node(a).unwrap().fills.len(), 2, "the layer keeps its other fill");
|
||||
assert!(doc.node(b).unwrap().styles.fill.is_none());
|
||||
// The single-paint layer alone still makes a style.
|
||||
let b_only: Vec<_> = red.targets.iter().filter(|t| t.id == b).cloned().collect();
|
||||
assert!(selection_colors::create_refusal(s.doc().unwrap(), &b_only).is_none());
|
||||
run(&mut s, "selection.createColorStyle", json!({"targets":b_only,"name":"Red"}));
|
||||
assert!(s.doc().unwrap().node(b).unwrap().styles.fill.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_style_created_from_a_variable_bound_row_keeps_following_the_variable() {
|
||||
let mut s = Session::new();
|
||||
let a = rectangle(&mut s, "#ff0000");
|
||||
let b = rectangle(&mut s, "#ff0000");
|
||||
let v = theme_variable(&mut s, "Brand", "#ff0000");
|
||||
for id in [a, b] {
|
||||
run(&mut s, "variable.bind", json!({"id":id,"field":"fill","variable":v}));
|
||||
}
|
||||
let red = group(&s, &[a, b], "FF0000");
|
||||
assert_eq!(red.targets.len(), 2);
|
||||
run(&mut s, "selection.createColorStyle", json!({"targets":red.targets,"name":"Brand"}));
|
||||
let style = s.doc().unwrap().style("Brand").unwrap();
|
||||
assert_eq!(style.bound.get("fills/0/color").map(String::as_str), v.as_str());
|
||||
run(&mut s, "variable.set", json!({"variable":v,"value":"#00ff00"}));
|
||||
assert_eq!(fill(&s, a), "00FF00");
|
||||
assert_eq!(fill(&s, b), "00FF00");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_style_created_from_a_gradient_keeps_its_stop_variables() {
|
||||
use figcraft_color::{Color, Gradient, GradientKind, PaintKind};
|
||||
let mut s = Session::new();
|
||||
let a = rectangle(&mut s, "#ff0000");
|
||||
let paint = Paint::gradient(Gradient::default_for(GradientKind::Linear, Color::BLACK));
|
||||
run(&mut s, "fill.set", json!({"id":a,"paint":paint}));
|
||||
let v = theme_variable(&mut s, "Brand", "#ff0000");
|
||||
run(&mut s, "variable.bind", json!({"id":a,"field":"fills/0/stops/0/color","variable":v}));
|
||||
let row = collect(s.doc().unwrap(), &[a]).into_iter().next().unwrap();
|
||||
run(&mut s, "selection.createColorStyle", json!({"targets":row.targets,"name":"Shade"}));
|
||||
assert!(s.doc().unwrap().style("Shade").unwrap().bound.contains_key("fills/0/stops/0/color"));
|
||||
run(&mut s, "variable.set", json!({"variable":v,"value":"#00ff00"}));
|
||||
let PaintKind::Gradient(g) = &s.doc().unwrap().node(a).unwrap().fills[0].kind else { panic!("not a gradient") };
|
||||
assert_eq!(g.stops[0].color.to_hex(), "00FF00");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn creating_a_style_refuses_targets_bound_to_different_variables() {
|
||||
let mut s = Session::new();
|
||||
let a = rectangle(&mut s, "#ff0000");
|
||||
let b = rectangle(&mut s, "#ff0000");
|
||||
let v = theme_variable(&mut s, "Brand", "#ff0000");
|
||||
run(&mut s, "variable.bind", json!({"id":a,"field":"fill","variable":v}));
|
||||
let targets: Vec<_> = collect(s.doc().unwrap(), &[a, b]).into_iter().flat_map(|g| g.targets).collect();
|
||||
assert_eq!(targets.len(), 2);
|
||||
assert!(selection_colors::create_refusal(s.doc().unwrap(), &targets).is_some());
|
||||
let before = s.undo_depth();
|
||||
let styles = s.doc().unwrap().styles.len();
|
||||
let err = s.execute("selection.createColorStyle", &json!({"targets":targets,"name":"Red"})).unwrap_err();
|
||||
assert!(err.to_string().contains("different variables"), "{err}");
|
||||
assert_eq!(s.undo_depth(), before);
|
||||
let doc = s.doc().unwrap();
|
||||
assert_eq!(doc.styles.len(), styles);
|
||||
assert!(!doc.node(a).unwrap().bound.is_empty());
|
||||
assert!(doc.node(b).unwrap().styles.fill.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_linked_row_switches_to_another_style() {
|
||||
let mut s = Session::new();
|
||||
let a = rectangle(&mut s, "#ff0000");
|
||||
let b = rectangle(&mut s, "#0000ff");
|
||||
run(&mut s, "style.create", json!({"type":"paint","name":"Brand","value":"#ff0000"}));
|
||||
let accent = run(&mut s, "style.create", json!({"type":"paint","name":"Accent","value":"#00ff00"}))["id"].clone();
|
||||
run(&mut s, "style.apply", json!({"id":a,"style":"Brand","target":"fill"}));
|
||||
let linked = collect(s.doc().unwrap(), &[a, b]).into_iter().find(|g| g.style.is_some()).unwrap();
|
||||
run(&mut s, "selection.applyColorStyle", json!({"targets":linked.targets,"style":"Accent"}));
|
||||
assert_eq!(s.doc().unwrap().node(a).unwrap().styles.fill.as_deref(), accent.as_str());
|
||||
assert_eq!(fill(&s, a), "00FF00");
|
||||
assert_eq!(fill(&s, b), "0000FF");
|
||||
}
|
||||
|
||||
struct Fixture(std::path::PathBuf);
|
||||
|
||||
impl Drop for Fixture {
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// A saved library file publishing the color style "Brand" (#0000ff) and the text style "Heading",
|
||||
/// with the color style "_Draft" left unpublished; the fixture, the file and the library's id.
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
fn color_library(tag: &str) -> (Fixture, std::path::PathBuf, Value) {
|
||||
let fixture = Fixture(std::env::temp_dir().join(format!("figcraft-selection-colors-{tag}-{}", std::process::id())));
|
||||
let _ = std::fs::remove_dir_all(&fixture.0);
|
||||
std::fs::create_dir(&fixture.0).unwrap();
|
||||
let path = fixture.0.join("library.figcraft");
|
||||
let mut publisher = Session::new();
|
||||
run(&mut publisher, "style.create", json!({"type":"paint","name":"Brand","value":"#0000ff"}));
|
||||
run(&mut publisher, "style.create", json!({"type":"paint","name":"_Draft","value":"#00ff00"}));
|
||||
let text = run(&mut publisher, "text.create", json!({"text":"Title"}))["id"].clone();
|
||||
run(&mut publisher, "style.create", json!({"type":"text","name":"Heading","from":text}));
|
||||
let published = run(&mut publisher, "library.publish", json!({}));
|
||||
assert_eq!(published["styles"], 2);
|
||||
run(&mut publisher, "file.saveAs", json!({"path":path}));
|
||||
(fixture, path, published["id"].clone())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_row_applies_a_published_library_style_as_a_linked_copy_in_one_undo_step() {
|
||||
let (_fixture, path, library) = color_library("apply");
|
||||
let mut s = Session::new();
|
||||
let a = rectangle(&mut s, "#ff0000");
|
||||
let b = rectangle(&mut s, "#00ff00");
|
||||
run(&mut s, "stroke.add", json!({"id":b,"color":"#ff0000"}));
|
||||
run(&mut s, "library.add", json!({"path":path}));
|
||||
let red = group(&s, &[a, b], "FF0000");
|
||||
let before = s.undo_depth();
|
||||
run(&mut s, "selection.applyColorStyle", json!({"targets":red.targets,"style":"Brand","library":library}));
|
||||
let doc = s.doc().unwrap();
|
||||
let copy = doc.node(a).unwrap().styles.fill.clone().unwrap();
|
||||
assert!(figcraft_engine::library::is_remote_style(doc, ©));
|
||||
assert_eq!(doc.node(b).unwrap().styles.stroke.as_deref(), Some(copy.as_str()));
|
||||
assert_eq!(fill(&s, a), "0000FF");
|
||||
assert_eq!(fill(&s, b), "00FF00");
|
||||
assert_eq!(s.undo_depth().0, before.0 + 1);
|
||||
s.undo().unwrap();
|
||||
let doc = s.doc().unwrap();
|
||||
assert!(doc.style(©).is_none());
|
||||
assert_eq!(doc.node(a).unwrap().styles.fill, None);
|
||||
assert_eq!(fill(&s, a), "FF0000");
|
||||
// Choosing it again reuses the one copy.
|
||||
s.redo().unwrap();
|
||||
let blue = group(&s, &[a, b], "0000FF");
|
||||
run(&mut s, "selection.applyColorStyle", json!({"targets":blue.targets,"style":"Brand","library":library}));
|
||||
assert_eq!(s.doc().unwrap().styles.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn library_styles_that_are_unpublished_not_colors_or_not_enabled_are_refused() {
|
||||
let (_fixture, path, library) = color_library("refuse");
|
||||
let mut s = Session::new();
|
||||
let a = rectangle(&mut s, "#ff0000");
|
||||
rectangle(&mut s, "#00ff00");
|
||||
let red = group(&s, &[a], "FF0000");
|
||||
assert!(s.execute("selection.applyColorStyle", &json!({"targets":red.targets,"style":"Brand","library":library})).is_err());
|
||||
run(&mut s, "library.add", json!({"path":path}));
|
||||
let before = s.undo_depth();
|
||||
for (style, lib) in [("_Draft", library.clone()), ("Heading", library.clone()), ("Missing", library.clone()), ("Brand", json!("Elsewhere"))] {
|
||||
assert!(s.execute("selection.applyColorStyle", &json!({"targets":red.targets,"style":style,"library":lib})).is_err(), "{style}");
|
||||
}
|
||||
assert_eq!(s.undo_depth(), before);
|
||||
assert!(s.doc().unwrap().styles.is_empty());
|
||||
assert_eq!(s.doc().unwrap().node(a).unwrap().styles.fill, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_library_that_is_not_a_string_is_refused_rather_than_linking_a_local_style() {
|
||||
let mut s = Session::new();
|
||||
let a = rectangle(&mut s, "#ff0000");
|
||||
run(&mut s, "style.create", json!({"type":"paint","name":"Brand","value":"#0000ff"}));
|
||||
let red = group(&s, &[a], "FF0000");
|
||||
let before = s.undo_depth();
|
||||
for lib in [json!({}), json!([]), json!({"id":"Brand"})] {
|
||||
let err = s.execute("selection.applyColorStyle", &json!({"targets":red.targets,"style":"Brand","library":lib})).unwrap_err();
|
||||
assert!(err.to_string().contains("`library` must be a string"), "{lib}: {err}");
|
||||
}
|
||||
assert_eq!(s.undo_depth(), before);
|
||||
assert_eq!(s.doc().unwrap().node(a).unwrap().styles.fill, None);
|
||||
assert_eq!(fill(&s, a), "FF0000");
|
||||
}
|
||||
|
||||
@@ -191,9 +191,13 @@ impl<'b> Reader<'b> {
|
||||
let mut shift = 0;
|
||||
loop {
|
||||
let b = self.byte()?;
|
||||
value |= u32::from(b & 127).checked_shl(shift).unwrap_or(0);
|
||||
let part = b & 127;
|
||||
if shift == 28 && (part > 0x0f || b & 128 != 0) {
|
||||
return err("u32 varint overflow");
|
||||
}
|
||||
value |= u32::from(part) << shift;
|
||||
shift += 7;
|
||||
if b & 128 == 0 || shift >= 35 {
|
||||
if b & 128 == 0 {
|
||||
return Ok(value);
|
||||
}
|
||||
}
|
||||
@@ -670,3 +674,17 @@ fn numbered(token: &str, default: u32) -> Result<(String, u32), KiwiError> {
|
||||
Some((name, n)) => Ok((name.to_string(), n.parse().map_err(|_| KiwiError(format!("schema text: bad number in `{token}`")))?)),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::Reader;
|
||||
|
||||
#[test]
|
||||
fn overflowing_u32_varint_is_rejected() {
|
||||
let mut boundary = Reader { data: &[0xff, 0xff, 0xff, 0xff, 0x0f], pos: 0 };
|
||||
assert_eq!(boundary.var_uint(), Ok(u32::MAX));
|
||||
|
||||
let mut overflowing = Reader { data: &[0xff, 0xff, 0xff, 0xff, 0x7f], pos: 0 };
|
||||
assert!(overflowing.var_uint().is_err(), "overflowing u32 varint was accepted");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ use super::layer::{cap_name, own_text, svg_path, valid_size};
|
||||
use super::paint::{paint, stroke};
|
||||
use super::{Affine, Kv, Mapper, NO_STYLE, Obj, Point, Value, View, generated_record, guid, json, matrix, network, num, rows};
|
||||
use figcraft_doc::geom::kurbo::{BezPath, PathEl, Rect, Shape};
|
||||
use figcraft_doc::{RouteEnd, Routing, Side, route_points};
|
||||
use figcraft_doc::{ConnectorPath, MAX_RUNS, RouteEnd, Routing, Side, attach_points, attached_sides, route_along};
|
||||
|
||||
/// How a connector imports: from its saved snapshot (`terminal`: as one vector, no room for its
|
||||
/// label), or drawn from its ends, as a frame with its line and `label` when it has one.
|
||||
@@ -48,7 +48,8 @@ impl<'a> Mapper<'a> {
|
||||
|
||||
/// A connector's end caps, and when it has no saved outline or network its line between its
|
||||
/// ends (free points, or a sibling layer): straight to the point given on the layer (its
|
||||
/// centre unless given), or elbowed or curved from a side of it, as a board connector runs.
|
||||
/// centre unless given), or elbowed or curved from a side of it, as a board connector runs;
|
||||
/// an elbow saved with its path (FigJam's control points) runs along it (#1910).
|
||||
/// Returns the middle of that line by length, in the connector's own coordinates.
|
||||
pub(super) fn connector(&mut self, o: &mut Obj, v: &View<'a>, space: Affine) -> Option<Point> {
|
||||
for (from, to) in [("connectorStartCap", "strokeCapStart"), ("connectorEndCap", "strokeCapEnd")] {
|
||||
@@ -77,8 +78,13 @@ impl<'a> Mapper<'a> {
|
||||
let (w, h) = n.get("size").map_or((0.0, 0.0), |s| (num(s, "x").unwrap_or(0.0), num(s, "y").unwrap_or(0.0)));
|
||||
let at = e.get("relativePosition").and_then(|r| Some((num(r, "x")?, num(r, "y")?)));
|
||||
let t = n.get("transform").and_then(matrix).unwrap_or_default();
|
||||
// An automatic magnet (`AUTO`: the side is picked when the connector is drawn;
|
||||
// `CENTER`: the end aims at the layer's middle) attaches to the side facing the
|
||||
// other end, as a board connector drawn here does; the file's `relativePosition`
|
||||
// is not where such an end sits (#1909).
|
||||
let automatic = matches!(e.get("magnet").and_then(Kv::str), Some("AUTO" | "CENTER"));
|
||||
match routing {
|
||||
Routing::Straight => {
|
||||
Routing::Straight if !automatic => {
|
||||
let (rx, ry) = at.unwrap_or((0.5, 0.5));
|
||||
RouteEnd::Point(t * Point::new(w * rx, h * ry))
|
||||
}
|
||||
@@ -94,11 +100,13 @@ impl<'a> Mapper<'a> {
|
||||
};
|
||||
ok.then_some(end)
|
||||
};
|
||||
let Some(pts) = end("connectorStart").zip(end("connectorEnd")).and_then(|(a, b)| route_points(a, b, routing)) else {
|
||||
let ends = end("connectorStart").zip(end("connectorEnd"));
|
||||
let path = ends.filter(|_| routing == Routing::Elbow).and_then(|(a, b)| saved_runs(v, a, b));
|
||||
let Some(pts) = ends.and_then(|(a, b)| route_along(a, b, routing, path.as_ref())) else {
|
||||
self.warn("connectors whose ends can't be placed are empty");
|
||||
return None;
|
||||
};
|
||||
if routing != Routing::Straight {
|
||||
if routing != Routing::Straight && path.is_none() {
|
||||
self.warn("elbowed and curved connectors without a saved path follow FigCraft's own routing");
|
||||
}
|
||||
// A curved route is one curve: its ends and the two control points between them.
|
||||
@@ -407,7 +415,51 @@ pub(super) fn connector_has_saved_label(v: &View<'_>) -> bool {
|
||||
.is_some_and(|s| !s.trim().is_empty())
|
||||
}
|
||||
|
||||
/// The side of its layer a connector end leaves from: the `magnet` the file names, else the edge
|
||||
/// The path a FigJam elbow connector was saved with: its `connectorControlPoints`, one per run
|
||||
/// between the first and the last, each a point on its run (in the connector's parent's
|
||||
/// coordinates, like its ends) with the run's axis; the first run leaves the start's side and the
|
||||
/// last arrives at the end's, so neither is saved. `None` without any, or when they don't make
|
||||
/// such a path: a point off both axes, two runs in a row the same way, a first or last run that
|
||||
/// would leave or arrive sideways to its side, or more runs than a hand could make here.
|
||||
fn saved_runs(v: &View<'_>, from: RouteEnd, to: RouteEnd) -> Option<ConnectorPath> {
|
||||
let saved = v.list("connectorControlPoints");
|
||||
if saved.is_empty() || saved.len() + 2 > MAX_RUNS {
|
||||
return None;
|
||||
}
|
||||
let (p0, p1) = attach_points(from, to);
|
||||
let mid = p0.midpoint(p1);
|
||||
let mut at = Vec::with_capacity(saved.len());
|
||||
let (mut first, mut last) = (None, None);
|
||||
for p in saved {
|
||||
let pos = p.get("position").and_then(|q| Some(Point::new(num(q, "x")?, num(q, "y")?)))?;
|
||||
let (ax, ay) = p.get("axis").and_then(|q| Some((num(q, "x")?, num(q, "y")?)))?;
|
||||
let sideways = match (ax != 0.0, ay != 0.0) {
|
||||
(true, false) => true,
|
||||
(false, true) => false,
|
||||
_ => return None,
|
||||
};
|
||||
if last == Some(sideways) {
|
||||
return None;
|
||||
}
|
||||
first.get_or_insert(!sideways);
|
||||
last = Some(sideways);
|
||||
at.push(if sideways { pos.y - mid.y } else { pos.x - mid.x });
|
||||
}
|
||||
// The run through each end goes the way its side faces, out of the object: the first leaves
|
||||
// the start's side for the first saved run, the last arrives at the end's from the last saved
|
||||
// run. One along the side, or back into the object, doesn't.
|
||||
let (across, last) = (first?, last?);
|
||||
let (&a0, &a1) = (at.first()?, at.last()?);
|
||||
// Where the run from `p` (`sideways`: going across) meets the saved run at `v`.
|
||||
let onto = |sideways: bool, p: Point, v: f64| if sideways { Point::new(mid.x + v, p.y) } else { Point::new(p.x, mid.y + v) };
|
||||
let out_of = |s: Option<Side>, p: Point, q: Point| s.is_none_or(|s| (q - p).dot(s.normal()) > 0.0);
|
||||
let (s0, s1) = attached_sides(from, to);
|
||||
let fits = out_of(s0, p0, onto(across, p0, a0)) && out_of(s1, p1, onto(!last, p1, a1));
|
||||
fits.then_some(ConnectorPath::Runs { across, at })
|
||||
}
|
||||
|
||||
/// The side of its layer a connector end leaves from: the `magnet` the file names (`AUTO` and
|
||||
/// `CENTER`: the side facing the other end, whatever `relativePosition` says; #1909), else the edge
|
||||
/// its point on the layer (`relativePosition`, 0–1) lies on, else the side facing the other end.
|
||||
fn side(e: &Kv<'_>, at: Option<(f64, f64)>) -> Side {
|
||||
match e.get("magnet").and_then(Kv::str) {
|
||||
@@ -415,6 +467,7 @@ fn side(e: &Kv<'_>, at: Option<(f64, f64)>) -> Side {
|
||||
Some("RIGHT") => Side::Right,
|
||||
Some("BOTTOM") => Side::Bottom,
|
||||
Some("LEFT") => Side::Left,
|
||||
Some("AUTO" | "CENTER") => Side::Auto,
|
||||
_ => match at {
|
||||
Some((x, _)) if x <= 0.0 => Side::Left,
|
||||
Some((x, _)) if x >= 1.0 => Side::Right,
|
||||
|
||||
@@ -666,6 +666,54 @@ fn connectors_without_a_saved_path_follow_their_line_style() {
|
||||
assert!(warnings.iter().any(|w| w.contains("FigCraft's own routing")), "{warnings:?}");
|
||||
}
|
||||
|
||||
/// #1909: a connector end whose magnet is `AUTO` (FigJam picks the side when it draws) or `CENTER`
|
||||
/// (the end aims at the layer's middle) leaves the side facing the other end, as a board connector
|
||||
/// drawn here does, whatever `relativePosition` the file kept for it; a named magnet still wins.
|
||||
#[test]
|
||||
fn connectors_with_an_automatic_side_leave_the_side_facing_the_target() {
|
||||
let mut message = tail_message();
|
||||
let Kv::Array(nodes) = field_mut(&mut message, "nodeChanges").unwrap() else { panic!() };
|
||||
let box_at = |id, name: &str, x| node(id, Some((1, "*")), "RECTANGLE", name, vec![("size", xy(100.0, 100.0)), ("transform", at(x, 600.0))]);
|
||||
// The ends keep a stale point on the left of A and the right of B, as the reporter's file did.
|
||||
let end = |node, magnet: &'static str, x| o(vec![("endpointNodeID", g(node)), ("magnet", e(magnet)), ("relativePosition", xy(x, 0.5))]);
|
||||
let joined = |id, name: &str, style: &'static str, start: &'static str, finish: &'static str| {
|
||||
node(
|
||||
id,
|
||||
Some((1, "+")),
|
||||
"CONNECTOR",
|
||||
name,
|
||||
vec![
|
||||
("strokePaints", arr(vec![solid(0.0, 0.0, 0.0)])),
|
||||
("connectorStart", end(60, start, 0.0)),
|
||||
("connectorEnd", end(61, finish, 1.0)),
|
||||
("connectorLineStyle", e(style)),
|
||||
],
|
||||
)
|
||||
};
|
||||
nodes.extend([
|
||||
box_at(60, "A", 0.0),
|
||||
box_at(61, "B", 300.0),
|
||||
joined(62, "Elbow", "ELBOWED", "AUTO", "AUTO"),
|
||||
joined(63, "Line", "STRAIGHT", "CENTER", "CENTER"),
|
||||
joined(64, "Curve", "CURVED", "AUTO", "AUTO"),
|
||||
joined(65, "Named", "ELBOWED", "BOTTOM", "AUTO"),
|
||||
]);
|
||||
let (doc, _) = import(&canvas(&schema(), &message), "Sides").unwrap();
|
||||
let ends = |name: &str| -> ((f64, f64), (f64, f64)) {
|
||||
let world = doc.world_transform(named(&doc, name).id);
|
||||
let pts: Vec<(f64, f64)> =
|
||||
network_of(&doc, name).vertices.iter().map(|v| world * figcraft_doc::geom::Point::new(v.x, v.y)).map(|p| (p.x, p.y)).collect();
|
||||
(pts[0], pts[pts.len() - 1])
|
||||
};
|
||||
// From A's right side (facing B) to B's left side (facing A), not from the stale left point; each
|
||||
// end starts `END_GAP` (4) outside its side.
|
||||
for name in ["Elbow", "Line", "Curve"] {
|
||||
assert_eq!(ends(name), ((104.0, 650.0), (296.0, 650.0)), "{name}");
|
||||
}
|
||||
// A named magnet keeps its side: the bottom of A; the automatic end still faces A.
|
||||
assert_eq!(ends("Named"), ((50.0, 704.0), (296.0, 650.0)));
|
||||
}
|
||||
|
||||
/// A connector with a label but no saved snapshot: a frame holding its line and its label,
|
||||
/// centred on the line's middle, in black when the connector gives no paint.
|
||||
#[test]
|
||||
@@ -863,3 +911,85 @@ fn write_fixture() {
|
||||
std::fs::write(out, zip_file(&tail_canvas())).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// An elbow connector saved with its path (#1910): FigJam's control points, one per run between
|
||||
/// the first and the last, each on its run with the run's axis, give the path the connector keeps;
|
||||
/// the first run leaves the start's side and the last arrives at the end's.
|
||||
#[test]
|
||||
fn an_elbow_connector_saved_with_its_path_keeps_it() {
|
||||
let mut message = tail_message();
|
||||
let Kv::Array(nodes) = field_mut(&mut message, "nodeChanges").unwrap() else { panic!() };
|
||||
let box_at = |id, name: &str, x, y| node(id, Some((1, "*")), "RECTANGLE", name, vec![("size", xy(100.0, 100.0)), ("transform", at(x, y))]);
|
||||
let point = |x, y, ax, ay| o(vec![("position", xy(x, y)), ("axis", xy(ax, ay))]);
|
||||
// From A's bottom, across at y 740, down at x 200, into B's left: four runs.
|
||||
let saved = node(
|
||||
66,
|
||||
Some((1, "+")),
|
||||
"CONNECTOR",
|
||||
"Saved",
|
||||
vec![
|
||||
("strokePaints", arr(vec![solid(0.0, 0.0, 0.0)])),
|
||||
("connectorStart", o(vec![("endpointNodeID", g(64)), ("relativePosition", xy(0.5, 1.0))])),
|
||||
("connectorEnd", o(vec![("endpointNodeID", g(65)), ("relativePosition", xy(0.0, 0.5))])),
|
||||
("connectorLineStyle", e("ELBOWED")),
|
||||
("connectorControlPoints", arr(vec![point(150.0, 740.0, 1.0, 0.0), point(200.0, 800.0, 0.0, 1.0)])),
|
||||
],
|
||||
);
|
||||
nodes.extend([box_at(64, "A", 0.0, 600.0), box_at(65, "B", 300.0, 800.0), saved]);
|
||||
let (doc, warnings) = import(&canvas(&schema(), &message), "Saved path").unwrap();
|
||||
let world = doc.world_transform(named(&doc, "Saved").id);
|
||||
let line: Vec<_> =
|
||||
network_of(&doc, "Saved").vertices.iter().map(|v| world * figcraft_doc::geom::Point::new(v.x, v.y)).map(|p| (p.x, p.y)).collect();
|
||||
// Each end starts `END_GAP` (4) outside its side's border.
|
||||
assert_eq!(line, [(50.0, 704.0), (50.0, 740.0), (200.0, 740.0), (200.0, 850.0), (296.0, 850.0)]);
|
||||
// The fixture's own Link, saved without a path, is routed here: the note counts it alone.
|
||||
let routed: Vec<_> = warnings.iter().filter(|w| w.contains("FigCraft's own routing")).collect();
|
||||
assert_eq!(routed.len(), 1, "{warnings:?}");
|
||||
assert!(!routed[0].contains('×'), "a connector with its path isn't counted among those routed here: {routed:?}");
|
||||
}
|
||||
|
||||
/// Saved control points that don't make a path from the connector's sides (#1910): a first run
|
||||
/// that would leave the bottom sideways, a point off both axes, or two runs in a row the same way
|
||||
/// leave the connector to FigCraft's routing, as one saved without a path is.
|
||||
#[test]
|
||||
fn an_elbow_whose_saved_path_doesnt_fit_its_sides_is_routed_here() {
|
||||
let mut message = tail_message();
|
||||
let Kv::Array(nodes) = field_mut(&mut message, "nodeChanges").unwrap() else { panic!() };
|
||||
let box_at = |id, name: &str, x, y| node(id, Some((1, "*")), "RECTANGLE", name, vec![("size", xy(100.0, 100.0)), ("transform", at(x, y))]);
|
||||
let point = |x, y, ax, ay| o(vec![("position", xy(x, y)), ("axis", xy(ax, ay))]);
|
||||
let elbow = |id, name: &str, points: Vec<Kv<'static>>| {
|
||||
let mut fields = vec![
|
||||
("strokePaints", arr(vec![solid(0.0, 0.0, 0.0)])),
|
||||
("connectorStart", o(vec![("endpointNodeID", g(64)), ("relativePosition", xy(0.5, 1.0))])),
|
||||
("connectorEnd", o(vec![("endpointNodeID", g(65)), ("relativePosition", xy(0.0, 0.5))])),
|
||||
("connectorLineStyle", e("ELBOWED")),
|
||||
];
|
||||
if !points.is_empty() {
|
||||
fields.push(("connectorControlPoints", arr(points)));
|
||||
}
|
||||
node(id, Some((1, "+")), "CONNECTOR", name, fields)
|
||||
};
|
||||
nodes.extend([
|
||||
box_at(64, "A", 0.0, 600.0),
|
||||
box_at(65, "B", 300.0, 800.0),
|
||||
elbow(66, "Plain", vec![]),
|
||||
elbow(67, "Sideways", vec![point(100.0, 650.0, 0.0, 1.0)]),
|
||||
elbow(68, "Askew", vec![point(150.0, 740.0, 1.0, 1.0)]),
|
||||
elbow(69, "Repeated", vec![point(150.0, 740.0, 1.0, 0.0), point(150.0, 760.0, 1.0, 0.0)]),
|
||||
// The first run would go up from A's bottom, through A; the last would arrive at B's left
|
||||
// from inside B. Each run is at right angles to its side, so only the way it goes is wrong.
|
||||
elbow(70, "Backwards", vec![point(100.0, 650.0, 1.0, 0.0), point(200.0, 740.0, 0.0, 1.0)]),
|
||||
elbow(71, "Inside", vec![point(150.0, 740.0, 1.0, 0.0), point(350.0, 800.0, 0.0, 1.0)]),
|
||||
]);
|
||||
let (doc, warnings) = import(&canvas(&schema(), &message), "Unfit paths").unwrap();
|
||||
let line = |name: &str| -> Vec<(f64, f64)> {
|
||||
let world = doc.world_transform(named(&doc, name).id);
|
||||
network_of(&doc, name).vertices.iter().map(|v| world * figcraft_doc::geom::Point::new(v.x, v.y)).map(|p| (p.x, p.y)).collect()
|
||||
};
|
||||
let plain = line("Plain");
|
||||
assert!(plain.len() >= 3, "routed in right angles: {plain:?}");
|
||||
for name in ["Sideways", "Askew", "Repeated", "Backwards", "Inside"] {
|
||||
assert_eq!(line(name), plain, "{name} is routed as one without a path");
|
||||
}
|
||||
assert!(warnings.iter().any(|w| w.contains("FigCraft's own routing")), "{warnings:?}");
|
||||
}
|
||||
|
||||
@@ -29,6 +29,7 @@ enum StrokeJoin MITER BEVEL ROUND
|
||||
enum VectorMirror NONE ANGLE ANGLE_AND_LENGTH
|
||||
enum ShapeWithTextType SQUARE ELLIPSE
|
||||
enum ConnectorLineStyle ELBOWED STRAIGHT CURVED
|
||||
enum ConnectorMagnet NONE AUTO TOP LEFT BOTTOM RIGHT CENTER
|
||||
enum ExpressionFunction ADDITION SUBTRACTION RESOLVE_VARIANT MULTIPLY DIVIDE EQUALS
|
||||
enum NavigationType NAVIGATE OVERLAY
|
||||
enum TransitionType INSTANT_TRANSITION DISSOLVE SMART_ANIMATE
|
||||
@@ -50,7 +51,8 @@ message VariableTarget VariableID id
|
||||
message VariableSetID GUID guid, AssetRef assetRef
|
||||
message ConditionalActions Action[] actions, VariableData condition
|
||||
message VectorData uint vectorNetworkBlob, Vector normalizedSize, NodeChange[] styleOverrideTable
|
||||
message ConnectorEndpoint GUID endpointNodeID, Vector position, Vector relativePosition
|
||||
message ConnectorEndpoint GUID endpointNodeID, Vector position, Vector relativePosition, ConnectorMagnet magnet
|
||||
message ConnectorControlPoint Vector position, Vector axis
|
||||
message VariableData AnyValue value, DataType dataType
|
||||
message Paint PaintType type, Color color, float opacity, bool visible, Image image, Matrix transform, ColorStop[] stops, VariableData colorVar, ImageScaleMode imageScaleMode
|
||||
message ParentIndex GUID guid, string position
|
||||
@@ -74,7 +76,7 @@ message Event InteractionType interactionType
|
||||
message Action GUID transitionNodeID, TransitionType transitionType, float transitionDuration, EasingType easingType, ConnectionType connectionType, NavigationType navigationType, VariableTarget targetVariable, VariableData targetVariableData, VariableSetID targetVariableSetID, GUID targetVariableModeID, ConditionalActions[] conditionalActions
|
||||
message Interaction Event event, Action[] actions
|
||||
message StartingPoint string name, string position
|
||||
message NodeChange GUID guid, ParentIndex parentIndex, NodeType type, string name, bool visible, float opacity, Vector size, Matrix transform, Paint[] fillPaints, Paint[] strokePaints, float strokeWeight, float cornerRadius, bool resizeToFit, bool internalOnly, float fontSize, FontName fontName, TextData textData, uint styleID, Path[] fillGeometry, Path[] strokeGeometry, StyleType styleType, StyleId styleIdForFill, SymbolData symbolData, PropDef[] componentPropDefs, PropAssignment[] componentPropAssignments, VariableDataMap parameterConsumptionMap, SetMode[] variableSetModes, VariableID variableSetID, ResolvedType variableResolvedType, Values variableDataValues, ModeMap variableModeBySetMap, Interaction[] prototypeInteractions, StartingPoint prototypeStartingPoint, GUIDPath guidPath, StackMode stackMode, float stackSpacing, float stackHorizontalPadding, float stackVerticalPadding, uint count, float starInnerScale, VectorData vectorData, StrokeCap strokeCap, StrokeJoin strokeJoin, VectorMirror handleMirroring, ShapeWithTextType shapeWithTextType, ConnectorEndpoint connectorStart, ConnectorEndpoint connectorEnd, StrokeCap connectorStartCap, StrokeCap connectorEndCap, ConnectorLineStyle connectorLineStyle, ConstraintType horizontalConstraint, ConstraintType verticalConstraint, NodeChange[] derivedSymbolData, string key, string version, LeadingTrim leadingTrim, float[] dashPattern
|
||||
message NodeChange GUID guid, ParentIndex parentIndex, NodeType type, string name, bool visible, float opacity, Vector size, Matrix transform, Paint[] fillPaints, Paint[] strokePaints, float strokeWeight, float cornerRadius, bool resizeToFit, bool internalOnly, float fontSize, FontName fontName, TextData textData, uint styleID, Path[] fillGeometry, Path[] strokeGeometry, StyleType styleType, StyleId styleIdForFill, SymbolData symbolData, PropDef[] componentPropDefs, PropAssignment[] componentPropAssignments, VariableDataMap parameterConsumptionMap, SetMode[] variableSetModes, VariableID variableSetID, ResolvedType variableResolvedType, Values variableDataValues, ModeMap variableModeBySetMap, Interaction[] prototypeInteractions, StartingPoint prototypeStartingPoint, GUIDPath guidPath, StackMode stackMode, float stackSpacing, float stackHorizontalPadding, float stackVerticalPadding, uint count, float starInnerScale, VectorData vectorData, StrokeCap strokeCap, StrokeJoin strokeJoin, VectorMirror handleMirroring, ShapeWithTextType shapeWithTextType, ConnectorEndpoint connectorStart, ConnectorEndpoint connectorEnd, StrokeCap connectorStartCap, StrokeCap connectorEndCap, ConnectorLineStyle connectorLineStyle, ConstraintType horizontalConstraint, ConstraintType verticalConstraint, NodeChange[] derivedSymbolData, string key, string version, LeadingTrim leadingTrim, float[] dashPattern, ConnectorControlPoint[] connectorControlPoints
|
||||
message Blob byte[] bytes
|
||||
message Message NodeChange[] nodeChanges, Blob[] blobs
|
||||
";
|
||||
|
||||
@@ -3978,7 +3978,7 @@ fn vector_path(v: &Value, warnings: &mut Vec<String>) -> Option<VectorNetwork> {
|
||||
/// Parse supported vector commands and report unrepresentable geometry.
|
||||
fn vector_bezpath(v: &Value, warnings: &mut Vec<String>) -> Option<BezPath> {
|
||||
if let Some(d) = v.get("content").and_then(Value::as_str) {
|
||||
let path = BezPath::from_svg(d).ok().filter(|p| !p.elements().is_empty())?;
|
||||
let path = figcraft_doc::geom::svg_path(d).ok().filter(|p| !p.elements().is_empty())?;
|
||||
let origin = Affine::translate((-geometry(v, "x", 0.0), -geometry(v, "y", 0.0)));
|
||||
return Some(origin * path);
|
||||
}
|
||||
|
||||
@@ -859,7 +859,7 @@ impl<'a> Ctx<'a> {
|
||||
self.warn("very long vector paths were skipped");
|
||||
continue;
|
||||
}
|
||||
match BezPath::from_svg(d) {
|
||||
match figcraft_doc::geom::svg_path(d) {
|
||||
Ok(bp) if sane(&bp) && out.elements().len() + bp.elements().len() <= MAX_PATH_ELEMENTS => {
|
||||
winding.get_or_insert(if text(p, "windingRule") == Some("EVENODD") { WindingRule::EvenOdd } else { WindingRule::NonZero });
|
||||
out.extend(bp);
|
||||
|
||||
+67
-7
@@ -18,6 +18,62 @@ pub use transform::*;
|
||||
/// Corner radii in clockwise order from the top-left: `[tl, tr, br, bl]`.
|
||||
pub type Radii = [f64; 4];
|
||||
|
||||
/// The tolerance an arc of radius `r` is turned into cubics with: a hundredth of a unit, or a
|
||||
/// millionth of the radius once that is more. kurbo's cubic count grows with radius ÷ tolerance,
|
||||
/// so a fixed tolerance let a radius of 1e300 ask for more cubics than memory holds.
|
||||
pub fn arc_tolerance(r: f64) -> f64 {
|
||||
// An infinite radius (finite inputs can overflow on the way, 1e300 squared) gets an infinite
|
||||
// tolerance: kurbo's count is then NaN, which it floors to its minimum of a few cubics.
|
||||
if r.is_finite() { (r.abs() * 1e-6).max(0.01) } else { f64::INFINITY }
|
||||
}
|
||||
|
||||
/// Largest coordinate, radius or other number SVG path data may carry ([`svg_path`]).
|
||||
pub const MAX_SVG_COORD: f64 = 1e9;
|
||||
|
||||
/// `d` (SVG path data) as a path. A number past [`MAX_SVG_COORD`] is refused before parsing: the
|
||||
/// parser turns an arc into cubics by its radius at a fixed tolerance, so a radius of 1e300 would
|
||||
/// be unbounded work and memory on the way to geometry that is refused anyway.
|
||||
pub fn svg_path(d: &str) -> Result<BezPath, String> {
|
||||
if number_past(d, MAX_SVG_COORD) {
|
||||
return Err(format!("path data holds a number too large (past {MAX_SVG_COORD:e})"));
|
||||
}
|
||||
BezPath::from_svg(d).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Whether a number in SVG path data `d` lies past ±`max` (or isn't finite). Numbers are split as
|
||||
/// the SVG grammar does (`1-2` and `.5.5` are two each; `1e-3` is one).
|
||||
fn number_past(d: &str, max: f64) -> bool {
|
||||
fn big(cur: &mut String, max: f64) -> bool {
|
||||
let big = cur.parse::<f64>().is_ok_and(|v| v.is_nan() || v.abs() > max);
|
||||
cur.clear();
|
||||
big
|
||||
}
|
||||
let (mut cur, mut dot, mut exp) = (String::new(), false, false);
|
||||
for c in d.chars() {
|
||||
let continues = match c {
|
||||
'0'..='9' => true,
|
||||
'.' => !dot && !exp,
|
||||
'e' | 'E' => !exp && cur.chars().any(|c| c.is_ascii_digit()),
|
||||
'+' | '-' => cur.ends_with(['e', 'E']),
|
||||
_ => false,
|
||||
};
|
||||
if continues {
|
||||
dot |= c == '.';
|
||||
exp |= matches!(c, 'e' | 'E');
|
||||
cur.push(c);
|
||||
continue;
|
||||
}
|
||||
if big(&mut cur, max) {
|
||||
return true;
|
||||
}
|
||||
(dot, exp) = (c == '.', false);
|
||||
if matches!(c, '+' | '-' | '.') {
|
||||
cur.push(c);
|
||||
}
|
||||
}
|
||||
big(&mut cur, max)
|
||||
}
|
||||
|
||||
fn finite(v: f64) -> f64 {
|
||||
if v.is_finite() { v } else { 0.0 }
|
||||
}
|
||||
@@ -126,7 +182,7 @@ fn append_corner(path: &mut BezPath, corner: Point, din: Vec2, dout: Vec2, prof:
|
||||
}
|
||||
if sweep.abs() > 1e-9 {
|
||||
let arc = kurbo::Arc::new(center, (r, r), a0, sweep, 0.0);
|
||||
arc.to_cubic_beziers(0.01, |p1, p2, p| path.curve_to(p1, p2, p));
|
||||
arc.to_cubic_beziers(arc_tolerance(r), |p1, p2, p| path.curve_to(p1, p2, p));
|
||||
}
|
||||
let end = at(0.0, p);
|
||||
if a + b + c > 1e-9 {
|
||||
@@ -260,7 +316,7 @@ pub fn smoothed_polygon(points: &[Point], radius: f64, smoothing: f64) -> BezPat
|
||||
None => path.line_to(k.p3),
|
||||
}
|
||||
if k.sweep.abs() > 1e-9 {
|
||||
kurbo::Arc::new(k.center, (k.r, k.r), k.a0, k.sweep, 0.0).to_cubic_beziers(0.01, |p1, p2, q| path.curve_to(p1, p2, q));
|
||||
kurbo::Arc::new(k.center, (k.r, k.r), k.a0, k.sweep, 0.0).to_cubic_beziers(arc_tolerance(k.r), |p1, p2, q| path.curve_to(p1, p2, q));
|
||||
}
|
||||
match k.ease_out {
|
||||
Some((h1, h2)) => path.curve_to(h1, h2, k.end),
|
||||
@@ -400,25 +456,29 @@ pub fn ellipse(width: f64, height: f64, start: f64, sweep: f64, inner: f64) -> B
|
||||
let start = finite(start);
|
||||
let inner = finite(inner).clamp(0.0, 1.0);
|
||||
let full = full_sweep(sweep);
|
||||
let tol = arc_tolerance(rx.max(ry));
|
||||
let mut path = BezPath::new();
|
||||
// A whole turn as an arc with these radii: kurbo's `Ellipse` recovers its radii from an
|
||||
// affine map, which overflows to infinity for radii near f64's limit (and infinite cubics).
|
||||
let whole = |rx: f64, ry: f64| kurbo::Arc::new(c, (rx, ry), 0.0, TAU, 0.0);
|
||||
if full && inner <= 0.0 {
|
||||
return kurbo::Ellipse::new(c, (rx, ry), 0.0).to_path(0.01);
|
||||
return whole(rx, ry).to_path(tol);
|
||||
}
|
||||
if full {
|
||||
// A ring: outer clockwise, inner counter-clockwise.
|
||||
path.extend(kurbo::Ellipse::new(c, (rx, ry), 0.0).path_elements(0.01));
|
||||
let inner_path = kurbo::Ellipse::new(c, (rx * inner, ry * inner), 0.0).to_path(0.01);
|
||||
path.extend(whole(rx, ry).path_elements(tol));
|
||||
let inner_path = whole(rx * inner, ry * inner).to_path(tol);
|
||||
path.extend(inner_path.reverse_subpaths());
|
||||
return path;
|
||||
}
|
||||
let outer = kurbo::Arc::new(c, (rx, ry), start, sweep, 0.0);
|
||||
path.move_to(c + Vec2::new(rx * start.cos(), ry * start.sin()));
|
||||
outer.to_cubic_beziers(0.01, |p1, p2, p| path.curve_to(p1, p2, p));
|
||||
outer.to_cubic_beziers(tol, |p1, p2, p| path.curve_to(p1, p2, p));
|
||||
if inner > 0.0 {
|
||||
let end = start + sweep;
|
||||
path.line_to(c + Vec2::new(rx * inner * end.cos(), ry * inner * end.sin()));
|
||||
let back = kurbo::Arc::new(c, (rx * inner, ry * inner), end, -sweep, 0.0);
|
||||
back.to_cubic_beziers(0.01, |p1, p2, p| path.curve_to(p1, p2, p));
|
||||
back.to_cubic_beziers(tol, |p1, p2, p| path.curve_to(p1, p2, p));
|
||||
} else {
|
||||
path.line_to(c);
|
||||
}
|
||||
|
||||
@@ -210,6 +210,13 @@ fn set_rotation_keeps_center() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_to_handles_large_precision_without_changing_finite_values() {
|
||||
assert_eq!(round_to(1.25, 400), 1.25);
|
||||
assert_eq!(round_to(-1.25, 400), -1.25);
|
||||
assert_eq!(round_to(1.23456, 2), 1.23);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reverse_subpaths_preserves_open_and_closed() {
|
||||
let mut open = BezPath::new();
|
||||
@@ -224,3 +231,49 @@ fn reverse_subpaths_preserves_open_and_closed() {
|
||||
let r = <BezPath as ReverseSubpaths>::reverse_subpaths(&closed);
|
||||
assert!(matches!(r.elements().last(), Some(kurbo::PathEl::ClosePath)), "{:?}", r.elements());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_huge_ellipse_arc_is_a_few_cubics() {
|
||||
let big = ellipse(1e300, 1e300, 0.3, 2.0, 0.5);
|
||||
assert!(big.elements().len() < 200, "{}", big.elements().len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_huge_ring_is_a_few_cubics() {
|
||||
let ring = ellipse(1e300, 1e300, 0.0, TAU, 0.5);
|
||||
assert!(ring.elements().len() < 200, "{}", ring.elements().len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_huge_smoothed_star_is_a_few_cubics() {
|
||||
let star = smoothed_polygon(&star_points(1e300, 1e300, 5, 0.5), 1e299, 0.5);
|
||||
assert!(star.elements().len() < 400, "{}", star.elements().len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_huge_rounded_rect_is_a_few_cubics() {
|
||||
let rect = rounded_rect(1e300, 1e300, [1e299; 4], 0.0);
|
||||
assert!(rect.elements().len() < 100, "{}", rect.elements().len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_infinite_radius_is_a_few_cubics() {
|
||||
let mut n = 0;
|
||||
kurbo::Arc::new((0.0, 0.0), (f64::INFINITY, 1.0), 0.0, 1.0, 0.0).to_cubic_beziers(arc_tolerance(f64::INFINITY), |_, _, _| n += 1);
|
||||
assert!(n < 16, "{n}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_path_refuses_numbers_past_the_limit_before_parsing() {
|
||||
let start = std::time::Instant::now();
|
||||
for d in ["M0 0 A1e300 1e300 0 0 1 1 1", "M0 0A1e300-1e300 0 0 1 1 1", "M 0 0 L 1e10 5", "M0 0L-2e9.5 0", "M0 0 L 1e999 0"] {
|
||||
assert!(svg_path(d).is_err(), "{d}");
|
||||
}
|
||||
assert!(start.elapsed() < std::time::Duration::from_secs(2), "{:?}", start.elapsed());
|
||||
for d in ["M0 0 L 1e9 5 A 5 5 0 0 1 10 10 Z", "M0 0 L-2.5 0.5 L1e-3 -4e2 Z", "M10,20 l1,-2.5e+1"] {
|
||||
assert!(svg_path(d).is_ok(), "{d}");
|
||||
}
|
||||
assert!(!number_past("M0 0L-2.5.5 1e-3-4e2z", 1e3));
|
||||
assert!(number_past("M0 0L-2.5.5 1e-3-4e3z", 1e3));
|
||||
assert!(number_past("M.5.5e10", 1e3));
|
||||
}
|
||||
|
||||
@@ -57,6 +57,9 @@ pub fn rotate_about(xf: Affine, pivot: Point, degrees: f64) -> Affine {
|
||||
/// Round a value to `digits` decimals for display (avoids `-0` and float noise).
|
||||
pub fn round_to(v: f64, digits: i32) -> f64 {
|
||||
let f = 10f64.powi(digits);
|
||||
if v.is_finite() && !f.is_finite() {
|
||||
return v;
|
||||
}
|
||||
let r = (v * f).round() / f;
|
||||
if r == 0.0 { 0.0 } else { r }
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ name = "figcraft-pathops"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
description = "FigCraft path operations: booleans (union, subtract, intersect, exclude), outline stroke with inside/center/outside alignment, arrowheads"
|
||||
|
||||
[lints]
|
||||
|
||||
@@ -21,14 +21,25 @@ fn props(weight: f64, b: &Brush) -> StrokeProps {
|
||||
StrokeProps { weight, align: StrokeAlign::Center, brush: Some(b.clone()), ..Default::default() }
|
||||
}
|
||||
|
||||
/// What a brush paints stays within half [`StrokeProps::max_weight`] of the path, which the
|
||||
/// stroke's bounds go by: plain, with copies grown, turned and strayed all they can, and with a
|
||||
/// width profile thinning or widening it (strays keep their distance, whatever the profile).
|
||||
#[test]
|
||||
fn every_preset_draws_inside_its_reach() {
|
||||
for p in PRESETS {
|
||||
let b = brush(p.id);
|
||||
let out = outline(&line(200.0), 10.0, &props(10.0, &b), &b).unwrap();
|
||||
let bb = out.bounding_box();
|
||||
assert!(!out.elements().is_empty(), "{}", p.id);
|
||||
assert!(bb.y0 >= -5.5 && bb.y1 <= 5.5 && bb.x0 >= -5.5 && bb.x1 <= 205.5, "{}: {bb:?}", p.id);
|
||||
let wild = Brush { size_jitter: 1.0, rotation_jitter: 1.0, scatter: 4.0, ..brush(p.id) };
|
||||
for (b, profile) in [(brush(p.id), None), (wild.clone(), None), (wild.clone(), Some(0.2)), (wild, Some(2.0))] {
|
||||
let k = StrokeProps { width_profile: profile.map(|s| WidthProfile::new([(0.0, s), (1.0, s)])), ..props(10.0, &b) };
|
||||
let out = outline(&line(200.0), 10.0, &k, &b).unwrap();
|
||||
let bb = out.bounding_box();
|
||||
let reach = k.max_weight() / 2.0;
|
||||
assert!(!out.elements().is_empty(), "{}", p.id);
|
||||
assert!(
|
||||
bb.y0 >= -reach && bb.y1 <= reach && bb.x0 >= -reach && bb.x1 <= 200.0 + reach,
|
||||
"{} {b:?} {profile:?}: {bb:?}, reach {reach}",
|
||||
p.id
|
||||
);
|
||||
}
|
||||
}
|
||||
assert!(outline(&line(10.0), 1.0, &props(1.0, &brush("nope")), &brush("nope")).is_none());
|
||||
}
|
||||
|
||||
@@ -112,7 +112,7 @@ impl Fenwick {
|
||||
let mut i = rank + 1;
|
||||
while let Some(c) = self.0.get_mut(i) {
|
||||
*c += by;
|
||||
i += i.isolate_lowest_one();
|
||||
i += i & i.wrapping_neg();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,7 +123,7 @@ impl Fenwick {
|
||||
&& let Some(c) = self.0.get(i)
|
||||
{
|
||||
n += c;
|
||||
i -= i.isolate_lowest_one();
|
||||
i -= i & i.wrapping_neg();
|
||||
}
|
||||
u64::try_from(n).unwrap_or(0)
|
||||
}
|
||||
|
||||
@@ -93,3 +93,9 @@ fn a_fold_stops_once_it_has_swept_its_budget() {
|
||||
assert_eq!(steps, MAX_FOLD_SEGMENTS / 100_004);
|
||||
assert_eq!(budget.spend(&BezPath::new(), &BezPath::new()), Err(PathOpsError::TooComplex), "spent stays spent");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_rectangle_bounds_count_self_and_cross_pairs() {
|
||||
let shapes = rects([Rect::new(0.0, 0.0, 2.0, 2.0), Rect::new(1.0, 1.0, 3.0, 3.0), Rect::new(4.0, 4.0, 5.0, 5.0)]);
|
||||
assert_eq!(complexity([&shapes]), Some(Complexity { segments: 12, crossings: 14 }));
|
||||
}
|
||||
|
||||
@@ -619,7 +619,8 @@ fn elliptical_rect(r: figcraft_geom::Rect, [tl, tr, br, bl]: [(f64, f64); 4]) ->
|
||||
if rx > 0.0 && ry > 0.0 {
|
||||
let c = Point::new(corner.x + sx * rx, corner.y + sy * ry);
|
||||
p.line_to((c.x + rx * start.cos(), c.y + ry * start.sin()));
|
||||
kurbo::Arc::new(c, (rx, ry), start, FRAC_PI_2, 0.0).to_cubic_beziers(0.01, |a, b, e| p.curve_to(a, b, e));
|
||||
kurbo::Arc::new(c, (rx, ry), start, FRAC_PI_2, 0.0)
|
||||
.to_cubic_beziers(figcraft_geom::arc_tolerance(rx.max(ry)), |a, b, e| p.curve_to(a, b, e));
|
||||
} else {
|
||||
p.line_to(corner);
|
||||
}
|
||||
|
||||
@@ -57,7 +57,7 @@ pub(crate) fn draw(pix: &mut Pixmap, view: &View, d: &Dots) {
|
||||
let strong = |k: i64| k.rem_euclid(major) == 0;
|
||||
// The device-pixel span of the mark on line `k` along an axis `len` pixels long from `o`.
|
||||
let span = |k: i64, o: f64, len: i64| {
|
||||
let a = ((k as f64 * d.step * s - o).round() as i64).saturating_sub(lead);
|
||||
let a = (nearest_px(k as f64 * d.step * s, o) as i64).saturating_sub(lead);
|
||||
(a.max(0), a.saturating_add(side).min(len))
|
||||
};
|
||||
let row = w as usize * 4;
|
||||
@@ -92,6 +92,22 @@ pub(crate) fn draw(pix: &mut Pixmap, view: &View, d: &Dots) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The first device pixel of a mark whose edge is `at` pixels from the page origin, in a view whose
|
||||
/// top-left is `o` pixels from it: the pixel whose left (or top) edge is nearest, and the right (or
|
||||
/// lower) one when two are as near. A view a whole number of pixels off (a pan, a band, a patch)
|
||||
/// gets `o` back from its origin with a rounding error, so `at` and `o` are each rounded to
|
||||
/// 1/65536 px first: the mark's own position decides the pixel, and the view only counts it out
|
||||
/// from its corner. The mark's halves go up and the origin's down: far out, where the origin's
|
||||
/// error is half a step, it still comes back to the whole pixel. Past 2³⁷ px the step is finer
|
||||
/// than `f64` and values are used as they are.
|
||||
fn nearest_px(at: f64, o: f64) -> f64 {
|
||||
const STEPS: f64 = 65_536.0;
|
||||
const EXACT: f64 = 137_438_953_472.0; // 2³⁷
|
||||
let up = |v: f64| if v.abs() < EXACT { (v * STEPS + 0.5).floor() / STEPS } else { v };
|
||||
let down = |v: f64| if v.abs() < EXACT { (v * STEPS - 0.5).ceil() / STEPS } else { v };
|
||||
(up(at) - down(o) + 0.5).floor()
|
||||
}
|
||||
|
||||
/// Which line covers each device pixel along an axis: 0 none, 1 a faded one, 2 a strong one.
|
||||
type Cover = Vec<u8>;
|
||||
|
||||
|
||||
@@ -134,3 +134,103 @@ fn graph_paper_is_strong_every_major_line() {
|
||||
assert_eq!(at(x, -195), strong, "a strong line at {x}");
|
||||
}
|
||||
}
|
||||
|
||||
/// At a zoom of 1.0625, a step of 24 is 25.5 pixels: every second dot falls halfway between two
|
||||
/// pixels. A view a whole number of pixels on (a pan, a band, a patch) has to put it on the same
|
||||
/// one, on whichever side of that view's origin it is.
|
||||
#[test]
|
||||
fn dots_halfway_between_pixels_stay_put() {
|
||||
let (d, page) = page_with_square();
|
||||
for lines in [false, true] {
|
||||
let opts = Options { dots: Some(Dots { lines, ..dots() }), ..Default::default() };
|
||||
let s = 1.0625;
|
||||
let full = View { origin: (0.0, 0.0), scale: s, width: 400, height: 300 };
|
||||
let a = render_view_single(&d, page, &full, &opts).unwrap();
|
||||
for dx in 1..100u32 {
|
||||
let dy = (dx * 37) % 100;
|
||||
let v = View { origin: (f64::from(dx) / s, f64::from(dy) / s), scale: s, width: 250, height: 180 };
|
||||
let b = render_view_single(&d, page, &v, &opts).unwrap();
|
||||
for y in 0..180 {
|
||||
for x in 0..250 {
|
||||
assert_eq!(rgba(&b, x, y), rgba(&a, x + dx, y + dy), "lines {lines}, a pan by ({dx}, {dy}), at {x}, {y}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A mark that rounds to a half step of 1/65536 px goes the same way on both sides of a view's
|
||||
/// origin too: at a step of 25.5 − 2⁻¹⁷ px, the first mark is where 1/65536 px rounds up.
|
||||
#[test]
|
||||
fn dots_on_the_rounding_step_stay_put() {
|
||||
let (d, page) = page_with_square();
|
||||
let step = 25.5 - 2f64.powi(-17);
|
||||
for lines in [false, true] {
|
||||
let opts = Options { dots: Some(Dots { step, lines, ..dots() }), ..Default::default() };
|
||||
let full = View { origin: (0.0, 0.0), scale: 1.0, width: 300, height: 200 };
|
||||
let a = render_view_single(&d, page, &full, &opts).unwrap();
|
||||
for pan in 1..60u32 {
|
||||
let v = View { origin: (f64::from(pan), f64::from(pan)), scale: 1.0, width: 200, height: 120 };
|
||||
let b = render_view_single(&d, page, &v, &opts).unwrap();
|
||||
for y in 0..120 {
|
||||
for x in 0..200 {
|
||||
assert_eq!(rgba(&b, x, y), rgba(&a, x + pan, y + pan), "lines {lines}, a pan by {pan}, at {x}, {y}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The view's origin is quantized apart from the marks: converted to pixels, a whole-pixel origin
|
||||
/// comes back a hair off, and taken together with a mark one step short of a half it would push the
|
||||
/// mark across.
|
||||
#[test]
|
||||
fn dots_one_rounding_step_short_of_a_half_stay_put() {
|
||||
let (d, page) = page_with_square();
|
||||
let s = (75.5 - 2f64.powi(-17)) / 24.0;
|
||||
for lines in [false, true] {
|
||||
let opts = Options { dots: Some(Dots { lines, ..dots() }), ..Default::default() };
|
||||
let a = render_view_single(&d, page, &View { origin: (0.0, 0.0), scale: s, width: 300, height: 200 }, &opts).unwrap();
|
||||
for pan in 1..100u32 {
|
||||
let v = View { origin: (f64::from(pan) / s, f64::from(pan) / s), scale: s, width: 200, height: 100 };
|
||||
let b = render_view_single(&d, page, &v, &opts).unwrap();
|
||||
for y in 0..100 {
|
||||
for x in 0..200 {
|
||||
assert_eq!(rgba(&b, x, y), rgba(&a, x + pan, y + pan), "lines {lines}, a pan by {pan}, at {x}, {y}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Far out (some 4 × 10¹⁰ pixels), a whole-pixel origin comes back from page units exactly half a
|
||||
/// rounding step off: rounded up, it would move the marks that fall halfway between pixels.
|
||||
#[test]
|
||||
fn far_out_dots_stay_put() {
|
||||
let (d, page) = page_with_square();
|
||||
let s = 0.3;
|
||||
let at = 42_536_140_695.0;
|
||||
let opts = Options { dots: Some(Dots { step: 5.0, ..dots() }), ..Default::default() };
|
||||
let a = render_view_single(&d, page, &View { origin: (at / s, 0.0), scale: s, width: 420, height: 40 }, &opts).unwrap();
|
||||
for dx in 1..200u32 {
|
||||
let v = View { origin: ((at + f64::from(dx)) / s, 0.0), scale: s, width: 200, height: 40 };
|
||||
let b = render_view_single(&d, page, &v, &opts).unwrap();
|
||||
for y in 0..40 {
|
||||
for x in 0..200 {
|
||||
assert_eq!(rgba(&b, x, y), rgba(&a, x + dx, y), "a pan by {dx}, at {x}, {y}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Positions too far out to quantize draw nothing rather than a mark at the corner.
|
||||
#[test]
|
||||
fn dots_out_past_any_page_draw_nothing() {
|
||||
let (d, page) = page_with_square();
|
||||
let plain = render_view_single(&d, page, &View { origin: (1e304, 0.0), scale: 1.0, width: 40, height: 40 }, &Options::default()).unwrap();
|
||||
for (step, x) in [(1e290, 1e304), (1e299, 1e305), (3e303, 1.5e308)] {
|
||||
let opts = Options { dots: Some(Dots { step, ..dots() }), ..Default::default() };
|
||||
let p = render_view_single(&d, page, &View { origin: (x, 0.0), scale: 1.0, width: 40, height: 40 }, &opts).unwrap();
|
||||
assert_eq!(p.data(), plain.data(), "a step of {step} at {x}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,6 +26,14 @@ fn unit(h: u64, at: u32) -> f32 {
|
||||
f32::from(((h >> at) & 0xFFFF) as u16) / 65536.0
|
||||
}
|
||||
|
||||
/// Cell positions are rounded to 1 / `STEPS_PER_CELL` of a cell before they're cut into cells. A
|
||||
/// pixel centre can fall exactly on a cell edge (at a zoom of 1.7, a 1-unit cell is 1.7 pixels
|
||||
/// across: every tenth edge does), and a view whose origin is a whole number of pixels off (a
|
||||
/// patch, a band, a pan) reaches it with another rounding error. Unrounded, a row of grains lands
|
||||
/// in the next cell; rounded, the edge moves 1 / 2²¹ of a cell aside, off the centres layers at
|
||||
/// round positions and zooms put it on.
|
||||
const STEPS_PER_CELL: f64 = 1_048_576.0;
|
||||
|
||||
/// Maps layer pixels to the grain cells under their centres.
|
||||
struct Cells {
|
||||
/// Layer pixels → local units, divided by the grain size: `[a, b, c, d, e, f]`.
|
||||
@@ -44,7 +52,8 @@ impl Cells {
|
||||
fn at(&self, x: u32, y: u32) -> (i64, i64) {
|
||||
let (px, py) = (f64::from(x) + 0.5, f64::from(y) + 0.5);
|
||||
let [a, b, c, d, e, f] = self.m;
|
||||
((a * px + c * py + e).floor() as i64, (b * px + d * py + f).floor() as i64)
|
||||
let cell = |v: f64| ((v * STEPS_PER_CELL).round() / STEPS_PER_CELL).floor() as i64;
|
||||
(cell(a * px + c * py + e), cell(b * px + d * py + f))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,11 +129,14 @@ pub fn texture(layer: &mut Pixmap, t: &Texture, xf: Affine, scale: f64, seed: u3
|
||||
let hv = hash(ix, iy, seed ^ 0x7E57_u32);
|
||||
// A uniform point in the disc of radius r.
|
||||
let (ang, dist) = (unit(hv, 0) * std::f32::consts::TAU, unit(hv, 16).sqrt() * r);
|
||||
let (fx, fy) = (x as f32 + 0.5 + ang.cos() * dist, y as f32 + 0.5 + ang.sin() * dist);
|
||||
// The move in whole pixels, apart from `x` and `y`: the same pixel of the page moves
|
||||
// the same way wherever the layer's pixels start.
|
||||
let (mx, my) = ((0.5 + ang.cos() * dist).floor() as i64, (0.5 + ang.sin() * dist).floor() as i64);
|
||||
let (fx, fy) = (i64::from(x) + mx, i64::from(y) + my);
|
||||
let i = ((y * w + x) * 4) as usize;
|
||||
let mut px = [0u8; 4];
|
||||
if fx >= 0.0 && fy >= 0.0 && (fx as u32) < w && (fy as u32) < h {
|
||||
let j = (((fy as u32) * w + fx as u32) * 4) as usize;
|
||||
if fx >= 0 && fy >= 0 && fx < i64::from(w) && fy < i64::from(h) {
|
||||
let j = ((fy * i64::from(w) + fx) * 4) as usize;
|
||||
if let Some(s) = src.get(j..j + 4) {
|
||||
px.copy_from_slice(s);
|
||||
}
|
||||
|
||||
@@ -96,6 +96,26 @@ fn noise_grains_have_their_size_and_stay_put() {
|
||||
assert_eq!(px(&z, 23, 23), c);
|
||||
}
|
||||
|
||||
/// Panning by whole pixels at a zoom where grain edges fall on pixel centres (1.7: a 1-unit grain
|
||||
/// is 1.7 pixels, every tenth edge on a centre) reaches those edges from another origin, with
|
||||
/// another rounding error: the grains still stay put.
|
||||
#[test]
|
||||
fn grains_stay_put_where_their_edges_fall_on_pixel_centres() {
|
||||
let s = 1.7;
|
||||
for (why, kind) in [
|
||||
("noise", noise(Noise { density: 0.5, size: 0.5, color: Color::BLACK, ..Noise::default() })),
|
||||
("texture", EffectKind::Texture(Texture { size: 0.5, radius: 12.0, clip_to_shape: false, ..Texture::default() })),
|
||||
] {
|
||||
let (d, r) = square(kind);
|
||||
let a = render_at(&d, r, (0.0, 0.0), s);
|
||||
for (dx, dy) in [(79u32, 62u32), (13, 7), (31, 47), (5, 99)] {
|
||||
let b = render_at(&d, r, (f64::from(dx) / s, f64::from(dy) / s), s);
|
||||
let off = (0..200 - dy).flat_map(|y| (0..200 - dx).map(move |x| (x, y))).filter(|&(x, y)| px(&a, x + dx, y + dy) != px(&b, x, y)).count();
|
||||
assert_eq!(off, 0, "{why}, a pan by ({dx}, {dy}) pixels");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noise_blend_mode_applies() {
|
||||
let (d, r) = square(noise(Noise { density: 1.0, color: Color::WHITE, blend: figcraft_color::BlendMode::Multiply, ..Noise::default() }));
|
||||
@@ -138,3 +158,32 @@ fn hostile_grain_values_do_not_crash() {
|
||||
let _ = render_at(&d, r, (0.0, 0.0), 1.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Texture moves each pixel by whole pixels, the same in any layer: far from the layer's left edge
|
||||
/// (past 1024 pixels), a move worked out in `f32` together with the pixel's index came out a
|
||||
/// pixel off for some indices, so a pan changed which pixel a grain took. (The stripes' gradient
|
||||
/// itself can differ by a level between the two renders; a grain taking the wrong pixel differs by
|
||||
/// far more.)
|
||||
#[test]
|
||||
fn texture_moves_far_into_a_wide_layer_stay_put() {
|
||||
use figcraft_color::{ColorStop, Gradient, GradientKind};
|
||||
let mut d = Document::new("wide");
|
||||
let p = d.first_page().unwrap();
|
||||
let r = d.create(p, NodeKind::Rectangle, "Stripes", 0.0, 0.0, 2400.0, 60.0).unwrap();
|
||||
let n = d.get_mut(r).unwrap();
|
||||
// Black and white stripes, 3 units each: a pixel's neighbours differ.
|
||||
let stops = (0..=800).map(|i| ColorStop { position: i as f32 / 800.0, color: if i % 2 == 0 { Color::BLACK } else { Color::WHITE } }).collect();
|
||||
n.fills = vec![Paint::gradient(Gradient { kind: GradientKind::Linear, stops, from: (0.0, 0.5), to: (1.0, 0.5), width: (0.0, 1.0) })];
|
||||
n.effects =
|
||||
vec![Effect { kind: EffectKind::Texture(Texture { size: 1.0, radius: 12.0, clip_to_shape: false, ..Texture::default() }), visible: true }];
|
||||
let view = |x: f64, w: u32| View { origin: (x, -20.0), scale: 1.0, width: w, height: 100 };
|
||||
let mut a = Pixmap::new(2440, 100).unwrap();
|
||||
render_nodes_into(&d, &[r], &view(-20.0, 2440), &mut a);
|
||||
for dx in [300u32, 1021, 1500] {
|
||||
let mut b = Pixmap::new(900, 100).unwrap();
|
||||
render_nodes_into(&d, &[r], &view(f64::from(dx) - 20.0, 900), &mut b);
|
||||
let far = |p: [u8; 4], q: [u8; 4]| p.iter().zip(q).any(|(u, v)| u.abs_diff(v) > 8);
|
||||
let off = (0..100).flat_map(|y| (0..900).map(move |x| (x, y))).filter(|&(x, y)| far(px(&a, x + dx, y), px(&b, x, y))).count();
|
||||
assert_eq!(off, 0, "a pan by {dx} pixels");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -570,6 +570,8 @@ mod solo_tests;
|
||||
#[cfg(test)]
|
||||
mod spread_tests;
|
||||
#[cfg(test)]
|
||||
mod stroke_reach_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
mod width_tests;
|
||||
|
||||
@@ -569,3 +569,33 @@ fn pans_patch_backdrops_at_the_edges_that_moved_in() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grainy_layers_patch_as_they_render() {
|
||||
fonts();
|
||||
let texture = |clip_to_shape| EffectKind::Texture(figcraft_doc::Texture { size: 0.5, radius: 12.0, clip_to_shape, ..Default::default() });
|
||||
let noise = EffectKind::Noise(figcraft_doc::Noise { size: 0.5, density: 0.4, color: Color::BLACK, ..Default::default() });
|
||||
// At a zoom of 1.7, a grain of 0.5 is 1.7 pixels across: every tenth grain edge falls on a row
|
||||
// of pixel centres, and a patch renders those rows from another origin than a full render.
|
||||
for (why, kind) in [("texture", texture(false)), ("texture clipped to its shape", texture(true)), ("noise", noise)] {
|
||||
let mut d = Document::new("grain");
|
||||
let p = d.first_page().unwrap();
|
||||
let e = d.create(p, NodeKind::Rectangle, "E", 60.0, 50.0, 120.0, 90.0).unwrap();
|
||||
solid(d.get_mut(e).unwrap(), "E03030");
|
||||
d.get_mut(e).unwrap().effects = vec![Effect { kind, visible: true }];
|
||||
let m = d.create(p, NodeKind::Rectangle, "M", 220.0, 60.0, 30.0, 30.0).unwrap();
|
||||
solid(d.get_mut(m).unwrap(), "20A060");
|
||||
let doc = Arc::new(d);
|
||||
let v = View { origin: (0.0, 0.0), scale: 1.7, width: 400, height: 300 };
|
||||
let mut r = Retained::default();
|
||||
check(&mut r, &doc, p, &v);
|
||||
// Over the grainy layer, which is redrawn whole.
|
||||
let over = edit(&doc, |d| d.get_mut(m).unwrap().transform = Affine::translate((100.0, 80.0)));
|
||||
let (shown, pix, work) = r.render(&over, p, &v, &Options::default()).unwrap();
|
||||
let pix = pix.clone();
|
||||
let full = render_view(&over, p, &shown, &Options::default()).unwrap();
|
||||
let worst = pix.data().iter().zip(full.data()).map(|(a, b)| a.abs_diff(*b)).max().unwrap_or(0);
|
||||
assert!(partial(work), "{why}: {work:?}");
|
||||
assert!(worst <= 2, "{why}: {work:?} is {worst} levels off a full render");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -192,3 +192,58 @@ fn arc_stroke_mitres_are_not_cut_off() {
|
||||
assert!(worst <= 2, "{align:?}: {worst} levels cut off");
|
||||
}
|
||||
}
|
||||
|
||||
/// A dashed stroke is cut into separate dashes with square ends, a width profile can step its
|
||||
/// width and a brush lays down shapes of its own: round a whole ellipse or a rounded box, a spread
|
||||
/// mitres out at their corners, past the box grown by the spread, and keeps its whole shadow.
|
||||
#[test]
|
||||
fn stroke_corners_spread_mitres_are_not_cut_off() {
|
||||
use figcraft_doc::{Brush, Node, StrokeAlign, StrokeCap, WidthProfile};
|
||||
type Style = fn(&mut Node);
|
||||
let strokes: [(&str, Style); 4] = [
|
||||
("dashed", |n| n.stroke.dashes = vec![30.0, 30.0]),
|
||||
("dashed with square caps", |n| (n.stroke.dashes, n.stroke.dash_cap) = (vec![30.0, 30.0], Some(StrokeCap::Square))),
|
||||
("stepped", |n| n.stroke.width_profile = Some(WidthProfile::new([(0.0, 1.0), (0.25, 4.0), (0.26, 0.2), (0.75, 4.0)]))),
|
||||
("starry", |n| n.stroke.brush = Some(Brush::new("stars"))),
|
||||
];
|
||||
let shapes = [(NodeKind::Ellipse { start: 0.0, sweep: std::f64::consts::TAU, inner: 0.0 }, 0.0), (NodeKind::Rectangle, 100.0)];
|
||||
for (kind, radius) in shapes {
|
||||
for (name, style) in strokes {
|
||||
for align in [StrokeAlign::Outside, StrokeAlign::Center] {
|
||||
let make = |effects: Vec<EffectKind>| {
|
||||
let (mut d, n) = shape(kind.clone(), effects);
|
||||
let node = d.get_mut(n).unwrap();
|
||||
node.corners.radii = [radius; 4];
|
||||
node.strokes = vec![Paint::solid(Color::WHITE)];
|
||||
(node.stroke.weight, node.stroke.align) = (20.0, align);
|
||||
style(node);
|
||||
(d, n)
|
||||
};
|
||||
let (d, n) = make(vec![EffectKind::DropShadow(shadow(30.0))]);
|
||||
let clear = Shadow { color: Color::new(0.0, 0.0, 0.0, 0.0), ..shadow(120.0) };
|
||||
let (roomy, m) = make(vec![EffectKind::DropShadow(shadow(30.0)), EffectKind::DropShadow(clear)]);
|
||||
let (a, b) = (render(&d, n), render(&roomy, m));
|
||||
let worst = a.data().chunks(4).zip(b.data().chunks(4)).map(|(p, q)| p[3].abs_diff(q[3])).max().unwrap_or(0);
|
||||
// The stroke lands a little differently on a layer of another size, even when
|
||||
// both have room to spare: up to 16 levels at a pixel or two. Cut off is 255.
|
||||
assert!(worst <= 16, "{kind:?} radius {radius}, {name} {align:?}: {worst} levels cut off");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Without a spread, a dashed stroke reaches no further than a solid one: the bounds an export
|
||||
/// goes by stay the box grown by the stroke.
|
||||
#[test]
|
||||
fn a_dashed_stroke_without_a_spread_keeps_its_bounds() {
|
||||
use figcraft_doc::StrokeAlign;
|
||||
for kind in [NodeKind::Rectangle, NodeKind::Ellipse { start: 0.0, sweep: std::f64::consts::TAU, inner: 0.0 }] {
|
||||
let (mut d, n) = shape(kind.clone(), vec![]);
|
||||
let node = d.get_mut(n).unwrap();
|
||||
node.strokes = vec![Paint::solid(Color::WHITE)];
|
||||
(node.stroke.weight, node.stroke.align) = (20.0, StrokeAlign::Outside);
|
||||
node.stroke.dashes = vec![30.0, 30.0];
|
||||
let b = crate::export_bounds(&d, n).unwrap();
|
||||
assert_eq!((b.x0, b.y0, b.x1, b.y1), (80.0, 80.0, 320.0, 320.0), "{kind:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
//! What a stroke paints stays within the bounds an export and a redraw go by: square dash ends
|
||||
//! that stand out round a curve, brush shapes past half the weight and brush copies that stray
|
||||
//! further than a width profile thins them included.
|
||||
|
||||
use figcraft_color::{Color, Paint};
|
||||
use figcraft_doc::{Brush, Document, Node, NodeKind, StrokeAlign, StrokeCap, StrokeJoin, WidthProfile};
|
||||
|
||||
use super::*;
|
||||
|
||||
/// How many pixels `kind` (at (200, 200), `size` square) with a 40-unit stroke styled by `style`
|
||||
/// paints more than a pixel outside its export bounds, on a 600 × 600 view.
|
||||
fn painted_outside(kind: &NodeKind, size: f64, align: StrokeAlign, miter_limit: f64, style: fn(&mut Node)) -> usize {
|
||||
let mut d = Document::new("reach");
|
||||
let p = d.first_page().unwrap();
|
||||
let n = d.create(p, kind.clone(), "S", 200.0, 200.0, size, size).unwrap();
|
||||
let node = d.get_mut(n).unwrap();
|
||||
node.fills.clear();
|
||||
node.corners.radii = [30.0; 4];
|
||||
node.strokes = vec![Paint::solid(Color::WHITE)];
|
||||
(node.stroke.weight, node.stroke.align, node.stroke.join, node.stroke.miter_limit) = (40.0, align, StrokeJoin::Miter, miter_limit);
|
||||
style(node);
|
||||
let b = crate::export_bounds(&d, n).unwrap();
|
||||
let mut pix = Pixmap::new(600, 600).unwrap();
|
||||
render_nodes_into(&d, &[n], &View { origin: (0.0, 0.0), scale: 1.0, width: 600, height: 600 }, &mut pix);
|
||||
let (xs, ys) = (b.x0 - 1.0..=b.x1 + 1.0, b.y0 - 1.0..=b.y1 + 1.0);
|
||||
let inside = |i: usize| xs.contains(&((i % 600) as f64 + 0.5)) && ys.contains(&((i / 600) as f64 + 0.5));
|
||||
pix.data().chunks(4).enumerate().filter(|(i, p)| p[3] > 0 && !inside(*i)).count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stroke_with_corners_paints_within_its_bounds() {
|
||||
type Style = fn(&mut Node);
|
||||
let strokes: [(&str, Style); 4] = [
|
||||
("square dash ends", |n| (n.stroke.dashes, n.stroke.dash_cap) = (vec![30.0, 30.0], Some(StrokeCap::Square))),
|
||||
("short square dashes", |n| (n.stroke.dashes, n.stroke.dash_cap) = (vec![1.0, 7.0], Some(StrokeCap::Square))),
|
||||
("the ink brush", |n| n.stroke.brush = Some(Brush::new("ink"))),
|
||||
("a thinned scatter brush", |n| {
|
||||
n.stroke.brush = Some(Brush { scatter: 1.0, ..Brush::new("dots") });
|
||||
n.stroke.width_profile = Some(WidthProfile::new([(0.0, 0.5), (1.0, 0.5)]));
|
||||
}),
|
||||
];
|
||||
let circle = NodeKind::Ellipse { start: 0.0, sweep: std::f64::consts::TAU, inner: 0.0 };
|
||||
let shapes = [(&circle, 200.0), (&circle, 30.0), (&NodeKind::Rectangle, 200.0), (&NodeKind::Star { count: 5, inner_ratio: 0.4 }, 200.0)];
|
||||
for (kind, size) in shapes {
|
||||
for (name, style) in strokes {
|
||||
for align in [StrokeAlign::Center, StrokeAlign::Outside] {
|
||||
for miter_limit in [4.0, 1.0] {
|
||||
let outside = painted_outside(kind, size, align, miter_limit, style);
|
||||
assert_eq!(outside, 0, "{kind:?} {size}, {name}, {align:?}, mitre limit {miter_limit}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -755,6 +755,12 @@ impl FontDb {
|
||||
|
||||
/// Style names of a family, by weight then italic.
|
||||
pub fn styles(&mut self, family: &str) -> Vec<String> {
|
||||
self.style_weights(family).into_iter().map(|(name, _)| name).collect()
|
||||
}
|
||||
|
||||
/// [`styles`](Self::styles) with the weight each is listed by: the face's own (Segoe UI
|
||||
/// Semilight is 350), a named instance's `wght`, or for a face not read yet its name's.
|
||||
pub fn style_weights(&mut self, family: &str) -> Vec<(String, u16)> {
|
||||
self.load_family(family, None);
|
||||
let key = self.key(family);
|
||||
// (weight, italic, order in the font, name): named instances keep the font's order.
|
||||
@@ -773,14 +779,29 @@ impl FontDb {
|
||||
v.push((w, f.italic || italic_name(&inst.name), k, inst.name.clone()));
|
||||
}
|
||||
}
|
||||
// A family installed as one family per weight offers those weights too.
|
||||
for (_, style) in self.split_families(&key) {
|
||||
v.push((pending_weight(&style).clamp(1, 1000) as u16, italic_name(&style), 0, style));
|
||||
// A family installed as one family per weight offers those weights too, upright and italic
|
||||
// as that family's faces are ("Foo Bold" with Regular and Italic faces: Bold and Bold
|
||||
// Italic, the names `resolve` finds them by). A face read gives its own weight, one not
|
||||
// read the name's; the families aren't read for this.
|
||||
for (k, style) in self.split_families(&key) {
|
||||
let named = pending_weight(&style).clamp(1, 1000) as u16;
|
||||
let italic = italic_name(&style);
|
||||
let read = self.families.get(&k).map(|(_, idx)| idx.as_slice()).unwrap_or_default().iter().filter_map(|i| self.faces.get(*i));
|
||||
let unread = self.pending.get(&k).into_iter().flat_map(|(_, entries)| entries).map(|e| (named, italic_name(&e.style)));
|
||||
let faces: Vec<(u16, bool)> = read.map(|f| (f.weight, f.italic)).chain(unread).collect();
|
||||
if faces.is_empty() {
|
||||
v.push((named, italic, 0, style));
|
||||
continue;
|
||||
}
|
||||
for (w, slanted) in faces {
|
||||
let name = if slanted && !italic { format!("{style} Italic") } else { style.clone() };
|
||||
v.push((w, slanted || italic, 0, name));
|
||||
}
|
||||
}
|
||||
v.sort();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
v.retain(|x| seen.insert(norm_style(&x.3)));
|
||||
v.into_iter().map(|x| x.3).collect()
|
||||
v.into_iter().map(|x| (x.3, x.0)).collect()
|
||||
}
|
||||
|
||||
/// The key `family` is known under: itself in any case; for a name designs use for Apple's
|
||||
@@ -1334,7 +1355,7 @@ fn index_font_file(path: &std::path::Path, meta: &std::fs::Metadata, out: &mut B
|
||||
return;
|
||||
}
|
||||
let ext = path.extension().and_then(std::ffi::OsStr::to_str).map(str::to_ascii_lowercase).unwrap_or_default();
|
||||
if !matches!(ext.as_str(), "ttf" | "otf" | "ttc" | "otc") && !(path.extension().is_none() && starts_like_a_font(path)) {
|
||||
if !(matches!(ext.as_str(), "ttf" | "otf" | "ttc" | "otc") || (path.extension().is_none() && starts_like_a_font(path))) {
|
||||
return;
|
||||
}
|
||||
// Very large files are indexed all the same (Apple Color Emoji is ~180 MB and is where the
|
||||
@@ -1514,6 +1535,11 @@ pub fn family_styles(family: &str) -> Vec<String> {
|
||||
db().write().unwrap_or_else(std::sync::PoisonError::into_inner).styles(family)
|
||||
}
|
||||
|
||||
/// [`family_styles`] with the weight each is listed by (see [`FontDb::style_weights`]).
|
||||
pub fn family_style_weights(family: &str) -> Vec<(String, u16)> {
|
||||
db().write().unwrap_or_else(std::sync::PoisonError::into_inner).style_weights(family)
|
||||
}
|
||||
|
||||
/// Scan system fonts into the global db (desktop; a no-op on the web, or with
|
||||
/// `FIGCRAFT_NO_SYSTEM_FONTS` set). Runs once per process: a concurrent caller waits for that scan.
|
||||
/// The directory walk runs without holding the database lock; results are merged in one short write.
|
||||
|
||||
@@ -5,9 +5,10 @@
|
||||
//! case; the picker lists what is installed. Synthetic family names only, over pending entries
|
||||
//! (no files) and the embedded faces when the build has them.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::{CRAFT_FONTS, Face, FontBytes, FontDb, Pending, style_words};
|
||||
use super::{CRAFT_FONTS, Face, FontBytes, FontDb, LocalFont, Pending, scan_dir, style_words, system_font_dirs};
|
||||
|
||||
fn entry(style: &str) -> Pending {
|
||||
Pending { path: format!("no-such-dir/{style}.ttf").into(), index: 0, style: style.into(), postscript: None, local: None }
|
||||
@@ -104,3 +105,43 @@ fn faces_are_found_and_listed_under_either_name() {
|
||||
assert!(Arc::ptr_eq(&db.find("Synthetic Text SemiBold", "Regular").unwrap(), &semibold));
|
||||
assert!(Arc::ptr_eq(&db.find("synthetictext", "Semibold").unwrap(), &semibold));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_family_per_weight_offers_its_italics_too() {
|
||||
// Listed by name before anything is read: Synthetic Slab Bold's Italic face is Bold Italic.
|
||||
let local = |id: usize, family: &str, style: &str| LocalFont { id, family: family.into(), style: style.into(), postscript: String::new() };
|
||||
let mut db = FontDb::default();
|
||||
db.add_local(vec![
|
||||
local(0, "Synthetic Slab", "Regular"),
|
||||
local(1, "Synthetic Slab", "Italic"),
|
||||
local(2, "Synthetic Slab Bold", "Regular"),
|
||||
local(3, "Synthetic Slab Bold", "Italic"),
|
||||
]);
|
||||
let listed = |db: &mut FontDb| db.style_weights("Synthetic Slab");
|
||||
let want = |v: &[(&str, u16)]| v.iter().map(|(s, w)| ((*s).to_string(), *w)).collect::<Vec<_>>();
|
||||
assert_eq!(listed(&mut db), want(&[("Regular", 400), ("Italic", 400), ("Bold", 700), ("Bold Italic", 700)]));
|
||||
assert_eq!(resolved(&db, "Synthetic Slab", "Bold Italic"), pair("synthetic slab bold", "Italic"), "the style drawn by that face");
|
||||
// Faces read give their own weights: Synthetic Slab Semi Light's are 350, not the name's 300.
|
||||
let stand_in = CRAFT_FONTS.first().map(|f| f.bytes.to_vec()).or_else(|| {
|
||||
let mut installed = BTreeMap::new();
|
||||
for dir in system_font_dirs() {
|
||||
scan_dir(&dir, 0, &mut installed);
|
||||
}
|
||||
installed.values().flat_map(|(_, v)| v).find_map(|p| std::fs::read(&p.path).ok())
|
||||
});
|
||||
let Some(bytes) = stand_in.map(Arc::new) else {
|
||||
eprintln!("skipping the read faces: no font to stand in");
|
||||
return;
|
||||
};
|
||||
let face = |family: &str, style: &str, weight: u16, italic: bool| {
|
||||
let mut f = Face::from_bytes(FontBytes::Shared(bytes.clone()), 0, Some(family), Some(style)).unwrap();
|
||||
f.instances.clear();
|
||||
(f.weight, f.italic) = (weight, italic);
|
||||
f
|
||||
};
|
||||
let mut db = FontDb::default();
|
||||
db.add(face("Synthetic Slab", "Regular", 400, false));
|
||||
db.add(face("Synthetic Slab Semi Light", "Regular", 350, false));
|
||||
db.add(face("Synthetic Slab Semi Light", "Italic", 350, true));
|
||||
assert_eq!(listed(&mut db), want(&[("Semi Light", 350), ("Semi Light Italic", 350), ("Regular", 400)]));
|
||||
}
|
||||
|
||||
@@ -17,8 +17,8 @@ pub use breaks::{backspace_step, grapheme_step};
|
||||
pub use color::{ColorBitmap, ColorInk, ColorLayer};
|
||||
pub use fontdb::{
|
||||
Axis, CRAFT_FONTS, Coords, Face, FontDb, LocalFont, NamedInstance, Rescan, add_local_fonts, axis_label, db, face_with_char, family_names,
|
||||
family_styles, find_face, has_family, installed_fonts_known, load_font_bytes, load_local_font, local_only, no_coords, opt_out_of_system_fonts,
|
||||
rescan_system_fonts, scan_system_fonts, scan_system_fonts_on_demand, system_fonts_scanned, take_wanted_local_fonts,
|
||||
family_style_weights, family_styles, find_face, has_family, installed_fonts_known, load_font_bytes, load_local_font, local_only, no_coords,
|
||||
opt_out_of_system_fonts, rescan_system_fonts, scan_system_fonts, scan_system_fonts_on_demand, system_fonts_scanned, take_wanted_local_fonts,
|
||||
};
|
||||
pub use layout::{Decoration, Glyph, Line, TextLayout, layout};
|
||||
pub use onpath::OnPath;
|
||||
|
||||
@@ -413,6 +413,12 @@ name = "English"
|
||||
"Scope: all supported properties" = "Scope: all supported properties"
|
||||
"Scope: hidden from pickers" = "Scope: hidden from pickers"
|
||||
"Scope: only {scope}" = "Scope: only {scope}"
|
||||
"Disconnected. Reconnecting…" = "Disconnected. Reconnecting…"
|
||||
"Disconnected. Your edits stay here and sync when the connection returns. Reconnecting…" = "Disconnected. Your edits stay here and sync when the connection returns. Reconnecting…"
|
||||
"Dismiss" = "Dismiss"
|
||||
"Not connected: {reason}. Your work is still in this tab." = "Not connected: {reason}. Your work is still in this tab."
|
||||
"Retry now" = "Retry now"
|
||||
"Save a copy…" = "Save a copy…"
|
||||
"Wrap style" = "Wrap style"
|
||||
"Text direction" = "Text direction"
|
||||
"Auto: by the first letter with a direction" = "Auto: by the first letter with a direction"
|
||||
@@ -426,6 +432,7 @@ name = "English"
|
||||
"Set hug contents" = "Set hug contents"
|
||||
"Set fill container" = "Set fill container"
|
||||
"Double-click an edge of an auto layout frame" = "Double-click an edge of an auto layout frame"
|
||||
"{name}, disconnected from its live session" = "{name}, disconnected from its live session"
|
||||
"⌥ double-click an edge of an auto layout child" = "⌥ double-click an edge of an auto layout child"
|
||||
"Alt+double-click an edge of an auto layout child" = "Alt+double-click an edge of an auto layout child"
|
||||
"Default" = "Default"
|
||||
|
||||
@@ -1971,6 +1971,7 @@ status = "draft — needs native review"
|
||||
"collab.openFile" = "Abrir archivo en línea"
|
||||
"collab.peers" = "Personas en este archivo"
|
||||
"collab.publish" = "Publicar en el servidor"
|
||||
"collab.reconnect" = "Reconectar"
|
||||
"collab.recoverFile" = "Recuperar archivo en línea"
|
||||
"collab.registerLinks" = "Abrir enlaces de invitación en FigCraft"
|
||||
"collab.removePerson" = "Quitar de la sesión"
|
||||
@@ -2270,6 +2271,7 @@ status = "draft — needs native review"
|
||||
"selection.applyColorStyle" = "Aplicar estilo de color a la selección"
|
||||
"selection.bindColorVariable" = "Aplicar variable de color a la selección"
|
||||
"selection.colors" = "Colores de la selección"
|
||||
"selection.createColorStyle" = "Crear estilo de color"
|
||||
"selection.detachColor" = "Separar color de la selección"
|
||||
"selection.selectColor" = "Seleccionar capas con este color"
|
||||
"selection.setPaint" = "Cambiar color de la selección"
|
||||
|
||||
@@ -328,11 +328,13 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) {
|
||||
crate::live::draw(app, &painter, &ctx);
|
||||
crate::live::agent::draw(app, &painter, &ctx);
|
||||
crate::live::chat_box(app, &ctx);
|
||||
crate::live::spotlight_banner(app, &ctx, rect);
|
||||
// The other banners float below the strip that says the session is disconnected.
|
||||
let banners = rect.with_min_y(rect.min.y + crate::live::connection_banner(app, &ctx, rect));
|
||||
crate::live::spotlight_banner(app, &ctx, banners);
|
||||
crate::comments::popovers(app, &ctx);
|
||||
crate::versions::preview_banner(app, &ctx, rect);
|
||||
crate::branch_ui::banner(app, &ctx, rect);
|
||||
crate::dev_mode::focus_bar(app, &ctx, rect);
|
||||
crate::versions::preview_banner(app, &ctx, banners);
|
||||
crate::branch_ui::banner(app, &ctx, banners);
|
||||
crate::dev_mode::focus_bar(app, &ctx, banners);
|
||||
// The cursor: the tool's, unless something on the canvas with its own has the pointer.
|
||||
app.canvas.cursor = None;
|
||||
if let (true, Some(at)) = (own_cursor && resp.hovered(), ctx.input(|i| i.pointer.hover_pos())) {
|
||||
|
||||
@@ -41,11 +41,16 @@ enum Drag {
|
||||
type UnitRect = (f64, f64, f64, f64);
|
||||
|
||||
/// The paint list a picker paint at an index belongs to on layer `n`, as the Fill section and the
|
||||
/// colour picker list it: for fills, a text's characters' shared fills (`character_fills`: the
|
||||
/// layer's own when the characters have none), else the layer's strokes. None when a text's
|
||||
/// characters have different fills. Writes go through `fill.set`, which moves the characters'
|
||||
/// list to the layer first, so the handles read and write the same paint (#1856).
|
||||
fn edited_list(n: &figcraft_doc::Node, fills: bool) -> Option<Vec<Paint>> {
|
||||
/// colour picker list it: the selected regions' own fills while regions of it are selected in
|
||||
/// vector edit mode (#1875); else, for fills, a text's characters' shared fills (`character_fills`:
|
||||
/// the layer's own when the characters have none, #1856), or the layer's strokes. None when those
|
||||
/// regions' or characters' fills differ. Writes go through `fill.set`, which edits the selected
|
||||
/// regions or moves the characters' list to the layer first, so the handles read and write the
|
||||
/// same paint.
|
||||
fn edited_list(app: &FigApp, n: &figcraft_doc::Node, fills: bool) -> Option<Vec<Paint>> {
|
||||
if fills && let Some(regions) = figcraft_engine::vectoredit::selected_region_fills(&app.session, n.id) {
|
||||
return regions;
|
||||
}
|
||||
if fills { figcraft_engine::cmd::lists::character_fills(n) } else { Some(n.strokes.clone()) }
|
||||
}
|
||||
|
||||
@@ -62,7 +67,7 @@ fn crop_target(app: &FigApp) -> Option<(NodeId, bool, usize, ImagePaint, UnitRec
|
||||
};
|
||||
let doc = app.session.doc().ok()?;
|
||||
let n = doc.node(id)?;
|
||||
let list = edited_list(n, fills)?;
|
||||
let list = edited_list(app, n, fills)?;
|
||||
let PaintKind::Image(img) = &list.get(index)?.kind else { return None };
|
||||
if img.scale_mode != ImageScaleMode::Crop {
|
||||
return None;
|
||||
@@ -229,7 +234,7 @@ fn gradient_target(app: &FigApp) -> Option<(NodeId, bool, usize, figcraft_color:
|
||||
return None;
|
||||
}
|
||||
let n = app.session.doc().ok()?.node(id)?;
|
||||
let list = edited_list(n, *fills)?;
|
||||
let list = edited_list(app, n, *fills)?;
|
||||
match &list.get(*index)?.kind {
|
||||
PaintKind::Gradient(g) => Some((id, *fills, *index, g.clone())),
|
||||
_ => None,
|
||||
@@ -269,7 +274,7 @@ fn line_param(a: Pos2, b: Pos2, p: Pos2) -> Option<(f64, f32)> {
|
||||
|
||||
fn set_gradient(app: &mut FigApp, id: NodeId, fills: bool, index: usize, g: figcraft_color::Gradient) {
|
||||
let Some(n) = app.session.doc().ok().and_then(|d| d.node(id)).cloned() else { return };
|
||||
let Some(list) = edited_list(&n, fills) else { return };
|
||||
let Some(list) = edited_list(app, &n, fills) else { return };
|
||||
let Some(mut paint) = list.get(index).cloned() else { return };
|
||||
paint.kind = PaintKind::Gradient(g);
|
||||
let cmd = if fills { "fill.set" } else { "stroke.set" };
|
||||
@@ -693,7 +698,7 @@ fn apply(app: &mut FigApp, drag: &Drag, pos: Pos2, shift: bool) {
|
||||
Drag::Gradient { id, fills, index, which } => {
|
||||
let Some(u) = screen_to_unit(app, *id, pos) else { return };
|
||||
let Some(n) = app.session.doc().ok().and_then(|d| d.node(*id)).cloned() else { return };
|
||||
let Some(list) = edited_list(&n, *fills) else { return };
|
||||
let Some(list) = edited_list(app, &n, *fills) else { return };
|
||||
let Some(mut paint) = list.get(*index).cloned() else { return };
|
||||
if let PaintKind::Gradient(g) = &mut paint.kind {
|
||||
match which {
|
||||
@@ -768,7 +773,7 @@ fn apply(app: &mut FigApp, drag: &Drag, pos: Pos2, shift: bool) {
|
||||
(ax.min(ax + nw), ay.min(ay + nh), ax.max(ax + nw), ay.max(ay + nh))
|
||||
};
|
||||
let Some(n) = app.session.doc().ok().and_then(|d| d.node(*id)).cloned() else { return };
|
||||
let Some(list) = edited_list(&n, *fills) else { return };
|
||||
let Some(list) = edited_list(app, &n, *fills) else { return };
|
||||
let Some(mut paint) = list.get(*index).cloned() else { return };
|
||||
if let PaintKind::Image(img) = &mut paint.kind {
|
||||
img.crop = Some(ImagePaint::crop_from_rect(r.0, r.1, r.2, r.3));
|
||||
@@ -793,3 +798,5 @@ fn apply(app: &mut FigApp, drag: &Drag, pos: Pos2, shift: bool) {
|
||||
|
||||
#[cfg(test)]
|
||||
mod character_fill_tests;
|
||||
#[cfg(test)]
|
||||
mod region_tests;
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
//! The canvas paint handles with a region of a vector selected in edit mode (#1875): they read
|
||||
//! and write the paint the colour picker shows, the region's own, not the layer's.
|
||||
|
||||
use figcraft_color::{Color, Gradient, GradientKind, Paint, PaintKind};
|
||||
use serde_json::json;
|
||||
|
||||
use super::{gradient_target, set_gradient};
|
||||
use crate::colorpicker::PickerTarget;
|
||||
use crate::layers_drag_tests::Ui;
|
||||
|
||||
#[test]
|
||||
fn the_gradient_handles_edit_a_selected_regions_own_paint() {
|
||||
let mut s = figcraft_engine::Session::new();
|
||||
let id = crate::region_fill_rows_tests::two_region_vector(&mut s);
|
||||
s.execute("vector.edit.begin", &json!({"id": id.0})).unwrap();
|
||||
s.execute("vector.edit.select", &json!({"regions": [1]})).unwrap();
|
||||
// The region's own paint: a gradient at half opacity; the layer keeps its solid grey.
|
||||
let mut paint = Paint::gradient(Gradient::default_for(GradientKind::Linear, Color::BLACK));
|
||||
paint.opacity = 0.5;
|
||||
s.execute("fill.set", &json!({"ids": [id.0], "paint": paint})).unwrap();
|
||||
let mut u = Ui::new(s);
|
||||
u.app.ui.picker = Some(PickerTarget::Paint { fills: true, index: 0, ids: vec![id] });
|
||||
let (at, fills, index, g) = gradient_target(&u.app).expect("the handles show the region's gradient");
|
||||
assert_eq!((at, fills, index), (id, true, 0));
|
||||
let mut moved = g.clone();
|
||||
moved.from = (0.1, 0.2);
|
||||
set_gradient(&mut u.app, id, true, 0, moved);
|
||||
let doc = u.app.session.doc().unwrap();
|
||||
let n = doc.node(id).unwrap();
|
||||
let figcraft_doc::NodeKind::Vector { network } = &n.kind else { panic!("not a vector") };
|
||||
let region = network.regions[1].fills.clone().unwrap();
|
||||
assert!(matches!(®ion[0].kind, PaintKind::Gradient(x) if x.from == (0.1, 0.2)), "{region:?}");
|
||||
assert_eq!(region[0].opacity, 0.5, "the region's paint keeps its own opacity");
|
||||
assert!(matches!(n.fills[0].kind, PaintKind::Solid { .. }), "the layer's fill is untouched: {:?}", n.fills);
|
||||
}
|
||||
@@ -434,8 +434,10 @@ fn pen_overlay(app: &FigApp, painter: &egui::Painter, zoom: f64) {
|
||||
if !ov.pen.is_empty() {
|
||||
let pts: Vec<Pos2> = ov.pen.iter().map(|[x, y]| app.to_screen(*x, *y)).collect();
|
||||
if app.session.tool.tool == ToolId::Pencil {
|
||||
// The stroke it will make, in its colour and weight (at least a point when zoomed out).
|
||||
let (color, weight) = figcraft_engine::tools::PENCIL_STROKE;
|
||||
// The stroke it will make, in its colour and weight (at least a point when zoomed out):
|
||||
// white over a dark page or frame, as the stroke will be (#1741).
|
||||
let (default, weight) = figcraft_engine::tools::PENCIL_STROKE;
|
||||
let color = ov.pen_color.unwrap_or(default);
|
||||
painter.add(Shape::line(pts, stroke(doc_c32(painter.ctx(), color), ((weight * zoom) as f32).max(1.0))));
|
||||
} else {
|
||||
for [x0, y0, x1, y1] in &ov.pen_handles {
|
||||
|
||||
@@ -186,6 +186,23 @@ fn the_pencil_previews_its_stroke_in_its_colour_and_weight() {
|
||||
assert!((w - 1.0).abs() < 0.01, "at least a point: {w}");
|
||||
}
|
||||
|
||||
/// Over a dark page the Pencil's preview is white, as the stroke it makes will be (#1741).
|
||||
#[test]
|
||||
fn the_pencil_previews_white_over_a_dark_page() {
|
||||
let mut u = Ui::new(Session::new());
|
||||
u.app.run("page.setBackground", json!({"color": "#1E1E1E"}));
|
||||
u.app.run("tool.set", json!({"tool": "pencil"}));
|
||||
let white = egui::epaint::ColorMode::Solid(crate::theme::c32(figcraft_color::Color::WHITE));
|
||||
let at = |u: &Ui, x: f64, y: f64| u.app.to_screen(x, y);
|
||||
u.button(at(&u, 10.0, 10.0), true);
|
||||
for i in 1..=6 {
|
||||
let p = at(&u, 10.0 + 12.0 * f64::from(i), 10.0 + 6.0 * f64::from(i % 2));
|
||||
u.frame(vec![egui::Event::PointerMoved(p)]);
|
||||
}
|
||||
let shapes = flat(&u.frame_output(vec![]).shapes);
|
||||
assert!(shapes.iter().any(|s| matches!(s, Shape::Path(p) if !p.closed && p.points.len() >= 3 && p.stroke.color == white)), "a white preview");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selected_layer_shows_its_constraint_guides_in_its_frame() {
|
||||
// A child pinned left (the default) in a frame without auto layout: a dashed guide runs from its
|
||||
|
||||
@@ -1036,7 +1036,10 @@ fn ui_key(app: &mut FigApp, ctx: &Context, p: &Value) -> Result<Value, String> {
|
||||
{
|
||||
return app.session.execute("tool.crosshair", &json!({"dx": dx, "dy": dy, "big": m.shift})).map_err(|e| e.to_string());
|
||||
}
|
||||
let (cmd, params) = if (m.cmd || m.ctrl) && m.alt {
|
||||
// Otherwise, with nothing selected the arrows pan the view, as the window's own key path does.
|
||||
let (cmd, params) = if app.session.selection().is_empty() {
|
||||
("view.pan", json!({"dx": dx, "dy": dy, "big": m.shift}))
|
||||
} else if (m.cmd || m.ctrl) && m.alt {
|
||||
// Rotate a degree, 15 with Shift: down and right clockwise, up and left back, about
|
||||
// the selection's rotation origin; nothing while points are being edited.
|
||||
if app.session.ds().is_ok_and(|d| d.vector_edit.is_some()) {
|
||||
|
||||
@@ -288,6 +288,9 @@ fn header(app: &mut FigApp, ui: &mut Ui, open: &mut bool) {
|
||||
// Import and export, left of Close.
|
||||
let bar = Rect::from_min_max(pos2(r.max.x - 280.0, r.min.y + 10.0), pos2(r.max.x - 40.0, r.max.y - 10.0));
|
||||
let mut bar = ui.new_child(UiBuilder::new().max_rect(bar).layout(egui::Layout::right_to_left(egui::Align::Center)));
|
||||
// The window lays itself out without item spacing (set by the caller); the buttons in this bar
|
||||
// keep the same gap between them as the one between Export and the Close button (#1754).
|
||||
bar.spacing_mut().item_spacing.x = 16.0;
|
||||
let export = widgets::button(&mut bar, tr("Export…"), false, true);
|
||||
crate::right::menu_popup(&export).show(|ui| {
|
||||
for (label, format) in [(tr("Variables JSON…"), "json"), (tr("CSS custom properties…"), "css"), (tr("Dart constants for Flutter…"), "dart")]
|
||||
|
||||
@@ -1215,6 +1215,62 @@ fn sidebar_field_text_stays_in_place_on_focus() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Page section's opacity field edits the page background's alpha (#1748; it was a label),
|
||||
/// one undo step per commit, and the hex field keeps that opacity unless the typed colour
|
||||
/// carries its own.
|
||||
#[test]
|
||||
fn the_page_background_opacity_field_sets_the_page_colour_alpha() {
|
||||
let mut u = Ui::new(Session::new());
|
||||
u.ctx.enable_accesskit();
|
||||
u.frame(vec![]);
|
||||
let page_bg = |u: &Ui| {
|
||||
let page = u.app.session.page().unwrap();
|
||||
match &u.app.session.doc().unwrap().node(page).unwrap().kind {
|
||||
figcraft_doc::NodeKind::Page { background, .. } => *background,
|
||||
_ => panic!("the page"),
|
||||
}
|
||||
};
|
||||
// Within an 8-bit step: the colour travels as RRGGBBAA.
|
||||
let near = |a: f32, b: f32| (a - b).abs() < 1.0 / 255.0;
|
||||
assert!(near(page_bg(&u).a, 1.0));
|
||||
let steps = undo_steps(&u);
|
||||
type_into(&mut u, "Opacity", "50", Key::Enter);
|
||||
assert!(near(page_bg(&u).a, 0.5), "{:?}", page_bg(&u));
|
||||
assert_eq!(undo_steps(&u), steps + 1, "one undo step for the commit");
|
||||
// No label is drawn, so the field's leading strip scrubs it: a percent a point, live, and one
|
||||
// undo step for the whole drag.
|
||||
let edge = lead(&u, Id::unique("pagebg_a"));
|
||||
drag(&mut u, edge, -25.0, Modifiers::NONE);
|
||||
assert!(near(page_bg(&u).a, 0.25), "{:?}", page_bg(&u));
|
||||
assert_eq!(undo_steps(&u), steps + 2, "one undo step for the whole scrub");
|
||||
u.app.run("edit.undo", json!({}));
|
||||
assert!(near(page_bg(&u).a, 0.5), "undo takes back the scrub alone");
|
||||
// The hex field keeps the opacity when the typed colour has none, and takes one it carries.
|
||||
let hex = |u: &mut Ui| u.ctx.read_response(Id::unique("pagebg").with("click")).expect("the hex field").rect.center();
|
||||
let at = hex(&mut u);
|
||||
click(&mut u, at);
|
||||
u.frame(vec![Event::Text("FF0000".into())]);
|
||||
key(&mut u, Key::Enter, Modifiers::NONE);
|
||||
let c = page_bg(&u);
|
||||
assert!(near(c.r, 1.0) && near(c.g, 0.0) && near(c.a, 0.5), "{c:?}");
|
||||
let at = hex(&mut u);
|
||||
click(&mut u, at);
|
||||
u.frame(vec![Event::Text("00FF0080".into())]);
|
||||
key(&mut u, Key::Enter, Modifiers::NONE);
|
||||
let c = page_bg(&u);
|
||||
assert!(near(c.g, 1.0) && near(c.a, 128.0 / 255.0), "{c:?}");
|
||||
// Eight digits asking for opaque set 100 %: an alpha of 1 in the text is not "no alpha".
|
||||
let at = hex(&mut u);
|
||||
click(&mut u, at);
|
||||
u.frame(vec![Event::Text("0000FFFF".into())]);
|
||||
key(&mut u, Key::Enter, Modifiers::NONE);
|
||||
let c = page_bg(&u);
|
||||
assert!(near(c.b, 1.0) && near(c.a, 1.0), "{c:?}");
|
||||
assert_eq!(undo_steps(&u), steps + 4);
|
||||
u.app.run("edit.undo", json!({}));
|
||||
assert!(near(page_bg(&u).g, 1.0) && near(page_bg(&u).a, 128.0 / 255.0), "undo takes back the last colour alone");
|
||||
}
|
||||
|
||||
/// "You can also hover the input field itself and hold down the modifier key: Mac: ⌥ Option
|
||||
/// Windows: Alt" to scrub it (Adjust alignment, rotation, position, and dimensions). Alt is what
|
||||
/// makes the drag a scrub there, not the fine rate: a point moves a step, as on the label. Without
|
||||
|
||||
@@ -207,6 +207,8 @@ icons! {
|
||||
Online,
|
||||
/// In a live session others get into: a point sending waves to both sides.
|
||||
LiveShared,
|
||||
/// Disconnected from a live session: the point and its waves, struck through.
|
||||
LiveDisconnected,
|
||||
/// A file of yours on a server that only you get into: a point inside a closed ring.
|
||||
LivePrivate,
|
||||
/// A design file: a pen nib leaning to the left, its grip filled.
|
||||
|
||||
@@ -834,6 +834,14 @@ fn draw(p: &P, icon: Icon) {
|
||||
p.arc(8.0, 8.0, r, PI - FRAC_PI_4, PI + FRAC_PI_4);
|
||||
}
|
||||
}
|
||||
LiveDisconnected => {
|
||||
p.dot(8.0, 8.0, 1.6);
|
||||
for r in [3.6, 6.0] {
|
||||
p.arc(8.0, 8.0, r, -FRAC_PI_4, FRAC_PI_4);
|
||||
p.arc(8.0, 8.0, r, PI - FRAC_PI_4, PI + FRAC_PI_4);
|
||||
}
|
||||
p.line(3.0, 13.0, 13.0, 3.0);
|
||||
}
|
||||
LivePrivate => {
|
||||
p.dot(8.0, 8.0, 1.6);
|
||||
p.circle(8.0, 8.0, 5.0);
|
||||
|
||||
@@ -46,3 +46,36 @@ fn control_inspection_rejects_invalid_options_consistently() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `ui.key` with an arrow and nothing selected pans the view, as the window's own key path does
|
||||
/// (before, it answered that nothing was selected); with a selection it nudges (Shift: farther).
|
||||
#[test]
|
||||
fn control_key_arrows_pan_with_nothing_selected() {
|
||||
let mut u = Ui::new(Session::new());
|
||||
let r =
|
||||
call(&mut u, "engine.execute", json!({"command": "shape.rectangle", "params": {"x": 0, "y": 0, "width": 40, "height": 40}})).unwrap()["id"]
|
||||
.clone();
|
||||
u.app.run("select.set", json!({"ids": []}));
|
||||
u.app.run("view.set", json!({"zoom": 2.0, "cx": 0, "cy": 0}));
|
||||
let view = |u: &Ui| {
|
||||
let v = &u.app.session.ds().unwrap().view;
|
||||
(v.cx, v.cy)
|
||||
};
|
||||
call(&mut u, "ui.key", json!({"key": "ArrowRight"})).unwrap();
|
||||
assert_eq!(view(&u), (10.0, 0.0), "20 screen pixels at 200%");
|
||||
call(&mut u, "ui.key", json!({"key": "ArrowUp", "shift": true})).unwrap();
|
||||
assert_eq!(view(&u), (10.0, -100.0), "Shift: ten times as far");
|
||||
u.app.run("select.set", json!({"ids": [r]}));
|
||||
call(&mut u, "ui.key", json!({"key": "ArrowRight"})).unwrap();
|
||||
assert_eq!(view(&u), (10.0, -100.0), "with a selection the view stays");
|
||||
let id = figcraft_engine::params::id_of(&r).unwrap();
|
||||
assert_eq!(u.app.session.doc().unwrap().world_bounds(id).unwrap().x0, 1.0, "the selection moved instead");
|
||||
// With a shape tool chosen and nothing selected the arrows move the placement crosshair
|
||||
// first (#1869), and the view stays.
|
||||
u.app.run("select.set", json!({"ids": []}));
|
||||
u.app.run("tool.rectangle", json!({}));
|
||||
let before = view(&u);
|
||||
call(&mut u, "ui.key", json!({"key": "ArrowRight"})).unwrap();
|
||||
assert_eq!(view(&u), before, "the crosshair, not a pan");
|
||||
assert!(u.app.session.crosshair().is_some());
|
||||
}
|
||||
|
||||
@@ -227,6 +227,8 @@ mod proto_reorder_tests;
|
||||
#[cfg(test)]
|
||||
mod proto_responsive_tests;
|
||||
#[cfg(test)]
|
||||
mod region_fill_rows_tests;
|
||||
#[cfg(test)]
|
||||
mod resources_tests;
|
||||
#[cfg(test)]
|
||||
mod sampled_color_tests;
|
||||
|
||||
@@ -439,6 +439,67 @@ pub fn chat_box(app: &mut FigApp, ctx: &egui::Context) {
|
||||
app.ui.live.chat = Some(chat);
|
||||
}
|
||||
|
||||
/// While the active document's live session is disconnected: a thin strip across the top of the
|
||||
/// canvas that says so, with what can be done about it. Returns how much of the canvas it takes.
|
||||
pub fn connection_banner(app: &mut FigApp, ctx: &egui::Context, canvas: Rect) -> f32 {
|
||||
const H: f32 = 30.0;
|
||||
let live = app.session.live();
|
||||
if !app.session.docs.get(app.session.active).is_some_and(|d| crate::tabs::live_lost(app, d.uid)) {
|
||||
return 0.0;
|
||||
}
|
||||
let (text, retry, gone) = match &live.status {
|
||||
Status::Failed { reason } => {
|
||||
(trf("Not connected: {reason}. Your work is still in this tab.", &[("reason", &failure_text(reason))]), Some(tr("Try again")), true)
|
||||
}
|
||||
Status::Reconnecting { .. } => {
|
||||
(tr("Disconnected. Your edits stay here and sync when the connection returns. Reconnecting…").to_string(), Some(tr("Retry now")), false)
|
||||
}
|
||||
_ => (tr("Disconnected. Reconnecting…").to_string(), None, false),
|
||||
};
|
||||
let t = Tokens::get(ctx);
|
||||
let ink = text_on(t.danger);
|
||||
let (mut try_now, mut save, mut dismiss) = (false, false, false);
|
||||
let strip = Rect::from_min_size(canvas.min, vec2(canvas.width(), H));
|
||||
egui::Area::new(egui::Id::unique("live_connection_banner")).order(egui::Order::Foreground).fixed_pos(strip.min).show(ctx, |ui| {
|
||||
ui.set_min_size(strip.size());
|
||||
ui.set_max_size(strip.size());
|
||||
ui.painter().rect_filled(strip, egui::CornerRadius::ZERO, t.danger);
|
||||
let button = |ui: &mut Ui, label: &str| {
|
||||
ui.add(
|
||||
egui::Button::new(egui::RichText::new(label).font(regular(11.0)).color(ink))
|
||||
.fill(Color32::TRANSPARENT)
|
||||
.stroke(Stroke::new(1.0, ink))
|
||||
.corner_radius(egui::CornerRadius::same(4)),
|
||||
)
|
||||
.clicked()
|
||||
};
|
||||
let inner = strip.shrink2(vec2(12.0, 0.0));
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(inner).layout(egui::Layout::right_to_left(egui::Align::Center)), |ui| {
|
||||
ui.spacing_mut().item_spacing.x = 8.0;
|
||||
if gone {
|
||||
dismiss = button(ui, tr("Dismiss"));
|
||||
save = button(ui, tr("Save a copy…"));
|
||||
}
|
||||
if let Some(label) = retry {
|
||||
try_now = button(ui, label);
|
||||
}
|
||||
ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
|
||||
ui.add(egui::Label::new(egui::RichText::new(text).font(regular(11.0)).color(ink)).truncate());
|
||||
});
|
||||
});
|
||||
});
|
||||
if try_now {
|
||||
app.run("collab.reconnect", json!({}));
|
||||
}
|
||||
if save {
|
||||
app.save_as_dialog();
|
||||
}
|
||||
if dismiss {
|
||||
app.run("collab.leave", json!({}));
|
||||
}
|
||||
H
|
||||
}
|
||||
|
||||
/// While you spotlight, or someone does and you stopped following them: a banner on the canvas to
|
||||
/// stop, or to follow again.
|
||||
pub fn spotlight_banner(app: &mut FigApp, ctx: &egui::Context, canvas: Rect) {
|
||||
|
||||
@@ -97,3 +97,52 @@ fn leave_takes_a_session_id() {
|
||||
assert_eq!(h.app.session.execute("collab.leave", &json!({"session": id})).unwrap()["ended"], true);
|
||||
assert!(h.app.session.live.get(id).is_none());
|
||||
}
|
||||
|
||||
/// Joined, with the file in its tab.
|
||||
fn joined(h: &mut Harness) -> u64 {
|
||||
join(h);
|
||||
h.welcome();
|
||||
h.sync();
|
||||
h.app.session.docs[h.app.session.active].uid
|
||||
}
|
||||
|
||||
const STRIP: &str = "Disconnected. Your edits stay here and sync when the connection returns. Reconnecting…";
|
||||
|
||||
#[test]
|
||||
fn a_dropped_connection_shows_on_the_tab_and_across_the_canvas_with_retry() {
|
||||
let (mut h, _) = Harness::new();
|
||||
let uid = joined(&mut h);
|
||||
assert!(!crate::tabs::live_lost(&h.app, uid));
|
||||
assert!(!has_text(&h.frames(2), STRIP), "not while connected");
|
||||
h.send(vec![LiveEvent::Status(Status::Reconnecting { attempt: 3 })]);
|
||||
let shapes = h.frames(2);
|
||||
assert!(crate::tabs::live_lost(&h.app, uid));
|
||||
assert!(has_text(&shapes, STRIP));
|
||||
h.click(text_center(&shapes, "Retry now"));
|
||||
assert!(h.app.ui.last_error.is_none(), "{:?}", h.app.ui.last_error);
|
||||
assert_eq!(h.app.session.live().status, Status::Reconnecting { attempt: 3 });
|
||||
// Back: the strip goes.
|
||||
h.welcome();
|
||||
assert!(!has_text(&h.frames(2), STRIP));
|
||||
assert!(!crate::tabs::live_lost(&h.app, uid));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_that_ended_stays_on_its_tab_until_dismissed() {
|
||||
let (mut h, _) = Harness::new();
|
||||
let uid = joined(&mut h);
|
||||
h.send(vec![LiveEvent::Status(Status::Failed { reason: "The host refused: this link isn't valid".into() })]);
|
||||
let shapes = h.frames(2);
|
||||
assert!(crate::tabs::live_lost(&h.app, uid));
|
||||
assert!(has_text(&shapes, "Not connected: The host refused: this link isn't valid. Your work is still in this tab."));
|
||||
assert!(has_text(&shapes, "Save a copy…"));
|
||||
h.click(text_center(&shapes, "Try again"));
|
||||
assert_eq!(h.app.session.live().status, Status::Connecting);
|
||||
assert!(crate::tabs::live_lost(&h.app, uid), "still disconnected while it tries");
|
||||
h.send(vec![LiveEvent::Status(Status::Failed { reason: "no".into() })]);
|
||||
let shapes = h.frames(2);
|
||||
h.click(text_center(&shapes, "Dismiss"));
|
||||
assert!(!has_text(&h.frames(2), "Try again"));
|
||||
assert!(!crate::tabs::live_lost(&h.app, uid));
|
||||
assert_eq!(h.app.session.live().status, Status::Off);
|
||||
}
|
||||
|
||||
@@ -126,7 +126,7 @@ impl Harness {
|
||||
color: "#14AE5C".into(),
|
||||
file_name: "Shared".into(),
|
||||
pages: vec![],
|
||||
link: String::new(),
|
||||
link: "figcraft://join?host=127.0.0.1:47900&file=f&token=t".into(),
|
||||
url: String::new(),
|
||||
address: "127.0.0.1:47900".into(),
|
||||
network: false,
|
||||
|
||||
@@ -317,27 +317,50 @@ fn design(app: &mut FigApp, ui: &mut Ui) {
|
||||
/// Draw the page section: background and colour profile, local variables/styles, and the
|
||||
/// page export section.
|
||||
fn page_section(app: &mut FigApp, ui: &mut Ui, doc: &Document) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let Ok(page) = app.session.page() else { return };
|
||||
let bg = match doc.node(page).map(|n| &n.kind) {
|
||||
Some(NodeKind::Page { background, .. }) => *background,
|
||||
_ => figcraft_color::Color::DEFAULT_PAGE,
|
||||
};
|
||||
widgets::section_header(ui, tr("Page"), &[], false);
|
||||
let mut new_hex = None;
|
||||
// The new colour and, from a scrub, whether the scrub is over (live edits stay one undo step).
|
||||
let mut new_color: Option<(figcraft_color::Color, Option<bool>)> = None;
|
||||
row(ui, 32.0, |ui| {
|
||||
let p = Paint::solid(bg);
|
||||
let sw = widgets::swatch(ui, &p, 16.0);
|
||||
app.picker_control(crate::colorpicker::PickerTarget::PageBackground, &sw);
|
||||
if let Some(h) = widgets::text_field(ui, Id::unique("pagebg"), &bg.to_hex(), 96.0, "") {
|
||||
new_hex = Some(h);
|
||||
// A typed colour keeps the page's opacity unless it carries one: 4 or 8 hex digits
|
||||
// (`FF000080`; `FF0000FF` asks for opaque).
|
||||
if let Some(h) = widgets::text_field(ui, Id::unique("pagebg"), &bg.to_hex(), 96.0, "")
|
||||
&& let Some(c) = figcraft_color::Color::from_hex_or_name(&h)
|
||||
{
|
||||
let digits = h.trim().trim_start_matches('#');
|
||||
let carries_alpha = matches!(digits.len(), 4 | 8) && digits.chars().all(|ch| ch.is_ascii_hexdigit());
|
||||
new_color = Some((if carries_alpha { c } else { c.with_alpha(bg.a) }, None));
|
||||
}
|
||||
// The opacity: a field like every other opacity field, not a label (#1748).
|
||||
let alpha = |v: f64| bg.with_alpha((v / 100.0).clamp(0.0, 1.0) as f32);
|
||||
let shown = Some(f64::from((bg.a * 100.0).round()));
|
||||
match widgets::number_field(ui, Id::unique("pagebg_a"), Lead::Named(tr("Opacity")), shown, "%", 56.0, 1.0) {
|
||||
Some(FieldEdit::Set(v)) => new_color = Some((alpha(v), None)),
|
||||
Some(FieldEdit::Scrub(v, done)) => new_color = Some((alpha(v), Some(done))),
|
||||
None => {}
|
||||
}
|
||||
widgets::label(ui, "100 %", t.text);
|
||||
});
|
||||
if let Some(h) = new_hex
|
||||
&& let Some(c) = figcraft_color::Color::from_hex_or_name(&h)
|
||||
{
|
||||
app.run("page.setBackground", json!({"color": c.to_css_hex()}));
|
||||
if let Some((c, scrub)) = new_color {
|
||||
let p = json!({"color": c.to_css_hex()});
|
||||
match scrub {
|
||||
None => {
|
||||
app.run("page.setBackground", p);
|
||||
}
|
||||
Some(done) => {
|
||||
let _ = app.session.begin_interaction("Page background");
|
||||
let _ = app.session.execute("page.setBackground", &p);
|
||||
if done {
|
||||
let _ = app.session.commit_interaction();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
widgets::separator(ui);
|
||||
widgets::section_header(ui, tr("Color profile"), &[], false);
|
||||
|
||||
@@ -293,21 +293,28 @@ pub(super) fn paints(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeI
|
||||
}
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let ids = sel.to_vec();
|
||||
// A text's fills are what its characters show: one list they share, or mixed (#1856).
|
||||
let list = common(doc, sel, |n| if fills { figcraft_engine::cmd::lists::character_fills(n) } else { Some(n.strokes.clone()) }).flatten();
|
||||
// Regions selected in vector edit mode: their own fills (#1875); the fill commands edit those too.
|
||||
let region_list = match sel {
|
||||
[id] if fills => figcraft_engine::vectoredit::selected_region_fills(&app.session, *id),
|
||||
_ => None,
|
||||
};
|
||||
// The fill style, a variable bound to the layer's fill and the image crop are the layer's:
|
||||
// they stay off a region's rows.
|
||||
let region = region_list.is_some();
|
||||
// Else a text's fills are what its characters show: one list they share, or mixed (#1856).
|
||||
let list = region_list.unwrap_or_else(|| {
|
||||
common(doc, sel, |n| if fills { figcraft_engine::cmd::lists::character_fills(n) } else { Some(n.strokes.clone()) }).flatten()
|
||||
});
|
||||
let title = if fills { tr("Fill") } else { tr("Stroke") };
|
||||
let empty = list.as_ref().is_none_or(|l| l.is_empty());
|
||||
let slot = if fills { StyleSlot::Fill } else { StyleSlot::Stroke };
|
||||
// The section's right-click menu adds the copied paint (`fill.paste` / `stroke.paste`).
|
||||
let paste = if fills { tr("Paste fill") } else { tr("Paste stroke") };
|
||||
let (clicked, header) = widgets::section_header_resp(
|
||||
ui,
|
||||
title,
|
||||
&[(Icon::Styles, tr("Styles")), (Icon::Plus, if fills { tr("Add fill") } else { tr("Add stroke") })],
|
||||
empty,
|
||||
);
|
||||
let add = (Icon::Plus, if fills { tr("Add fill") } else { tr("Add stroke") });
|
||||
let buttons = if region { vec![add] } else { vec![(Icon::Styles, tr("Styles")), add] };
|
||||
let (clicked, header) = widgets::section_header_resp(ui, title, &buttons, empty);
|
||||
if let Some(i) = clicked {
|
||||
if i == 1 {
|
||||
if buttons.get(i).is_some_and(|(icon, _)| *icon == Icon::Plus) {
|
||||
// The new paint goes on top; open its picker. A mixed selection has no one index to edit.
|
||||
if app.run(if fills { "fill.add" } else { "stroke.add" }, json!({"ids": ids})).is_some()
|
||||
&& let Some(l) = &list
|
||||
@@ -324,14 +331,16 @@ pub(super) fn paints(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeI
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
style_picker::chip(app, ui, doc, &ids, slot);
|
||||
if !region {
|
||||
style_picker::chip(app, ui, doc, &ids, slot);
|
||||
}
|
||||
match &list {
|
||||
None => widgets::note(ui, tr("Click + to replace mixed content"), t.text_secondary),
|
||||
Some(l) => {
|
||||
// The last paint is on top: shown first. Rows drag to reorder.
|
||||
let mut drag = ListDrag::new(ui, if fills { "fills" } else { "strokes" });
|
||||
for (i, p) in l.iter().enumerate().rev() {
|
||||
let r = paint_row(app, ui, &ids, i, p, fills);
|
||||
let r = paint_row(app, ui, &ids, i, p, fills, region);
|
||||
drag.row(ui, i, r, r, || paint_label(p));
|
||||
}
|
||||
if let Some((from, to)) = drag.finish(ui) {
|
||||
@@ -441,7 +450,9 @@ pub(super) fn paints(app: &mut FigApp, ui: &mut Ui, doc: &Document, sel: &[NodeI
|
||||
}
|
||||
|
||||
/// Paint `i`'s row (swatch, colour or kind, opacity, visibility, remove); returns its area.
|
||||
fn paint_row(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], i: usize, p: &Paint, fills: bool) -> Rect {
|
||||
/// One paint's row; `region`: a row of the regions selected in vector edit mode (#1875), which
|
||||
/// leaves out what belongs to the layer (its variable binding, the image crop).
|
||||
fn paint_row(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], i: usize, p: &Paint, fills: bool, region: bool) -> Rect {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let ids = ids.to_vec();
|
||||
let cmd = if fills { "fill.set" } else { "stroke.set" };
|
||||
@@ -450,7 +461,7 @@ fn paint_row(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], i: usize, p: &Paint,
|
||||
let (sresp, e) = widgets::paint_field(ui, Id::unique(("swatch", fills, i)), Id::unique(("pop", fills, i)), p, w, |child, text_r| {
|
||||
let r = child.max_rect();
|
||||
// The variable bound to this paint's colour (its key on the layers: `fill` or `fills/<i>/color`).
|
||||
let bound = app.session.doc().ok().and_then(|d| {
|
||||
let bound = app.session.doc().ok().filter(|_| !region).and_then(|d| {
|
||||
let key = ids.first().and_then(|id| d.node(*id)).and_then(|n| figcraft_engine::cmd::lists::paint_binding_key(n, fills, i))?;
|
||||
Some((key.to_string(), crate::variable_ui::bound_name(d, &ids, key)?))
|
||||
});
|
||||
@@ -491,7 +502,7 @@ fn paint_row(app: &mut FigApp, ui: &mut Ui, ids: &[NodeId], i: usize, p: &Paint,
|
||||
_ => {
|
||||
child.painter().text(pos2(text_r.min.x, r.center().y), Align2::LEFT_CENTER, paint_label(p), regular(11.0), t.text);
|
||||
// One layer's image fill: crop it on the canvas.
|
||||
if fills && ids.len() == 1 && matches!(p.kind, PaintKind::Image(_)) {
|
||||
if fills && ids.len() == 1 && !region && matches!(p.kind, PaintKind::Image(_)) {
|
||||
let cr = Rect::from_center_size(pos2(text_r.max.x - 9.0, r.center().y), vec2(18.0, 18.0));
|
||||
let cresp = child.interact(cr, Id::unique(("crop_image", i)), Sense::click()).tip(tr("Crop image"));
|
||||
icons::paint(child.painter(), cr.shrink(3.0), Icon::Crop, if cresp.hovered() { t.icon } else { t.icon_secondary });
|
||||
|
||||
@@ -4,9 +4,10 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use egui::{Id, Ui};
|
||||
use figcraft_color::Color;
|
||||
use figcraft_doc::{Document, NodeId, StyleKind, VariableType};
|
||||
use figcraft_engine::selection_colors::{PaintTarget, SelectionColor, bind_refusal, collect, in_scope};
|
||||
use figcraft_color::{Color, Paint};
|
||||
use figcraft_doc::{Document, NodeId, PublishedLibrary, Style, StyleKind, VariableType};
|
||||
use figcraft_engine::library;
|
||||
use figcraft_engine::selection_colors::{PaintTarget, SelectionColor, bind_refusal, collect, create_refusal, in_scope};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::a11y::Tip;
|
||||
@@ -65,13 +66,15 @@ pub(crate) fn toggle(app: &mut FigApp, targets: Vec<PaintTarget>, response: Opti
|
||||
}
|
||||
|
||||
/// Draw the selection-colour groups (at least two): swatch opens the picker, hex and opacity
|
||||
/// edits, style/variable detach/apply/bind, and “select layers with this color”; disabled
|
||||
/// during an interaction.
|
||||
/// edits, style/variable detach/apply/bind, a style from this file or an enabled library, Create
|
||||
/// style, and “select layers with this color”; disabled during an interaction.
|
||||
pub fn section(app: &mut FigApp, ui: &mut Ui, doc: &Arc<Document>, ids: &[NodeId]) {
|
||||
let Ok(ds) = app.session.ds() else { return };
|
||||
let interacting = ds.interaction.is_some();
|
||||
let colors = colors(ui, ds.uid, doc, ids, interacting);
|
||||
let uid = ds.uid;
|
||||
let colors = colors(ui, uid, doc, ids, interacting);
|
||||
if colors.len() < 2 {
|
||||
ui.data_mut(|d| d.remove::<CreateForm>(create_form_id()));
|
||||
return;
|
||||
}
|
||||
let t = Tokens::get(ui.ctx());
|
||||
@@ -92,7 +95,9 @@ pub fn section(app: &mut FigApp, ui: &mut Ui, doc: &Arc<Document>, ids: &[NodeId
|
||||
.as_ref()
|
||||
.and_then(|id| doc.style(id).map(|s| s.name.as_str()))
|
||||
.or_else(|| group.variable.as_ref().and_then(|id| doc.variables.get_by_id(id).map(|v| v.name.as_str())));
|
||||
let width = ui.available_width() - 60.0;
|
||||
// A linked row has a Detach button beside its Styles button.
|
||||
let buttons = if linked_name.is_some() { 92.0 } else { 60.0 };
|
||||
let width = ui.available_width() - buttons;
|
||||
let mut paint = group.paint.clone();
|
||||
if let Some(scrub) = &scrubbing
|
||||
&& scrub.targets == group.targets
|
||||
@@ -159,29 +164,15 @@ pub fn section(app: &mut FigApp, ui: &mut Ui, doc: &Arc<Document>, ids: &[NodeId
|
||||
});
|
||||
app.field_run_named(Some(edit), "Opacity", "selection.setPaint", |_| json!({"targets": group.targets, "paint": paint}));
|
||||
}
|
||||
widgets::tight_end(ui, |ui| {
|
||||
if linked_name.is_some() {
|
||||
let detach = if group.style.is_some() { tr("Detach style") } else { tr("Detach variable") };
|
||||
if icons::button(ui, Icon::Detach, 24.0, false, detach).clicked() {
|
||||
app.run("selection.detachColor", json!({"targets": group.targets}));
|
||||
}
|
||||
} else {
|
||||
let styles = icons::button(ui, Icon::Styles, 24.0, false, tr("Color styles"));
|
||||
crate::right::menu_popup(&styles).show(|ui| {
|
||||
let mut any = false;
|
||||
for style in &doc.styles {
|
||||
if !matches!(style.kind, StyleKind::Paint { .. }) {
|
||||
continue;
|
||||
}
|
||||
any = true;
|
||||
if crate::right::menu_item(ui, &style.name, "") {
|
||||
app.run("selection.applyColorStyle", json!({"targets": group.targets, "style": style.id}));
|
||||
app.ui.picker = None;
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
if !any {
|
||||
widgets::label(ui, tr("No color styles"), t.text_secondary);
|
||||
widgets::tight_end_n(ui, if linked_name.is_some() { 3 } else { 2 }, |ui| {
|
||||
let styles = icons::button(ui, Icon::Styles, 24.0, false, tr("Color styles"));
|
||||
crate::right::menu_popup(&styles).show(|ui| {
|
||||
style_items(app, ui, doc, group, &t);
|
||||
if linked_name.is_none() {
|
||||
ui.separator();
|
||||
if create_refusal(doc, &group.targets).is_none() && crate::right::menu_item(ui, tr("Create style"), "") {
|
||||
open_create_form(app, ui, doc, group);
|
||||
ui.close();
|
||||
}
|
||||
let variables: Vec<_> = doc
|
||||
.variables
|
||||
@@ -204,7 +195,13 @@ pub fn section(app: &mut FigApp, ui: &mut Ui, doc: &Arc<Document>, ids: &[NodeId
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
if linked_name.is_some() {
|
||||
let detach = if group.style.is_some() { tr("Detach style") } else { tr("Detach variable") };
|
||||
if icons::button(ui, Icon::Detach, 24.0, false, detach).clicked() {
|
||||
app.run("selection.detachColor", json!({"targets": group.targets}));
|
||||
}
|
||||
}
|
||||
if icons::button(ui, Icon::SelectColor, 24.0, false, tr("Select layers with this color")).clicked() {
|
||||
app.run("selection.selectColor", json!({"targets": group.targets}));
|
||||
@@ -217,6 +214,106 @@ pub fn section(app: &mut FigApp, ui: &mut Ui, doc: &Arc<Document>, ids: &[NodeId
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
widgets::separator(ui);
|
||||
create_form(app, ui.ctx(), uid);
|
||||
}
|
||||
|
||||
/// The paint styles a row's Styles menu offers: this file's (not library copies), then each enabled
|
||||
/// library's published ones under its name (a library this session hasn't read offers none). A choice
|
||||
/// applies the style to the row's targets.
|
||||
fn style_items(app: &mut FigApp, ui: &mut Ui, doc: &Document, group: &SelectionColor, t: &Tokens) {
|
||||
let paint = |s: &&Style| matches!(s.kind, StyleKind::Paint { .. });
|
||||
let local: Vec<&Style> = library::local_styles(doc).filter(paint).collect();
|
||||
let libs = crate::variable_ui::libraries(app, doc);
|
||||
let offered: Vec<(&PublishedLibrary, Vec<&Style>)> = libs
|
||||
.iter()
|
||||
.map(|l| (l.as_ref(), l.doc.styles.iter().filter(|s| l.manifest.style(&s.id).is_some_and(|x| x.published)).filter(paint).collect::<Vec<_>>()))
|
||||
.filter(|(_, list)| !list.is_empty())
|
||||
.collect();
|
||||
if local.is_empty() && offered.is_empty() {
|
||||
widgets::label(ui, tr("No color styles"), t.text_secondary);
|
||||
}
|
||||
for style in local {
|
||||
if crate::right::menu_item(ui, &style.name, "") {
|
||||
app.run("selection.applyColorStyle", json!({"targets": group.targets, "style": style.id}));
|
||||
app.ui.picker = None;
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
for (lib, list) in offered {
|
||||
ui.separator();
|
||||
widgets::label(ui, &lib.manifest.name, t.text_secondary);
|
||||
for style in list {
|
||||
if crate::right::menu_item(ui, &style.name, "") {
|
||||
app.run("selection.applyColorStyle", json!({"targets": group.targets, "style": style.id, "library": lib.manifest.id}));
|
||||
app.ui.picker = None;
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Create style window's state: the document and row it was opened for, and the name typed.
|
||||
#[derive(Clone)]
|
||||
struct CreateForm {
|
||||
document: u64,
|
||||
targets: Vec<PaintTarget>,
|
||||
paint: Paint,
|
||||
name: String,
|
||||
}
|
||||
|
||||
fn create_form_id() -> Id {
|
||||
Id::unique("selection_color_create_style")
|
||||
}
|
||||
|
||||
/// Open the Create style window for `group`, with the next free "Color n" name.
|
||||
fn open_create_form(app: &mut FigApp, ui: &Ui, doc: &Document, group: &SelectionColor) {
|
||||
let Ok(ds) = app.session.ds() else { return };
|
||||
let form = CreateForm {
|
||||
document: ds.uid,
|
||||
targets: group.targets.clone(),
|
||||
paint: group.paint.clone(),
|
||||
name: crate::style_picker::next_name(doc, "Color"),
|
||||
};
|
||||
app.ui.picker = None;
|
||||
ui.data_mut(|d| d.insert_temp(create_form_id(), form));
|
||||
}
|
||||
|
||||
/// The Create style window: the row's paint, a name, Cancel and Create (Enter creates). Create runs
|
||||
/// `selection.createColorStyle`; when it fails (a name in use, a row that changed) the window stays
|
||||
/// open with the name for correction.
|
||||
fn create_form(app: &mut FigApp, ctx: &egui::Context, document: u64) {
|
||||
let Some(mut form) = ctx.data(|d| d.get_temp::<CreateForm>(create_form_id())) else { return };
|
||||
if form.document != document {
|
||||
ctx.data_mut(|d| d.remove::<CreateForm>(create_form_id()));
|
||||
return;
|
||||
}
|
||||
let (mut open, mut cancel, mut create) = (true, false, false);
|
||||
crate::dialogs::window(tr("Create style"), ctx).id(create_form_id().with("window")).open(&mut open).show(ctx, |ui| {
|
||||
ui.set_width(240.0);
|
||||
ui.horizontal(|ui| {
|
||||
widgets::swatch(ui, &form.paint, 24.0);
|
||||
ui.label(widgets::paint_name(&form.paint));
|
||||
});
|
||||
ui.add_space(6.0);
|
||||
let name = ui.add(egui::TextEdit::singleline(&mut form.name).hint_text(tr("Name")).desired_width(220.0));
|
||||
widgets::select_all_on_focus(ui, &name, &form.name);
|
||||
if ui.memory(|m| m.focused().is_none()) {
|
||||
name.request_focus();
|
||||
}
|
||||
ui.add_space(10.0);
|
||||
let ready = !form.name.trim().is_empty();
|
||||
ui.horizontal(|ui| {
|
||||
cancel = widgets::button(ui, tr("Cancel"), false, true).clicked() || ui.input(|i| i.key_pressed(egui::Key::Escape));
|
||||
let enter = name.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
|
||||
create = (widgets::button(ui, tr("Create"), true, ready).clicked() || enter) && ready;
|
||||
});
|
||||
});
|
||||
let made = create && app.run("selection.createColorStyle", json!({"targets": form.targets, "name": form.name.trim()})).is_some();
|
||||
if open && !cancel && !made {
|
||||
ctx.data_mut(|d| d.insert_temp(create_form_id(), form));
|
||||
} else {
|
||||
ctx.data_mut(|d| d.remove::<CreateForm>(create_form_id()));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -546,4 +643,100 @@ mod tests {
|
||||
assert!(texts.iter().any(|(s, _)| s == "FF0000") && texts.iter().any(|(s, _)| s == "0000FF"));
|
||||
assert!(p.app.ui.last_error.is_none());
|
||||
}
|
||||
|
||||
fn text_at(texts: &[(String, Pos2)], s: &str) -> Pos2 {
|
||||
texts.iter().rev().find(|(t, _)| t == s).unwrap_or_else(|| panic!("{s:?} isn't drawn")).1
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn styles_menu_offers_an_enabled_librarys_published_color_styles() {
|
||||
let dir = std::env::temp_dir().join(format!("figcraft-selection-colors-panel-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
let path = dir.join("library.figcraft");
|
||||
let mut publisher = Session::new();
|
||||
publisher.execute("style.create", &json!({"type":"paint","name":"Ocean","value":"#00ffff"})).unwrap();
|
||||
publisher.execute("style.create", &json!({"type":"paint","name":"_Draft","value":"#ffff00"})).unwrap();
|
||||
publisher.execute("library.publish", &json!({})).unwrap();
|
||||
publisher.execute("file.saveAs", &json!({"path":path})).unwrap();
|
||||
let (mut p, a, b) = Panel::new();
|
||||
p.app.run("library.add", json!({"path":path}));
|
||||
let red = text_at(&p.frame(vec![]), "FF0000");
|
||||
p.click(Pos2::new(228.0, red.y));
|
||||
let texts = p.frame(vec![]);
|
||||
let library_name = p.app.session.doc().unwrap().libraries.enabled[0].name.clone();
|
||||
assert!(texts.iter().any(|(s, _)| *s == library_name), "library styles are listed under the library's name");
|
||||
assert!(!texts.iter().any(|(s, _)| s == "_Draft"), "unpublished styles aren't offered");
|
||||
p.click(text_at(&texts, "Ocean"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let doc = p.app.session.doc().unwrap();
|
||||
let copy = doc.node(a).unwrap().styles.fill.clone().unwrap();
|
||||
assert!(library::is_remote_style(doc, ©));
|
||||
assert_eq!(doc.node(a).unwrap().fills[0].solid_color().unwrap().to_hex(), "00FFFF");
|
||||
assert!(doc.node(b).unwrap().styles.fill.is_none());
|
||||
assert!(p.app.ui.last_error.is_none());
|
||||
// The copy is listed under its library, not as one of this file's styles.
|
||||
let blue = text_at(&p.frame(vec![]), "0000FF");
|
||||
p.click(Pos2::new(228.0, blue.y));
|
||||
let texts = p.frame(vec![]);
|
||||
assert_eq!(texts.iter().filter(|(s, _)| s == "Ocean").count(), 2, "the linked row's name and the library's entry");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_style_names_the_row_links_it_and_stays_open_on_a_taken_name() {
|
||||
let (mut p, a, b) = Panel::new();
|
||||
let red = text_at(&p.frame(vec![]), "FF0000");
|
||||
p.click(Pos2::new(228.0, red.y));
|
||||
let create = text_at(&p.frame(vec![]), "Create style");
|
||||
p.click(create);
|
||||
for _ in 0..2 {
|
||||
p.frame(vec![]);
|
||||
}
|
||||
let form = p.ctx.data(|d| d.get_temp::<CreateForm>(create_form_id())).expect("Create style opens its window");
|
||||
assert_eq!(form.name, "Color 1");
|
||||
// Another style takes the name first: Create fails and the window stays for a new name.
|
||||
p.app.run("style.create", json!({"type":"paint","name":"Color 1","value":"#00ff00"}));
|
||||
let button = text_at(&p.frame(vec![]), "Create");
|
||||
p.click(button);
|
||||
assert!(p.ctx.data(|d| d.get_temp::<CreateForm>(create_form_id())).is_some());
|
||||
assert!(p.app.session.doc().unwrap().node(a).unwrap().styles.fill.is_none());
|
||||
p.ctx.data_mut(|d| d.get_temp_mut_or_insert_with(create_form_id(), || form.clone()).name = "Brand".into());
|
||||
let before = p.app.session.undo_depth();
|
||||
let button = text_at(&p.frame(vec![]), "Create");
|
||||
p.click(button);
|
||||
assert!(p.ctx.data(|d| d.get_temp::<CreateForm>(create_form_id())).is_none());
|
||||
let doc = p.app.session.doc().unwrap();
|
||||
let brand = doc.style("Brand").unwrap().id.clone();
|
||||
assert_eq!(doc.node(a).unwrap().styles.fill.as_deref(), Some(brand.as_str()));
|
||||
assert!(doc.node(b).unwrap().styles.fill.is_none());
|
||||
assert_eq!(p.app.session.undo_depth().0, before.0 + 1);
|
||||
assert!(p.frame(vec![]).iter().any(|(s, _)| s == "Brand"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_style_is_left_out_for_a_row_whose_list_holds_other_paints() {
|
||||
let (mut p, a, _) = Panel::new();
|
||||
p.app.run("fill.add", json!({"id":a,"paint":"#00ff00"}));
|
||||
let red = text_at(&p.frame(vec![]), "FF0000");
|
||||
p.click(Pos2::new(228.0, red.y));
|
||||
let texts = p.frame(vec![]);
|
||||
assert!(texts.iter().any(|(s, _)| s == "No color styles"), "the Styles menu opens");
|
||||
assert!(!texts.iter().any(|(s, _)| s == "Create style"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_linked_rows_styles_menu_switches_its_style() {
|
||||
let (mut p, a, _) = Panel::new();
|
||||
p.app.run("style.create", json!({"type":"paint","name":"Brand","value":"#ff0000"}));
|
||||
p.app.run("style.create", json!({"type":"paint","name":"Accent","value":"#00ff00"}));
|
||||
p.app.run("style.apply", json!({"id":a,"style":"Brand","target":"fill"}));
|
||||
let row = text_at(&p.frame(vec![]), "Brand");
|
||||
p.click(Pos2::new(196.0, row.y));
|
||||
let texts = p.frame(vec![]);
|
||||
assert!(!texts.iter().any(|(s, _)| s == "Create style"), "a linked row has a style already");
|
||||
p.click(text_at(&texts, "Accent"));
|
||||
let doc = p.app.session.doc().unwrap();
|
||||
assert_eq!(doc.node(a).unwrap().styles.fill.as_deref(), doc.style("Accent").map(|s| s.id.as_str()));
|
||||
assert!(p.app.ui.last_error.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
//! The Fill section with a region of a vector selected in edit mode (#1875), driven through egui
|
||||
//! headless: the region's own fill shows, and what belongs to the layer (its fill style, a
|
||||
//! variable bound to its fill) stays off the region's rows.
|
||||
|
||||
use egui::accesskit::Role;
|
||||
use egui::{Pos2, pos2};
|
||||
use figcraft_doc::{NodeId, NodeKind, Region, Segment, VectorNetwork, Vertex};
|
||||
use figcraft_engine::Session;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::layers_drag_tests::Ui;
|
||||
|
||||
/// Four points and four straight segments of a square, appended to `n`.
|
||||
fn square(n: &mut VectorNetwork, x0: f64, y0: f64, size: f64) {
|
||||
let v0 = n.vertices.len();
|
||||
for (x, y) in [(x0, y0), (x0 + size, y0), (x0 + size, y0 + size), (x0, y0 + size)] {
|
||||
n.vertices.push(Vertex::new(x, y));
|
||||
}
|
||||
for k in 0..4 {
|
||||
n.segments.push(Segment::line(v0 + k, v0 + (k + 1) % 4));
|
||||
}
|
||||
}
|
||||
|
||||
/// A vector of two squares on the page, the outer one's region then the inner one's, both
|
||||
/// inheriting the layer's default grey fill (also used by the canvas handle and picker tests).
|
||||
pub(crate) fn two_region_vector(s: &mut Session) -> NodeId {
|
||||
let r = s.execute("vector.create", &json!({"points": [[0, 0], [10, 0], [10, 10]], "closed": true})).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
{
|
||||
let doc = s.doc_mut().unwrap();
|
||||
let node = doc.get_mut(id).unwrap();
|
||||
let mut n = VectorNetwork::default();
|
||||
square(&mut n, 0.0, 0.0, 200.0);
|
||||
square(&mut n, 60.0, 60.0, 80.0);
|
||||
n.regions =
|
||||
vec![Region { loops: vec![vec![0, 1, 2, 3]], ..Default::default() }, Region { loops: vec![vec![4, 5, 6, 7]], ..Default::default() }];
|
||||
node.kind = NodeKind::Vector { network: n };
|
||||
node.transform = figcraft_geom::Affine::IDENTITY;
|
||||
node.fills = vec![figcraft_color::Paint::solid(figcraft_color::Color::DEFAULT_SHAPE)];
|
||||
figcraft_engine::vectoredit::refit(doc, id).unwrap();
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
/// [`two_region_vector`] with its fill bound to a blue colour variable; in edit mode with the
|
||||
/// inner region selected and given a red fill of its own.
|
||||
fn ui() -> Ui {
|
||||
let mut s = Session::new();
|
||||
let id = two_region_vector(&mut s);
|
||||
s.execute("variable.createCollection", &json!({"name": "Theme"})).unwrap();
|
||||
s.execute("variable.create", &json!({"collection": "Theme", "name": "brand", "type": "color", "value": "#0000FF"})).unwrap();
|
||||
s.execute("variable.bind", &json!({"ids": [id.0], "field": "fill", "variable": "brand"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("vector.edit.begin", &json!({"id": id.0})).unwrap();
|
||||
s.execute("vector.edit.select", &json!({"regions": [1]})).unwrap();
|
||||
s.execute("fill.set", &json!({"ids": [id.0], "color": "#FF0000"})).unwrap();
|
||||
let mut u = Ui::new(s);
|
||||
u.ctx.enable_accesskit();
|
||||
u.frame(vec![]);
|
||||
u
|
||||
}
|
||||
|
||||
/// The accessible controls after a frame: role, label, value and centre.
|
||||
fn controls(u: &mut Ui) -> Vec<(Role, String, String, Pos2)> {
|
||||
u.frame(vec![]);
|
||||
let out = u.frame_output(vec![]);
|
||||
let nodes = out.platform_output.accesskit_update.expect("an AccessKit update").nodes;
|
||||
nodes
|
||||
.iter()
|
||||
.map(|(_, n)| {
|
||||
let at = n.bounds().map_or(pos2(0.0, 0.0), |b| pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32));
|
||||
(n.role(), n.label().unwrap_or_default().to_string(), n.value().unwrap_or_default().to_string(), at)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn button(c: &[(Role, String, String, Pos2)], name: &str) -> Pos2 {
|
||||
c.iter().find(|(r, l, _, _)| *r == Role::Button && l == name).map(|(_, _, _, p)| *p).unwrap_or_else(|| panic!("no {name} button: {c:?}"))
|
||||
}
|
||||
|
||||
/// What the Fill section shows, between its + and the Stroke section's: its hex rows, whether a
|
||||
/// Detach variable button is there, and whether its header has a Styles button.
|
||||
fn fill_section(c: &[(Role, String, String, Pos2)]) -> (Vec<String>, bool, bool) {
|
||||
let (top, bottom) = (button(c, "Add fill"), button(c, "Add stroke"));
|
||||
let inside = |p: &Pos2| p.y > top.y + 2.0 && p.y < bottom.y - 2.0;
|
||||
let rows = c.iter().filter(|(r, _, _, p)| *r == Role::TextInput && inside(p)).map(|(_, _, v, _)| v.clone()).collect();
|
||||
let detach = c.iter().any(|(_, l, _, p)| l == "Detach variable" && inside(p));
|
||||
let styles = c.iter().any(|(r, l, _, p)| *r == Role::Button && l == "Styles" && (p.y - top.y).abs() < 2.0);
|
||||
(rows, detach, styles)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selected_regions_rows_leave_out_the_layers_style_and_variable() {
|
||||
let mut u = ui();
|
||||
let red = figcraft_color::Color::from_hex("#FF0000").unwrap().to_hex();
|
||||
let (rows, detach, styles) = fill_section(&controls(&mut u));
|
||||
assert_eq!(rows, [red], "the region's own red, as a hex field");
|
||||
assert!(!detach, "the layer's variable binding is not the region's");
|
||||
assert!(!styles, "no fill style for a region's fills");
|
||||
// No region selected: the layer's row again, with its bound variable and the Styles button.
|
||||
u.app.run("vector.edit.select", json!({}));
|
||||
let (rows, detach, styles) = fill_section(&controls(&mut u));
|
||||
assert!(rows.is_empty(), "the layer's paint shows as its variable, not a hex field: {rows:?}");
|
||||
assert!(detach && styles);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user