Files
routine/routine/gui/dayview.py
T

527 lines
22 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""One day: the date fixed at the top, block headers and a row per task scrolling in the middle
(the tasks area, its own gray), and the day's note fixed at the bottom."""
import datetime as dt
from routine.qt.QtCore import QPoint, QRectF, QSize, QTimer, Qt, Signal
from routine.qt.QtGui import QColor, QFontMetricsF, QPainter, QPainterPath, QPen
from routine.qt.QtWidgets import (QAbstractButton, QFrame, QHBoxLayout, QLabel, QMessageBox, QPlainTextEdit, QPushButton,
QScrollArea, QSizePolicy, QVBoxLayout, QWidget)
from routine import model
from routine.gui.look import display_font, paint_emboss
INDENT = 26
HIDE_AFTER_MS = 1000 # a ticked row leaves the INCOMPLETE list once its animation is over
PAST_TICK = "this is for a day in the past, you sure you want to check that off?"
def hour_label(h):
h %= 24
return "%d %s" % (12 if h % 12 == 0 else h % 12, "am" if h < 12 else "pm")
def now_target(blocks, now, day_starts_at):
"""Where » scrolls: the latest block that has started by now (so after the last block, until
the day rolls over, the last one; between blocks, the one just gone), else the first."""
h = now.hour + now.minute / 60
if h < day_starts_at:
h += 24
best, best_start = None, None
for i, b in enumerate(blocks):
start = b["start"] + (24 if b["start"] < day_starts_at else 0)
if start <= h and (best_start is None or start >= best_start):
best, best_start = i, start
return best if best is not None else (0 if blocks else None)
def current_block(blocks, now, day_starts_at):
"""Index of the block the clock is in, or None before the first block starts."""
h = now.hour + now.minute / 60
if h < day_starts_at:
h += 24
for i, b in enumerate(blocks):
start, end = b["start"], b["end"]
if end <= start:
end += 24
if start <= h < end:
return i
return None
class Box(QAbstractButton):
"""The checkbox: an embossed 22 px square; done = a check in the highlight color."""
def __init__(self, look):
super().__init__()
self.look = look
self.state = model.PENDING
self.setFixedSize(26, 26)
self.setFocusPolicy(Qt.FocusPolicy.TabFocus)
def sizeHint(self):
return QSize(26, 26)
def paintEvent(self, _):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
lk = self.look
c = lk.button.darker(125) if self.isDown() else lk.button.darker(107) if self.underMouse() else lk.button
r = QRectF(2.5, 2.5, 21, 21)
paint_emboss(p, r, c, 4, sunk=self.isDown())
if self.hasFocus():
p.setPen(QPen(lk.highlight, 2))
p.drawRoundedRect(r.adjusted(-1.5, -1.5, 1.5, 1.5), 5, 5)
if self.state == model.DONE:
pen = QPen(lk.highlight, 3)
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
p.setPen(pen)
path = QPainterPath()
path.moveTo(7, 13.5)
path.lineTo(11.5, 18)
path.lineTo(19.5, 8)
p.drawPath(path)
elif self.state == model.SKIPPED:
p.setPen(QPen(lk.mid, 2.2))
p.drawLine(8, 13, 18, 13)
class ItemRow(QWidget):
toggled = Signal(str, str, object) # item id, new state, the box (for the animation)
def __init__(self, look, item):
super().__init__()
self.look, self.item = look, item
self.state = model.PENDING
lay = QHBoxLayout(self)
lay.setContentsMargins(12 + item["depth"] * INDENT, 3, 8, 3)
lay.setSpacing(10)
self.box = Box(look)
self.box.setToolTip("Done")
self.box.clicked.connect(self._box)
self.label = QLabel(item["label"])
self.label.setWordWrap(True)
self.label.setFont(display_font(12.5 if item["depth"] == 0 else 11.5))
self.label.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)
self.hint = bool(item.get("hint"))
if self.hint: # suggestion text: no box, no skip, quieter words
lay.addSpacing(self.box.width())
f = self.label.font()
f.setItalic(True)
self.label.setFont(f)
self.label.setStyleSheet("color: %s;" % look.mid.name())
lay.addWidget(self.label, 1)
return
self.skip = QPushButton("skip")
self.skip.setProperty("flat", True)
self.skip.setToolTip("Skip: hide it without ticking it off")
self.skip.clicked.connect(self._skip)
lay.addWidget(self.box, 0, Qt.AlignmentFlag.AlignTop)
lay.addWidget(self.label, 1)
lay.addWidget(self.skip, 0, Qt.AlignmentFlag.AlignTop)
def set_state(self, s):
if self.hint:
return
self.state = s
self.box.state = s
self.box.setToolTip("Not done after all" if s == model.DONE else "Done")
self.skip.setText("unskip" if s == model.SKIPPED else "skip")
self.skip.setToolTip("Bring it back" if s == model.SKIPPED else "Skip: hide it without ticking it off")
f = self.label.font()
f.setStrikeOut(s == model.SKIPPED)
self.label.setFont(f)
col = self.look.mid if s != model.PENDING else self.look.text
self.label.setStyleSheet("color: %s;" % col.name())
self.box.update()
def _box(self):
new = model.PENDING if self.state == model.DONE else model.DONE
self.toggled.emit(self.item["id"], new, self.box if new == model.DONE else None)
def _skip(self):
self.toggled.emit(self.item["id"], model.PENDING if self.state == model.SKIPPED else model.SKIPPED, None)
class BlockHeader(QWidget):
"""A block's heading. Clicking it hides or shows the block's rows."""
clicked = Signal()
def __init__(self, look, block):
super().__init__()
self.look, self.block = look, block
self.now = False
lay = QHBoxLayout(self)
lay.setContentsMargins(34, 20, 12, 9) # a little taller than a row: a target
self.title = QLabel(block["label"])
self.title.setFont(display_font(16, bold=True))
self.hours = QLabel("%s – %s" % (hour_label(block["start"]), hour_label(block["end"])))
self.hours.setStyleSheet("color: %s;" % look.mid.name())
self.note = QLabel("")
self.note.setStyleSheet("color: %s;" % look.mid.name())
self.helper = QLabel("") # "click to hide", until it's been learned
self.helper.setStyleSheet("color: %s; font-style: italic;" % look.mid.name())
# one text baseline: bottom-align every label, then lift the smaller ones by the descent they lack
bottom = Qt.AlignmentFlag.AlignBottom
drop = QFontMetricsF(self.title.font()).descent()
for w in (self.hours, self.helper, self.note):
w.setContentsMargins(0, 0, 0, max(0, round(drop - QFontMetricsF(w.font()).descent())))
lay.addWidget(self.title, 0, bottom)
lay.addWidget(self.hours, 0, bottom)
lay.addStretch(1)
lay.addWidget(self.helper, 0, bottom)
lay.addWidget(self.note, 0, bottom)
self.hovered = self.pressed = False
def _state(self, hovered=None, pressed=None):
self.hovered = self.hovered if hovered is None else hovered
self.pressed = self.pressed if pressed is None else pressed
self.update()
if self.look.block_style == "block" and self.parentWidget():
self.parentWidget().update() # the whole block is this heading's face
def face(self, c):
"""The block colour as a button face: darker on hover, more when pressed (design.html#states)."""
return c.darker(125) if self.pressed else c.darker(107) if self.hovered else c
def enterEvent(self, e):
self._state(hovered=True)
def leaveEvent(self, e):
self._state(hovered=False, pressed=False)
def mousePressEvent(self, e):
if e.button() == Qt.MouseButton.LeftButton:
self._state(pressed=True)
def mouseReleaseEvent(self, e):
was = self.pressed
self._state(pressed=False)
if was and e.button() == Qt.MouseButton.LeftButton and self.rect().contains(e.position().toPoint()):
self.clicked.emit()
def set_now(self, now):
self.now = now
self.note.setText("now" if now and self.look.show_now else "")
self.note.setStyleSheet("color: %s; font-weight: bold;" % (self.look.highlight.name() if now
else self.look.mid.name()))
self.update()
def paintEvent(self, _):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
style = self.look.block_style
emboss = self.look.emboss_blocks
if style == "heading": # the heading row in the block's colour
r = QRectF(6, 8, self.width() - 12, self.height() - 8)
fill = self.look.block_fill(self.block["color"])
if emboss:
paint_emboss(p, r.adjusted(0.5, 0.5, -0.5, -0.5), self.face(fill), 8, sunk=self.pressed,
outline=self.look.block_outline)
else:
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(fill)
p.drawRoundedRect(r, 8, 8)
elif style == "chip":
# the block's colour as a chip: flat like a picture, or (emboss_blocks) a little button
r = QRectF(12, 22 + (self.title.height() - 16) / 2, 14, 14)
if emboss:
paint_emboss(p, r, self.face(QColor(self.block["color"])), 4, sunk=self.pressed,
outline=self.look.block_outline)
else:
p.setPen(QPen(QColor(self.block["color"]).darker(135), 1))
p.setBrush(QColor(self.block["color"]))
p.drawRoundedRect(r, 4, 4)
class DateHeader(QLabel):
"""The date, as big as the header allows: its capitals fill most of the height, sitting at
the bottom with room above; smaller only when the window is too narrow for it."""
FILL = 0.6 # cap height as a share of the header's height
BOTTOM = 0.12 # baseline this share of the height above the bottom
def __init__(self, look, text, height):
super().__init__(text)
self.look = look
self.setFixedHeight(height)
self.setMinimumWidth(1)
self._fit()
@staticmethod
def _cap(f):
"""The capitals' real height, drawn (fonts' own capHeight figures can't be trusted)."""
return QFontMetricsF(f).tightBoundingRect("HEMT").height()
def _fit(self):
room = max(50, self.width() - 24)
pt = 30.0
pt *= self.height() * self.FILL / max(1.0, self._cap(self.look.chrome_font(pt)))
f = self.look.chrome_font(pt)
w = QFontMetricsF(f).horizontalAdvance(self.text())
if w > room:
f = self.look.chrome_font(pt * room / w)
self.setFont(f)
def resizeEvent(self, e):
super().resizeEvent(e)
self._fit()
def paintEvent(self, _):
"""On a fixed baseline: a little space below, the rest above (the font's room for
descenders doesn't count)."""
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.TextAntialiasing)
p.setFont(self.font())
p.setPen(self.palette().color(self.foregroundRole()))
p.drawText(QPoint(12, round(self.height() * (1 - self.BOTTOM))), self.text())
p.end()
class BlockBox(QWidget):
"""One block: its heading and rows; in the "whole block" style, all on the block's colour."""
def __init__(self, look, block):
super().__init__()
self.look, self.block = look, block
self.lay = QVBoxLayout(self)
whole = look.block_style == "block"
self.lay.setContentsMargins(0, 0, 0, 8 if whole else 0)
self.lay.setSpacing(0)
self.header = None # its BlockHeader, set by the day view
def paintEvent(self, _):
if self.look.block_style != "block":
return
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
r = QRectF(6, 8, self.width() - 12, self.height() - 8)
fill = self.look.block_fill(self.block["color"])
if self.look.emboss_blocks: # a tall button: its heading is what's pressed
h = self.header
paint_emboss(p, r.adjusted(0.5, 0.5, -0.5, -0.5), h.face(fill) if h else fill, 8,
sunk=bool(h and h.pressed), outline=self.look.block_outline)
return
p.setPen(Qt.PenStyle.NoPen)
p.setBrush(fill)
p.drawRoundedRect(r, 8, 8)
class DayView(QWidget):
"""One day: date header, the scrolling tasks, the note."""
changed = Signal(dict) # the day record after an edit here
swipe = Signal(int) # -1 = an earlier day, +1 = a later one
prefs_changed = Signal() # a block was hidden/shown: save the config
def __init__(self, look, schedule, day, filter_, today, cfg=None):
super().__init__()
self.cfg = cfg if cfg is not None else {}
self.look, self.schedule, self.day, self.filter = look, schedule, day, filter_
self.is_today = day["date"] == today.isoformat()
self.player = None # (box, done_before, calm, streak) -> [(name, set)]: the overlay
self.streak_of = None # (day, item id) -> the streak ticking it there reaches
outer = QVBoxLayout(self)
outer.setContentsMargins(0, 0, 0, 0)
outer.setSpacing(0)
d = dt.date.fromisoformat(day["date"])
text = look.date_text(d)
probe = QLabel(text)
probe.setFont(look.chrome_font(20))
probe.setContentsMargins(12, 8, 12, 8)
title = self.header = DateHeader(look, text, probe.sizeHint().height() * 2) # twice the height it had
outer.addWidget(title) # the header: always in view
self.scroll = QScrollArea()
self.scroll.setWidgetResizable(True)
self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self.scroll.setFrameShape(QFrame.Shape.NoFrame)
body = self.body = QWidget()
body.setObjectName("scrollbody")
self.col = QVBoxLayout(body)
self.col.setContentsMargins(0, 0, 0, 16)
self.col.setSpacing(0)
self.rows, self.headers, self.block_rows = {}, [], []
self.hscroll = 0
colors = {b["id"]: b["color"] for b in schedule.get("blocks", [])}
self.flipped = set() # blocks opened/closed by hand in Completed: this view only
for b in day["blocks"]:
b = dict(b, color=colors.get(b["id"], b["color"])) # today's colour; the day's if since deleted
box = BlockBox(look, b)
h = BlockHeader(look, b)
h.clicked.connect(lambda bid=b["id"]: self._toggle_block(bid))
box.header = h
self.headers.append(h)
box.lay.addWidget(h)
rows = []
for it in b["items"]:
r = ItemRow(look, it)
r.toggled.connect(self._toggled)
self.rows[it["id"]] = r
rows.append(r)
box.lay.addWidget(r)
self.block_rows.append(rows)
self.col.addWidget(box)
self.col.addStretch(1)
self.scroll.setWidget(body)
outer.addWidget(self.scroll, 1)
lab = QLabel("notes")
lab.setFont(look.note_font(20))
lab.setContentsMargins(12, 10, 12, 6)
outer.addWidget(lab) # the note: always in view too
self.note = QPlainTextEdit()
self.note.setFixedHeight(110)
self.note.setPlainText(day["note"]["text"])
self.note.textChanged.connect(lambda: self.note_timer.start())
wrap = QWidget()
wl = QVBoxLayout(wrap)
wl.setContentsMargins(12, 0, 12, 0)
wl.addWidget(self.note)
outer.addWidget(wrap)
self.note_timer = QTimer(self, singleShot=True, interval=700, timeout=self._save_note)
self.hide_timer = QTimer(self, singleShot=True, interval=HIDE_AFTER_MS, timeout=self.apply_filter)
self.scroll.viewport().installEventFilter(self)
self.refresh(day)
self.mark_now()
# ── state ──
def refresh(self, day):
"""Show a (possibly remotely changed) record without losing what's being typed."""
self.day = day
for iid, r in self.rows.items():
r.set_state(model.state(day, iid))
if not self.note.hasFocus() and self.note.toPlainText() != day["note"]["text"]:
self.note.blockSignals(True)
self.note.setPlainText(day["note"]["text"])
self.note.blockSignals(False)
self.apply_filter()
def set_filter(self, f):
self.filter = f
self.apply_filter()
def _toggle_block(self, bid):
if self.filter == "completed": # Completed opens what got done: a click here is for now
self.flipped ^= {bid}
self.apply_filter()
return
hidden = set(self.cfg.get("hidden_blocks", []))
hidden ^= {bid}
self.cfg["hidden_blocks"] = sorted(hidden)
self.cfg["block_tap_learned"] = True # no more "click to hide / show" helpers
self.apply_filter()
self.prefs_changed.emit()
def apply_filter(self):
inc, comp = self.filter == "incomplete", self.filter == "completed"
done = {iid for iid, r in self.rows.items() if not r.hint and r.state == model.DONE}
has_done = {iid.rpartition("/")[0] for iid in done} # a done task keeps its parents in view
for iid in list(has_done):
while iid:
has_done.add(iid)
iid = iid.rpartition("/")[0]
hidden = set(self.cfg.get("hidden_blocks", []))
learned = self.cfg.get("block_tap_learned", False)
for h, rows in zip(self.headers, self.block_rows):
bid = h.block["id"]
gone = bid in hidden
left, got, shown = 0, 0, {}
for r in rows:
iid = r.item["id"]
if r.hint: # a suggestion goes with the task it's under
par = iid.rpartition("/")[0]
show = shown.get(par, True)
else:
show = (iid in done or iid in has_done) if comp else not inc or r.state == model.PENDING
left += r.state == model.PENDING
got += r.state == model.DONE
shown[iid] = show
if comp: # open if anything got done, closed if not; clicks flip it
gone = (not got) != (bid in self.flipped)
if not got: # a none-done block opened: all of it
shown = dict.fromkeys(shown, True)
for r in rows:
r.setVisible(shown[r.item["id"]] and not gone)
h.helper.setText("" if learned or not rows else "click to show" if gone else "click to hide")
if not rows:
h.hours.setText(hour_label(h.block["start"]))
elif inc and left == 0:
h.hours.setText("all done")
else:
h.hours.setText("%s – %s" % (hour_label(h.block["start"]), hour_label(h.block["end"])))
def _past_ok(self):
"""Ticking on an earlier day: ask first. yes / oops (Escape = oops)."""
m = QMessageBox(QMessageBox.Icon.Question, "Routine", PAST_TICK, parent=self)
yes = m.addButton("yes", QMessageBox.ButtonRole.YesRole)
oops = m.addButton("oops", QMessageBox.ButtonRole.NoRole)
m.setDefaultButton(oops)
m.setEscapeButton(oops)
m.exec()
return m.clickedButton() is yes
def _toggled(self, iid, s, box):
if s == model.DONE and not self.is_today and not self._past_ok():
return
done_before = model.ticks(self.day)
for cid in model.set_with_children(self.day, iid, s):
self.rows[cid].set_state(model.state(self.day, cid))
if box is not None:
if self.player:
streak = 0
if self.streak_of and self.cfg.get("streak_anims", True):
streak = self.streak_of(self.day, iid)
for name, set_no in self.player(box, done_before, bool(self.rows[iid].item.get("calm")), streak):
model.add_play(self.day, name, iid, set_no,
streak if set_no in (model.STREAK_SET, model.STREAK_CALM_SET) else None)
self.hide_timer.start()
else:
self.apply_filter()
self.changed.emit(self.day)
def _save_note(self):
model.set_note(self.day, self.note.toPlainText())
self.changed.emit(self.day)
def flush(self):
if self.note_timer.isActive():
self.note_timer.stop()
self._save_note()
# ── now ──
def mark_now(self):
idx = current_block(self.day["blocks"], dt.datetime.now(), self.schedule.get("dayStartsAt", 4)) \
if self.is_today else None
for i, h in enumerate(self.headers):
h.set_now(i == idx)
return idx
def verticalScrollBar(self):
return self.scroll.verticalScrollBar()
def scroll_to_now(self):
self.mark_now()
idx = now_target(self.day["blocks"], dt.datetime.now(), self.schedule.get("dayStartsAt", 4)) \
if self.is_today else None
if idx is None:
self.verticalScrollBar().setValue(0)
else:
QTimer.singleShot(0, lambda: self.verticalScrollBar().setValue(
self.headers[idx].parentWidget().mapTo(self.body, QPoint(0, 0)).y()))
# ── sideways = other days ──
def eventFilter(self, obj, ev):
if ev.type() == ev.Type.Wheel:
dx = ev.angleDelta().x()
if dx and abs(dx) > abs(ev.angleDelta().y()):
self.hscroll += dx
if abs(self.hscroll) >= 240:
self.swipe.emit(-1 if self.hscroll > 0 else 1)
self.hscroll = 0
return True
return super().eventFilter(obj, ev)