Digitale bierlijst

gui.py 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. """
  2. Provides the graphical front-end for Piket.
  3. """
  4. import collections
  5. import logging
  6. import os
  7. import sys
  8. from math import ceil, sqrt
  9. import qdarkstyle
  10. # pylint: disable=E0611
  11. from PySide6.QtWidgets import (
  12. QApplication,
  13. QGridLayout,
  14. QInputDialog,
  15. QLineEdit,
  16. QMainWindow,
  17. QMessageBox,
  18. QPushButton,
  19. QSizePolicy,
  20. QToolBar,
  21. QWidget,
  22. )
  23. from PySide6.QtGui import (
  24. QAction,
  25. QActionGroup,
  26. )
  27. from PySide6.QtGui import QIcon
  28. from PySide6.QtMultimedia import QSoundEffect
  29. from PySide6.QtCore import QObject, QSize, Qt, Signal, Slot, QUrl
  30. # pylint: enable=E0611
  31. try:
  32. import dbus
  33. except ImportError:
  34. dbus = None
  35. from piket_client.model import (
  36. Person,
  37. ConsumptionType,
  38. Consumption,
  39. ServerStatus,
  40. Settlement,
  41. )
  42. import piket_client.logger
  43. LOG = logging.getLogger(__name__)
  44. PLOP_WAVE = QSoundEffect()
  45. UNDO_WAVE = QSoundEffect()
  46. class NameButton(QPushButton):
  47. """ Wraps a QPushButton to provide a counter. """
  48. consumption_created = Signal(Consumption)
  49. def __init__(self, person: Person, active_id: str, *args, **kwargs) -> None:
  50. self.person = person
  51. self.active_id = active_id
  52. super().__init__(self.current_label, *args, **kwargs)
  53. self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
  54. self.consumption_created.connect(self.window().consumption_added)
  55. self.clicked.connect(self.process_click)
  56. self.setContextMenuPolicy(Qt.CustomContextMenu)
  57. self.customContextMenuRequested.connect(self.confirm_hide)
  58. @Slot(str)
  59. def new_active_id(self, new_id: str) -> None:
  60. """ Change the active ConsumptionType id, update the label. """
  61. self.active_id = new_id
  62. self.setText(self.current_label)
  63. @Slot()
  64. def rebuild(self) -> None:
  65. """ Refresh the Person object and the label. """
  66. self.person = self.person.reload()
  67. self.setText(self.current_label)
  68. @property
  69. def current_count(self) -> int:
  70. """ Return the count of the currently active ConsumptionType for this
  71. Person. """
  72. return self.person.consumptions.get(self.active_id, 0)
  73. @property
  74. def current_label(self) -> str:
  75. """ Return the label to show on the button. """
  76. return f"{self.person.name}\n{self.current_count}"
  77. def process_click(self) -> None:
  78. """ Process a click on this button. """
  79. LOG.debug("Button clicked.")
  80. result = self.person.add_consumption(self.active_id)
  81. if result:
  82. PLOP_WAVE.play()
  83. self.setText(self.current_label)
  84. self.consumption_created.emit(result)
  85. else:
  86. LOG.error("Failed to add consumption", extra={"person": self.person})
  87. def confirm_hide(self) -> None:
  88. LOG.debug("Button right-clicked.")
  89. ok = QMessageBox.warning(
  90. self.window(),
  91. "Persoon verbergen?",
  92. f"Wil je {self.person.name} verbergen?",
  93. QMessageBox.Yes,
  94. QMessageBox.Cancel,
  95. )
  96. if ok == QMessageBox.Yes:
  97. LOG.warning("Hiding person %s", self.person.name)
  98. self.person.set_active(False)
  99. self.parent().init_ui()
  100. class NameButtons(QWidget):
  101. """ Main widget responsible for capturing presses and registering them.
  102. """
  103. new_id_set = Signal(str)
  104. def __init__(self, consumption_type_id: str, *args, **kwargs) -> None:
  105. super().__init__(*args, **kwargs)
  106. self.layout = None
  107. self.layout = QGridLayout()
  108. self.setLayout(self.layout)
  109. self.active_consumption_type_id = consumption_type_id
  110. self.init_ui()
  111. @Slot(str)
  112. def consumption_type_changed(self, new_id: str):
  113. """ Process a change of the consumption type and propagate to the
  114. contained buttons. """
  115. LOG.debug("Consumption type updated in NameButtons.", extra={"new_id": new_id})
  116. self.active_consumption_type_id = new_id
  117. self.new_id_set.emit(new_id)
  118. def init_ui(self) -> None:
  119. """ Initialize UI: build GridLayout, retrieve People and build a button
  120. for each. """
  121. LOG.debug("Initializing NameButtons.")
  122. ps = Person.get_all(True)
  123. # num_columns = round(len(ps) / 10) + 1
  124. num_columns = min(5, ceil(sqrt(len(ps))))
  125. if self.layout:
  126. LOG.debug("Removing %s widgets for rebuild", self.layout.count())
  127. for index in range(self.layout.count()):
  128. item = self.layout.itemAt(0)
  129. LOG.debug("Removing item %s: %s", index, item)
  130. if item:
  131. w = item.widget()
  132. LOG.debug("Person %s", w.person)
  133. self.layout.removeItem(item)
  134. w.deleteLater()
  135. for index, person in enumerate(ps):
  136. button = NameButton(person, self.active_consumption_type_id, self)
  137. self.new_id_set.connect(button.new_active_id)
  138. self.layout.addWidget(button, index // num_columns, index % num_columns)
  139. class PiketMainWindow(QMainWindow):
  140. """ QMainWindow subclass responsible for showing the main application
  141. window. """
  142. consumption_type_changed = Signal(str)
  143. def __init__(self) -> None:
  144. LOG.debug("Initializing PiketMainWindow.")
  145. super().__init__()
  146. self.main_widget = None
  147. self.dark_theme = True
  148. self.toolbar = None
  149. self.osk = None
  150. self.undo_action = None
  151. self.undo_queue = collections.deque([], 15)
  152. self.init_ui()
  153. def init_ui(self) -> None:
  154. """ Initialize the UI: construct main widget and toolbar. """
  155. # Connect to dbus, get handle to virtual keyboard
  156. if dbus:
  157. try:
  158. session_bus = dbus.SessionBus()
  159. self.osk = session_bus.get_object(
  160. "org.onboard.Onboard", "/org/onboard/Onboard/Keyboard"
  161. )
  162. except dbus.exceptions.DBusException as exception:
  163. # Onboard not present or dbus broken
  164. self.osk = None
  165. LOG.error("Could not connect to Onboard:")
  166. LOG.exception(exception)
  167. else:
  168. LOG.warning("Onboard disabled due to missing dbus.")
  169. # Go full screen
  170. self.setWindowState(Qt.WindowActive | Qt.WindowFullScreen)
  171. font_metrics = self.fontMetrics()
  172. icon_size = font_metrics.height() * 1.45
  173. # Initialize toolbar
  174. self.toolbar = QToolBar()
  175. self.toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
  176. self.toolbar.setIconSize(QSize(icon_size, icon_size))
  177. # Left
  178. self.toolbar.addAction(
  179. self.load_icon("add_person.png"), "+ Naam", self.add_person
  180. )
  181. self.undo_action = self.toolbar.addAction(
  182. self.load_icon("undo.png"), "Oeps", self.do_undo
  183. )
  184. self.undo_action.setDisabled(True)
  185. self.toolbar.addAction(
  186. self.load_icon("quit.png"), "Afsluiten", self.confirm_quit
  187. )
  188. self.toolbar.addWidget(self.create_spacer())
  189. # Right
  190. self.toolbar.addAction(
  191. self.load_icon("add_consumption_type.png"),
  192. "Nieuw",
  193. self.add_consumption_type,
  194. )
  195. self.toolbar.setContextMenuPolicy(Qt.PreventContextMenu)
  196. self.toolbar.setFloatable(False)
  197. self.toolbar.setMovable(False)
  198. self.ct_ag = QActionGroup(self.toolbar)
  199. self.ct_ag.setExclusive(True)
  200. cts = ConsumptionType.get_all()
  201. if not cts:
  202. self.show_keyboard()
  203. name, ok = QInputDialog.getItem(
  204. self,
  205. "Consumptietype toevoegen",
  206. (
  207. "Dit lijkt de eerste keer te zijn dat Piket start. Wat wil je "
  208. "tellen? Je kunt later meer typen toevoegen."
  209. ),
  210. ["Bier", "Wijn", "Cola"],
  211. current=0,
  212. editable=True,
  213. )
  214. self.hide_keyboard()
  215. if ok and name:
  216. c_type = ConsumptionType(name=name)
  217. c_type = c_type.create()
  218. cts.append(c_type)
  219. else:
  220. QMessageBox.critical(
  221. self,
  222. "Kan niet doorgaan",
  223. (
  224. "Je drukte op 'Annuleren' of voerde geen naam in, dus ik"
  225. "sluit af."
  226. ),
  227. )
  228. sys.exit()
  229. for ct in cts:
  230. action = QAction(
  231. self.load_icon(ct.icon or "beer_bottle.png"), ct.name, self.ct_ag
  232. )
  233. action.setCheckable(True)
  234. action.setData(str(ct.consumption_type_id))
  235. self.ct_ag.actions()[0].setChecked(True)
  236. [self.toolbar.addAction(a) for a in self.ct_ag.actions()]
  237. self.ct_ag.triggered.connect(self.consumption_type_change)
  238. self.addToolBar(self.toolbar)
  239. # Initialize main widget
  240. self.main_widget = NameButtons(self.ct_ag.actions()[0].data(), self)
  241. self.consumption_type_changed.connect(self.main_widget.consumption_type_changed)
  242. self.setCentralWidget(self.main_widget)
  243. @Slot(QAction)
  244. def consumption_type_change(self, action: QAction):
  245. self.consumption_type_changed.emit(action.data())
  246. def show_keyboard(self) -> None:
  247. """ Show the virtual keyboard, if possible. """
  248. if self.osk:
  249. self.osk.Show()
  250. def hide_keyboard(self) -> None:
  251. """ Hide the virtual keyboard, if possible. """
  252. if self.osk:
  253. self.osk.Hide()
  254. def add_person(self) -> None:
  255. """ Ask for a new Person and register it, then rebuild the central
  256. widget. """
  257. inactive_persons = Person.get_all(False)
  258. inactive_persons.sort(key=lambda p: p.name)
  259. inactive_names = [p.name for p in inactive_persons]
  260. self.show_keyboard()
  261. name, ok = QInputDialog.getItem(
  262. self,
  263. "Persoon toevoegen",
  264. "Voer de naam van de nieuwe persoon in, of kies uit de lijst.",
  265. inactive_names,
  266. 0,
  267. True,
  268. )
  269. self.hide_keyboard()
  270. if ok and name:
  271. if name in inactive_names:
  272. person = inactive_persons[inactive_names.index(name)]
  273. person.set_active(True)
  274. else:
  275. person = Person(name=name)
  276. person = person.create()
  277. self.main_widget.init_ui()
  278. def add_consumption_type(self) -> None:
  279. self.show_keyboard()
  280. name, ok = QInputDialog.getItem(
  281. self, "Lijst toevoegen", "Wat wil je strepen?", ["Wijn", "Radler"]
  282. )
  283. self.hide_keyboard()
  284. if ok and name:
  285. ct = ConsumptionType(name=name)
  286. ct = ct.create()
  287. action = QAction(
  288. self.load_icon(ct.icon or "beer_bottle.png"), ct.name, self.ct_ag
  289. )
  290. action.setCheckable(True)
  291. action.setData(str(ct.consumption_type_id))
  292. self.toolbar.addAction(action)
  293. def confirm_quit(self) -> None:
  294. """ Ask for confirmation that the user wishes to quit, then do so. """
  295. ok = QMessageBox.warning(
  296. self,
  297. "Wil je echt afsluiten?",
  298. "Bevestig dat je wilt afsluiten.",
  299. QMessageBox.Yes,
  300. QMessageBox.Cancel,
  301. )
  302. if ok == QMessageBox.Yes:
  303. LOG.warning("Shutdown by user.")
  304. QApplication.instance().quit()
  305. def do_undo(self) -> None:
  306. """ Undo the last marked consumption. """
  307. UNDO_WAVE.play()
  308. to_undo = self.undo_queue.pop()
  309. LOG.warning("Undoing consumption %s", to_undo)
  310. result = to_undo.reverse()
  311. if not result or not result.reversed:
  312. LOG.error("Reversed consumption %s but was not reversed!", to_undo)
  313. self.undo_queue.append(to_undo)
  314. elif not self.undo_queue:
  315. self.undo_action.setDisabled(True)
  316. self.main_widget.init_ui()
  317. @Slot(Consumption)
  318. def consumption_added(self, consumption):
  319. """ Mark an added consumption in the queue. """
  320. self.undo_queue.append(consumption)
  321. self.undo_action.setDisabled(False)
  322. @staticmethod
  323. def create_spacer() -> QWidget:
  324. """ Return an empty QWidget that automatically expands. """
  325. spacer = QWidget()
  326. spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
  327. return spacer
  328. icons_dir = os.path.join(os.path.dirname(__file__), "icons")
  329. def load_icon(self, filename: str) -> QIcon:
  330. """ Return a QtIcon loaded from the given `filename` in the icons
  331. directory. """
  332. if self.dark_theme:
  333. filename = "white_" + filename
  334. icon = QIcon(os.path.join(self.icons_dir, filename))
  335. return icon
  336. def main() -> None:
  337. """ Main entry point of GUI client. """
  338. LOG.info("Loading piket_client")
  339. app = QApplication(sys.argv)
  340. # Set dark theme
  341. app.setStyleSheet(qdarkstyle.load_stylesheet_pyside6())
  342. # Load sounds
  343. global PLOP_WAVE, UNDO_WAVE
  344. sounds_dir = os.path.join(os.path.dirname(__file__), "sounds")
  345. PLOP_WAVE.setSource(QUrl.fromLocalFile(os.path.join(sounds_dir, "plop.wav")))
  346. UNDO_WAVE.setSource(QUrl.fromLocalFile(os.path.join(sounds_dir, "undo.wav")))
  347. # Enlarge font size
  348. font = app.font()
  349. size = font.pointSize()
  350. font.setPointSize(size * 1.5)
  351. app.setFont(font)
  352. # Test connectivity
  353. server_running, info = ServerStatus.is_server_running()
  354. if not server_running:
  355. LOG.critical("Could not connect to server", extra={"info": info})
  356. QMessageBox.critical(
  357. None,
  358. "Help er is iets kapot",
  359. "Kan niet starten omdat de server niet reageert, stuur een foto van "
  360. "dit naar Maarten: " + repr(info),
  361. )
  362. return 1
  363. # Load main window
  364. main_window = PiketMainWindow()
  365. # Test unsettled consumptions
  366. status = ServerStatus.unsettled_consumptions()
  367. unsettled = status["unsettled"]["amount"]
  368. if unsettled > 0:
  369. first = status["unsettled"]["first"]
  370. first_date = first.strftime("%c")
  371. ok = QMessageBox.information(
  372. None,
  373. "Onafgesloten lijst",
  374. f"Wil je verdergaan met een lijst met {unsettled} onafgesloten "
  375. f"consumpties sinds {first_date}?",
  376. QMessageBox.Yes,
  377. QMessageBox.No,
  378. )
  379. if ok == QMessageBox.No:
  380. main_window.show_keyboard()
  381. name, ok = QInputDialog.getText(
  382. None,
  383. "Lijst afsluiten",
  384. "Voer een naam in voor de lijst of druk op OK. Laat de datum " "staan.",
  385. QLineEdit.Normal,
  386. f"{first.strftime('%Y-%m-%d')}",
  387. )
  388. main_window.hide_keyboard()
  389. if name and ok:
  390. settlement = Settlement.create(name)
  391. info = [
  392. f'{item["count"]} {item["name"]}'
  393. for item in settlement.consumption_summary.values()
  394. ]
  395. info = ", ".join(info)
  396. QMessageBox.information(
  397. None, "Lijst afgesloten", f"VO! Op deze lijst stonden: {info}"
  398. )
  399. main_window = PiketMainWindow()
  400. main_window.show()
  401. # Let's go
  402. LOG.info("Starting QT event loop.")
  403. app.exec_()
  404. if __name__ == "__main__":
  405. main()