Digitale bierlijst

gui.py 6.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. """
  2. Provides the graphical front-end for Piket.
  3. """
  4. import os
  5. import sys
  6. # pylint: disable=E0611
  7. from PySide2.QtWidgets import (
  8. QAction,
  9. QActionGroup,
  10. QApplication,
  11. QGridLayout,
  12. QInputDialog,
  13. QMainWindow,
  14. QPushButton,
  15. QSizePolicy,
  16. QToolBar,
  17. QWidget,
  18. )
  19. from PySide2.QtGui import QIcon
  20. from PySide2.QtCore import QSize, Qt, QObject, Signal, Slot
  21. # pylint: enable=E0611
  22. try:
  23. import dbus
  24. except ImportError:
  25. dbus = None
  26. from piket_client.sound import PLOP_WAVE
  27. from piket_client.model import Person, ConsumptionType
  28. def plop() -> None:
  29. """ Asynchronously play the plop sound. """
  30. PLOP_WAVE.play()
  31. class NameButton(QPushButton):
  32. """ Wraps a QPushButton to provide a counter. """
  33. def __init__(self, person: Person, active_id: str, *args, **kwargs) -> None:
  34. self.person = person
  35. self.active_id = active_id
  36. super().__init__(self.current_label, *args, **kwargs)
  37. self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
  38. self.clicked.connect(self.process_click)
  39. @Slot(str)
  40. def new_active_id(self, new_id: str):
  41. self.active_id = new_id
  42. self.setText(self.current_label)
  43. @property
  44. def active_consumption_type_id(self) -> str:
  45. return self.parent().active_consumption_type_id
  46. @property
  47. def current_count(self) -> int:
  48. return self.person.consumptions.get(self.active_id, 0)
  49. @property
  50. def current_label(self) -> str:
  51. """ Return the label to show on the button. """
  52. return f"{self.person.name} ({self.current_count})"
  53. def process_click(self) -> None:
  54. """ Process a click on this button. """
  55. if self.person.add_consumption(self.active_id):
  56. self.setText(self.current_label)
  57. plop()
  58. else:
  59. print("Jantoeternuitje, kapot")
  60. class NameButtons(QWidget):
  61. """ Main widget responsible for capturing presses and registering them.
  62. """
  63. new_id_set = Signal(str)
  64. def __init__(self, consumption_type_id) -> None:
  65. super().__init__()
  66. self.layout = None
  67. self.active_consumption_type_id = consumption_type_id
  68. self.init_ui()
  69. @Slot(str)
  70. def consumption_type_changed(self, new_id: str):
  71. self.active_consumption_type_id = new_id
  72. self.new_id_set.emit(new_id)
  73. def init_ui(self) -> None:
  74. """ Initialize UI: build GridLayout, retrieve People and build a button
  75. for each. """
  76. self.layout = QGridLayout()
  77. for index, person in enumerate(Person.get_all()):
  78. button = NameButton(person, self.active_consumption_type_id, self)
  79. self.new_id_set.connect(button.new_active_id)
  80. self.layout.addWidget(button, index // 2, index % 2)
  81. self.setLayout(self.layout)
  82. class PiketMainWindow(QMainWindow):
  83. """ QMainWindow subclass responsible for showing the main application
  84. window. """
  85. consumption_type_changed = Signal(str)
  86. def __init__(self) -> None:
  87. super().__init__()
  88. self.main_widget = None
  89. self.toolbar = None
  90. self.osk = None
  91. self.init_ui()
  92. def init_ui(self) -> None:
  93. """ Initialize the UI: construct main widget and toolbar. """
  94. # Connect to dbus, get handle to virtual keyboard
  95. if dbus:
  96. try:
  97. session_bus = dbus.SessionBus()
  98. self.osk = session_bus.get_object('org.onboard.Onboard',
  99. '/org/onboard/Onboard/Keyboard')
  100. except dbus.exceptions.DBusException:
  101. # Onboard not present or dbus broken
  102. self.osk = None
  103. # Go full screen
  104. self.setWindowState(Qt.WindowActive | Qt.WindowFullScreen)
  105. font_metrics = self.fontMetrics()
  106. icon_size = font_metrics.height() * 2
  107. # Initialize toolbar
  108. self.toolbar = QToolBar()
  109. self.toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
  110. self.toolbar.setIconSize(QSize(icon_size, icon_size))
  111. # Left
  112. self.toolbar.addAction(
  113. self.load_icon("add_person.svg"), "Nieuw persoon", self.add_person
  114. )
  115. self.toolbar.addAction(self.load_icon("undo.svg"), "Oeps")
  116. self.toolbar.addWidget(self.create_spacer())
  117. # Right
  118. ag = QActionGroup(self.toolbar)
  119. ag.setExclusive(True)
  120. for ct in ConsumptionType.get_all():
  121. action = QAction(
  122. self.load_icon(ct.icon or 'beer_bottle.svg'),
  123. ct.name,
  124. ag
  125. )
  126. action.setCheckable(True)
  127. action.setData(str(ct.consumption_type_id))
  128. ag.actions()[0].setChecked(True)
  129. [self.toolbar.addAction(a) for a in ag.actions()]
  130. ag.triggered.connect(self.consumption_type_change)
  131. self.addToolBar(self.toolbar)
  132. # Initialize main widget
  133. self.main_widget = NameButtons(ag.actions()[0].data())
  134. self.consumption_type_changed.connect(self.main_widget.consumption_type_changed)
  135. self.setCentralWidget(self.main_widget)
  136. @Slot(QAction)
  137. def consumption_type_change(self, action: QAction):
  138. self.consumption_type_changed.emit(action.data())
  139. def show_keyboard(self) -> None:
  140. ''' Show the virtual keyboard, if possible. '''
  141. if self.osk:
  142. self.osk.Show()
  143. def hide_keyboard(self) -> None:
  144. ''' Hide the virtual keyboard, if possible. '''
  145. if self.osk:
  146. self.osk.Hide()
  147. def add_person(self) -> None:
  148. """ Ask for a new Person and register it, then rebuild the central
  149. widget. """
  150. self.show_keyboard()
  151. name, ok = QInputDialog.getItem(
  152. self,
  153. "Persoon toevoegen",
  154. "Voer de naam van de nieuwe persoon in, of kies uit de lijst.",
  155. ["Cas", "Frenk"],
  156. 0,
  157. True,
  158. )
  159. self.hide_keyboard()
  160. if ok and name:
  161. person = Person(name=name)
  162. person = person.save()
  163. self.main_widget = NameButtons()
  164. self.setCentralWidget(self.main_widget)
  165. @staticmethod
  166. def create_spacer() -> QWidget:
  167. """ Return an empty QWidget that automatically expands. """
  168. spacer = QWidget()
  169. spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
  170. return spacer
  171. icons_dir = os.path.join(os.path.dirname(__file__), "icons")
  172. @classmethod
  173. def load_icon(cls, filename: str) -> QIcon:
  174. """ Return a QtIcon loaded from the given `filename` in the icons
  175. directory. """
  176. return QIcon(os.path.join(cls.icons_dir, filename))
  177. def main() -> None:
  178. """ Main entry point of GUI client. """
  179. app = QApplication(sys.argv)
  180. font = app.font()
  181. size = font.pointSize()
  182. font.setPointSize(size * 1.75)
  183. app.setFont(font)
  184. main_window = PiketMainWindow()
  185. main_window.show()
  186. app.exec_()
  187. if __name__ == "__main__":
  188. main()