Digitale bierlijst

gui.py 15KB

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