Digitale bierlijst

gui.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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
  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:
  148. # Onboard not present or dbus broken
  149. self.osk = None
  150. # Go full screen
  151. self.setWindowState(Qt.WindowActive | Qt.WindowFullScreen)
  152. font_metrics = self.fontMetrics()
  153. icon_size = font_metrics.height() * 1.45
  154. # Initialize toolbar
  155. self.toolbar = QToolBar()
  156. self.toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
  157. self.toolbar.setIconSize(QSize(icon_size, icon_size))
  158. # Left
  159. self.toolbar.addAction(
  160. self.load_icon("add_person.svg"), "+ Naam", self.add_person
  161. )
  162. self.undo_action = self.toolbar.addAction(
  163. self.load_icon("undo.svg"), "Oeps", self.do_undo
  164. )
  165. self.undo_action.setDisabled(True)
  166. self.toolbar.addAction(
  167. self.load_icon("quit.svg"), "Afsluiten", self.confirm_quit
  168. )
  169. self.toolbar.addWidget(self.create_spacer())
  170. # Right
  171. self.toolbar.addAction(
  172. self.load_icon("add_consumption_type.svg"), "Nieuw",
  173. self.add_consumption_type)
  174. self.toolbar.setContextMenuPolicy(Qt.PreventContextMenu)
  175. self.toolbar.setFloatable(False)
  176. self.toolbar.setMovable(False)
  177. self.ct_ag = QActionGroup(self.toolbar)
  178. self.ct_ag.setExclusive(True)
  179. cts = ConsumptionType.get_all()
  180. if not cts:
  181. self.show_keyboard()
  182. name, ok = QInputDialog.getItem(
  183. self,
  184. "Consumptietype toevoegen",
  185. (
  186. "Dit lijkt de eerste keer te zijn dat Piket start. Wat wil je "
  187. "tellen? Je kunt later meer typen toevoegen."
  188. ),
  189. ["Bier", "Wijn", "Cola"],
  190. current=0,
  191. editable=True,
  192. )
  193. self.hide_keyboard()
  194. if ok and name:
  195. c_type = ConsumptionType(name=name)
  196. c_type = c_type.create()
  197. cts.append(c_type)
  198. else:
  199. QMessageBox.critical(
  200. self,
  201. "Kan niet doorgaan",
  202. (
  203. "Je drukte op 'Annuleren' of voerde geen naam in, dus ik"
  204. "sluit af."
  205. ),
  206. )
  207. sys.exit()
  208. for ct in cts:
  209. action = QAction(self.load_icon(ct.icon or "beer_bottle.svg"),
  210. ct.name, self.ct_ag)
  211. action.setCheckable(True)
  212. action.setData(str(ct.consumption_type_id))
  213. self.ct_ag.actions()[0].setChecked(True)
  214. [self.toolbar.addAction(a) for a in self.ct_ag.actions()]
  215. self.ct_ag.triggered.connect(self.consumption_type_change)
  216. self.addToolBar(self.toolbar)
  217. # Initialize main widget
  218. self.main_widget = NameButtons(self.ct_ag.actions()[0].data(), self)
  219. self.consumption_type_changed.connect(self.main_widget.consumption_type_changed)
  220. self.setCentralWidget(self.main_widget)
  221. @Slot(QAction)
  222. def consumption_type_change(self, action: QAction):
  223. self.consumption_type_changed.emit(action.data())
  224. def show_keyboard(self) -> None:
  225. """ Show the virtual keyboard, if possible. """
  226. if self.osk:
  227. self.osk.Show()
  228. def hide_keyboard(self) -> None:
  229. """ Hide the virtual keyboard, if possible. """
  230. if self.osk:
  231. self.osk.Hide()
  232. def add_person(self) -> None:
  233. """ Ask for a new Person and register it, then rebuild the central
  234. widget. """
  235. inactive_persons = Person.get_all(False)
  236. inactive_persons.sort(key=lambda p: p.name)
  237. inactive_names = [p.name for p in inactive_persons]
  238. self.show_keyboard()
  239. name, ok = QInputDialog.getItem(
  240. self,
  241. "Persoon toevoegen",
  242. "Voer de naam van de nieuwe persoon in, of kies uit de lijst.",
  243. inactive_names,
  244. 0,
  245. True,
  246. )
  247. self.hide_keyboard()
  248. if ok and name:
  249. if name in inactive_names:
  250. person = inactive_persons[inactive_names.index(name)]
  251. person.set_active(True)
  252. else:
  253. person = Person(name=name)
  254. person = person.create()
  255. self.main_widget.init_ui()
  256. def add_consumption_type(self) -> None:
  257. self.show_keyboard()
  258. name, ok = QInputDialog.getItem(
  259. self,
  260. "Lijst toevoegen",
  261. "Wat wil je strepen?",
  262. ["Wijn", "Radler"]
  263. )
  264. self.hide_keyboard()
  265. if ok and name:
  266. ct = ConsumptionType(name=name)
  267. ct = ct.create()
  268. action = QAction(
  269. self.load_icon(ct.icon or "beer_bottle.svg"),
  270. ct.name,
  271. self.ct_ag
  272. )
  273. action.setCheckable(True)
  274. action.setData(str(ct.consumption_type_id))
  275. self.toolbar.addAction(action)
  276. def confirm_quit(self) -> None:
  277. """ Ask for confirmation that the user wishes to quit, then do so. """
  278. ok = QMessageBox.warning(
  279. self,
  280. "Wil je echt afsluiten?",
  281. "Bevestig dat je wilt afsluiten.",
  282. QMessageBox.Yes,
  283. QMessageBox.Cancel,
  284. )
  285. if ok == QMessageBox.Yes:
  286. LOG.warning("Shutdown by user.")
  287. QApplication.instance().quit()
  288. def do_undo(self) -> None:
  289. """ Undo the last marked consumption. """
  290. UNDO_WAVE.play()
  291. to_undo = self.undo_queue.pop()
  292. LOG.warning("Undoing consumption %s", to_undo)
  293. result = to_undo.reverse()
  294. if not result or not result.reversed:
  295. LOG.error("Reversed consumption %s but was not reversed!", to_undo)
  296. self.undo_queue.append(to_undo)
  297. elif not self.undo_queue:
  298. self.undo_action.setDisabled(True)
  299. self.main_widget.init_ui()
  300. @Slot(Consumption)
  301. def consumption_added(self, consumption):
  302. """ Mark an added consumption in the queue. """
  303. self.undo_queue.append(consumption)
  304. self.undo_action.setDisabled(False)
  305. @staticmethod
  306. def create_spacer() -> QWidget:
  307. """ Return an empty QWidget that automatically expands. """
  308. spacer = QWidget()
  309. spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
  310. return spacer
  311. icons_dir = os.path.join(os.path.dirname(__file__), "icons")
  312. def load_icon(self, filename: str) -> QIcon:
  313. """ Return a QtIcon loaded from the given `filename` in the icons
  314. directory. """
  315. if self.dark_theme:
  316. filename = 'white_' + filename
  317. icon = QIcon(os.path.join(self.icons_dir, filename))
  318. return icon
  319. def main() -> None:
  320. """ Main entry point of GUI client. """
  321. app = QApplication(sys.argv)
  322. app.setStyleSheet(qdarkstyle.load_stylesheet_pyside2())
  323. font = app.font()
  324. size = font.pointSize()
  325. font.setPointSize(size * 1.5)
  326. app.setFont(font)
  327. main_window = PiketMainWindow()
  328. main_window.show()
  329. app.exec_()
  330. if __name__ == "__main__":
  331. main()