Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-photo

Source of release 0.1.0

0.1.0 / src / develop_session.luc

## The develop session: the photo whose develop the controls show; saving it a
## moment after edits settle (so a drag is one change, not hundreds); undo and
## redo, a history per photo; and settings carried between photos — Copy and
## Paste, Sync from the lead photo to the rest of the selection, Reset, film
## presets, and presets. The recipe (the photo's film process) is part of the
## settings, so undo, copying and presets carry it too. Geometry (perspective,
## crop, guides) belongs to one photo's framing: copying leaves it out and
## pasting keeps the target's own. A preset stacks, as
## Capture One's styles do: what it sets replaces the photo's, the rest stays.
from photo_library import PhotoLibrary
from develop_controls import DevelopControls
from viewer import Viewer
from library_pane import LibraryPane
from rerender import Rerenderer
from luce_develop import settings
from luce_develop import looks
from luce_develop import recipe
import preset_marks
from luce_ui.ui import Application

## Seconds an edit waits for more before it is saved as one step.
let save_delay: float = 0.5
## The most undo steps kept per photo.
let history_limit: int = 100

## The parts of settings text `text` (`name=value` pairs, `;` between) that
## belong to the photo's framing (`framing`) or not.
func parts_of(text: str, framing: bool) -> list[str]:
    var kept: list[str] = []
    if text == "":
        return kept
    for part in text.split(";"):
        let frames = part.starts_with("geometry_") or part.starts_with("crop_") or part.starts_with("guides=")
        if frames == framing:
            kept.append(part)
    return kept

## Settings `look` without its framing, over `target`'s framing.
func carried(look: str, target: str) -> str:
    return (parts_of(look, false) + parts_of(target, true)).join(";")

## The name a part of settings text sets: "exposure" of "exposure=0.7".
func name_in(part: str) -> str:
    let parts = part.split("=")
    return parts[0]

## The sections that are the photo's own, not its film: the light it was taken
## in, how it was exposed, and its framing. A film preset carries the rest.
func own_sections() -> list[str]:
    return ["White Balance", "Exposure", "Geometry", "Crop"]

## The curves' names in the text form.
func curve_names() -> list[str]:
    var names: list[str] = []
    for at in 0..<settings.curve_total():
        names.append(settings.curve_name(at))
    return names

## Settings `text`'s film preset: its recipe and every parameter of the stages
## from the lens to the print and the grade, each named even at its default
## (and its curves even when straight), so pasting it replaces another photo's
## film whole while that photo keeps its own light and framing.
func film_part(text: str) -> str!:
    let look = settings.look(text)
    var parts: list[str] = []
    let own = own_sections()
    for at in 0..<settings.parameter_total():
        if not (settings.section_of(at) in own):
            let name = settings.name_of(at)
            parts.append(settings.part_text(name, look.get(name)))
    var shaped: set[str] = {}
    for part in parts_of(text, false):
        if part.starts_with("curve_"):
            parts.append(part)
            shaped.insert(name_in(part))
    for name in curve_names():
        if not (name in shaped):
            parts.append(f"{name}=0,0 1,1")
    parts.append(look.recipe_text())
    return parts.join(";")

## The film look (else the start) settings `text` carry whole: giving it to
## them would change nothing. "" when none.
func carried_mark(text: str) -> str!:
    let own = settings.look(text).text()
    for at in 0..<looks.count():
        if stacked(looks.text(at), text) == own:
            return preset_marks.for_look(at)
    # An untouched photo is Television's already: a start counts only where the
    # photo names a stock or a recipe of its own.
    if not (text.contains("film_stock=") or text.contains("recipe=")):
        return ""
    for at in 0..<recipe.mode_total():
        if stacked(settings.mode_text(at), text) == own:
            return preset_marks.for_start(at)
    return ""

## Preset `preset` stacked on settings `target`: the preset's values replace
## the target's of those names, the target's others and its framing stay. In
## the text form's own order, so an unchanged photo compares equal.
func stacked(preset: str, target: str) -> str!:
    let laid = parts_of(preset, false)
    var named: set[str] = {}
    for part in laid:
        named.insert(name_in(part))
    var kept: list[str] = []
    if target != "":
        for part in target.split(";"):
            if not (name_in(part) in named):
                kept.append(part)
    return settings.look((kept + laid).join(";")).text()

pub class DevelopSession:
    let library: PhotoLibrary
    let controls: DevelopControls
    let viewer: Viewer
    let pane: LibraryPane
    let rerenderer: Rerenderer
    ## The photo developed (an id, -1 for none), its settings as last saved,
    ## whether an edit is not saved yet, and the save waiting for it (an
    ## Application.after handle, -1 none).
    pub var developing: int = -1
    var committed: str = ""
    var unsaved: bool = false
    var save_due: int = -1
    ## The window, for the save's delay (`connect`).
    var app: Application? = none
    var undo_steps: map[int, list[str]] = {}
    var redo_steps: map[int, list[str]] = {}
    ## Copied settings, without framing.
    var copied: str? = none
    ## The film preset copied (`copy_film`), and the photo's preset mark
    ## (preset_marks.luc) the photos it is pasted on take.
    var film_copied: str? = none
    pub var film_mark: str = ""
    pub var on_status: func(str) -> unit!? = none
    ## Told after a photo is sent to be developed again (the window shows it busy).
    pub var on_requested: func() -> unit!? = none

    pub func init(self, library: PhotoLibrary, controls: DevelopControls, viewer: Viewer, pane: LibraryPane, rerenderer: Rerenderer):
        self.library = library
        self.controls = controls
        self.viewer = viewer
        self.pane = pane
        self.rerenderer = rerenderer

    ## Develop photo `id`, whose settings are `text`; the photo before is saved.
    pub func open(self, id: int, text: str) -> unit!:
        self.flush()
        self.developing = id
        self.committed = text
        self.controls.show(text, 5500.0, 0.0)
        self.viewer.set_look(self.controls.look)

    ## Develop nothing.
    pub func close_photo(self) -> unit!:
        self.flush()
        self.developing = -1

    ## Forget every photo's history: another library is open, whose ids name
    ## other photos. Copied settings stay, to paste into the new library.
    pub func forget(self) -> unit!:
        self.close_photo()
        self.undo_steps = {}
        self.redo_steps = {}

    ## The controls changed the look: show it, and save it once edits settle.
    pub func changed(self) -> unit!:
        # An edit shows as it is made, even in the Library mode.
        self.viewer.go_live()
        self.viewer.set_look(self.controls.look)
        self.viewer.want_histogram()
        if self.developing < 0:
            return
        self.unsaved = true
        # Saved once edits settle: each edit puts the save off again.
        let app = self.app else return
        if self.save_due >= 0:
            app.cancel(self.save_due)
        self.save_due = app.after(save_delay, self.flush)

    ## Run the save's delay on `app`.
    pub func connect(self, app: Application) -> unit!:
        self.app = app

    ## Save an edit not saved yet, as one undo step.
    pub func flush(self) -> unit!:
        if self.save_due >= 0:
            if let app = self.app:
                app.cancel(self.save_due)
            self.save_due = -1
        if not self.unsaved or self.developing < 0:
            return
        self.unsaved = false
        let text = self.controls.look.text()
        if text == self.committed:
            return
        self.remember(self.developing, self.committed)
        self.store(self.developing, text)
        self.committed = text

    ## Push `text` as photo `id`'s last undo step, forgetting its redo steps.
    func remember(self, id: int, text: str):
        var steps = self.undo_steps[id] else []
        steps.append(text)
        if steps.length > history_limit:
            _ = steps.remove_at(0)
        self.undo_steps[id] = steps
        self.redo_steps[id] = []

    ## Save `text` as photo `id`'s settings, and make its files again.
    func store(self, id: int, text: str) -> unit!:
        self.library.save_settings(id, text) catch failure:
            self.tell(f"The develop was not saved: {failure.message}")
            return
        let at = self.library.index.position_of(id)
        if at >= 0:
            self.pane.refresh_badges([at])
            self.rerenderer.request(id, self.library.root, self.library.original_path(at), text)
            if let told = self.on_requested:
                told()

    ## Show settings `text` on the developed photo and save them, without a step.
    ## It is an edit: the viewer develops it live at once (even in the Library
    ## mode), not after its picture is made again.
    func take(self, text: str) -> unit!:
        self.controls.reload(text)
        self.viewer.go_live()
        self.viewer.set_look(self.controls.look)
        self.viewer.want_histogram()
        self.store(self.developing, text)
        self.committed = text

    # mark: history =============================================================================

    pub func undo(self) -> unit!:
        self.flush()
        if self.developing < 0:
            return
        var steps = self.undo_steps[self.developing] else []
        if steps.length == 0:
            self.tell("Nothing to undo.")
            return
        let text = steps.pop()
        self.undo_steps[self.developing] = steps
        var later = self.redo_steps[self.developing] else []
        later.append(self.committed)
        self.redo_steps[self.developing] = later
        self.take(text)

    pub func redo(self) -> unit!:
        self.flush()
        if self.developing < 0:
            return
        var later = self.redo_steps[self.developing] else []
        if later.length == 0:
            self.tell("Nothing to redo.")
            return
        let text = later.pop()
        self.redo_steps[self.developing] = later
        var steps = self.undo_steps[self.developing] else []
        steps.append(self.committed)
        self.undo_steps[self.developing] = steps
        self.take(text)

    # mark: between photos ======================================================================

    ## Copy the developed photo's settings, without its framing.
    pub func copy(self) -> unit!:
        self.flush()
        if self.developing < 0:
            return
        self.copied = parts_of(self.committed, false).join(";")
        self.tell("Settings copied.")

    ## Give the photos at `positions` settings `text`, each keeping its framing,
    ## or stacked on their own (`stack`); every photo changed gets an undo step.
    func give(self, positions: list[int], text: str, stack: bool = false) -> int!:
        self.flush()
        var changed = 0
        let index = self.library.index
        for at in positions:
            let id = index.id(at)
            let before = index.settings(at)
            let after = stacked(text, before) if stack else carried(text, before)
            if after == before:
                continue
            self.remember(id, before)
            if id == self.developing:
                self.take(after)
            else:
                self.store(id, after)
            changed += 1
        return changed

    ## Paste the copied settings onto the photos at `positions`.
    pub func paste(self, positions: list[int]) -> unit!:
        let text = self.copied else return
        let changed = self.give(positions, text)
        self.tell(f"Pasted settings onto {changed} photo{"" if changed == 1 else "s"}.")

    ## Give the photos at `positions` the developed photo's settings.
    pub func sync(self, positions: list[int]) -> unit!:
        self.flush()
        if self.developing < 0:
            return
        let changed = self.give(positions, self.committed)
        self.tell(f"Synced settings to {changed} photo{"" if changed == 1 else "s"}.")

    ## Put the photos at `positions` back as shot, keeping their framing.
    pub func reset(self, positions: list[int]) -> unit!:
        let changed = self.give(positions, "")
        self.tell(f"Reset {changed} photo{"" if changed == 1 else "s"}.")

    ## Copy the film preset of the photo at `at`: everything but its own light
    ## and framing (`film_part`).
    pub func copy_film(self, at: int) -> unit!:
        self.flush()
        let index = self.library.index
        if at < 0 or at >= index.count():
            self.tell("Select the photo whose film to copy.")
            return
        self.film_copied = film_part(index.settings(at))
        self.film_mark = index.preset(at)
        self.tell(f"Copied the film preset of {index.name(at)}.")

    ## Stack the copied film preset on the photos at `positions`; how many changed.
    pub func paste_film(self, positions: list[int]) -> int!:
        if self.film_copied == none:
            self.tell("Copy a film preset first: right-click a photo, Copy Film Preset.")
            return 0
        let text = self.film_copied else return 0
        if positions.length == 0:
            self.tell("Select photos to paste the film preset onto.")
            return 0
        let changed = self.give(positions, text, stack = true)
        self.tell(f"Pasted the film preset onto {changed} photo{"" if changed == 1 else "s"}." if changed > 0 else "The film preset changes nothing here.")
        return changed

    # mark: presets ===========================================================================

    ## What a photo with preset mark `mark` and settings `text` was given: its
    ## mark, or for one without (given a look before marks were kept), the
    ## film look, else the start, its settings carry whole.
    pub func mark_of(self, mark: str, text: str) -> str!:
        return mark if mark != "" else carried_mark(text)

    ## The developed photo's settings as a saved preset holds them: without its
    ## framing, and naming its recipe even when it is the default one; none
    ## without a developed photo.
    pub func preset_text(self) -> str?!:
        self.flush()
        if self.developing < 0:
            return none
        var parts = parts_of(self.committed, false)
        if not self.committed.contains("recipe="):
            parts.append(self.controls.look.recipe_text())
        return parts.join(";")

    ## Stack preset `name`, settings `text`, on the photos at `positions`.
    pub func apply_preset(self, positions: list[int], name: str, text: str) -> unit!:
        if positions.length == 0:
            self.tell("Select photos to apply a preset to.")
            return
        let changed = self.give(positions, text, stack = true)
        self.tell(f"Applied “{name}” to {changed} photo{"" if changed == 1 else "s"}." if changed > 0 else f"“{name}” changes nothing here.")

    func tell(self, text: str) -> unit!:
        if let say = self.on_status:
            say(text)

test "a pasted film preset replaces the film whole and keeps the photo's light and framing":
    let copied = film_part("film_stock=Kodak EXR 500T 5298;film_grain=110;exposure=1;temperature=3200")
    let pasted = stacked(copied, "film_stock=Kodak Vision 500T 5279;develop_time=4;temperature=4000;crop_left=0.1")
    let look = settings.look(pasted)
    assert(look.get("film_stock") == 1.0 and look.get("film_grain") == 110.0)
    # The target's own development is gone, its light and framing stay.
    assert(look.get("develop_time") == settings.look("").get("develop_time"))
    assert(look.get("temperature") == 4000.0 and look.get("crop_left") == 0.1 and look.get("exposure") == 0.0)

test "a photo given a look carries its mark":
    let given = stacked(looks.text(0), "exposure=0.5;crop_left=0.1")
    assert(carried_mark(given) == preset_marks.for_look(0))
    assert(carried_mark(stacked(settings.mode_text(1), "exposure=0.5")) == preset_marks.for_start(1))
    assert(carried_mark("exposure=0.5;film_grain=150") == "")