Digitale bierlijst

gui.py 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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.QtMultimedia import QSoundEffect
  27. from PySide2.QtCore import QObject, QSize, Qt, Signal, Slot, QUrl
  28. # pylint: enable=E0611
  29. try:
  30. import dbus
  31. except ImportError:
  32. dbus = None
  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. PLOP_WAVE = QSoundEffect()
  43. UNDO_WAVE = QSoundEffect()
  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_WAVE.play()
  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. num_columns = min(5, ceil(sqrt(len(ps))))
  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. # Load sounds
  341. global PLOP_WAVE, UNDO_WAVE
  342. sounds_dir = os.path.join(os.path.dirname(__file__), "sounds")
  343. PLOP_WAVE.setSource(QUrl.fromLocalFile(os.path.join(sounds_dir, "plop.wav")))
  344. UNDO_WAVE.setSource(QUrl.fromLocalFile(os.path.join(sounds_dir, "undo.wav")))
  345. # Enlarge font size
  346. font = app.font()
  347. size = font.pointSize()
  348. font.setPointSize(size * 1.5)
  349. app.setFont(font)
  350. # Test connectivity
  351. server_running, info = ServerStatus.is_server_running()
  352. if not server_running:
  353. LOG.critical("Could not connect to server", extra={"info": info})
  354. QMessageBox.critical(
  355. None,
  356. "Help er is iets kapot",
  357. "Kan niet starten omdat de server niet reageert, stuur een foto van "
  358. "dit naar Maarten: " + repr(info),
  359. )
  360. return 1
  361. # Load main window
  362. main_window = PiketMainWindow()
  363. # Test unsettled consumptions
  364. status = ServerStatus.unsettled_consumptions()
  365. unsettled = status["unsettled"]["amount"]
  366. if unsettled > 0:
  367. first = status["unsettled"]["first"]
  368. first_date = first.strftime("%c")
  369. ok = QMessageBox.information(
  370. None,
  371. "Onafgesloten lijst",
  372. f"Wil je verdergaan met een lijst met {unsettled} onafgesloten "
  373. f"consumpties sinds {first_date}?",
  374. QMessageBox.Yes,
  375. QMessageBox.No,
  376. )
  377. if ok == QMessageBox.No:
  378. main_window.show_keyboard()
  379. name, ok = QInputDialog.getText(
  380. None,
  381. "Lijst afsluiten",
  382. "Voer een naam in voor de lijst of druk op OK. Laat de datum " "staan.",
  383. QLineEdit.Normal,
  384. f"{first.strftime('%Y-%m-%d')}",
  385. )
  386. main_window.hide_keyboard()
  387. if name and ok:
  388. settlement = Settlement.create(name)
  389. info = [
  390. f'{item["count"]} {item["name"]}'
  391. for item in settlement.consumption_summary.values()
  392. ]
  393. info = ", ".join(info)
  394. QMessageBox.information(
  395. None, "Lijst afgesloten", f"VO! Op deze lijst stonden: {info}"
  396. )
  397. main_window = PiketMainWindow()
  398. main_window.show()
  399. # Let's go
  400. LOG.info("Starting QT event loop.")
  401. app.exec_()
  402. if __name__ == "__main__":
  403. main()