Digitale bierlijst

gui.py 15KB

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