Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-photo

Source of release 0.1.0

0.1.0 / src / panels.luc

## The window: a toolbar with the mode bar (modes.luc) over docked panes, a
## status line below. In Library mode the photos' grid, the viewer, Presets and
## Properties (the photo's facts and marks); in Capture, Develop, Print and View
## the viewer and Properties (the mode's controls) with the photos along the
## bottom as a filmstrip. Each mode tints the window's accent with its color.
## The panels carry what happens between the panes: picking photos in the grid
## shows the lead one in the viewer and Properties; ratings, flags and labels
## act on the whole selection; an import's progress shows in the status line
## while the grid fills in.
from luce_ui.ui import Notifier, VStack, HStack, Text, Font, Spacer, DStack, DockPosition, Application, Menu, CommandPalette, Command
from interop import Connection
from actions import Actions, label_number
from photo_library import PhotoLibrary
from library_pane import LibraryPane
from viewer import Viewer
from properties import PropertiesPane
from presets_pane import PresetsPane
from folders_pane import FoldersPane
from modes import ModeBar
import modes
import folder_tree
import theme
from rerender import Rerenderer
from develop_session import DevelopSession
from exporter import Exporter
import exporter
from export_dialog import ExportDialog
from luce_std import paths
from luce_ptp import ptp
from luce_ptp.ptp import Watcher
import wakers
from wakers import CameraWaker
from luce_develop import geometry
import rerender
import remembered
import library


## Seconds the grid waits, once an import adds photos, before it reads the catalog again.
let new_photos_delay: float = 1.0

pub class Panels:
    pub let body: VStack
    pub let actions: Actions
    pub let library: PhotoLibrary
    pub let library_pane: LibraryPane
    ## The folders, beside the photos in the Library mode.
    pub let folders: FoldersPane
    pub let viewer: Viewer
    pub let properties: PropertiesPane
    pub let presets: PresetsPane
    pub let dock: DStack
    pub let mode_bar: ModeBar
    ## The mode shown (modes.luc).
    pub var mode: int = -1
    var mode_before: int = -1
    ## Each mode's arrangement of panels (DStack.layout_text), kept when the
    ## mode is left and between runs (remembered.luc); "" for its usual one.
    var layouts: list[str] = []
    let status: Text
    ## What runs in the background, at the status line's right ("Developing 3 photos…").
    let activity: Text
    let palette: CommandPalette
    ## Develops edited photos' previews and thumbnails again.
    let rerenderer: Rerenderer
    ## Writes exports, and asks how.
    let exporter: Exporter
    let export_dialog: ExportDialog
    var connections: list[Connection] = []
    ## The developed photo: saving, undo and redo, settings between photos.
    pub let session: DevelopSession
    ## Whether photos an import added will show soon (a reload is waiting).
    var showing_soon: bool = false
    ## The workers' notifiers (`connect`).
    var notifiers: list[Notifier] = []
    ## The cameras plugged in, and what tells the window of them (`connect`).
    var cameras: Watcher? = none
    var camera_waker: CameraWaker? = none
    pub var app: Application? = none

    pub func init(self, font: Font, root: str) -> unit!:
        self.library = PhotoLibrary(root)
        self.actions = Actions()
        self.rerenderer = rerender.start()
        self.exporter = exporter.start()
        self.export_dialog = ExportDialog(font)
        self.export_dialog.chosen = self.export
        self.export_dialog.ask_target = func (name: str) -> str!:
            let app = self.app else return ""
            return app.save_file("Export to", name)
        let shared = self.actions
        self.library_pane = LibraryPane(self.library, font, [shared.import_folder, shared.import_photos],
                                        [shared.copy_film, shared.paste_film, Command("", divider = true), shared.copy_settings, shared.paste_settings,
                                         shared.sync_settings, Command("", divider = true), shared.reset_settings, Command("", divider = true),
                                         shared.move_to_trash, shared.put_back])
        self.folders = FoldersPane(self.library, font, [self.actions.import_folder, self.actions.import_photos])
        self.folders.on_status = self.tell
        self.folders.on_camera_import = self.import_camera
        self.folders.on_pick = func (id: int) -> unit!:
            self.library.show_folder(id)
            self.library_pane.refresh()
            self.library_pane.select(-1)
            self.show_selection(-1)
        self.folders.tree.on_drop = self.move_photos
        self.folders.on_move_here = func (id: int) -> unit!:
            self.move_photos(id, self.library_pane.selection())
        self.viewer = Viewer()
        self.properties = PropertiesPane(self.library, self.actions, font)
        self.status = Text("", font = font, muted = true)
        self.activity = Text("", font = font)
        self.palette = CommandPalette(self.actions.all, font = font)
        self.session = DevelopSession(self.library, self.properties.develop, self.viewer, self.library_pane, self.rerenderer)
        self.session.on_status = self.tell
        self.session.on_requested = self.show_activity
        self.presets = PresetsPane(self.library, font)
        self.presets.current = self.session.preset_text
        self.presets.on_status = self.tell
        self.presets.on_apply = func (name: str, text: str, mark: str) -> unit!:
            let picked = self.library_pane.selection()
            self.session.apply_preset(picked, name, text)
            self.show_activity()
            # The photos remember what they were given (preset_marks.luc); a
            # saved preset's parameters the Library mode then shows.
            if picked.length > 0:
                self.library.set_preset_mark(picked, mark)
                self.properties.show(self.library_pane.lead(), picked.length)
                self.library_pane.refresh_badges(picked)
                self.presets.follow(mark)
        self.mode_bar = ModeBar(font)
        self.mode_bar.on_pick = self.set_mode
        self.library_pane.on_pick = self.show_selection
        self.properties.develop.on_change = self.session.changed
        let controls = self.properties.develop
        controls.on_guide_tool = func (on: bool) -> unit!:
            self.viewer.set_guiding(on, controls.guide_points())
        controls.on_crop_tool = func (on: bool, aspect: float) -> unit!:
            self.viewer.set_cropping(on, controls.crop_values(), self.aspect_ratio(aspect))
        controls.on_turn = func () -> unit!:
            self.viewer.swap_sides()
        controls.on_crop_aspect = func (aspect: float) -> unit!:
            self.viewer.set_crop_aspect(self.aspect_ratio(aspect))
        self.viewer.on_crop = func (edges: list[float]) -> unit!:
            controls.set_crop(edges)
            self.session.changed()
        controls.on_guides_cleared = func () -> unit!:
            if self.viewer.guiding:
                self.viewer.set_guiding(true, [])
        self.viewer.on_guides = func (points: list[float]) -> unit!:
            controls.set_guide_points(points)
            # The guides decide the perspective: solve, show, develop.
            if self.viewer.photo_width() > 0:
                geometry.solve_look(controls.look, float(self.viewer.photo_width()), float(self.viewer.photo_height()))
            controls.show_values()
            self.session.changed()
        self.viewer.on_developed = func (temperature: float, tint: float, seconds: float) -> unit!:
            self.properties.develop.set_shot(temperature, tint, seconds)
            self.viewer.want_histogram()
        self.bind_actions()
        let actions = self.actions
        let toolbar = HStack([Spacer(), self.mode_bar, Spacer(),
                              Menu("Library", [actions.new_library, actions.open_library, Command("", divider = true), actions.import_photos, actions.import_folder, actions.export_photos, actions.select_all, actions.bigger, actions.smaller], font = font),
                              Menu("Filter", self.library_pane.filters, font = font),
                              Menu("Photo", actions.ratings + [actions.pick, actions.reject, actions.unflag] + actions.labels + [actions.previous, actions.next, actions.zoom, actions.before_after, actions.move_to_trash, actions.put_back, actions.watch_development, actions.refine_grain], font = font),
                              Menu("Edit", [actions.undo, actions.redo, actions.copy_settings, actions.paste_settings, actions.copy_film, actions.paste_film,
                                                    actions.sync_settings, actions.reset_settings], font = font),
                              Menu("Window", actions.modes + [Command("", divider = true), actions.palette, actions.reset_layout], font = font)], spacing = 4.0, padding = 4.0)
        self.dock = DStack([self.viewer.panel], font = font)
        self.dock.add(self.properties.panel, self.viewer.panel, DockPosition.right)
        self.dock.set_fraction(self.viewer.panel, 0.74)
        self.dock.layout().set_flex()
        let footer = HStack([self.status, Spacer(), self.activity], padding = 6.0)
        self.body = VStack([toolbar, self.dock, footer, self.export_dialog.dialog, self.palette], spacing = 0.0)
        self.body.layout().set_flex()
        self.actions.refresh(false)
        for mode in 0..<modes.count:
            self.layouts.append(remembered.layout(mode))
        self.arrange(modes.library)
        self.greet()

    func bind_actions(self) -> unit!:
        let actions = self.actions
        self.connections.append(actions.new_library.on_trigger(self.choose_new_library))
        self.connections.append(actions.open_library.on_trigger(self.choose_library))
        self.connections.append(actions.import_photos.on_trigger(self.choose_import))
        self.connections.append(actions.import_folder.on_trigger(self.choose_import_folder))
        self.connections.append(self.library_pane.grid.on_drop(self.import_dropped))
        self.connections.append(actions.select_all.on_trigger(func () -> unit!:
            self.library_pane.select_all()
            self.show_selection(self.library_pane.lead())))
        self.connections.append(actions.bigger.on_trigger(func () -> unit!:
            self.library_pane.grid.set_cell_size(self.library_pane.grid.cell_size() * 1.25)))
        self.connections.append(actions.smaller.on_trigger(func () -> unit!:
            self.library_pane.grid.set_cell_size(self.library_pane.grid.cell_size() / 1.25)))
        for (stars, command) in actions.ratings.indexed():
            self.connections.append(command.on_trigger(func () -> unit!:
                self.mark("rating", stars)))
        self.connections.append(actions.pick.on_trigger(func () -> unit!:
            self.mark("flag", 1)))
        self.connections.append(actions.reject.on_trigger(func () -> unit!:
            self.mark("flag", -1)))
        self.connections.append(actions.unflag.on_trigger(func () -> unit!:
            self.mark("flag", 0)))
        for (at, command) in actions.labels.indexed():
            let label = label_number(at)
            self.connections.append(command.on_trigger(func () -> unit!:
                self.mark("label", label)))
        self.connections.append(actions.next.on_trigger(func () -> unit!:
            self.step(1)))
        self.connections.append(actions.previous.on_trigger(func () -> unit!:
            self.step(-1)))
        self.connections.append(actions.export_photos.on_trigger(func () -> unit!:
            let picked = self.library_pane.selection()
            if picked.length > 0:
                self.session.flush()
                self.export_dialog.open(picked.length, self.library.index.name(picked[0]))))
        self.connections.append(actions.undo.on_trigger(self.session.undo))
        self.connections.append(actions.redo.on_trigger(self.session.redo))
        self.connections.append(actions.copy_settings.on_trigger(self.session.copy))
        for command in [actions.move_to_trash, actions.move_to_trash_forward]:
            self.connections.append(command.on_trigger(func () -> unit!:
                self.trash_selection()))
        self.connections.append(actions.put_back.on_trigger(func () -> unit!:
            let picked = self.library_pane.selection()
            if self.library.folder != folder_tree.trash or picked.length == 0:
                self.tell("Put Back takes photos out of the Trash: show the Trash and select them.")
                return
            self.move_photos(0, picked)))
        self.connections.append(actions.copy_film.on_trigger(func () -> unit!:
            self.session.copy_film(self.library_pane.lead())))
        self.connections.append(actions.paste_film.on_trigger(func () -> unit!:
            let picked = self.library_pane.selection()
            if self.session.paste_film(picked) > 0:
                # The photos take the copied photo's preset mark, so the
                # Presets pane and Properties name what they now have.
                self.library.set_preset_mark(picked, self.session.film_mark)
                self.library_pane.refresh_badges(picked)
                self.show_selection(self.library_pane.lead())
            self.show_activity()))
        self.connections.append(actions.paste_settings.on_trigger(func () -> unit!:
            self.session.paste(self.library_pane.selection())))
        self.connections.append(actions.sync_settings.on_trigger(func () -> unit!:
            self.session.sync(self.library_pane.selection())))
        self.connections.append(actions.reset_settings.on_trigger(func () -> unit!:
            self.session.reset(self.library_pane.selection())))
        self.connections.append(actions.zoom.on_trigger(func () -> unit!:
            self.viewer.toggle_zoom()))
        self.connections.append(actions.before_after.on_trigger(func () -> unit!:
            let on = not actions.before_after.is_checked()
            actions.before_after.set_checked(on)
            self.viewer.compare_before(on)))
        self.connections.append(actions.watch_development.on_trigger(func () -> unit!:
            let on = not actions.watch_development.is_checked()
            actions.watch_development.set_checked(on)
            self.viewer.watch_development(on)))
        self.connections.append(actions.refine_grain.on_trigger(func () -> unit!:
            let on = not actions.refine_grain.is_checked()
            actions.refine_grain.set_checked(on)
            self.viewer.refine_grain(on)))
        for (mode, command) in actions.modes.indexed():
            self.connections.append(command.on_trigger(func () -> unit!:
                self.set_mode(mode)))
        # The current mode's panes back where they start.
        self.connections.append(actions.reset_layout.on_trigger(func () -> unit!:
            self.layouts[self.mode] = ""
            self.arrange(self.mode, keep = false)))
        self.connections.append(actions.palette.on_trigger(func () -> unit!:
            self.palette.open()))
        self.connections.append(actions.quit.on_trigger(func () -> unit!:
            if let app = self.app:
                app.stop()))

    ## Put the selected photos in the Trash (in the Trash already: nothing).
    func trash_selection(self) -> unit!:
        if self.library.folder == folder_tree.trash:
            self.tell("These photos are in the Trash: right-click the Trash to empty it, or Put Back.")
            return
        self.move_photos(folder_tree.trash, self.library_pane.selection())

    ## Move the photos at `picked` (Photos pane positions) into folder `id` (0: none).
    func move_photos(self, id: int, picked: list[int]) -> unit!:
        if picked.length == 0:
            self.tell("Select photos to move.")
            return
        self.session.flush()
        self.library.move_photos(picked, id)
        self.library_pane.refresh()
        self.folders.refresh()
        # The photos moved may have left the view: nothing stays selected.
        self.library_pane.select(-1)
        self.show_selection(-1)
        let at = self.library.folders.position_of(id)
        let name = f"“{self.library.folders.name(at)}”" if at >= 0 else ("the Trash" if id == folder_tree.trash else "no folder")
        self.tell(f"Moved {picked.length} photo{"" if picked.length == 1 else "s"} to {name}.")

    # mark: modes ===============================================================================

    ## Go to mode `mode`: its panes, its controls, its color.
    pub func set_mode(self, mode: int) -> unit!:
        if mode == self.mode:
            return
        self.session.flush()
        self.arrange(mode)

    ## Lay the panes out for `mode`: Library with the grid at the left and
    ## Presets over Properties at the right; the others with the photos as a
    ## filmstrip along the bottom and the mode's controls in Properties.
    ## The mode left keeps its arrangement (unless `keep` is false); mode
    ## `mode` gets back the one it had, else its usual one.
    func arrange(self, mode: int, keep: bool = true) -> unit!:
        if keep and self.mode_before >= 0:
            self.layouts[self.mode_before] = self.dock.layout_text()
        self.mode = mode
        self.mode_bar.choose(mode)
        let was_strip = self.mode_before >= 0 and self.mode_before != modes.library
        if (mode != modes.library) != was_strip or self.mode_before < 0:
            self.library_pane.set_strip(mode != modes.library)
        self.mode_before = mode
        if not self.restore_layout(mode):
            self.usual_layout(mode)
        self.properties.set_mode(mode)
        # The Library mode shows developed pictures; the others develop live.
        self.viewer.set_live(mode != modes.library)
        for (at, command) in self.actions.modes.indexed():
            command.set_checked(at == mode)
        if let app = self.app:
            app.set_theme(theme.editor_theme(modes.color(mode)))

    ## Mode `mode`'s arrangement as it was left; whether there was one that held.
    func restore_layout(self, mode: int) -> bool!:
        let text = self.layouts[mode]
        if text == "":
            return false
        let panels = [self.viewer.panel, self.properties.panel, self.library_pane.panel, self.presets.panel, self.folders.panel]
        self.dock.restore_layout(text, panels) catch failure:
            self.layouts[mode] = ""
            return false
        return true

    ## Mode `mode`'s usual arrangement: the viewer with Properties at its right;
    ## in Library the folders, the photos at its left and Presets over
    ## Properties, else the photos as a filmstrip under the viewer.
    func usual_layout(self, mode: int) -> unit!:
        for panel in [self.library_pane.panel, self.presets.panel, self.folders.panel, self.properties.panel]:
            if self.dock.contains(panel):
                self.dock.remove(panel)
        self.dock.add(self.properties.panel, self.viewer.panel, DockPosition.right)
        self.dock.set_fraction(self.viewer.panel, 0.74)
        if mode == modes.library:
            self.dock.add(self.library_pane.panel, self.viewer.panel, DockPosition.left)
            self.dock.set_fraction(self.library_pane.panel, 0.4)
            self.dock.add(self.folders.panel, self.library_pane.panel, DockPosition.left)
            self.dock.set_fraction(self.folders.panel, 0.32)
            self.dock.add(self.presets.panel, self.properties.panel, DockPosition.top)
            self.dock.set_fraction(self.presets.panel, 0.4)
        else:
            self.dock.add(self.library_pane.panel, self.viewer.panel, DockPosition.bottom)
            self.dock.set_fraction(self.viewer.panel, 0.84)

    # mark: libraries ===========================================================================

    ## Library › New Library…: one save panel names it and says where it
    ## goes; the library is the folder <name>.library made there.
    func choose_new_library(self) -> unit!:
        let app = self.app else return
        let chosen = app.save_file("Name the new library and choose where to make it", "Photos")
        if chosen == "":
            return
        let root = chosen if chosen.ends_with(".library") else chosen + ".library"
        if library.exists(root) and not library.exists(library.catalog_path(root)):
            self.tell(f"{paths.base(root)} is already a folder there and not a library; choose another name.")
            return
        self.open_library(root)

    ## Library › Open Library…: a library bundle (the folder holding library.prism).
    func choose_library(self) -> unit!:
        let app = self.app else return
        let root = app.choose_folder("Choose a library to open")
        if root == "":
            return
        if not library.exists(library.catalog_path(root)):
            self.tell(f"{paths.base(root)} is not a Luced Photo library: it has no library.prism.")
            return
        self.open_library(root)

    ## Show the library at `root` in this window, made when it is missing.
    pub func open_library(self, root: str) -> unit!:
        if root == self.library.root:
            return
        self.session.flush()
        self.library.switch_to(root) catch failure:
            self.tell(f"Could not open {paths.base(root)}: {failure.message}")
            return
        self.session.forget()
        self.showing_soon = false
        self.library_pane.show_library()
        self.folders.refresh()
        self.presets.show()
        self.show_selection(-1)
        self.show_library_title()
        self.greet()

    ## The window's title names the library; it is remembered for the next run.
    pub func show_library_title(self) -> unit!:
        if let app = self.app:
            app.set_title(f"Luced Photo — {paths.stem(self.library.root)}")
        remembered.remember_library(self.library.root) catch failure:
            _ = failure

    func greet(self) -> unit!:
        let total = self.library.index.total()
        let name = paths.stem(self.library.root)
        self.tell(f"{name}: no photos yet" if total == 0 else f"{total} photos in {name}")

    # mark: importing ===========================================================================

    ## Import every photo under a folder (a card, a drive, a shoot): the importer walks it.
    func choose_import_folder(self) -> unit!:
        let app = self.app else return
        let chosen = app.choose_folder("Choose a folder of photos to import")
        if chosen != "":
            self.start_import([chosen])

    func choose_import(self) -> unit!:
        let app = self.app else return
        let chosen = app.open_files("Choose photos to import")
        if chosen != "":
            self.start_import(chosen.lines())

    func import_dropped(self) -> unit!:
        let box = self.library_pane.grid.layout()
        var dropped: list[str] = []
        for at in 0..<box.drop_count():
            dropped.append(box.drop_path(at))
        self.start_import(dropped)

    ## Import the files and folders at `sources`.
    pub func start_import(self, sources: list[str]) -> unit!:
        if sources.length == 0:
            return
        self.library.start_import(sources) catch failure:
            self.tell(failure.message)
            return
        self.tell("Looking for photos…")

    ## Import the photos on camera `at` the library lacks.
    func import_camera(self, at: int) -> unit!:
        let cameras = self.cameras else return
        self.library.start_camera_import(cameras, at) catch failure:
            self.tell(failure.message)
            return
        self.tell(f"Reading {cameras.name(at)}…")

    ## A camera came, went or got ready.
    func cameras_changed(self) -> unit!:
        let cameras = self.cameras else return
        self.folders.show_cameras(cameras)

    func take_import_events(self) -> unit!:
        for line in self.library.poll_import():
            let fields = line.split("\t")
            match fields[0]:
                "found":
                    self.tell(f"Importing {fields[1]} files…")
                "fetching":
                    self.tell(f"Copying {fields[1]} from the camera ({fields[2]} of {fields[3]})")
                "added":
                    self.tell(f"Imported {fields[2]} of {fields[3]}: {fields[4]}")
                    # New photos show a few at a time while the import goes on.
                    if not self.showing_soon:
                        self.showing_soon = true
                        if let app = self.app:
                            _ = app.after(new_photos_delay, func () -> unit!:
                                if self.showing_soon:
                                    self.show_new_photos())
                "skipped":
                    self.tell(f"Already in the library: {fields[1]}")
                "failed":
                    self.tell(f"Not imported: {fields[1]}: {fields[2]}")
                "done":
                    self.show_new_photos()
                    let skipped = f", {fields[2]} already in the library" if fields[2] != "0" else ""
                    let failed = f", {fields[3]} not imported" if fields[3] != "0" else ""
                    let stopped = f" The import stopped: {fields[4]}" if fields.length > 4 and fields[4] != "" else ""
                    self.tell(f"Imported {fields[1]} photos{skipped}{failed}.{stopped}")
                "error":
                    self.tell(f"The import stopped: {fields[1]}")
                _:
                    continue

    ## Read the catalog again and show it, keeping the lead photo selected.
    func show_new_photos(self) -> unit!:
        self.showing_soon = false
        let photos = self.library_pane
        let lead = photos.lead()
        let lead_id = self.library.index.id(lead) if lead >= 0 else -1
        self.library.reload()
        photos.refresh()
        self.folders.refresh()
        if lead_id >= 0:
            let at = self.library.index.position_of(lead_id)
            if at >= 0:
                photos.select(at)

    # mark: exporting ==========================================================================

    ## Export the selected photos as `format` at `quality` and long edge `edge`:
    ## the first to `target`, the rest beside it under their own names.
    pub func export(self, format: int, quality: int, edge: int, target: str, space: int = 0) -> unit!:
        let picked = self.library_pane.selection()
        let folder = paths.directory(target)
        let extension = ".png" if format == 1 else ".jpg"
        self.exporter.configure(format, quality, edge, space)
        var taken: set[str] = {}
        for (at, position) in picked.indexed():
            let index = self.library.index
            var path = target if at == 0 else paths.join(folder, paths.stem(index.name(position)) + extension)
            # Two photos of one name do not overwrite each other.
            var number = 2
            while path in taken:
                path = paths.join(folder, f"{paths.stem(index.name(position))}-{number}{extension}")
                number += 1
            taken.insert(path)
            self.exporter.add(self.library.original_path(position), index.settings(position), path)
        self.tell(f"Exporting {picked.length} photos…" if picked.length > 1 else "Exporting…")

    func take_export_events(self) -> unit!:
        for line in self.exporter.poll().lines():
            let fields = line.split("\t")
            match fields[0]:
                "exported":
                    self.tell(f"Exported {fields[1]} of {fields[2]}: {fields[3]}")
                "failed":
                    self.tell(f"Not exported: {fields[3]}: {fields[4]}")
                "done":
                    let failed = f", {fields[2]} failed" if fields[2] != "0" else ""
                    self.tell(f"Exported {fields[1]} photos{failed}.")
                _:
                    continue

    # mark: the selection =======================================================================

    ## Show the photo at `lead` (-1 none) in the viewer and Properties.
    pub func show_selection(self, lead: int) -> unit!:
        self.properties.develop.set_guiding(false)
        self.properties.develop.set_cropping(false)
        let selected = self.library_pane.selected_count()
        self.actions.refresh(lead >= 0)
        self.properties.show(lead, selected)
        if lead < 0:
            self.presets.follow("")
            self.session.close_photo()
            # The controls show the defaults, not the photo let go.
            self.properties.develop.show("", 5500.0, 0.0)
            self.viewer.clear()
            self.properties.histogram.clear()
            return
        let index = self.library.index
        let id = index.id(lead)
        let other = id != self.session.developing
        self.presets.follow(self.session.mark_of(index.preset(lead), index.settings(lead)))
        self.session.open(id, index.settings(lead))
        # The developed picture when it is of these settings; else the camera's
        # preview while the picture is made again.
        let settings = index.settings(lead)
        let ready = self.library.developed_ready(id, settings)
        let picture = self.library.developed_path(id) if ready else self.library.preview_path(id)
        if not ready:
            self.rerenderer.request(id, self.library.root, self.library.original_path(lead), settings)
        # A photo turned on its side shows its sides swapped.
        let sideways = int(self.properties.develop.look.get("geometry_turn")) % 2 == 1
        let width = index.height(lead) if sideways else index.width(lead)
        let height = index.width(lead) if sideways else index.height(lead)
        self.viewer.show(id, picture, self.library.original_path(lead), width, height)
        self.show_activity()

    ## Select the photo at `position` alone and show it.
    pub func show_photo(self, position: int) -> unit!:
        let photos = self.library_pane
        if position < 0 or position >= photos.item_count():
            return
        photos.select(position)
        self.show_selection(position)

    ## An Aspect menu value as width over height: -1 is the photo's own, 0 free.
    func aspect_ratio(self, value: float) -> float:
        if value >= 0.0:
            return value
        let height = float(self.viewer.photo_height())
        return float(self.viewer.photo_width()) / height if height > 0.0 else 0.0

    # mark: the develop =========================================================================

    ## Move the lead `direction` photos on, selecting it alone.
    func step(self, direction: int) -> unit!:
        let photos = self.library_pane
        let count = photos.item_count()
        if count == 0:
            return
        let lead = photos.lead()
        var target = lead + direction if lead >= 0 else 0
        target = 0 if target < 0 else (count - 1 if target >= count else target)
        photos.select(target)
        self.show_selection(target)

    ## Set `name` to `value` on every selected photo.
    func mark(self, name: str, value: int) -> unit!:
        let picked = self.library_pane.selection()
        if picked.length == 0:
            return
        self.library.set_marks(picked, name, value)
        self.library_pane.refresh_badges(picked)
        self.properties.show(self.library_pane.lead(), picked.length)

    # mark: the timer ===========================================================================

    ## Wire the background work to `app`'s loop: each worker's notifier runs
    ## what takes its results (no timer polls them), the save waits on
    ## `app.after`, and the histogram is measured right after the develop draws.
    pub func connect(self, app: Application) -> unit!:
        self.library_pane.wake_with(app)
        self.viewer.wake_with(app)
        self.session.connect(app)
        let exported = app.notifier(self.take_export_events)
        self.exporter.wake_with(exported)
        let redone = app.notifier(self.take_redone)
        self.rerenderer.wake_with(redone)
        let imported = app.notifier(self.take_import_events)
        self.library.import_notifier = imported
        let cameras = ptp.watch()
        let plugged = app.notifier(self.cameras_changed)
        self.camera_waker = wakers.wake_cameras(cameras, plugged)
        self.cameras = cameras
        self.cameras_changed()
        self.notifiers = [exported, redone, imported, plugged]
        self.viewer.on_histogram = func () -> unit!:
            # Read back after this frame, from the loop's next turn.
            _ = app.post(func () -> unit!:
                self.properties.histogram.set_bins(self.viewer.histogram()))

    ## Photos whose developed pictures were made again: their thumbnails, and
    ## the viewer's picture.
    func take_redone(self) -> unit!:
        var redone = self.rerenderer.take()
        while redone >= 0:
            self.library_pane.reload_thumbnail(redone)
            self.viewer.picture_ready(redone, self.library.developed_path(redone))
            redone = self.rerenderer.take()
        self.show_activity()

    ## The photos being developed again in the background, at the status line's
    ## right, and whether the one shown is among them (the viewer says so).
    func show_activity(self) -> unit!:
        let waiting = self.rerenderer.waiting()
        self.activity.set_text("" if waiting == 0 else (f"Developing {waiting} photos…" if waiting > 1 else "Developing 1 photo…"))
        let developing = self.session.developing
        self.viewer.set_pending(developing >= 0 and self.rerenderer.is_waiting(developing))

    pub func tell(self, text: str) -> unit!:
        self.status.set_text(text)

    pub func close(self):
        self.session.flush() catch failure:
            _ = failure
        # Each mode's arrangement for the next run.
        if self.mode_before >= 0:
            self.layouts[self.mode] = self.dock.layout_text() catch failure:
                recover ""
        remembered.remember_layouts(self.layouts) catch failure:
            _ = failure
        # Before the import stops: a camera's transaction waits for this thread,
        # and closing the watcher lets it go.
        if let waker = self.camera_waker:
            waker.close()
        if let cameras = self.cameras:
            cameras.close()
        for notifier in self.notifiers:
            notifier.close()
        for connection in self.connections:
            connection.disconnect()
        self.connections.clear()
        self.rerenderer.close()
        self.exporter.close()
        self.export_dialog.close()
        self.library_pane.close()
        self.viewer.close()
        self.properties.close()
        self.presets.close()
        self.folders.close()
        self.library.close()