Type: the point/area type widget converts between them; area type made by dragging resizes

Discord feedback: type in a frame dragged with the Type tool could not be resized or switched
between area and point type the way the reference app allows.

- The Selection tool shows the type widget beside a single selected point or area type object:
  a small circle outside the middle of its bounding box's right side, hollow on point type and
  filled on area type (vectorcraft_tools::typewidget, drawn by the canvas from the same geometry).
  Hovering it shows the arrow with a type badge; its clicks neither drag nor deselect, and a
  double-click runs type.convertToAreaType / type.convertToPointType (the Type menu's commands),
  keeping the text and its styles in place, one undo step, reachable over MCP.
- Resizing area type made by dragging already works on main (#252): the bounding box resizes the
  type area and the text reflows. A regression test now covers the reported flow.
- docs/mcp.md and ROADMAP.md describe the widget.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
bflatasticandClaude Opus 5.5 committed 2026-10-08 16:54:12 +07:00
1 parent 852848f4ed
commit 940285dd9e
8 files changed
+281 -7

No files matched your search

+2 -2
View File
@@ -4,7 +4,7 @@ VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adob
This file tracks **how far we are and what's left**. Time estimates are wall-clock hours of continuous Claude Opus 5.5 agent work (including builds and the CI gate), given both for **one agent** and for **4–6 parallel agents** on disjoint crates. They are counted from the remaining work (see [Parity estimate](#parity-estimate)), calibrated against measured throughput, and updated as work lands.
_Last updated: 2026-10-08 (after M4.14–M4.98, M8.1–M8.20, M14.4–M14.7, the MCP prompts, resource templates, completions and logging, the 2026-10-07 issue fixes, the Layers panel rework and the 2026-10-08 community contributions: Pen and shape-tool modifiers, path editing, Layers, Artboards, Swatches/Brushes and dialogs, Japanese composition and PDF text, Hebrew/Arabic type, interface languages (Spanish among them), the font menu, saved selections, MCP and EPS, the missing-font export warning (#319), open paths in the Shape Builder (#374), PDF/`.ai` import keeping strokes live and hidden and nested layers (#372), per-corner Live Corners (#381), SVG type opening at the size it draws at (#396), the Wayland clipboard with copied-file paste (#398), ruler guides that can be selected, moved and deleted (#414), two batches of Preferences options that were stored but unused (#394), skeleton reads with `document.find` for large documents over MCP (#416) and anchors dragged with Direct Selection snapping to points, segments and smart guides, clipped SVG layers opening as clipping layers (#420), PDF/`.ai` layers read on pages of tens of millions of operators (#419), Document Color Mode putting RGB greys on the black plate on request and converting pattern tiles (#421) and movable dialogs with Offset Path's Joins dropdown (#423) and numeric fields scrubbed by dragging their label (#400), stroke weight presets in the stroke unit (#426), the Appearance panel's Opacity popup (#430), type on a path brackets, flip and Type on a Path Options that keep the type in place (#429), Layers rows dragged with a ghost and dropped on the trash or New Layer (#435), tool flyouts opening on a right or corner press (#436), tool flyouts torn off into floating toolbars (#437), the Shape Builder's erase mode deleting edges too (#439), installed fonts registered outside the font folders and fonts installed while the app runs listed in the font menus (#443), alike circular corners on rectangles that aren't square (#442), tool cursors as OS cursors so the pointer no longer trails over the canvas (#444), artboards copied and pasted with their art (#446), guides dragged out of the rulers snapping to the art's side midpoints and the artboards, artboard guides (#451), the toolbar's double arrow and Window › Toolbars › Double Column switching between one and two columns in any window height (#455), the Smart Guides display options and Snapping Tolerance (#394), Font Size and Leading combo boxes with preset lists in the Character and Properties panels and the Control bar (#458), screenshots pasted from the clipboard on macOS, Windows and the web (#457), the Properties panel's Fill and Stroke matching the Control bar's, Illustrator's Window menu panel keys (Shift+F7 for Align…) and Alt-wheel zoom whatever the wheel preference (Discord feedback); see [Honest assessment](#honest-assessment-2026-10-05))._
_Last updated: 2026-10-08 (after M4.14–M4.98, M8.1–M8.20, M14.4–M14.7, the MCP prompts, resource templates, completions and logging, the 2026-10-07 issue fixes, the Layers panel rework and the 2026-10-08 community contributions: Pen and shape-tool modifiers, path editing, Layers, Artboards, Swatches/Brushes and dialogs, Japanese composition and PDF text, Hebrew/Arabic type, interface languages (Spanish among them), the font menu, saved selections, MCP and EPS, the missing-font export warning (#319), open paths in the Shape Builder (#374), PDF/`.ai` import keeping strokes live and hidden and nested layers (#372), per-corner Live Corners (#381), SVG type opening at the size it draws at (#396), the Wayland clipboard with copied-file paste (#398), ruler guides that can be selected, moved and deleted (#414), two batches of Preferences options that were stored but unused (#394), skeleton reads with `document.find` for large documents over MCP (#416) and anchors dragged with Direct Selection snapping to points, segments and smart guides, clipped SVG layers opening as clipping layers (#420), PDF/`.ai` layers read on pages of tens of millions of operators (#419), Document Color Mode putting RGB greys on the black plate on request and converting pattern tiles (#421) and movable dialogs with Offset Path's Joins dropdown (#423) and numeric fields scrubbed by dragging their label (#400), stroke weight presets in the stroke unit (#426), the Appearance panel's Opacity popup (#430), type on a path brackets, flip and Type on a Path Options that keep the type in place (#429), Layers rows dragged with a ghost and dropped on the trash or New Layer (#435), tool flyouts opening on a right or corner press (#436), tool flyouts torn off into floating toolbars (#437), the Shape Builder's erase mode deleting edges too (#439), installed fonts registered outside the font folders and fonts installed while the app runs listed in the font menus (#443), alike circular corners on rectangles that aren't square (#442), tool cursors as OS cursors so the pointer no longer trails over the canvas (#444), artboards copied and pasted with their art (#446), guides dragged out of the rulers snapping to the art's side midpoints and the artboards, artboard guides (#451), the toolbar's double arrow and Window › Toolbars › Double Column switching between one and two columns in any window height (#455), the Smart Guides display options and Snapping Tolerance (#394), Font Size and Leading combo boxes with preset lists in the Character and Properties panels and the Control bar (#458), screenshots pasted from the clipboard on macOS, Windows and the web (#457), the Properties panel's Fill and Stroke matching the Control bar's, Illustrator's Window menu panel keys (Shift+F7 for Align…) and Alt-wheel zoom whatever the wheel preference (Discord feedback), the point/area type widget (Discord feedback); see [Honest assessment](#honest-assessment-2026-10-05))._
## Where we are
@@ -133,7 +133,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
- **Geometry and effects:**
- Pathfinder (10 exact curve booleans), Offset, Outline Stroke, Simplify, Clean Up, Split Into Grid, Divide Objects Below. Object › Path › Remove Anchor Points (`path.removeAnchors`) removes the direct-selected anchors without opening their paths (the Delete key still deletes them with their segments): the neighbours keep their handle directions and their facing handles are refitted so one cubic follows the two old segments, and straight sides stay straight. The Delete Anchor Point tool uses the same refit. The Control bar, the contextual task bar, the Properties quick actions and the canvas context menu offer it when anchors are selected.
- Live effects with previewing dialogs: Distort & Transform, Path, Convert to Shape, 15 Warp styles, Round Corners, Scribble, Effect → Pathfinder (all 10 operations, live on groups; several loose objects are grouped first, in one undo step), Color Adjustments (Brightness/Contrast, Curves, Levels, Hue/Saturation, Shift to Color, Temperature/Tint, on vectors, live type and embedded images), and raster drop shadow, glows and feather. SVG and PDF export keep live effects (geometry baked; SVG raster effects as filters).
- **Type:** Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), Area Type Options (rows/columns/inset/first baseline), threaded text across any closed shapes, Fit Headline. Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`). Point type still scales. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. Variation axis sliders are not done. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458).
- **Type:** Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), Area Type Options (rows/columns/inset/first baseline), threaded text across any closed shapes, Fit Headline. Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`). Point type still scales. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. Variation axis sliders are not done. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458).
- **Interface languages, vertical type:** VectorCraft ▸ Language (or Preferences ▸ User Interface) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese and Spanish (neutral international Spanish, for every `es-*` locale) cover the whole interface, Czech and Brazilian Portuguese every menu label, Brazilian Portuguese the shell's `tl!` literals too (tested); Spanish also translates status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech and Spanish ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line); kinsoku (the strict set) applies to horizontal and vertical Japanese, and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a wrapped line flush with its start, and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline; Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline or the em box top/right, centre or bottom/left (ICF top and bottom not yet); Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines.
- **Transparency:** opacity masks (clip/invert/disable/link), exported as SVG `<mask>` and PDF soft masks.
- **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own; filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror).
+73 -1
View File
@@ -1,6 +1,6 @@
//! Resizing area type (#252): a bounding-box handle drag and Area Type Options size the type area
//! and the text reflows at its size; Direct Selection reshapes the frame by a corner or an edge.
//! Point type still scales.
//! Point type still scales. The type widget converts point type to area type and back.
use serde_json::{Value, json};
use vectorcraft_doc::{NodeKind, TextKind, TextObject};
@@ -267,3 +267,75 @@ fn reshape_area_is_a_registered_command() {
assert!(cmd::find_command("object.transform").unwrap().params.contains("typeAreas"));
assert!(session().commands().iter().any(|c| c.id == "text.reshapeArea" && c.enabled));
}
/// The Discord report: type in a frame dragged with the Type tool, then the Selection tool. Its
/// bounding box resizes the type area (the text reflows at its size), it doesn't scale the type.
#[test]
fn type_in_a_dragged_frame_resizes_with_the_selection_tool() {
let mut s = session();
drag(&mut s, "type", Point::new(40.0, 40.0), Point::new(160.0, 80.0));
let v = ViewInfo::default();
s.tool_text(STORY, v).unwrap();
s.select_tool("selection", v).unwrap();
let id = s.doc().unwrap().selection.objects[0];
assert_eq!(frame(&s, id), Rect::new(0.0, 0.0, 120.0, 40.0));
let lines = layout(&s, id).lines.len();
drag(&mut s, "selection", Point::new(160.0, 80.0), Point::new(200.0, 140.0));
assert_eq!(last_step(&s), "Resize Type Area");
assert_eq!(frame(&s, id), Rect::new(0.0, 0.0, 160.0, 100.0));
assert_eq!(text(&s, id).xf, Affine::translate((40.0, 40.0)), "the type isn't scaled");
assert!(layout(&s, id).lines.len() > lines, "the text reflows into the larger area");
}
/// The type widget beside the selected type's bounding box (as the Selection tool shows it at
/// the default view).
fn widget(s: &Session) -> vectorcraft_tools::typewidget::TypeWidget {
let st = s.doc().unwrap();
let bx = s.transform_box(&st.selection.objects).unwrap();
vectorcraft_tools::typewidget::TypeWidget::of(&st.doc, &st.selection, &bx, ViewInfo::default().zoom).unwrap()
}
fn double_click(s: &mut Session, p: Point) {
let v = ViewInfo::default();
s.select_tool("selection", v).unwrap();
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] {
s.pointer(&PointerEvent::new(kind, p.x, p.y).with_mods(Mods::default()), v).unwrap();
}
}
/// Double-clicking the type widget converts point type to area type and back, each one undo
/// step, keeping the text, its styles and where it stands; the selection stays.
#[test]
fn the_type_widget_converts_point_and_area_type() {
let mut s = session();
let id = id_of(&s.execute("text.create", &json!({"x": 40, "y": 100, "size": 18, "text": "Two words"})).unwrap());
s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 4, "end": 9, "size": 24})).unwrap();
sel(&mut s, &[id]);
let before = text(&s, id);
let glyph = |t: &TextObject| t.xf * vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).glyphs[0].origin;
let w = widget(&s);
assert!(!w.area);
let n = undo_len(&s);
double_click(&mut s, w.at);
assert_eq!(undo_len(&s), n + 1, "one step");
assert_eq!(last_step(&s), "Convert To Area Type");
let t = text(&s, id);
assert!(matches!(t.kind, TextKind::Area { .. }));
assert_eq!((t.plain_text(), &t.runs), (before.plain_text(), &before.runs), "the text and its styles stay");
assert!(glyph(&t).distance(glyph(&before)) < 0.01, "the type stays where it was");
assert!(!layout(&s, id).overflow);
assert_eq!(s.doc().unwrap().selection.objects, vec![id]);
// Now area type: a filled widget, and a double-click turns it back into point type.
let w = widget(&s);
assert!(w.area);
double_click(&mut s, w.at);
assert_eq!(undo_len(&s), n + 2);
assert_eq!(last_step(&s), "Convert To Point Type");
let t = text(&s, id);
assert!(matches!(t.kind, TextKind::Point));
assert_eq!(t.runs, before.runs);
assert!(glyph(&t).distance(glyph(&before)) < 0.01);
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(text(&s, id), before);
}
+4
View File
@@ -31,6 +31,7 @@ pub mod shape;
pub mod slice;
pub mod symbolism;
pub mod text;
pub mod typewidget;
pub mod xform;
use serde::{Deserialize, Serialize};
@@ -430,6 +431,9 @@ pub enum Cursor {
BlendAnchor,
/// Over a bracket of selected type on a path (a drag moves it): the arrow with a bracket.
PathBracket,
/// Over the type widget of selected type (a double-click converts point type to area type and
/// back): the arrow with a type badge.
TypeWidget,
/// The Shape Builder: a crosshair with a plus (merge mode)...
ShapeBuilder,
/// ...or, with Alt held, a minus (erase mode).
+12 -2
View File
@@ -5,7 +5,8 @@
//! double-click opens the Corners dialog), double-click to enter isolation mode (Double Click To
//! Isolate), Cmd/Ctrl-click to select the object behind (Command Click to Select Objects Behind),
//! click or drag a ruler guide ([`crate::rulerguide`]), drag the brackets of type on a path
//! ([`crate::pathtype`]).
//! ([`crate::pathtype`]), double-click the type widget to convert point type to area type and back
//! ([`crate::typewidget`]).
//! The bounding box stands at the selection's own angle after a rotation, so its handles scale
//! along the objects' axes. A handle drag resizes area type's frame (the type area) instead of
//! scaling its type: the text reflows at its size.
@@ -20,6 +21,7 @@ use crate::corners::{self, CornerDrag, over_widget};
use crate::guides::Targets;
use crate::pathtype::{self, BracketDrag, over_bracket};
use crate::rulerguide::GuideEdit;
use crate::typewidget;
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, json_ids};
#[derive(Clone, Debug, Default)]
@@ -165,7 +167,7 @@ impl Tool for SelectionTool {
match (ev.kind, self.state.clone()) {
(PointerKind::DoubleClick, _) => {
self.state = State::Idle;
if let Some(a) = corners::double_click(cx, p) {
if let Some(a) = corners::double_click(cx, p).or_else(|| typewidget::double_click(cx, p)) {
return vec![a];
}
if crate::rulerguide::guide_at(cx, p).is_some() {
@@ -195,6 +197,11 @@ impl Tool for SelectionTool {
self.state = State::Bracket(b);
return vec![];
}
// The type widget answers a double-click only: its clicks neither drag nor deselect.
if typewidget::over_widget(cx, p) {
self.state = State::Idle;
return vec![];
}
if cx.show_bbox
&& let Some(bx) = selection_box(cx)
{
@@ -382,6 +389,9 @@ impl Tool for SelectionTool {
if over_bracket(cx, p) {
return Cursor::PathBracket;
}
if typewidget::over_widget(cx, p) {
return Cursor::TypeWidget;
}
if cx.show_bbox
&& let Some(bx) = selection_box(cx)
{
+135
View File
@@ -0,0 +1,135 @@
//! The type widget: a small circle beside the right side of a selected type object's bounding
//! box, hollow on point type and filled on area type. Double-clicking it converts the type to the
//! other kind (Type › Convert To Area Type / Convert To Point Type), keeping its text and styles.
//! The Selection tool hits it and the canvas draws it from the same geometry.
use serde_json::json;
use vectorcraft_doc::{Document, NodeId, NodeKind, OrientedBox, Selection, TextKind};
use vectorcraft_geom::Point;
use crate::select::selection_box;
use crate::{Action, ToolContext};
/// The widget's centre sits this far (screen px) outside the middle of the box's right side, clear
/// of its handle.
const OFFSET_PX: f64 = 16.0;
/// The widget's radius (screen px), as the canvas draws it.
pub const RADIUS_PX: f32 = 3.5;
/// How near (screen px) the pointer must be to hit it.
const HIT_PX: f64 = 5.0;
/// The type widget of a selection that is exactly one editable point or area type object.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TypeWidget {
pub id: NodeId,
/// Centre in document coordinates.
pub at: Point,
/// Area type (a filled circle; point type's is hollow).
pub area: bool,
}
impl TypeWidget {
/// The widget beside `bx`, the selection's bounding box, at `zoom` (screen px per document
/// point). None unless the selection is one editable point or area type object (not type on a
/// path, nor type in perspective, which transforms whole).
pub fn of(doc: &Document, selection: &Selection, bx: &OrientedBox, zoom: f64) -> Option<Self> {
let [id] = selection.objects[..] else { return None };
if !doc.is_editable(id) || !zoom.is_finite() || zoom <= 0.0 {
return None;
}
let n = doc.node(id).filter(|n| n.perspective.is_none())?;
let NodeKind::Text(t) = &n.kind else { return None };
let area = match t.kind {
TextKind::Point => false,
TextKind::Area { .. } => true,
_ => return None,
};
let r = bx.rect;
Some(Self { id, at: bx.to_doc() * Point::new(r.x1 + OFFSET_PX / zoom, r.center().y), area })
}
/// The widget the Selection tool can double-click (its bounding box showing).
pub fn for_tool(cx: &ToolContext) -> Option<Self> {
if !cx.show_bbox {
return None;
}
Self::of(cx.doc, cx.selection, &selection_box(cx)?, cx.zoom)
}
/// The widget of `cx` if it is under `p`.
fn at(cx: &ToolContext, p: Point) -> Option<Self> {
Self::for_tool(cx).filter(|w| w.at.distance(p) <= cx.tol(HIT_PX))
}
/// The command converting the type to the other kind.
pub fn command(&self) -> &'static str {
if self.area { "type.convertToPointType" } else { "type.convertToAreaType" }
}
}
/// Is `p` over the type widget?
pub fn over_widget(cx: &ToolContext, p: Point) -> bool {
TypeWidget::at(cx, p).is_some()
}
/// A double-click on the type widget converts point type to area type and back.
pub fn double_click(cx: &ToolContext, p: Point) -> Option<Action> {
let w = TypeWidget::at(cx, p)?;
Some(Action::Exec(w.command().into(), json!({ "ids": [w.id.0] })))
}
#[cfg(test)]
mod tests {
use vectorcraft_doc::{Node, TextObject};
use super::*;
use crate::select::SelectionTool;
use crate::testutil::*;
use crate::{Cursor, Mods, PointerEvent, PointerKind, Tool};
fn ev(kind: PointerKind, p: Point) -> PointerEvent {
PointerEvent::new(kind, p.x, p.y)
}
#[test]
fn the_widget_sits_right_of_the_box_and_a_double_click_converts() {
let (mut d, area) = doc_with_area_type();
let point = d.alloc_id();
let l = d.layers[0].id;
let t = TextObject::point(Point::new(100.0, 300.0), "Point", Default::default());
d.insert(Some(l), 0, Node::new(point, NodeKind::Text(Box::new(t)))).unwrap();
let p = paint();
for (id, cmd) in [(area, "type.convertToPointType"), (point, "type.convertToAreaType")] {
let mut s = Selection::default();
s.add(id);
let c = cx(&d, &s, &p);
let bx = selection_box(&c).unwrap();
let w = TypeWidget::for_tool(&c).unwrap();
assert_eq!(w.area, id == area);
assert!((w.at.x - (bx.rect.x1 + 16.0)).abs() < 1e-9 && (w.at.y - bx.rect.center().y).abs() < 1e-9, "{w:?} {bx:?}");
// The presses and releases of a double-click change nothing (no marquee deselects).
let mut t = SelectionTool::default();
for k in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up] {
assert_eq!(t.pointer(&c, &ev(k, w.at)), vec![], "{k:?}");
}
let a = t.pointer(&c, &ev(PointerKind::DoubleClick, w.at + vectorcraft_geom::Vec2::new(2.0, 0.0)));
assert_eq!(a, vec![Action::Exec(cmd.into(), json!({ "ids": [id.0] }))]);
assert_eq!(t.cursor(&c, w.at, Mods::default()), Cursor::TypeWidget);
// A double-click on the type itself still edits it.
let inside = bx.center();
assert_eq!(t.pointer(&c, &ev(PointerKind::DoubleClick, inside)), vec![Action::SwitchTool("type".into())]);
// Hidden bounding box: no widget.
let c = ToolContext { show_bbox: false, ..cx(&d, &s, &p) };
assert!(TypeWidget::for_tool(&c).is_none());
}
// Two objects, or type on a path: no widget.
let mut s = Selection::default();
s.add(point);
s.add(area);
assert!(TypeWidget::for_tool(&cx(&d, &s, &p)).is_none());
let (pd, path_type) = doc_with_path_type();
let mut s = Selection::default();
s.add(path_type);
assert!(TypeWidget::for_tool(&cx(&pd, &s, &p)).is_none());
}
}
+31 -1
View File
@@ -416,7 +416,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
fn cursor_icon(c: Cursor) -> egui::CursorIcon {
use egui::CursorIcon as C;
match c {
Cursor::Arrow | Cursor::ArrowHollow | Cursor::CornerRadius | Cursor::PathBracket => C::Default,
Cursor::Arrow | Cursor::ArrowHollow | Cursor::CornerRadius | Cursor::PathBracket | Cursor::TypeWidget => C::Default,
Cursor::Move => C::Move,
Cursor::Crosshair => C::Crosshair,
Cursor::ResizeH => C::ResizeHorizontal,
@@ -1439,6 +1439,12 @@ fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: &Xf) {
p.rect_filled(hr, 0.0, Color32::WHITE);
p.rect_stroke(hr, 0.0, Stroke::new(1.0, color), StrokeKind::Inside);
}
// The type widget beside it: hollow on point type, filled on area type.
if let Some(w) = vectorcraft_tools::typewidget::TypeWidget::of(&st.doc, &st.selection, &b, xf.zoom) {
let (c, r) = (xf.to_screen(w.at), vectorcraft_tools::typewidget::RADIUS_PX);
p.circle_filled(c, r, if w.area { color } else { Color32::WHITE });
p.circle_stroke(c, r, Stroke::new(1.0, color));
}
}
}
@@ -2078,6 +2084,30 @@ mod tests {
assert_eq!(widgets(&mut app), 0);
}
/// The type widget beside selected type's bounding box: hollow (white) on point type, filled
/// in the layer colour on area type.
#[test]
fn the_type_widget_shows_which_kind_the_type_is() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let id = app.session.execute("text.create", &json!({"x": 100, "y": 100, "text": "Type"})).unwrap()["id"].as_u64().unwrap();
app.session.execute("select.set", &json!({"ids": [id]})).unwrap();
let layer = c32(app.session.active().unwrap().doc.layer_color(vectorcraft_doc::NodeId(id)));
let ctx = egui::Context::default();
let widget = |app: &mut VectorcraftApp| -> Vec<Color32> {
let r = vectorcraft_tools::typewidget::RADIUS_PX;
shapes(app, &ctx)
.iter()
.filter_map(|s| if let Shape::Circle(c) = s { (c.radius == r && c.fill != Color32::TRANSPARENT).then_some(c.fill) } else { None })
.collect()
};
assert_eq!(widget(&mut app), vec![Color32::WHITE]);
app.session.execute("type.convertToAreaType", &json!({})).unwrap();
assert_eq!(widget(&mut app), vec![layer]);
app.ui.view.bounding_box = false;
assert!(widget(&mut app).is_empty(), "no bounding box, no widget");
}
/// General › Zoom with Mouse Wheel (#394), through the control channel's `ui.wheel`: off,
/// the wheel scrolls and Cmd-wheel zooms; on, the wheel zooms about the pointer, Shift-wheel
/// scrolls up and down and Cmd/Ctrl-wheel sideways. Alt-wheel (Option on the Mac) and a
+11 -1
View File
@@ -149,6 +149,14 @@ fn path_bracket(p: &mut Ink, o: Pos2) {
}
}
/// Over the type widget: the arrow with a type badge (a T) below right.
fn type_widget(p: &mut Ink, o: Pos2) {
arrow(p, o, false);
let b = o + vec2(12.0, 13.0);
line(p, b, b + vec2(8.0, 0.0));
line(p, b + vec2(4.0, 0.0), b + vec2(4.0, 9.0));
}
/// The gradient annotator's stop cursors: the arrow with a plus (add a stop) or minus (delete it)
/// badge.
fn stop_badge(p: &mut Ink, o: Pos2, add: bool) {
@@ -272,6 +280,7 @@ fn glyph(c: Cursor, p: Pos2) -> Option<Vec<Shape>> {
Cursor::WidthPoint => width(ink, p, "point"),
Cursor::Blend | Cursor::BlendObject | Cursor::BlendAnchor => blend(ink, p, c),
Cursor::PathBracket => path_bracket(ink, p),
Cursor::TypeWidget => type_widget(ink, p),
Cursor::ShapeBuilder => shape_builder(ink, p, false),
Cursor::ShapeBuilderErase => shape_builder(ink, p, true),
_ => return None,
@@ -404,7 +413,7 @@ mod tests {
use crate::VectorcraftApp;
/// Every cursor with a glyph.
const GLYPHS: [Cursor; 31] = [
const GLYPHS: [Cursor; 32] = [
Cursor::Arrow,
Cursor::ArrowHollow,
Cursor::Move,
@@ -434,6 +443,7 @@ mod tests {
Cursor::BlendObject,
Cursor::BlendAnchor,
Cursor::PathBracket,
Cursor::TypeWidget,
Cursor::ShapeBuilder,
Cursor::ShapeBuilderErase,
];
+13
View File
@@ -2077,6 +2077,19 @@ undo step. Object › Transform › Scale, the Scale tool and the Transform pane
{"name":"run_command","arguments":{"command":"text.reshapeArea","params":{"id":42,"anchors":[[0,2]],"dx":40,"dy":60}}}
```
## Converting between point type and area type
With the Selection tool, a single selected point or area type object shows the type widget: a small circle beside
the middle of its bounding box's right side, hollow on point type and filled on area type. Double-clicking it runs
`type.convertToAreaType` (point type gets a frame around its text, which keeps its place and doesn't rewrap) or
`type.convertToPointType` (soft line wraps become line breaks), the same commands as the Type menu's Convert To Area
Type and Convert To Point Type. Either keeps the text and its styles and is one undo step; `ids` picks the objects
(default: the selection).
```json
{"name":"run_command","arguments":{"command":"type.convertToAreaType","params":{"ids":[42]}}}
```
## Moving and flipping type on a path
Type on a path flows between a start and an end bracket, stored as fractions of its path's length.