Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-2d

Source of release 0.5.1

0.5.1 / src / view.luc

## The canvas view: it draws the document at the workspace's zoom and offset
## with the view aids (view_aids.luc) and the tools' outlines over it, and
## turns pointer, key (view_keys.luc) and scroll input into what the active
## tool does. A press goes to the tool's handler (tool_handler.luc, one file
## per tool family) after the gestures that come before any tool — panning,
## sizing the brush, a guide, a warp, a box, a dialog's eyedropper; drags
## and the release go to whichever gesture is under way.
from luce_ui.ui import Widget, Layout, Size, Constraints, Event, Painter, Font
from luce_gpu.gpu import RenderTarget, Rect
from luce_window.input import EventKind, Cursor, ScrollUnit
from workspace import Workspace
from kit import outline, dropped_paths
from polygon_lasso import PolygonLasso
from magnetic_lasso import MagneticLasso
from guides import GuideDrag
from pen_tool import PenTool
from shape_tool import shape_tools
from vector_overlay import VectorOverlay
from tool_cursor import cursor_for, draw_magnifier
from tool_handler import ToolHandler, ToolContext, brushed
from view_gestures import BrushSizing, OnImageDrag, GuideGesture, WarpGesture, BoxGesture
from navigate_tools import PanGesture, ZoomTool, IdleTool
from paint_tools import PaintTool
from gradient_tool import GradientTool
from sample_tools import EyedropperTool
from text_tool import TextTool
from selection_tools import OutlineMove, MarqueeTool, WandTool, PolygonTool, MagneticTool
from vector_tools import ShapeTool, PenHandler
from move_tool import MoveTool, whole
from view_aids import ViewAids
from view_keys import ViewKeys
import theme
from luce_std import math

## The document on screen: backdrop, checkerboard under transparent pixels,
## the flattened document at the workspace's zoom and offset, and a hairline
## around it drawn at screen resolution. Touchpad scrolling pans; a mouse
## wheel, or scrolling with the primary modifier, zooms about the pointer; a
## pinch zooms; space or the middle button drags.
pub class CanvasView: Widget:
    let box: Layout
    pub let workspace: Workspace
    ## What the tool handlers share, with the window's callbacks for them.
    pub let context: ToolContext
    pub let keys: ViewKeys
    ## Files dropped on the canvas: the ones luced-2d can open.
    pub var on_open_files: func(list[str]) -> unit!? = none
    pub var pointer_x: float = 0.0
    pub var pointer_y: float = 0.0
    pub var pointer_inside: bool = false
    ## Layouts that show the pointer (the rulers), redrawn with the view.
    pub var linked: list[Layout]
    ## The Polygonal and Magnetic Lassos' shapes while their corners are clicked,
    ## the Pen's path, and a guide being dragged.
    pub let polygon: PolygonLasso
    pub let magnetic: MagneticLasso
    pub let pen: PenTool
    pub let guides: GuideDrag
    ## The gestures before any tool, and the tools' handlers.
    let pan: PanGesture
    let sizing: BrushSizing
    let on_image: OnImageDrag
    let guide_gesture: GuideGesture
    let warp: WarpGesture
    let boxes: BoxGesture
    let move: MoveTool
    let marquee: MarqueeTool
    let shapes: ShapeTool
    let paint: PaintTool
    let eyedropper: EyedropperTool
    ## The handler for each tool id; tools not listed paint.
    let handlers: map[str, ToolHandler]
    ## Every handler that can have a gesture under way, in the order a drag looks.
    let gestures: list[ToolHandler]
    ## The active vector element's outline over the canvas.
    let vector_overlay: VectorOverlay
    let aids: ViewAids
    ## Alt held, for the Zoom tool's minus.
    var alt_held: bool = false
    var ants: float = 0.0

    pub func init(self, workspace: Workspace, font: Font? = none) -> unit!:
        self.workspace = workspace
        let context = ToolContext(workspace)
        self.context = context
        self.polygon = PolygonLasso()
        self.magnetic = MagneticLasso()
        self.guides = GuideDrag()
        self.vector_overlay = VectorOverlay()
        self.aids = ViewAids(workspace, font)
        self.pan = PanGesture()
        self.sizing = BrushSizing()
        self.on_image = OnImageDrag()
        self.guide_gesture = GuideGesture(self.guides)
        self.warp = WarpGesture()
        self.boxes = BoxGesture()
        self.move = MoveTool(self.boxes)
        let outline_move = OutlineMove()
        self.marquee = MarqueeTool(outline_move)
        self.shapes = ShapeTool()
        let pen = PenHandler()
        self.pen = pen.pen
        self.paint = PaintTool()
        self.eyedropper = EyedropperTool()
        context.eyedropper = self.eyedropper
        let gradient = GradientTool()
        let text = TextTool()
        let zoom = ZoomTool()
        var handlers: map[str, ToolHandler] = {}
        handlers["zoom"] = zoom
        handlers["idle"] = IdleTool()
        handlers["pen"] = pen
        handlers["gradient"] = gradient
        handlers["eyedropper"] = self.eyedropper
        handlers["text"] = text
        handlers["wand"] = WandTool(outline_move)
        handlers["polygon"] = PolygonTool(self.polygon)
        handlers["magnetic"] = MagneticTool(self.magnetic)
        for tool in ["marquee", "ellipse", "lasso"]:
            handlers[tool] = self.marquee
        for tool in shape_tools():
            handlers[tool] = self.shapes
        self.handlers = handlers
        self.gestures = [self.eyedropper, self.sizing, self.on_image, self.shapes, pen, self.guide_gesture, gradient, self.warp, self.boxes,
                         self.pan, self.paint, zoom, self.marquee, self.move, outline_move, text]
        self.keys = ViewKeys(context, self.pan, self.paint, pen, self.marquee, self.polygon, self.magnetic, self.warp, self.boxes, gradient)
        self.box = Layout()
        self.box.set_focusable(true)
        # Tab steps the tool's modes on the canvas instead of moving focus.
        self.box.set_accepts_tab(true)
        self.box.set_cursor(Cursor.arrow)
        self.box.set_flex()
        self.box.set_limits(Size(200.0, 160.0), Size(16384.0, 16384.0))
        # Pictures and documents dropped on the canvas open, each in its own tab.
        self.box.set_drop_target(true)
        self.linked = []
        workspace.tools.on_choose(self.tool_changed)

    pub func layout(self) -> Layout:
        return self.box

    pub func measure(self, available: Constraints) -> Size!:
        return Size(900.0, 700.0)

    ## Another tool chosen mid-shape lets the Polygonal and Magnetic Lassos'
    ## shapes and the Pen's path go.
    func tool_changed(self, tool: str):
        if self.polygon.active and tool != "polygon":
            self.polygon.cancel()
        if self.magnetic.active and tool != "magnetic":
            self.magnetic.cancel(self.workspace)
        if self.pen.drawing and tool != "pen":
            self.pen.cancel()

    # -- Each frame.

    ## Once a frame, before drawing: a document not yet fitted is fitted to the
    ## view, and a live gradient follows the colors and the header's options.
    pub func settle(self) -> unit!:
        let viewport = self.workspace.viewport
        if not viewport.fitted:
            let bounds = self.box.bounds()
            if bounds.width > 0.0 and bounds.height > 0.0:
                viewport.fit(bounds.width, bounds.height)
                self.box.invalidate()
        self.workspace.painting.follow_gradient()

    ## Advance the marching ants, and keep drawing while a smudge finishes on
    ## its worker (each frame shows how far it got); called from the frame timer.
    pub func march(self):
        if self.workspace.canvas.has_selection():
            self.ants += 1.0
            self.box.repaint()
        elif self.workspace.canvas.busy():
            self.box.repaint()
        self.autoscroll()

    ## A marquee or lasso dragged past the view's edge pans toward the pointer
    ## each frame, faster the further past, and goes on growing.
    func autoscroll(self):
        let shape = self.marquee.shape
        if not shape.active:
            return
        let size = self.box.bounds()
        let dx = past_edge(self.pointer_x, size.width)
        let dy = past_edge(self.pointer_y, size.height)
        if dx == 0.0 and dy == 0.0:
            return
        self.workspace.viewport.pan(-dx, -dy)
        shape.drag_again(self.workspace, self.document_x(self.pointer_x), self.document_y(self.pointer_y)) catch failure:
            _ = failure
        self.box.invalidate()

    # -- Drawing.

    pub func draw(self, target: RenderTarget) -> unit!:
        let painter = Painter(target)
        let size = target.size()
        let workspace = self.workspace
        let canvas = workspace.canvas
        let zoom = workspace.viewport.zoom
        let left = workspace.viewport.offset_x
        let top = workspace.viewport.offset_y
        let move = self.move
        painter.rectangle(Rect(0.0, 0.0, size.width, size.height), theme.backdrop())
        let whole_view = Rect(0.0, 0.0, size.width, size.height)
        # The document's part of the view.
        let x0 = math.max(0.0, left)
        let y0 = math.max(0.0, top)
        let x1 = math.min(size.width, left + float(canvas.width()) * zoom)
        let y1 = math.min(size.height, top + float(canvas.height()) * zoom)
        if x1 > x0 and y1 > y0:
            self.aids.draw_checker(painter, x0, y0, x1, y1)
            # The canvas draws the checkerboard under the picture itself, so the
            # two mix as the document blends its colors (sRGB unless gamma 1.0).
            canvas.set_checker(8.0, theme.checker_light().red, theme.checker_dark().red)
            if move.moving and not move.pixels and not move.element:
                canvas.draw_moving(target, whole_view, zoom, left, top, workspace.layers.selected_id(), move.moved_x() / zoom, move.moved_y() / zoom)
            else:
                canvas.draw(target, whole_view, zoom, left, top)
            outline(painter, Rect(x0, y0, x1 - x0, y1 - y0), theme.border())
        # Marching ants along the selection's edge, at screen resolution, moving
        # with selected pixels being dragged; while a shape is being dragged its
        # outline is drawn plainly; while selected pixels float in a transform
        # the box shows where they go, and the outline follows on Apply. Quick
        # Mask tints what it masks instead.
        let floating = canvas.transforming() and canvas.transform_floats()
        if (canvas.has_selection() or canvas.quick_mask()) and not floating:
            var ants_left = left
            var ants_top = top
            if move.moving and move.pixels:
                ants_left += float(move.shown_x) * zoom
                ants_top += float(move.shown_y) * zoom
            canvas.draw_selection(target, whole_view, zoom, ants_left, ants_top, self.ants)
        # The grid over the picture and whatever tints it.
        if workspace.viewport.show_grid and x1 > x0 and y1 > y0:
            self.aids.draw_grid(painter, x0, y0, x1, y1)
        self.marquee.shape.draw(painter, zoom, left, top, theme.text())
        self.polygon.draw(painter, zoom, left, top, theme.text(), theme.backdrop())
        self.magnetic.draw(painter, workspace, left, top, theme.text(), theme.backdrop())
        self.guides.draw(painter, workspace, size.width, size.height)
        self.aids.draw_pixel_grid(painter, size.width, size.height)
        if self.eyedropper.ringing:
            self.aids.draw_sample_ring(painter, self.pointer_x, self.pointer_y, self.eyedropper.before)
        self.aids.draw_boxes(painter, size.width, size.height, move.moving)
        self.shapes.shape.draw(painter, workspace, zoom, left, top, theme.text(), theme.backdrop())
        self.pen.draw(painter, workspace, zoom, left, top, theme.text(), theme.backdrop())
        var element_dx = 0.0
        var element_dy = 0.0
        if move.moving and move.element:
            element_dx = float(whole(move.moved_x(), zoom))
            element_dy = float(whole(move.moved_y(), zoom))
        self.vector_overlay.draw(painter, workspace, element_dx, element_dy, workspace.look.accent, theme.backdrop())
        # The pointer may have gone to another panel without the view hearing of
        # it; the layout's hover says where it is now.
        let pointer_here = self.pointer_inside and (self.box.contains_pointer() or self.paint.painting)
        let tool = workspace.tools.tool
        let panning = self.pan.panning
        if pointer_here and not panning and not self.keys.space_held and tool == "zoom":
            draw_magnifier(painter, self.pointer_x, self.pointer_y, self.alt_held, theme.text(), theme.backdrop())
        if pointer_here and not panning and brushed(tool) and not workspace.eyedroppers.armed():
            # A right-drag sizing the brush keeps its outline where the drag began.
            let sizing = self.sizing
            self.aids.draw_brush_outline(painter, sizing.x if sizing.sizing else self.pointer_x, sizing.y if sizing.sizing else self.pointer_y)
            if tool == "clone" and canvas.has_clone_source():
                self.aids.draw_clone_preview(painter, self.pointer_x, self.pointer_y)
                self.aids.draw_clone_source(painter, self.pointer_x, self.pointer_y)
        painter.close()

    ## Document coordinates of a view point.
    func document_x(self, x: float) -> float:
        return (x - self.workspace.viewport.offset_x) / self.workspace.viewport.zoom

    func document_y(self, y: float) -> float:
        return (y - self.workspace.viewport.offset_y) / self.workspace.viewport.zoom

    # -- Input.

    pub func event(self, event: Event) -> unit!:
        let kind = event.kind
        let workspace = self.workspace
        if kind == EventKind.drag_entered:
            self.box.set_drop_accepted(dropped_paths(self.box, workspace.documents.can_open).length > 0)
            return
        if kind == EventKind.drop:
            let files = dropped_paths(self.box, workspace.documents.can_open)
            if let open = self.on_open_files:
                open(files)
            return
        if kind == EventKind.drag_moved or kind == EventKind.drag_left:
            return
        let was_inside = self.pointer_inside
        let was_alt = self.alt_held
        if event.cancelled:
            self.cancel()
        elif kind == EventKind.key_down or kind == EventKind.key_up or kind == EventKind.modifiers_changed:
            self.keys.key(event)
        elif kind == EventKind.scroll or kind == EventKind.magnify:
            self.scroll(event)
        elif kind == EventKind.pointer_down and event.inside:
            self.press(event)
        elif kind == EventKind.pointer_moved:
            self.pointer_x = event.x
            self.pointer_y = event.y
            self.pointer_inside = event.inside
            let x = self.document_x(event.x)
            let y = self.document_y(event.y)
            if self.polygon.active:
                self.polygon.hover(x, y)
            if self.magnetic.active:
                self.magnetic.hover(workspace, x, y)
            if self.pen.drawing and not self.pen.holding():
                self.pen.hover(x, y)
            self.drag(event)
        elif kind == EventKind.pointer_up:
            self.release(event)
        elif kind == EventKind.pointer_left:
            self.pointer_inside = false
        self.alt_held = event.alt
        # Sampling for a dialog (On Image, an eyedropper) shows cross hairs, whatever the tool.
        let panning = self.pan.panning
        self.box.set_cursor(Cursor.crosshair if workspace.eyedroppers.armed() and not panning else cursor_for(workspace.tools.tool, panning, self.keys.space_held, workspace.tools.brush.diameter * workspace.viewport.zoom < 5.0))
        if kind != EventKind.pointer_moved:
            self.box.invalidate()
            for linked in self.linked:
                linked.invalidate()
        elif was_inside or self.pointer_inside or was_alt != self.alt_held or self.following():
            # A move changes only what is drawn: the pointer's marks, a drag's work.
            self.box.repaint()
            for linked in self.linked:
                linked.repaint()

    ## Whether something drawn follows the pointer wherever it is: a drag under
    ## way, or a lasso's or a path's next segment.
    func following(self) -> bool:
        if self.polygon.active or self.magnetic.active or self.pen.drawing:
            return true
        for gesture in self.gestures:
            if gesture.active():
                return true
        return false

    ## The view lost the pointer mid-gesture: end what is in progress.
    func cancel(self) -> unit!:
        self.pan.panning = false
        self.shapes.shape.cancel()
        self.paint.stop(self.context, true)
        self.pointer_inside = false

    func scroll(self, event: Event) -> unit!:
        let viewport = self.workspace.viewport
        if event.kind == EventKind.magnify:
            # A touchpad pinch: the magnification change, about the pointer.
            viewport.zoom_about(1.0 + event.scroll_y, event.x, event.y)
        elif event.scroll_unit == ScrollUnit.lines and (event.shift or (event.scroll_x != 0.0 and event.scroll_y == 0.0)):
            # Shift-wheel, or a wheel tilted sideways, pans across; a notch is 40 points.
            let across = event.scroll_x if event.scroll_x != 0.0 else event.scroll_y
            viewport.pan(across * 40.0, 0.0)
        elif event.scroll_unit == ScrollUnit.lines or event.meta or event.control or event.alt:
            # A notched mouse wheel zooms about the pointer; so does any scroll with cmd, ctrl or alt held.
            let step = 1.0 if event.scroll_unit == ScrollUnit.points else 24.0
            viewport.zoom_about(math.pow(1.0025, event.scroll_y * step), event.x, event.y)
        else:
            # Precise touchpad scrolling pans.
            viewport.pan(event.scroll_x, event.scroll_y)

    ## A press on the canvas: the gestures that come before any tool, then
    ## the handler of the tool in hand.
    func press(self, event: Event) -> unit!:
        let workspace = self.workspace
        let context = self.context
        let tool = workspace.tools.tool
        let space_held = self.keys.space_held
        if event.button == 0 and not space_held:
            # A tool used while its key is held springs back when the key is let go.
            workspace.tools.tool_used = true
        let x = self.document_x(event.x)
        let y = self.document_y(event.y)
        if event.button == 2 or (event.button == 0 and (space_held or tool == "hand")):
            self.pan.press(context, event, x, y)
            return
        if event.button == 1 and brushed(tool):
            self.sizing.press(context, event, x, y)
            return
        if event.button != 0:
            return
        # While the picture opens (or the selection refines) the view pans and
        # zooms; edits wait for it (the status bar says how far it has come).
        if (workspace.canvas.is_opening() or workspace.canvas.refine_keeping()) and tool != "zoom":
            return
        let command = event.meta or event.control
        let boxed = workspace.transforms.transform != none or workspace.image.crop_box != none
        # With the Move tool (or Cmd held) a guide under the pointer is taken up.
        if (tool == "move" or command) and not boxed:
            self.guide_gesture.press(context, event, x, y)
            if self.guide_gesture.active():
                return
        if workspace.transforms.mesh_warp != none:
            self.warp.press(context, event, x, y)
            return
        if boxed:
            self.boxes.press(context, event, x, y)
            return
        if workspace.eyedroppers.drag_for != none:
            self.on_image.press(context, event, x, y)
            return
        # Color Range's eyedropper takes clicks while its dialog is up: a click
        # samples, Shift-click adds, Alt-click subtracts.
        if workspace.eyedroppers.range_sample_to(x, y, event.shift, event.alt):
            context.changed()
            return
        # Cmd (Ctrl) held makes most tools the Move tool for the press, as in Photoshop.
        if tool == "move" or (command and tool != "hand" and tool != "zoom"):
            self.move.press(context, event, x, y)
            return
        let handler = self.handlers[tool] else self.paint
        handler.press(context, event, x, y)

    ## The pointer moved: carry on the gesture under way.
    func drag(self, event: Event) -> unit!:
        let x = self.document_x(event.x)
        let y = self.document_y(event.y)
        for gesture in self.gestures:
            if gesture.active():
                gesture.drag(self.context, event, x, y)
                return

    ## The button let go: finish the gesture under way.
    func release(self, event: Event) -> unit!:
        let x = self.document_x(event.x)
        let y = self.document_y(event.y)
        self.pan.panning = false
        for gesture in self.gestures:
            if gesture.active():
                gesture.release(self.context, event, x, y)
                return

## How far to pan this frame for a pointer at `at` along a view `length`
## long: nothing inside, a fifth of the overshoot past an edge, at most 40.
func past_edge(at: float, length: float) -> float:
    if at < 0.0:
        return math.max(-40.0, at * 0.2)
    if at > length:
        return math.min(40.0, (at - length) * 0.2)
    return 0.0