Digitale bierlijst

gui.py 12KB

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