Digitale bierlijst

gui.py 15KB

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