Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-photo

Source of release 0.1.0

0.1.0 / src / library_pane.luc

## The Photos pane: the photos of the folder picked in the Library pane
## (folders_pane.luc), as a grid of thumbnails in justified rows, each tile its
## photo's shape, and its bar below with the filter, the count and the row
## height; or as a list (List beside the search): a table of name, capture time,
## camera, lens, rating and preset. Either drags its selected photos onto the
## Library pane's folders, and the selection carries between them. Thumbnails stream in from the loader's
## threads for the cells on screen and a few rows around them; pictures far
## from the screen are let go, so a library of any size costs a screenful.
## The search field over the grid shows only photos whose name, camera, lens,
## capture date or preset holds what is typed. An empty library says how to
## fill it, with the import commands at hand; a filter or search that hides
## every photo says so.
from luce_ui.ui import Application, Notifier, ThumbnailGrid, GridFlow, TableView, TableColumn, TableCell, Image, Slider, Text, TextField, HStack, VStack, Spacer, Menu, Command, Font, Panel, Size, Button, ButtonStyle, Widget, ContextMenu
from properties import camera_name
from interop import Connection
from photo_library import PhotoLibrary
from thumbs import Loader
import thumbs
import library
import preset_marks

## The list's rows, as tall as the Library pane's folders.
pub let list_row_height: float = 24.0

pub class LibraryPane:
    pub let panel: Panel
    pub let grid: ThumbnailGrid
    let library: PhotoLibrary
    let loader: Loader
    let count: Text
    ## What shows when the grid has nothing to show.
    let empty: VStack
    let empty_title: Text
    let empty_hint: Text
    let empty_buttons: HStack
    let size: Slider
    pub let search: TextField
    ## Told by the loader's threads when thumbnails are ready (`wake_with`).
    var loaded: Notifier? = none
    ## The list, and whether it shows in place of the grid; the bar's switches.
    pub let list: TableView
    pub var listing: bool = false
    let grid_button: Button
    let list_button: Button
    ## Whether the pane is the other modes' filmstrip (always the grid).
    var strip: bool = false
    var listing_before: bool = false
    let search_row: HStack
    ## Grid items whose thumbnails were asked for and have not arrived.
    var requested: set[int] = {}
    ## The pictures loaded, by photo id: they outlive a refresh, which may move
    ## photos to other positions (an import adds photos among them).
    var pictures: map[int, Image] = {}
    ## Each photo's aspect ratio as its thumbnail showed it, by id: exact, crops
    ## included, and kept when the picture is let go.
    var aspects: map[int, float] = {}
    ## The range of items thumbnails are kept for, as last arranged.
    var kept_first: int = -1
    var kept_last: int = -1
    var connections: list[Connection] = []
    ## The filter commands, for the Filter menu.
    pub let filters: list[Command]
    ## A library just opened shows its newest photos (the last, by capture
    ## time) once the grid has its size: the first visible range it reports.
    var newest_wanted: bool = true
    ## Called with the lead item when the selection changes.
    pub var on_pick: func(int) -> unit!? = none

    ## `imports` are the empty library's buttons; `photo_commands` the photos'
    ## right-click menu (a right-click selects the photo under it first).
    pub func init(self, photos: PhotoLibrary, font: Font, imports: list[Command], photo_commands: list[Command]) -> unit!:
        self.library = photos
        self.loader = thumbs.start(3, library.thumb_edge)
        self.grid = ThumbnailGrid(photos.index.count(), 160.0, font = font)
        # A tall pane scrolls down through rows; a wide, short one (the
        # filmstrip along the bottom of the other modes) scrolls sideways.
        self.grid.set_flow(GridFlow.automatic)
        # Photos drag onto the Library pane's folders.
        self.grid.set_drag_kind("photos")
        self.count = Text("", font = font, muted = true)
        self.size = Slider("", 64.0, 480.0, 160.0, font = font, show_value = false)
        self.size.layout().set_limits(Size(90.0, 0.0), Size(140.0, 16384.0))
        self.filters = [Command("All Photos", id = "filter_all"), Command("Picked", id = "filter_picked"),
                        Command("Rejected", id = "filter_rejected"), Command("Hide Rejected", id = "filter_unrejected"),
                        Command("★ and Above", id = "filter_1"), Command("★★★ and Above", id = "filter_3"),
                        Command("★★★★★", id = "filter_5")]
        let settings = [(0, 0), (0, 1), (0, -1), (0, 2), (1, 2), (3, 2), (5, 2)]
        for (at, command) in self.filters.indexed():
            let (stars, flags) = settings[at]
            self.connections.append(command.on_trigger(func () -> unit!:
                self.library.set_filter(stars, flags, 0)
                self.refresh()))
        self.connections.append(self.size.on_change(func (value: float) -> unit!:
            self.grid.set_cell_size(value)))
        # The cells on screen changed (a scroll, a resize): load theirs.
        self.connections.append(self.grid.on_visible(func (first: int) -> unit!:
            self.load_visible()))
        self.connections.append(self.grid.on_resize(func (cell: int) -> unit!:
            self.size.set_value(float(cell))))
        self.connections.append(self.grid.on_select(func (lead: int) -> unit!:
            if let pick = self.on_pick:
                pick(lead)))
        self.list = TableView([TableColumn(title = "Name", weight = 2.0), TableColumn(title = "Captured", width = 150.0),
                               TableColumn(title = "Camera", weight = 1.0), TableColumn(title = "Lens", weight = 1.0),
                               TableColumn(title = "Rating", width = 70.0), TableColumn(title = "Preset", weight = 1.0)],
                              [], row_height = list_row_height, font = font, multiple = true)
        self.list.set_drag_kind("photos")
        self.list.layout().set_visible(false)
        self.connections.append(self.list.on_select(func (lead: int) -> unit!:
            if let pick = self.on_pick:
                pick(lead)))
        self.grid_button = Button("Grid", font = font)
        self.list_button = Button("List", font = font)
        self.grid_button.set_grouped(true)
        self.list_button.set_grouped(true)
        self.connections.append(self.grid_button.on_click(func () -> unit!:
            self.show_list(false)))
        self.connections.append(self.list_button.on_click(func () -> unit!:
            self.show_list(true)))
        self.grid_button.set_style(ButtonStyle.selected)
        let bar = HStack([Menu("Filter", self.filters, font = font), Spacer(), self.count, self.size], spacing = 6.0, padding = 4.0)
        # Above the grid while it shows nothing; the grid stays, so photos drop on it.
        self.empty_title = Text("", font = font)
        self.empty_hint = Text("", font = font, muted = true)
        var buttons: list[Widget] = [Spacer()]
        for command in imports:
            let button = Button(command.text(), font = font)
            self.connections.append(button.on_click(func () -> unit!:
                command.trigger()))
            buttons.append(button)
        buttons.append(Spacer())
        self.empty_buttons = HStack(buttons, spacing = 8.0)
        self.empty = VStack([HStack([Spacer(), self.empty_title, Spacer()]), HStack([Spacer(), self.empty_hint, Spacer()]), self.empty_buttons],
                            spacing = 10.0, padding = 24.0)
        self.search = TextField("", font = font, placeholder = "Search", cells = 16.0)
        self.connections.append(self.search.on_change(func (text: str) -> unit!:
            self.library.set_search(text)
            self.refresh()))
        self.search_row = HStack([self.search, HStack([self.grid_button, self.list_button], spacing = 0.0)], spacing = 6.0, padding = 4.0)
        let photos_box = VStack([self.grid, self.list], spacing = 0.0)
        photos_box.layout().set_flex()
        let photo_menu = ContextMenu(photos_box, photo_commands, font = font)
        let content = VStack([self.search_row, self.empty, photo_menu], spacing = 0.0)
        content.layout().set_flex()
        self.panel = Panel("Photos", content, minimum = Size(240.0, 200.0), closable = false, footer = bar, id = "library")
        self.refresh()

    ## Show the library's index afresh. Positions may now name other photos, so
    ## requests in flight are dropped and loaded pictures move with their photos.
    pub func refresh(self) -> unit!:
        self.loader.clear()
        self.requested = {}
        self.kept_first = -1
        self.kept_last = -1
        self.grid.keep_images(0, 0)
        let index = self.library.index
        self.grid.set_count(index.count())
        for at in 0..<index.count():
            self.grid.set_badges(at, index.rating(at), index.flag(at), index.label(at), index.edited(at), raw = index.kind(at) == "RAW")
            self.grid.set_aspect(at, self.aspect_of(at))
            if let picture = self.pictures[index.id(at)]:
                self.grid.set_image(at, picture)
        self.fill_list()
        let total = index.total()
        let shown = index.count()
        self.count.set_text(f"{shown} photos" if shown == total else f"{shown} of {total} photos")
        self.empty.layout().set_visible(shown == 0)
        self.empty_buttons.layout().set_visible(total == 0)
        if total == 0:
            self.empty_title.set_text("This library has no photos yet")
            self.empty_hint.set_text("Import a folder or photos, or drop them here.")
        else:
            self.empty_title.set_text("No photos match the filter or search")
            self.empty_hint.set_text("Filter › All Photos and an empty search show them all.")

    ## As the Library mode's grid (`strip` false), with the search, or as a
    ## filmstrip along the bottom of the other modes: no search, the grid
    ## only (wide and short, it scrolls sideways).
    pub func set_strip(self, strip: bool) -> unit!:
        # A filmstrip is the grid; the list comes back with the Library mode.
        if strip and self.listing:
            self.show_list(false)
            self.listing_before = true
        elif not strip and self.listing_before:
            self.listing_before = false
            self.show_list(true)
        self.strip = strip
        self.search_row.layout().set_visible(not strip)
        let lead = self.grid.selected_index()
        if lead >= 0:
            self.grid.reveal(lead)

    ## Show another library: no picture loaded for this one's ids is kept.
    pub func show_library(self) -> unit!:
        self.pictures = {}
        self.aspects = {}
        self.grid.select(-1)
        self.newest_wanted = true
        self.refresh()

    ## The tile shape of the photo at `at`: its thumbnail's once seen, else
    ## the catalog's size (upright already).
    func aspect_of(self, at: int) -> float:
        let index = self.library.index
        if let known = self.aspects[index.id(at)]:
            return known
        let width = float(index.width(at))
        let height = float(index.height(at))
        return width / height if width > 0.0 and height > 0.0 else 1.5

    ## Redraw the badges of the items at `positions`.
    pub func refresh_badges(self, positions: list[int]) -> unit!:
        let index = self.library.index
        for at in positions:
            self.grid.set_badges(at, index.rating(at), index.flag(at), index.label(at), index.edited(at), raw = index.kind(at) == "RAW")
        # The list's rating column too, its selection kept.
        let picked = self.selection()
        let lead = self.list.selected_index()
        self.fill_list()
        if lead >= 0:
            self.list.select(lead)
            for at in picked:
                self.list.mark(at, true)

    ## Let photo `id`'s thumbnail go, so it loads again (its file changed).
    pub func reload_thumbnail(self, id: int) -> unit!:
        _ = self.pictures.remove(id)
        let at = self.library.index.position_of(id)
        if at >= 0:
            self.grid.clear_image(at)
            _ = self.requested.remove(at)

    ## The selected items, the lead among them.
    pub func selection(self) -> list[int]:
        var picked: list[int] = []
        for at in 0..<self.grid.item_count():
            if self.is_selected(at):
                picked.append(at)
        return picked

    ## The selection, in whichever view shows: its lead (-1 none), its size,
    ## whether `at` is in it; choosing `at` alone, or every photo.
    pub func lead(self) -> int:
        return self.list.selected_index() if self.listing else self.grid.selected_index()
    pub func selected_count(self) -> int:
        return self.list.selected_count() if self.listing else self.grid.selected_count()
    pub func is_selected(self, at: int) -> bool:
        return self.list.is_selected(at) if self.listing else self.grid.is_selected(at)
    pub func item_count(self) -> int:
        return self.grid.item_count()
    pub func select(self, at: int) -> unit!:
        self.grid.select(at)
        self.list.select(at)
    pub func select_all(self) -> unit!:
        self.grid.select_all()
        self.list.select_all()

    ## Show the list (`on`) or the grid, the selection carried across.
    pub func show_list(self, on: bool) -> unit!:
        if on == self.listing or (on and self.strip):
            return
        let picked = self.selection()
        let lead = self.lead()
        self.listing = on
        self.grid.layout().set_visible(not on)
        self.list.layout().set_visible(on)
        self.grid_button.set_style(ButtonStyle.plain if on else ButtonStyle.selected)
        self.list_button.set_style(ButtonStyle.selected if on else ButtonStyle.plain)
        if on:
            self.list.select(lead)
            for at in picked:
                self.list.mark(at, true)
        else:
            self.grid.select(lead)
            for at in picked:
                self.grid.mark(at, true)
            if lead >= 0:
                self.grid.reveal(lead)

    ## The list's rows: each photo's name, capture time, camera, lens, rating and preset.
    func fill_list(self) -> unit!:
        let index = self.library.index
        let presets = self.library.presets
        var cells: list[TableCell] = []
        for at in 0..<index.count():
            let preset = preset_marks.name_of(presets, index.preset(at))
            cells.append(TableCell(text = index.name(at)))
            cells.append(TableCell(text = index.captured(at).replace("T", "  "), muted = true))
            cells.append(TableCell(text = camera_name(index.make(at), index.model(at))))
            cells.append(TableCell(text = index.lens(at), muted = true))
            cells.append(TableCell(text = "★".repeat(index.rating(at))))
            cells.append(TableCell(text = preset, muted = true))
        self.list.set_rows(cells)

    ## Take in finished thumbnails and ask for the ones now on screen; called on
    ## the window's timer.
    ## Take thumbnails as the loader's threads finish them: `app` runs it when
    ## they say so.
    pub func wake_with(self, app: Application) -> unit!:
        let notifier = app.notifier(self.take_thumbnails)
        self.loader.wake_with(notifier)
        self.loaded = notifier

    ## Put the thumbnails the loader finished into the grid.
    func take_thumbnails(self) -> unit!:
        var at = self.loader.take()
        while at >= 0:
            if at < self.grid.item_count():
                let picture = Image(self.loader.taken_width(), self.loader.taken_height())
                picture.write(self.loader.taken_pixels())
                self.grid.set_image(at, picture)
                let id = self.library.index.id(at)
                self.pictures[id] = picture
                let aspect = float(self.loader.taken_width()) / float(self.loader.taken_height())
                self.aspects[id] = aspect
                self.grid.set_aspect(at, aspect)
            _ = self.requested.remove(at)
            at = self.loader.take()

    ## Ask for the thumbnails of the cells on screen and a few rows around
    ## them, and let go of those far from it.
    func load_visible(self) -> unit!:
        if self.newest_wanted and self.grid.item_count() > 0 and self.grid.layout().bounds().height > 0.0:
            self.newest_wanted = false
            # Revealing reports the new range, which comes back here.
            self.grid.reveal(self.grid.item_count() - 1)
            return
        let first = self.grid.first_visible()
        let last = self.grid.last_visible()
        if last <= first:
            return
        # A few rows either side load ahead of scrolling.
        let margin = self.grid.columns() * 3
        let low = first - margin if first > margin else 0
        let high = last + margin if last + margin < self.grid.item_count() else self.grid.item_count()
        if low != self.kept_first or high != self.kept_last:
            self.kept_first = low
            self.kept_last = high
            self.loader.keep(low, high)
            # Pictures stay a little longer than requests, so scrolling back is instant.
            let keep_low = low - margin * 2 if low > margin * 2 else 0
            let keep_high = high + margin * 2 if high + margin * 2 < self.grid.item_count() else self.grid.item_count()
            self.grid.keep_images(keep_low, keep_high)
            var kept: map[int, Image] = {}
            for position in keep_low..<keep_high:
                let id = self.library.index.id(position)
                if let picture = self.pictures[id]:
                    kept[id] = picture
            self.pictures = kept
            var still: set[int] = {}
            for wanted in self.requested:
                if wanted >= low and wanted < high:
                    still.insert(wanted)
            self.requested = still
        # The loader serves its newest requests first: ask for the rows around
        # the screen, then the screen from the bottom up, so its top comes first.
        for item in low..<first:
            self.request(item)
        for item in last..<high:
            self.request(item)
        var item = last - 1
        while item >= first:
            self.request(item)
            item -= 1

    func request(self, item: int) -> unit!:
        if self.grid.has_image(item) or item in self.requested:
            return
        self.requested.insert(item)
        self.loader.request(item, self.library.thumb_path(self.library.index.id(item)))

    pub func close(self):
        for connection in self.connections:
            connection.disconnect()
        self.connections.clear()
        if let notifier = self.loaded:
            notifier.close()
        self.loader.close()