Digitale bierlijst

gui.py 15KB

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