Digitale bierlijst

gui.py 8.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. """
  2. Provides the graphical front-end for Piket.
  3. """
  4. import logging
  5. import os
  6. import sys
  7. # pylint: disable=E0611
  8. from PySide2.QtWidgets import (
  9. QAction,
  10. QActionGroup,
  11. QApplication,
  12. QGridLayout,
  13. QInputDialog,
  14. QMainWindow,
  15. QPushButton,
  16. QSizePolicy,
  17. QToolBar,
  18. QWidget,
  19. )
  20. from PySide2.QtGui import QIcon
  21. from PySide2.QtCore import QObject, QSize, Qt, Signal, Slot
  22. # pylint: enable=E0611
  23. try:
  24. import dbus
  25. except ImportError:
  26. dbus = None
  27. from piket_client.sound import PLOP_WAVE
  28. from piket_client.model import Person, ConsumptionType
  29. import piket_client.logger
  30. LOG = logging.getLogger(__name__)
  31. def plop() -> None:
  32. """ Asynchronously play the plop sound. """
  33. PLOP_WAVE.play()
  34. class NameButton(QPushButton):
  35. """ Wraps a QPushButton to provide a counter. """
  36. def __init__(self, person: Person, active_id: str, *args, **kwargs) -> None:
  37. self.person = person
  38. self.active_id = active_id
  39. super().__init__(self.current_label, *args, **kwargs)
  40. self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
  41. self.clicked.connect(self.process_click)
  42. @Slot(str)
  43. def new_active_id(self, new_id: str) -> None:
  44. """ Change the active ConsumptionType id, update the label. """
  45. self.active_id = new_id
  46. self.setText(self.current_label)
  47. @Slot()
  48. def rebuild(self) -> None:
  49. """ Refresh the Person object and the label. """
  50. self.person = self.person.reload()
  51. self.setText(self.current_label)
  52. @property
  53. def current_count(self) -> int:
  54. """ Return the count of the currently active ConsumptionType for this
  55. Person. """
  56. return self.person.consumptions.get(self.active_id, 0)
  57. @property
  58. def current_label(self) -> str:
  59. """ Return the label to show on the button. """
  60. return f"{self.person.name} ({self.current_count})"
  61. def process_click(self) -> None:
  62. """ Process a click on this button. """
  63. if self.person.add_consumption(self.active_id):
  64. plop()
  65. self.setText(self.current_label)
  66. else:
  67. print("Jantoeternuitje, kapot")
  68. class NameButtons(QWidget):
  69. """ Main widget responsible for capturing presses and registering them.
  70. """
  71. new_id_set = Signal(str)
  72. def __init__(self, consumption_type_id: str) -> None:
  73. super().__init__()
  74. self.layout = None
  75. self.layout = QGridLayout()
  76. self.setLayout(self.layout)
  77. self.active_consumption_type_id = consumption_type_id
  78. self.init_ui()
  79. @Slot(str)
  80. def consumption_type_changed(self, new_id: str):
  81. """ Process a change of the consumption type and propagate to the
  82. contained buttons. """
  83. self.active_consumption_type_id = new_id
  84. self.new_id_set.emit(new_id)
  85. def init_ui(self) -> None:
  86. """ Initialize UI: build GridLayout, retrieve People and build a button
  87. for each. """
  88. ps = Person.get_all()
  89. num_columns = round(len(ps) / 10) + 1
  90. if self.layout:
  91. LOG.debug("Removing %s widgets for rebuild", self.layout.count())
  92. for index in range(self.layout.count()):
  93. item = self.layout.itemAt(0)
  94. LOG.debug("Removing item %s: %s", index, item)
  95. if item:
  96. w = item.widget()
  97. LOG.debug("Person %s", w.person)
  98. self.layout.removeItem(item)
  99. w.deleteLater()
  100. for index, person in enumerate(ps):
  101. button = NameButton(person, self.active_consumption_type_id, self)
  102. self.new_id_set.connect(button.new_active_id)
  103. self.layout.addWidget(button, index // num_columns, index % num_columns)
  104. class PiketMainWindow(QMainWindow):
  105. """ QMainWindow subclass responsible for showing the main application
  106. window. """
  107. consumption_type_changed = Signal(str)
  108. def __init__(self) -> None:
  109. super().__init__()
  110. self.main_widget = None
  111. self.toolbar = None
  112. self.osk = None
  113. self.init_ui()
  114. def init_ui(self) -> None:
  115. """ Initialize the UI: construct main widget and toolbar. """
  116. # Connect to dbus, get handle to virtual keyboard
  117. if dbus:
  118. try:
  119. session_bus = dbus.SessionBus()
  120. self.osk = session_bus.get_object(
  121. "org.onboard.Onboard", "/org/onboard/Onboard/Keyboard"
  122. )
  123. except dbus.exceptions.DBusException:
  124. # Onboard not present or dbus broken
  125. self.osk = None
  126. # Go full screen
  127. self.setWindowState(Qt.WindowActive | Qt.WindowFullScreen)
  128. font_metrics = self.fontMetrics()
  129. icon_size = font_metrics.height() * 2
  130. # Initialize toolbar
  131. self.toolbar = QToolBar()
  132. self.toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
  133. self.toolbar.setIconSize(QSize(icon_size, icon_size))
  134. # Left
  135. self.toolbar.addAction(
  136. self.load_icon("add_person.svg"), "Nieuw persoon", self.add_person
  137. )
  138. self.toolbar.addAction(self.load_icon("undo.svg"), "Oeps")
  139. self.toolbar.addWidget(self.create_spacer())
  140. # Right
  141. ag = QActionGroup(self.toolbar)
  142. ag.setExclusive(True)
  143. cts = ConsumptionType.get_all()
  144. if not cts:
  145. self.show_keyboard()
  146. name, ok = QInputDialog.getItem(
  147. self,
  148. "Consumptietype toevoegen",
  149. (
  150. "Dit lijkt de eerste keer te zijn dat Piket start. Wat wil je "
  151. "tellen? Je kunt later meer typen toevoegen."
  152. ),
  153. ["Bier", "Wijn", "Cola"],
  154. current=0,
  155. editable=True,
  156. )
  157. self.hide_keyboard()
  158. if ok and name:
  159. c_type = ConsumptionType(name=name)
  160. c_type = c_type.create()
  161. cts.append(c_type)
  162. else:
  163. QMessageBox.critical(
  164. self,
  165. "Kan niet doorgaan",
  166. (
  167. "Je drukte op 'Annuleren' of voerde geen naam in, dus ik"
  168. "sluit af."
  169. ),
  170. )
  171. sys.exit()
  172. for ct in cts:
  173. action = QAction(self.load_icon(ct.icon or "beer_bottle.svg"), ct.name, ag)
  174. action.setCheckable(True)
  175. action.setData(str(ct.consumption_type_id))
  176. ag.actions()[0].setChecked(True)
  177. [self.toolbar.addAction(a) for a in ag.actions()]
  178. ag.triggered.connect(self.consumption_type_change)
  179. self.addToolBar(self.toolbar)
  180. # Initialize main widget
  181. self.main_widget = NameButtons(ag.actions()[0].data())
  182. self.consumption_type_changed.connect(self.main_widget.consumption_type_changed)
  183. self.setCentralWidget(self.main_widget)
  184. @Slot(QAction)
  185. def consumption_type_change(self, action: QAction):
  186. self.consumption_type_changed.emit(action.data())
  187. def show_keyboard(self) -> None:
  188. """ Show the virtual keyboard, if possible. """
  189. if self.osk:
  190. self.osk.Show()
  191. def hide_keyboard(self) -> None:
  192. """ Hide the virtual keyboard, if possible. """
  193. if self.osk:
  194. self.osk.Hide()
  195. def add_person(self) -> None:
  196. """ Ask for a new Person and register it, then rebuild the central
  197. widget. """
  198. self.show_keyboard()
  199. name, ok = QInputDialog.getItem(
  200. self,
  201. "Persoon toevoegen",
  202. "Voer de naam van de nieuwe persoon in, of kies uit de lijst.",
  203. ["Cas", "Frenk"],
  204. 0,
  205. True,
  206. )
  207. self.hide_keyboard()
  208. if ok and name:
  209. person = Person(name=name)
  210. person = person.create()
  211. self.main_widget.init_ui()
  212. @staticmethod
  213. def create_spacer() -> QWidget:
  214. """ Return an empty QWidget that automatically expands. """
  215. spacer = QWidget()
  216. spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
  217. return spacer
  218. icons_dir = os.path.join(os.path.dirname(__file__), "icons")
  219. @classmethod
  220. def load_icon(cls, filename: str) -> QIcon:
  221. """ Return a QtIcon loaded from the given `filename` in the icons
  222. directory. """
  223. return QIcon(os.path.join(cls.icons_dir, filename))
  224. def main() -> None:
  225. """ Main entry point of GUI client. """
  226. app = QApplication(sys.argv)
  227. font = app.font()
  228. size = font.pointSize()
  229. font.setPointSize(size * 1.75)
  230. app.setFont(font)
  231. main_window = PiketMainWindow()
  232. main_window.show()
  233. app.exec_()
  234. if __name__ == "__main__":
  235. main()