Digitale bierlijst

gui.py 13KB

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