Digitale bierlijst

gui.py 9.3KB

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