Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-image

Source of release 0.45.0

0.45.0 / src / canvas / clipboard.lucb

#==============================================================================================
#
#   canvas/clipboard - Copy, cut and paste, and layers via copy
#
#   DESCRIPTION:
#       Photoshop's Edit menu pixel commands: the selected pixels of a layer (or of the
#       flattened document, Copy Merged) as a picture, cropped to the selection and faded by
#       its coverage, for the app to put on the system clipboard; a picture the app pasted
#       becomes a new layer. Layer via Copy and via Cut make that layer directly. The engine
#       never touches the system clipboard itself.
#
#==============================================================================================

extend Canvas:
    ## Copy the selected pixels of layer `id` as a picture for the app to put on
    ## the system clipboard, cropped to the selection and faded by its coverage —
    ## or of the flattened document when `merged` (Copy Merged). With `cut` they
    ## also leave the layer, undoably; cutting takes a selection of one layer.
    ## Without a selection the whole layer (or document) is copied.
    pub func copy_selection(id: i64, merged: bool = false, cut: bool = false) -> interop.Reference[Image]!:
        if cut and (merged or self.current().is_empty()):
            error(invalid, "cut takes a selection of one layer")
        var selected = try read_selected(&self, id, merged)
        defer free(selected.rgba) in memory.heap
        let picture = try Image.from_rgba8(selected.width, selected.height, selected.rgba)
        errdefer picture.release()
        copied_left = selected.left
        copied_top = selected.top
        copied_width = (u32)selected.width
        copied_height = (u32)selected.height
        if cut:
            try erase_selected(&self, (u64)id)
        return picture

    ## The selected pixels of layer `id` (of the flattened document when
    ## `merged`) as an RGBA image cropped to the selection and faded by its
    ## coverage, as Copy takes them: Define Brush Preset's source.
    pub func selection_image(id: i64, merged: bool = false) -> interop.Reference[Image]!:
        var selected = try read_selected(&self, id, merged)
        defer free(selected.rgba) in memory.heap
        return try Image.from_rgba8(selected.width, selected.height, selected.rgba)

    ## `picture` (the clipboard's) on a new top layer, centred on a document
    ## point; its id.
    pub func paste(picture: interop.Reference[Image], center_x: i64, center_y: i64) -> i64!:
        try self.begin_edit("Paste")
        defer self.end_edit()
        return try paste_picture(&self, picture, center_x, center_y)

    ## Layer via Copy (via Cut with `cut`): a new layer above `id` holding its
    ## selected pixels, or all of them without a selection; its id.
    pub func layer_via_copy(id: i64, cut: bool = false) -> i64!:
        try self.begin_edit("Layer via Copy")
        defer self.end_edit()
        return try layer_from_selection(&self, id, cut)

    ## `picture` (the clipboard's) where it was copied from when it is what
    ## this process copied last, else centred; its layer's id.
    pub func paste_in_place(picture: interop.Reference[Image]) -> i64!:
        try self.begin_edit("Paste in Place")
        defer self.end_edit()
        return try paste_picture(&self, picture, 0, 0, in_place = true)

## Where the last copy this process made came from, for Paste in Place.
var copied_left: i64 = 0
var copied_top: i64 = 0
var copied_width: u32 = 0
var copied_height: u32 = 0

## The selected pixels, straight 8-bit sRGB RGBA (on the heap, the caller's),
## and the box they came from.
struct Selected:
    var rgba: u8[]
    var left: i64
    var top: i64
    var width: usize
    var height: usize

## The selected pixels of layer `id`, or of the flattened document when
## `merged`, cropped to the selection and faded by its coverage; the whole
## layer (or document) without a selection.
func read_selected(canvas: Canvas*, id: i64, merged: bool) -> Selected!:
    try canvas.require_open()
    try canvas.require_idle()
    let document = canvas.document else error(invalid, "draw the document once before copying")
    let selection = canvas.current()
    let whole = selection.is_empty()
    let left = 0 if whole else selection.left
    let top = 0 if whole else selection.top
    let right = (i64)canvas.extent_x if whole else selection.right
    let bottom = (i64)canvas.extent_y if whole else selection.bottom
    let width = (usize)(right - left)
    let height = (usize)(bottom - top)
    # Only the selection's box is read, straight to 8-bit sRGB: nothing the size
    # of the document, and no float copy of the box either.
    let rgba = try new u8[width * height * 4] --- in memory.heap
    errdefer free(rgba) in memory.heap
    if merged:
        try copy_merged_window(canvas, rgba, left, top, width, height)
    else:
        let layer = document.find((u64)id) else error(invalid, "no such layer")
        let tiles = layer.tiles() else error(invalid, "a group has no pixels to copy")
        try copy_layer_window(tiles, rgba, left, top, width, height)
    # Faded by the selection's coverage.
    if not whole:
        for y in 0..<height:
            for x in 0..<width:
                let at = (y * width + x) * 4 + 3
                let cover = (u32)selection.at(left + (i64)x, top + (i64)y)
                rgba[at] = (u8)(((u32)rgba[at] * cover + 127) // 255)
    return Selected(rgba = rgba, left = left, top = top, width = width, height = height)

## `Canvas.paste`: `picture` (the clipboard's) on a new top layer named
## "Pasted", centred on a document point — or, `in_place`, where it was copied
## from when it is the size this process copied last, else on the canvas's
## centre; the new layer's id.
func paste_picture(canvas: Canvas*, picture: interop.Reference[Image], center_x: i64, center_y: i64, in_place: bool = false) -> i64!:
    try canvas.require_open()
    try canvas.require_idle()
    let width = (u32)(try picture.value().width())
    let height = (u32)(try picture.value().height())
    var x = center_x
    var y = center_y
    if in_place:
        x = (i64)canvas.extent_x // 2
        y = (i64)canvas.extent_y // 2
        if width == copied_width and height == copied_height:
            x = copied_left + (i64)(copied_width // 2)
            y = copied_top + (i64)(copied_height // 2)
    let id = try canvas.add_layer("Pasted")
    try place_image_at(canvas, id, picture, x, y)
    return id

## `Canvas.layer_via_copy`: a new layer holding the selected pixels of layer
## `id` (all of them without a selection); with `cut` they leave `id`. Its id.
func layer_from_selection(canvas: Canvas*, id: i64, cut: bool) -> i64!:
    try canvas.require_open()
    try canvas.require_idle()
    let document = canvas.document else error(invalid, "draw the document once before copying a layer")
    let passes = canvas.passes else trap("bound without selection passes")
    let copy = try canvas.duplicate_layer(id, "Layer via Cut" if cut else "Layer via Copy")
    let mask = try document.selection_tiles() else return copy
    # Nothing before, the copy after: mixed by coverage, the copy keeps only the selection.
    let device = canvas.device else trap("bound without a device")
    var nothing = try Tiles.create(device, canvas.extent_x, canvas.extent_y)
    defer nothing.destroy()
    try passes.restrict(document, (u64)copy, &nothing, mask)
    if cut:
        try erase_selected(canvas, (u64)id)
    return copy

## Erase the selected pixels of `layer` at full strength, undoably.
func erase_selected(canvas: Canvas*, layer: u64) -> !:
    let document = canvas.document else error(invalid, "draw the document once before erasing")
    var painter = canvas.painter else error(invalid, "draw the document once before erasing")
    var brush = canvas.brush
    brush.erase = true
    brush.opacity = 1.0
    brush.flow = 1.0
    let before = try fill_selection(&painter, document, layer, brush, false)
    try canvas.remember(layer, before, false, name = "Cut")

## The flattened document's box `left`, `top`, `width` by `height` into `rgba`
## as straight 8-bit sRGB, from the composited bands the box's rows cross.
func copy_merged_window(canvas: Canvas*, rgba: u8[], left: i64, top: i64, width: usize, height: usize) -> !:
    var bands = try Bands.begin(canvas, [-1.0, -1.0, -1.0])
    defer bands.close()
    let extent = (usize)canvas.extent_x
    let first = (u32)(top // (i64)tile_size)
    let last = (u32)((top + (i64)height - 1) // (i64)tile_size)
    for row in first..<last + 1:
        let rows = try bands.fill(canvas, row)
        let band_top = (i64)(row * tile_size)
        for y in 0..<rows:
            let document_y = band_top + (i64)y
            if document_y < top or document_y >= top + (i64)height:
                continue
            let source = (y * extent + (usize)left) * 4
            let target = (usize)(document_y - top) * width * 4
            memory.copy(rgba[target..<target + width * 4], bands.band[source..<source + width * 4], width * 4)

## Layer `tiles`' box into `rgba` as straight 8-bit sRGB, a cell at a time.
func copy_layer_window(tiles: const Tiles*, rgba: u8[], left: i64, top: i64, width: usize, height: usize) -> !:
    let side = (usize)tile_size
    let samples = try new f32[side * side * 4] --- in memory.heap
    defer free(samples) in memory.heap
    var steps: u8[4097] = ---
    transfer.srgb_byte_table(steps)
    memory.set(rgba, 0)
    let first_column = (u32)(left // (i64)tile_size)
    let last_column = (u32)((left + (i64)width - 1) // (i64)tile_size)
    let first_row = (u32)(top // (i64)tile_size)
    let last_row = (u32)((top + (i64)height - 1) // (i64)tile_size)
    for row in first_row..<last_row + 1:
        for column in first_column..<last_column + 1:
            if not tiles.painted(column, row):
                continue
            try tiles.read_cell(column, row, samples)
            let cell_x = (i64)(column * tile_size)
            let cell_y = (i64)(row * tile_size)
            let x0 = math.imax(left, cell_x)
            let x1 = math.imin(left + (i64)width, cell_x + (i64)tile_size)
            let y0 = math.imax(top, cell_y)
            let y1 = math.imin(top + (i64)height, cell_y + (i64)tile_size)
            var y = y0
            while y < y1:
                var x = x0
                while x < x1:
                    let source = (usize)((y - cell_y) * (i64)tile_size + (x - cell_x)) * 4
                    let target = ((usize)(y - top) * width + (usize)(x - left)) * 4
                    for channel in 0..<(usize)3:
                        rgba[target + channel] = steps[(usize)(math.clamp((f64)samples[source + channel], 0.0, 1.0) * 4096.0 + 0.5)]
                    rgba[target + 3] = (u8)(math.clamp((f64)samples[source + 3], 0.0, 1.0) * 255.0 + 0.5)
                    x += 1
                y += 1