feat: Presentations, for a teacher who downloaded tonight's session

PRESENTATIONS_ENABLED, off by default, independent of everything else. A
teacher downloads a session in ordinary Chrome and it is on the
Presentations screen a few seconds later, ready for the television. No
file manager, no import button, no Impress.

WHY NOTHING LAUNCHES A DOCUMENT APPLICATION. The brief was to use
existing presentation software, so the existing software was tried
first, on Debian 13, before any of this was designed. `soffice --show`
does start a real fullscreen slideshow — and needs XDG_SESSION_TYPE plus
a VCL plugin or it dies with "Failed to open display", shows a splash,
opened a "Tip of the Day: 1/225" dialog over the slides, and leaves the
Impress editor when the show ends. `okular --presentation` opens THREE
windows: the presentation, the ordinary document window behind it, and
an information dialog. zathura is not a presenter. pdfpc is the closest
and is another dependency with a presenter-console model. Every one of
them leaves an application on screen that can open any file on the
machine, and none of them knows there is a library to go back to.

So LibreOffice converts once, headless, at import, with no window on any
screen; poppler renders the pages; the classroom shows the pictures.
Measured: 0.34s for a ten-slide PPTX, 0.03s for its ten thumbnails,
0.10s for one slide at 1920px. That is not a new renderer — it is the
same engine Impress would have used live — and it means Escape is ours,
presenting is instant, and a PDF exported from Google Slides skips the
conversion entirely and keeps the appearance Google gave it.

THE THREE THINGS KEPT APART. The library thumbnail, the starting slide
and the retention clock are independent, because the first slide of a
Bible study session is a generic opening shared by every session and the
one that names it is usually the second. Quick Look chooses the picture;
it does not change where the slideshow starts and it does not count as
having presented anything. mark_presented() is called when a slide is
actually drawn, not when Present is pressed: an intention is not a
presentation, and a viewer that failed to start must not buy another
thirty days.

IMPORTING. The teacher's download is copied, never moved, renamed or
deleted. A file with a .crdownload beside it is still arriving. Wonder
Ink's own folder is not looked at. Two downloads of the same name are
two presentations, the second titled (2) — found in the lab, where a PDF
and a PPTX of one session both came out with the same name because the
import being named was excluded from the taken-titles set BY TITLE, and
a set holds one copy of a repeated string.

Metadata is written saying "importing" before any work, so a reboot
mid-conversion leaves a directory the next startup sweeps and imports
again. A file that cannot be converted gets a card saying so, offering
only Remove, with the teacher's download untouched.

Retention: 180 days never presented, 30 days from the last presentation,
every presentation starting the thirty over. The cleanup never touches a
presentation being shown, never leaves the library directory, and never
looks at Downloads.

The dock order is unchanged: Presentations is appended after the disc
player, so Wonder Ink, the browser and the player keep the places
teachers have been reaching for. There is a test for exactly that.

classroom-wonderink now asks feature() rather than carrying its own copy
of the default, so the panel and the command cannot disagree.

Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
ekklesia
2026-09-22 20:21:19 -05:00
co-authored by Claude Opus 5
parent 30d2d99230
commit 55f4c183c7
23 changed files with 2979 additions and 111 deletions
+52 -2
View File
@@ -3,7 +3,7 @@
"""Match the classroom's panel to the machine it is on.
Which applications a device offers is decided here, once, and written into
the three feature lines of the installed layout. The panel is then built
the feature lines of the installed layout. The panel is then built
from that layout at the next login.
Each application is its own question, and the shape of the machine is
@@ -15,6 +15,11 @@ never one of them:
Parent Call PARENT_CALL_ENABLED. Same rule.
Presentations PRESENTATIONS_ENABLED. Same rule again, and it asks
the machine nothing at all: a presentation needs a
screen, which every device has. Alone among these it
defaults to OFF, because no existing room has it.
the disc DVD_ENABLED *and* a drive being present. The setting can
player take the player away from a machine that has a drive;
nothing can put it on a machine that has none, because a
@@ -39,6 +44,7 @@ again at the next login.
"""
import glob
import json
import os
import re
import sys
@@ -61,10 +67,25 @@ FEATURE_LINES = (
("WONDERINK", "WONDERINK_ENABLED"),
("DVD", "DVD_ENABLED"),
("PARENT_CALL", "PARENT_CALL_ENABLED"),
("PRESENTATIONS", "PRESENTATIONS_ENABLED"),
)
MARKER = "/* CLASSROOM-FEATURES-BEGIN */"
# WHAT THE MANUAL IS ALLOWED TO KNOW ABOUT THIS DEVICE.
#
# This command already decides what the device offers, so it is also the
# place to write that answer down where the classroom account can read
# it. A list of setting NAMES, and nothing else: no values, no broker
# password, no Wi-Fi, no update address, none of the rest of device.conf
# — which the manual has no use for and the room should not be handed.
#
# In /run rather than /etc because it is derived, not configured: it is
# rewritten from device.conf at every boot by the same service that
# builds the bar, so it cannot go stale behind a setting somebody
# changed.
MANIFEST = "/run/ekklesia-classroom/features.json"
# The kernel names optical drives sr0, sr1, ... regardless of bus. Both
# views are checked: /dev is what anything opening the drive will use, and
# /sys/block is the kernel's own list, which cannot be left behind by a
@@ -121,6 +142,32 @@ def rewrite(text, variable, answer):
)
def publish(answers, path=MANIFEST):
"""Leave the enabled features where classroom-manual can read them.
Best effort on purpose. A room whose manual shows a page for
something it has not got is a small confusion; a panel that failed to
build because a directory was read-only is a room with no way of
getting anywhere.
"""
enabled = sorted(
setting for variable, setting in FEATURE_LINES if answers.get(variable)
)
try:
os.makedirs(os.path.dirname(path), exist_ok=True)
temporary = f"{path}.new"
with open(temporary, "w", encoding="utf-8") as handle:
json.dump(enabled, handle)
os.replace(temporary, path)
os.chmod(path, 0o644)
say(f"the manual will show {', '.join(enabled) or 'no optional pages'}")
except OSError as error:
say(f"could not write {path}: {error}")
def main():
path = sys.argv[1] if len(sys.argv) > 1 else LAYOUT
@@ -137,8 +184,11 @@ def main():
return 0
after = before
answers = wanted(read_device_config())
for variable, answer in wanted(read_device_config()).items():
publish(answers)
for variable, answer in answers.items():
after = rewrite(after, variable, answer)
if after == before:
+4 -89
View File
@@ -105,95 +105,10 @@ OVERALL_TIMEOUT = 210.0
CLOSE_AFTER_SUCCESS = 4.0
def load_colours():
"""The session's own palette, read from the colour scheme in use.
There is one set of design tokens in this classroom, and they live in
a Plasma colour scheme. Reading them here rather than repeating them
means this card follows classroom-theme light and dark without
knowing that either exists.
"""
palette = {
"window": "#141c20", "view": "#0f171a", "text": "#e6edef",
"dim": "#93a5aa", "accent": "#4fb3a8", "on_accent": "#0e1518",
"negative": "#e36a6a", "neutral": "#e0b15c", "positive": "#6fcf97",
"line": "#25333a",
}
scheme = "EkklesiaDark"
for path in (
os.path.expanduser("~/.config/kdeglobals"),
"/etc/ekklesia-classroom/xdg/kdeglobals",
"/etc/xdg/kdeglobals",
):
try:
with open(path, "r", encoding="utf-8") as handle:
section = None
for line in handle:
line = line.strip()
if line.startswith("["):
section = line
elif section and section.startswith("[General]") and \
line.startswith("ColorScheme="):
scheme = line.split("=", 1)[1].strip()
break
except OSError:
continue
else:
if scheme:
break
def rgb(value):
parts = [part.strip() for part in value.split(",")]
if len(parts) != 3:
return None
try:
return "#%02x%02x%02x" % tuple(int(part) for part in parts)
except ValueError:
return None
try:
with open(f"/usr/share/color-schemes/{scheme}.colors", "r",
encoding="utf-8") as handle:
group = None
for line in handle:
line = line.strip()
if line.startswith("["):
group = line
continue
if "=" not in line or group is None:
continue
key, value = (part.strip() for part in line.split("=", 1))
colour = rgb(value)
if colour is None:
continue
if group == "[Colors:Window]":
if key == "BackgroundNormal":
palette["window"] = colour
elif key == "ForegroundNormal":
palette["text"] = colour
elif key == "ForegroundInactive":
palette["dim"] = colour
elif key == "ForegroundNegative":
palette["negative"] = colour
elif key == "ForegroundNeutral":
palette["neutral"] = colour
elif key == "ForegroundPositive":
palette["positive"] = colour
elif key == "BackgroundAlternate":
palette["line"] = colour
elif group == "[Colors:View]" and key == "BackgroundNormal":
palette["view"] = colour
elif group == "[Colors:Selection]":
if key == "BackgroundNormal":
palette["accent"] = colour
elif key == "ForegroundNormal":
palette["on_accent"] = colour
except OSError:
pass
return palette
# The palette lives in classroom_style, so this card, the Presentations
# library and anything else the classroom draws cannot drift apart over
# what "the accent colour" means.
from classroom_style import load_colours # noqa: E402,F401
STYLE = """
+339
View File
@@ -0,0 +1,339 @@
#!/usr/bin/env python3
"""Watch the teacher's downloads, and keep the library tidy.
A teacher downloads a session in ordinary Chrome and then looks for it in
Presentations. Nothing in between is their job: no file manager, no
import button, no "where did you save it". This is the in between.
classroom-presentation-import run as a service, forever
classroom-presentation-import --once one pass, for a technician
classroom-presentation-import --status what the library holds
WHAT IT WILL NOT DO.
It never touches the teacher's download. The file Chrome wrote stays
where Chrome wrote it, with the name Chrome gave it, for as long as
the teacher leaves it there. Everything the library does is done to
its own copy.
It never imports a Wonder Ink worksheet. Wonder Ink downloads into a
directory of its own inside Downloads and those are worksheets, not
sessions; the cleanup will not remove one either.
It never imports a file that is still arriving. Chrome writes
`Session 7.pptx.crdownload` and renames it when the transfer is
done, so a finished name with that sibling beside it is a download in
progress, not a presentation.
It never overwrites a presentation with a later one of the same
name. Two downloads called "Bible Study.pdf" are two presentations.
"""
import argparse
import os
import shutil
import sys
import time
import uuid
sys.path.insert(0, "/usr/local/lib/ekklesia-classroom")
sys.path.insert(
0,
os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "lib"),
)
import classroom_presentations as library # noqa: E402
from classroom_config import feature, read_device_config # noqa: E402
# How often the downloads directory is looked at.
#
# Polling rather than inotify, deliberately. A teacher waits a few
# seconds either way, this cannot leak a watch descriptor or miss an
# event across a restart, and it is the kind of code somebody can still
# read in two years.
SCAN_SECONDS = 4
# How often expired presentations are cleared out.
CLEANUP_SECONDS = 3600
def say(message):
print(f"classroom-presentation-import: {message}", flush=True)
def new_directory(root):
root.mkdir(parents=True, exist_ok=True)
directory = root / uuid.uuid4().hex
directory.mkdir()
return directory
def import_one(source, root=None):
"""Take one finished download into the library.
Ordered so that an interruption is always recoverable. The metadata
is written first, saying "importing"; the sweep at startup throws
away anything still saying that and lets it be imported again. A
presentation only becomes visible to a teacher once every file it
needs is on disk.
"""
root = root if root is not None else library.library_root()
mark = library.fingerprint(source)
if mark is None:
return None
directory = new_directory(root)
managed = directory / source.name
data = {
"id": directory.name,
"state": "importing",
"title": library.readable_title(source.name),
"original_name": source.name,
"source_path": str(source),
"managed_copy": source.name,
"format": library.SUPPORTED.get(source.suffix.lower(), ""),
"imported_at": library.stamp(),
"last_presented_at": None,
"times_presented": 0,
"thumbnail_page": 1,
"pages": 0,
"error": None,
}
presentation = library.Presentation(directory, data)
presentation.save()
# Recorded before the work, so that a file which crashes the
# conversion every time cannot be retried in a loop forever. The
# startup sweep is what un-records an import interrupted part way.
library.remember(mark, directory.name, root)
say(f"importing {source.name}")
try:
# THE TEACHER'S OWN DOWNLOAD IS COPIED, NEVER MOVED.
shutil.copy2(source, managed)
if data["format"] == "pdf":
# Already the thing everything else is converted into. A
# session exported from Google Slides as a PDF keeps exactly
# the appearance Google gave it, with no conversion at all.
shutil.copy2(managed, presentation.slides)
else:
converted, error = library.convert_to_pdf(
managed, presentation.slides)
if not converted:
raise RuntimeError(error or "the file could not be converted")
pages, error = library.render_pages(
presentation.slides, presentation.pages_directory)
if not pages:
raise RuntimeError(error or "the slides could not be rendered")
data["pages"] = pages
data["title"] = library.unique_title(
library.readable_title(
source.name, library.first_text(presentation.slides)),
library.titles_in_use(root, exclude=presentation.id),
)
library.render_thumbnail(presentation.page_image(1),
presentation.thumbnail)
data["state"] = "ready"
presentation.save()
say(f"imported {data['title']!r} ({pages} slides)")
return presentation
except Exception as error: # noqa: BLE001
# A card that says it could not be opened, rather than a card
# that opens onto nothing. The teacher's download is untouched
# either way, which is what the message says.
data["state"] = "failed"
data["error"] = str(error)[:300]
presentation.save()
say(f"could not import {source.name}: {error}")
return presentation
def sweep(root=None):
"""Throw away imports that were interrupted, so they can happen again.
A reboot in the middle of a conversion leaves a directory that says
"importing" and a ledger entry claiming the download is dealt with.
Both go, and the next scan imports it properly.
"""
root = root if root is not None else library.library_root()
if not root.is_dir():
return 0
ledger = library.ledger(root)
stale = 0
for presentation in library.library(root):
if presentation.state != "importing":
continue
say(f"clearing an import that did not finish: {presentation.title!r}")
for mark, value in list(ledger.items()):
if value == presentation.id:
ledger.pop(mark, None)
shutil.rmtree(presentation.directory, ignore_errors=True)
stale += 1
if stale:
library.write_json(library.ledger_path(root), ledger)
return stale
def scan(root=None, downloads=None):
"""One look at the downloads directory."""
root = root if root is not None else library.library_root()
known = library.ledger(root)
imported = 0
for candidate in library.candidates(downloads):
mark = library.fingerprint(candidate)
if mark is None or mark in known:
continue
if import_one(candidate, root) is not None:
imported += 1
known = library.ledger(root)
return imported
def cleanup(root=None, moment=None):
"""Remove presentations whose time is up.
Only ever the library's own directory, and never the presentation on
the screen. The teacher's download is not part of this and is not
looked at.
"""
root = root if root is not None else library.library_root()
lock = library.presenting_lock()
showing = ""
try:
showing = lock.read_text().strip()
except OSError:
showing = ""
removed = 0
for presentation in library.library(root):
if not presentation.expired(moment):
continue
if presentation.id == showing:
# A retention timer must never interrupt a room. It will
# still be expired in an hour.
say(f"{presentation.title!r} is expired but is being presented")
continue
if presentation.last_presented_at is None:
why = f"never presented, imported {presentation.data['imported_at']}"
else:
why = f"last presented {presentation.data['last_presented_at']}"
say(f"removing {presentation.title!r} — {why}")
shutil.rmtree(presentation.directory, ignore_errors=True)
removed += 1
return removed
def status(root=None):
presentations = library.library(root)
if not presentations:
print("the library is empty")
return 0
for presentation in presentations:
expires = presentation.expires_at()
print(f"{presentation.title}")
print(f" state {presentation.state}"
f"{' — ' + presentation.error if presentation.error else ''}")
print(f" slides {presentation.pages}"
f" (card shows slide {presentation.thumbnail_page})")
print(f" imported {presentation.data.get('imported_at')}")
presented = presentation.data.get("last_presented_at") or "never"
print(f" presented {presented} "
f"({presentation.times_presented} times)")
print(f" expires {library.stamp(expires) if expires else 'unknown'}")
return 0
def main():
parser = argparse.ArgumentParser(
description="Bring finished downloads into the Presentations library.")
parser.add_argument("--once", action="store_true",
help="one pass, then stop")
parser.add_argument("--status", action="store_true",
help="what the library holds; changes nothing")
parser.add_argument("--cleanup", action="store_true",
help="apply the retention rules now")
arguments = parser.parse_args()
if arguments.status:
return status()
# A device that does not offer Presentations does not run an importer
# for them. Said out loud for the technician who started it by hand.
if not feature(read_device_config(), "PRESENTATIONS_ENABLED"):
say("PRESENTATIONS_ENABLED is false on this device; not starting")
return 0
if arguments.cleanup:
removed = cleanup()
say(f"removed {removed} expired presentation(s)")
return 0
sweep()
if arguments.once:
imported = scan()
cleanup()
say(f"imported {imported} presentation(s)")
return 0
say(f"watching {library.downloads_root()}")
last_cleanup = 0.0
while True:
try:
scan()
if time.monotonic() - last_cleanup > CLEANUP_SECONDS:
cleanup()
last_cleanup = time.monotonic()
except Exception as error: # noqa: BLE001
# One bad file must not stop the watcher. A teacher whose
# next download never appears has no way to find out why.
say(f"scan failed: {error}")
time.sleep(SCAN_SECONDS)
if __name__ == "__main__":
sys.exit(main())
+765
View File
@@ -0,0 +1,765 @@
#!/usr/bin/env python3
"""The Presentations library, as a teacher sees it.
Three buttons on a card — Present, Quick Look, Remove — and nothing else.
No storage locations, no file names, no import controls, no settings, no
retention. A teacher who has downloaded a session in Chrome opens this,
recognises tonight's by its picture, and presses Present.
WHY THE PRESENTER IS IN THIS WINDOW AND NOT A SEPARATE PROGRAM.
The disc player is a separate process, because a disc plays until
somebody stops it and the panel is how you get back to it. A
presentation is the opposite: it is a thing a teacher steps into and
must step out of, back to the library, reliably, with one key they
already know.
Making the presenter a fullscreen window of this same application is the
whole of that guarantee. Escape is handled here, the fullscreen window is
taken down here, and the library is already on the screen underneath it.
There is no second process to fail to start, no window to be left behind,
and no path by which a teacher ends up looking at something that is not
the library.
That is also why nothing here launches Impress, Okular or any other
document application. Every one of them that was measured leaves its own
editor or viewer on the screen when a slideshow ends — see
docs/presentations.md for what each one actually did. The slides are
pictures by the time they reach this window, rendered at import by
LibreOffice and poppler, and a picture cannot open a file dialog.
"""
import os
import shutil
import sys
import gi
gi.require_version("Gtk", "3.0")
gi.require_version("Gdk", "3.0")
gi.require_version("GdkPixbuf", "2.0")
from gi.repository import Gdk, GdkPixbuf, GLib, Gtk # noqa: E402
sys.path.insert(0, "/usr/local/lib/ekklesia-classroom")
sys.path.insert(
0,
os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "lib"),
)
import classroom_presentations as library # noqa: E402
from classroom_config import feature, read_device_config # noqa: E402
from classroom_style import load_colours # noqa: E402
APP_ID = "ekklesia-presentations"
# How often the library notices a newly imported presentation.
#
# The importer is a separate service, so a session downloaded while this
# window is open appears without the teacher doing anything. Two seconds
# is well under the time it takes to walk back to the machine.
REFRESH_SECONDS = 2
CARD_WIDTH = 320
STYLE = """
window {{ background-color: {window}; }}
.heading {{ color: {text}; font-size: 30px; font-weight: 700; }}
.subtle {{ color: {dim}; font-size: 16px; }}
.card {{
background-color: {view};
border: 1px solid {line};
border-radius: 18px;
padding: 14px;
}}
.card-title {{ color: {text}; font-size: 19px; font-weight: 600; }}
.card-note {{ color: {dim}; font-size: 14px; }}
.thumb {{
background-color: {window};
border: 1px solid {line};
border-radius: 10px;
}}
button {{
color: {text};
background-image: none;
background-color: rgba(255,255,255,0.06);
border: 1px solid {line};
border-radius: 12px;
padding: 10px 14px;
font-size: 16px;
}}
button:hover {{ background-color: rgba(255,255,255,0.12); }}
button.primary {{
color: {on_accent};
background-color: {accent};
border-color: {accent};
font-weight: 700;
}}
button.danger:hover {{ background-color: {negative}; color: {on_accent}; }}
.empty {{ color: {dim}; font-size: 20px; }}
.slide-counter {{
color: {text};
background-color: rgba(0,0,0,0.65);
border-radius: 10px;
padding: 6px 12px;
font-size: 16px;
}}
"""
def scaled_pixbuf(path, width):
try:
return GdkPixbuf.Pixbuf.new_from_file_at_scale(
str(path), width, -1, True)
except (GLib.Error, OSError):
return None
class Presenter(Gtk.Window):
"""The slideshow. A fullscreen window showing one picture at a time.
Everything a presentation remote and a keyboard can reasonably send
is accepted, because a teacher in front of a room does not get to
look up which key this one wants. The clicker in the cupboard sends
Page Up and Page Down; the keyboard sends arrows and space.
Escape is the way out and it is the only way out, which is what makes
this safe to put in front of a teacher: there is nothing else to
press and nowhere else to end up.
"""
def __init__(self, presentation, start_page=1, on_finish=None):
super().__init__(title=presentation.title)
self.presentation = presentation
self.on_finish = on_finish
self.page = min(max(start_page, 1), presentation.pages or 1)
self.counted = False
self.finished = False
self.set_app_paintable(True)
self.fullscreen()
# A slideshow is the only thing on the screen while it is running.
self.set_keep_above(True)
black = Gdk.RGBA()
black.parse("#000000")
self.override_background_color(Gtk.StateFlags.NORMAL, black)
self.image = Gtk.Image()
self.add(self.image)
self.connect("key-press-event", self._key)
self.connect("delete-event", lambda *_: self.finish())
self.connect("size-allocate", self._resized)
self.connect("window-state-event", self._state)
self._drawn_at = (0, 0, 0)
def _state(self, _widget, event):
"""Put the slideshow back on the whole screen if it is taken off it.
A compositor may unfullscreen a window without being asked:
measured in the lab, where focusing another window on the same
workspace dropped the slideshow to half the screen with the
library beside it, which is precisely the "teacher is left
looking at something that is not the presentation" this whole
design is built to prevent. KWin has its own occasions —
a notification, a second output appearing.
So fullscreen is re-asserted rather than assumed, for as long as
the presentation is running. It stops the moment Escape is
pressed, so this can never fight the teacher's way out.
"""
if self.finished:
return False
if not (event.new_window_state & Gdk.WindowState.FULLSCREEN):
self.fullscreen()
return False
# -- showing a slide ------------------------------------------
def _resized(self, _widget, _allocation):
self.show_page()
def show_page(self):
path = self.presentation.page_image(self.page)
allocation = self.get_allocation()
want = (self.page, allocation.width, allocation.height)
if want == self._drawn_at:
return
if not path.exists():
return
pixbuf = self._fitted(path, allocation.width, allocation.height)
if pixbuf is None:
return
self.image.set_from_pixbuf(pixbuf)
self._drawn_at = want
# A SLIDE IS ON THE SCREEN, SO THIS IS A PRESENTATION.
#
# Counted here and nowhere earlier. Pressing Present is an
# intention; a viewer that failed to start, a file that could not
# be read and a window that never drew are all not presentations,
# and none of them may buy another thirty days of retention.
if not self.counted:
self.counted = True
self.presentation.mark_presented()
def _fitted(self, path, width, height):
if width < 2 or height < 2:
return None
try:
original = GdkPixbuf.Pixbuf.new_from_file(str(path))
except (GLib.Error, OSError):
return None
# Letterboxed, never cropped and never stretched. A slide with a
# verse on it cannot lose its edges to fit a television.
ratio = min(width / original.get_width(),
height / original.get_height())
return original.scale_simple(
max(1, int(original.get_width() * ratio)),
max(1, int(original.get_height() * ratio)),
GdkPixbuf.InterpType.BILINEAR,
)
# -- moving about ---------------------------------------------
def go(self, delta):
target = self.page + delta
if target < 1:
return
if target > self.presentation.pages:
# PAST THE LAST SLIDE IS THE END, AND THE END IS THE LIBRARY.
#
# Not a black "click to exit" slide, and certainly not an
# editor. A teacher who clicks once more than there are
# slides is finished, and being finished means being back
# where they started.
self.finish()
return
self.page = target
self.show_page()
def _key(self, _widget, event):
key = event.keyval
forward = (
Gdk.KEY_Right, Gdk.KEY_Down, Gdk.KEY_space, Gdk.KEY_Page_Down,
Gdk.KEY_KP_Page_Down, Gdk.KEY_Return, Gdk.KEY_KP_Enter,
Gdk.KEY_KP_Right, Gdk.KEY_KP_Down, Gdk.KEY_n,
)
backward = (
Gdk.KEY_Left, Gdk.KEY_Up, Gdk.KEY_Page_Up, Gdk.KEY_KP_Page_Up,
Gdk.KEY_BackSpace, Gdk.KEY_KP_Left, Gdk.KEY_KP_Up, Gdk.KEY_p,
)
if key in forward:
self.go(1)
elif key in backward:
self.go(-1)
elif key in (Gdk.KEY_Home, Gdk.KEY_KP_Home):
self.page = 1
self.show_page()
elif key in (Gdk.KEY_End, Gdk.KEY_KP_End):
self.page = self.presentation.pages
self.show_page()
elif key in (Gdk.KEY_Escape, Gdk.KEY_q, Gdk.KEY_F5):
self.finish()
return True
def finish(self):
if self.finished:
return True
self.finished = True
try:
library.presenting_lock().unlink()
except OSError:
pass
if self.on_finish is not None:
self.on_finish()
self.destroy()
return True
class QuickLook(Gtk.Window):
"""Look through the slides before showing them to a room.
Three things a teacher can do here, and they are kept apart on
purpose because conflating any two of them would be wrong:
browse which slide is on this screen right now;
Use this slide which slide the library card shows;
Present start the slideshow, from the beginning.
Browsing is not presenting: coming in here, looking through every
slide and leaving again must not mark the session as presented or
move its retention timer by a second. Choosing the picture is not
presenting either, and it does not change where a presentation
starts.
"""
def __init__(self, presentation, parent, on_close=None, on_present=None):
super().__init__(title=presentation.title)
self.presentation = presentation
self.on_close = on_close
self.on_present = on_present
self.page = 1
self.set_transient_for(parent)
self.set_modal(True)
self.set_default_size(1000, 760)
outer = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12)
outer.set_border_width(16)
self.add(outer)
heading = Gtk.Label(label=presentation.title, xalign=0)
heading.get_style_context().add_class("heading")
heading.set_line_wrap(True)
outer.pack_start(heading, False, False, 0)
self.slide = Gtk.Image()
frame = Gtk.EventBox()
frame.get_style_context().add_class("thumb")
frame.add(self.slide)
outer.pack_start(frame, True, True, 0)
# Browsing.
browse = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10)
browse.set_halign(Gtk.Align.CENTER)
self.back = Gtk.Button(label="◀ Previous")
self.back.connect("clicked", lambda *_: self.go(-1))
browse.pack_start(self.back, False, False, 0)
self.counter = Gtk.Label()
self.counter.get_style_context().add_class("subtle")
browse.pack_start(self.counter, False, False, 12)
self.forward = Gtk.Button(label="Next ▶")
self.forward.connect("clicked", lambda *_: self.go(1))
browse.pack_start(self.forward, False, False, 0)
outer.pack_start(browse, False, False, 0)
# The three things this window is for.
actions = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10)
self.choose = Gtk.Button(label="Use this slide as the picture")
self.choose.connect("clicked", self._choose)
actions.pack_start(self.choose, False, False, 0)
actions.pack_start(Gtk.Box(), True, True, 0)
close = Gtk.Button(label="Back to Presentations")
close.connect("clicked", lambda *_: self.close_quietly())
actions.pack_start(close, False, False, 0)
present = Gtk.Button(label="Present")
present.get_style_context().add_class("primary")
present.connect("clicked", self._present)
actions.pack_start(present, False, False, 0)
outer.pack_start(actions, False, False, 0)
self.connect("key-press-event", self._key)
self.connect("delete-event", lambda *_: self.close_quietly())
self.connect("size-allocate", lambda *_: self.show_page(False))
self._drawn_at = (0, 0, 0)
self.show_page()
def show_page(self, force=True):
allocation = self.slide.get_allocation()
width = max(320, allocation.width or 900)
want = (self.page, width, 0)
if want == self._drawn_at and not force:
return
path = self.presentation.page_image(self.page)
pixbuf = scaled_pixbuf(path, width) if path.exists() else None
if pixbuf is not None:
self.slide.set_from_pixbuf(pixbuf)
self._drawn_at = want
total = self.presentation.pages
chosen = self.presentation.thumbnail_page
note = " · this is the library picture" if self.page == chosen else ""
self.counter.set_text(f"Slide {self.page} of {total}{note}")
self.back.set_sensitive(self.page > 1)
self.forward.set_sensitive(self.page < total)
self.choose.set_sensitive(self.page != chosen)
def go(self, delta):
target = self.page + delta
if 1 <= target <= self.presentation.pages:
self.page = target
self.show_page()
def _choose(self, *_):
# Writes the chosen slide and nothing else. Not a presentation,
# and not a change to where the slideshow starts.
self.presentation.set_thumbnail_page(self.page)
self.show_page()
if self.on_close is not None:
self.on_close()
def _present(self, *_):
self.destroy()
if self.on_present is not None:
self.on_present(self.presentation)
def close_quietly(self):
"""Leave without having presented anything."""
self.destroy()
if self.on_close is not None:
self.on_close()
return True
def _key(self, _widget, event):
key = event.keyval
if key in (Gdk.KEY_Right, Gdk.KEY_Down, Gdk.KEY_Page_Down,
Gdk.KEY_space):
self.go(1)
elif key in (Gdk.KEY_Left, Gdk.KEY_Up, Gdk.KEY_Page_Up):
self.go(-1)
elif key == Gdk.KEY_Escape:
self.close_quietly()
else:
return False
return True
class Library(Gtk.Window):
"""The window the panel button opens."""
def __init__(self):
super().__init__(title="Presentations")
self.set_default_size(1180, 820)
self.presenter = None
self._signature = None
self._apply_style()
outer = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=8)
outer.set_border_width(20)
self.add(outer)
heading = Gtk.Label(label="Presentations", xalign=0)
heading.get_style_context().add_class("heading")
outer.pack_start(heading, False, False, 0)
self.note = Gtk.Label(xalign=0)
self.note.get_style_context().add_class("subtle")
outer.pack_start(self.note, False, False, 0)
scroller = Gtk.ScrolledWindow()
scroller.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
outer.pack_start(scroller, True, True, 8)
self.grid = Gtk.FlowBox()
self.grid.set_valign(Gtk.Align.START)
self.grid.set_max_children_per_line(4)
self.grid.set_min_children_per_line(1)
self.grid.set_selection_mode(Gtk.SelectionMode.NONE)
self.grid.set_row_spacing(16)
self.grid.set_column_spacing(16)
self.grid.set_homogeneous(True)
scroller.add(self.grid)
self.connect("key-press-event", self._key)
self.connect("destroy", lambda *_: Gtk.main_quit())
self.refresh()
GLib.timeout_add_seconds(REFRESH_SECONDS, self._tick)
def _apply_style(self):
css = Gtk.CssProvider()
css.load_from_data(STYLE.format(**load_colours()).encode("utf-8"))
Gtk.StyleContext.add_provider_for_screen(
self.get_screen(), css, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
# -- the wall of cards ----------------------------------------
def _tick(self):
self.refresh()
return True
def signature(self, presentations):
"""What the library looks like, so it is only rebuilt when it changes.
Rebuilding a FlowBox under a teacher's pointer every two seconds
would make the buttons unclickable.
"""
return tuple(
(p.id, p.state, p.pages, p.thumbnail_page, p.title)
for p in presentations
)
def refresh(self):
presentations = library.library()
signature = self.signature(presentations)
if signature == self._signature:
return
self._signature = signature
for child in self.grid.get_children():
self.grid.remove(child)
if not presentations:
self.note.set_text(
"Download a presentation in Chrome and it will appear here.")
empty = Gtk.Label(
label="Nothing here yet.\n\n"
"Download a PowerPoint or PDF in Chrome, and it will "
"appear on this screen by itself.")
empty.get_style_context().add_class("empty")
empty.set_justify(Gtk.Justification.CENTER)
self.grid.add(empty)
else:
# Three states, and a file that could not be opened is not
# the same as one still being got ready. Telling a teacher
# something is "being prepared" when it never will be is how
# somebody ends up waiting through a Bible study for it.
ready = sum(1 for p in presentations if p.ready)
broken = sum(1 for p in presentations if p.failed)
working = len(presentations) - ready - broken
parts = [f"{ready} ready to present"]
if working:
parts.append(f"{working} still being prepared")
if broken:
parts.append(f"{broken} could not be opened")
self.note.set_text(", ".join(parts) + ".")
for presentation in presentations:
self.grid.add(self.card(presentation))
self.grid.show_all()
def card(self, presentation):
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
box.get_style_context().add_class("card")
box.set_size_request(CARD_WIDTH, -1)
picture = Gtk.Image()
picture.get_style_context().add_class("thumb")
pixbuf = None
if presentation.thumbnail.exists():
pixbuf = scaled_pixbuf(presentation.thumbnail, CARD_WIDTH - 28)
if pixbuf is not None:
picture.set_from_pixbuf(pixbuf)
else:
picture.set_from_icon_name("view-presentation", Gtk.IconSize.DIALOG)
picture.set_pixel_size(96)
box.pack_start(picture, False, False, 0)
title = Gtk.Label(label=presentation.title, xalign=0)
title.get_style_context().add_class("card-title")
title.set_line_wrap(True)
title.set_max_width_chars(26)
box.pack_start(title, False, False, 0)
note = Gtk.Label(xalign=0)
note.get_style_context().add_class("card-note")
box.pack_start(note, False, False, 0)
buttons = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
if presentation.ready:
note.set_text(f"{presentation.pages} slides")
present = Gtk.Button(label="Present")
present.get_style_context().add_class("primary")
present.connect("clicked",
lambda *_: self.start_presenting(presentation))
buttons.pack_start(present, True, True, 0)
look = Gtk.Button(label="Quick Look")
look.connect("clicked", lambda *_: self.quick_look(presentation))
buttons.pack_start(look, True, True, 0)
elif presentation.failed:
# SHORT, AND IN WORDS A TEACHER CAN ACT ON.
#
# Never the converter's error text, never a path, never a
# terminal. The one useful fact is that their own download is
# still where they left it.
note.set_text("This file could not be opened.\n"
"Your download in Chrome is still there.")
note.set_line_wrap(True)
else:
note.set_text("Getting this ready…")
remove = Gtk.Button(label="Remove")
remove.get_style_context().add_class("danger")
remove.connect("clicked", lambda *_: self.remove(presentation))
buttons.pack_start(remove, True, True, 0)
box.pack_start(buttons, False, False, 0)
return box
# -- what the buttons do --------------------------------------
def start_presenting(self, presentation, start_page=1):
if not presentation.ready:
return
first = presentation.page_image(start_page)
if not first.exists():
self.trouble(presentation,
"This presentation is not ready yet.")
return
try:
lock = library.presenting_lock()
lock.parent.mkdir(parents=True, exist_ok=True)
lock.write_text(presentation.id)
except OSError:
# A lock that could not be written only costs the cleanup its
# politeness. It must not stop a teacher presenting.
pass
self.presenter = Presenter(
presentation, start_page, on_finish=self._presented)
self.presenter.show_all()
self.presenter.present()
def _presented(self):
self.presenter = None
self._signature = None
self.refresh()
self.present_window()
def present_window(self):
self.show_all()
self.present()
def quick_look(self, presentation):
if not presentation.ready:
return
window = QuickLook(
presentation, self,
on_close=self._looked,
on_present=lambda p: self.start_presenting(p),
)
window.show_all()
def _looked(self):
# Coming back from Quick Look is not a presentation. The only
# thing that may have changed is which slide the card shows.
self._signature = None
self.refresh()
def remove(self, presentation):
dialog = Gtk.MessageDialog(
transient_for=self,
modal=True,
message_type=Gtk.MessageType.QUESTION,
buttons=Gtk.ButtonsType.NONE,
text=f"Remove “{presentation.title}”?",
)
dialog.format_secondary_text(
"It will be taken off this screen.\n"
"Your download in Chrome is not affected.")
dialog.add_button("Keep it", Gtk.ResponseType.CANCEL)
dialog.add_button("Remove", Gtk.ResponseType.OK)
dialog.set_default_response(Gtk.ResponseType.CANCEL)
answer = dialog.run()
dialog.destroy()
if answer != Gtk.ResponseType.OK:
return
shutil.rmtree(presentation.directory, ignore_errors=True)
self._signature = None
self.refresh()
def trouble(self, presentation, message):
dialog = Gtk.MessageDialog(
transient_for=self,
modal=True,
message_type=Gtk.MessageType.INFORMATION,
buttons=Gtk.ButtonsType.OK,
text=presentation.title,
)
dialog.format_secondary_text(message)
dialog.run()
dialog.destroy()
def _key(self, _widget, event):
if event.keyval == Gdk.KEY_Escape:
# Escape in the library closes the library, which is the same
# thing it does everywhere else in this room.
self.destroy()
return True
return False
def main():
GLib.set_prgname(APP_ID)
GLib.set_application_name("Presentations")
# A device that does not offer Presentations does not open them. The
# panel has no button, so nothing should reach here; saying it out
# loud is for the technician who ran the command by hand.
if not feature(read_device_config(), "PRESENTATIONS_ENABLED"):
print("classroom-presentations: PRESENTATIONS_ENABLED is false on "
"this device; not starting", flush=True)
return 0
window = Library()
window.show_all()
Gtk.main()
return 0
if __name__ == "__main__":
sys.exit(main())
+6 -2
View File
@@ -62,7 +62,7 @@ sys.path.insert(
os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "lib"),
)
from classroom_config import enabled, read_device_config # noqa: E402
from classroom_config import feature, read_device_config # noqa: E402
HOME_PAGE = "https://app.wonderink.org/"
@@ -682,7 +682,11 @@ def main():
# A device that has no Wonder Ink has no Wonder Ink. The panel does not
# offer it, so nothing should reach here; saying it out loud is for the
# technician who ran the command by hand and wants to know why.
if not enabled(config, "WONDERINK_ENABLED", default=True):
# feature(), not enabled(..., default=True). The default belongs in
# classroom_config.FEATURES with every other application's, so that
# the panel and the command can never disagree about whether a device
# offers this — which is the whole reason that table exists.
if not feature(config, "WONDERINK_ENABLED"):
say("WONDERINK_ENABLED is false on this device; not starting")
return 0