gui.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. """
  2. Copyright © 2024 Noah Vogt <noah@noahvogt.com>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. """
  14. import sys
  15. from os import path
  16. from re import match
  17. from dataclasses import dataclass
  18. from PyQt5.QtWidgets import ( # pylint: disable=no-name-in-module
  19. QApplication,
  20. QDialog,
  21. QVBoxLayout,
  22. QHBoxLayout,
  23. QStyle,
  24. QLabel,
  25. QRadioButton,
  26. QCheckBox,
  27. QPushButton,
  28. QMessageBox,
  29. QButtonGroup,
  30. QScrollArea,
  31. QWidget,
  32. )
  33. from PyQt5.QtMultimedia import ( # pylint: disable=no-name-in-module
  34. QMediaPlayer,
  35. QMediaContent,
  36. )
  37. from PyQt5.QtCore import ( # pylint: disable=no-name-in-module
  38. QSize,
  39. QUrl,
  40. QTimer,
  41. )
  42. from utils import CustomException, get_wave_duration_in_secs
  43. @dataclass
  44. class LabelConstruct:
  45. rel_path: str
  46. label: QLabel
  47. @dataclass
  48. class CheckBoxConstruct:
  49. rel_path: str
  50. check_box: QCheckBox
  51. # pylint: disable=too-few-public-methods
  52. class InfoMsgBox:
  53. def __init__(self, icon: QMessageBox.Icon, title: str, text: str) -> None:
  54. self.app = QApplication([])
  55. self.title = title
  56. self.text = text
  57. self.icon = icon
  58. self.show_msg_box()
  59. self.app.exec_()
  60. def show_msg_box(self):
  61. self.message_box = QMessageBox()
  62. self.message_box.setIcon(self.icon)
  63. self.message_box.setWindowTitle(self.title)
  64. self.message_box.setText(self.text)
  65. self.message_box.show()
  66. class RadioButtonDialog(QDialog): # pylint: disable=too-few-public-methods
  67. def __init__(self, options: list[str], window_title: str):
  68. super().__init__()
  69. self.setWindowTitle(window_title)
  70. self.master_layout = QVBoxLayout(self)
  71. scroll_area_layout = self.get_scroll_area_layout()
  72. self.radio_button_group = QButtonGroup(self)
  73. self.chosen = ""
  74. for num, item in enumerate(options):
  75. radio_button = QRadioButton(item)
  76. if num == 0:
  77. radio_button.setChecked(True)
  78. self.radio_button_group.addButton(radio_button)
  79. scroll_area_layout.addWidget(radio_button)
  80. ok_button = QPushButton("OK")
  81. ok_button.clicked.connect(self.accept)
  82. self.master_layout.addWidget(ok_button)
  83. def get_scroll_area_layout(self):
  84. scroll_area = QScrollArea()
  85. scroll_area.setWidgetResizable(True)
  86. self.master_layout.addWidget(scroll_area)
  87. scroll_content = QWidget()
  88. scroll_area.setWidget(scroll_content)
  89. scroll_area_layout = QVBoxLayout(scroll_content)
  90. return scroll_area_layout
  91. def accept(self):
  92. selected_button = self.radio_button_group.checkedButton()
  93. if selected_button:
  94. self.chosen = selected_button.text()
  95. # QMessageBox.information(
  96. # self, "Selection", f"You selected: {selected_button.text()}"
  97. # )
  98. super().accept()
  99. else:
  100. QMessageBox.warning(
  101. self,
  102. "No Selection",
  103. "Please select an option before proceeding.",
  104. )
  105. class SheetAndPreviewChooser(QDialog): # pylint: disable=too-few-public-methods
  106. def __init__(
  107. self, base_dir: str, options: list[str], window_title: str
  108. ) -> None:
  109. super().__init__()
  110. self.base_dir = base_dir
  111. self.setWindowTitle(window_title)
  112. self.master_layout = QVBoxLayout(self)
  113. scroll_area_layout = self.get_scroll_area_layout()
  114. self.check_buttons = []
  115. self.player = QMediaPlayer()
  116. self.chosen_sheets = []
  117. self.position_labels = []
  118. for num, item in enumerate(options):
  119. rel_wave_path = self.get_wav_relative_path_from_cue_sheet(item)
  120. check_box = QCheckBox(item)
  121. if num == 0:
  122. check_box.setChecked(True)
  123. button_layout = QHBoxLayout()
  124. check_box_construct = CheckBoxConstruct(item, check_box)
  125. self.check_buttons.append(check_box_construct)
  126. button_layout.addWidget(check_box)
  127. play_button = self.get_player_button("SP_MediaPlay")
  128. play_button.setToolTip("Play CD Preview")
  129. play_button.clicked.connect(
  130. lambda _, x=rel_wave_path: self.play_audio(x)
  131. )
  132. pause_button = self.get_player_button("SP_MediaPause")
  133. pause_button.setToolTip("Pause CD Preview")
  134. pause_button.clicked.connect(
  135. lambda _, x=rel_wave_path: self.pause_player(x)
  136. )
  137. stop_button = self.get_player_button("SP_MediaStop")
  138. stop_button.setToolTip("Stop CD Preview")
  139. stop_button.clicked.connect(
  140. lambda _, x=rel_wave_path: self.stop_player(x)
  141. )
  142. seek_bwd_button = self.get_player_button("SP_MediaSeekBackward")
  143. seek_bwd_button.setToolTip("Seek 10 seconds backwards")
  144. seek_bwd_button.clicked.connect(
  145. lambda _, x=rel_wave_path: self.seek_bwd_10secs(x)
  146. )
  147. seek_fwd_button = self.get_player_button("SP_MediaSeekForward")
  148. seek_fwd_button.setToolTip("Seek 10 seconds forwards")
  149. seek_fwd_button.clicked.connect(
  150. lambda _, x=rel_wave_path: self.seek_fwd_10secs(x)
  151. )
  152. button_layout.addWidget(play_button)
  153. button_layout.addWidget(pause_button)
  154. button_layout.addWidget(stop_button)
  155. button_layout.addWidget(seek_bwd_button)
  156. button_layout.addWidget(seek_fwd_button)
  157. secs = get_wave_duration_in_secs(path.join(base_dir, rel_wave_path))
  158. mins = secs // 60
  159. secs %= 60
  160. time_label = QLabel(f"00:00 / {mins:02}:{secs:02}")
  161. label_construct = LabelConstruct(rel_wave_path, time_label)
  162. self.position_labels.append(label_construct)
  163. button_layout.addWidget(time_label)
  164. timer = QTimer(self)
  165. timer.timeout.connect(self.update_position)
  166. timer.start(1000)
  167. scroll_area_layout.addLayout(button_layout)
  168. ok_button = QPushButton("OK")
  169. ok_button.clicked.connect(self.accept)
  170. self.master_layout.addWidget(ok_button)
  171. def play_audio(self, rel_path: str) -> None:
  172. if self.player.state() == QMediaPlayer.PausedState: # pyright: ignore
  173. media = self.player.media()
  174. if media.isNull():
  175. return
  176. if path.split(media.canonicalUrl().toString())[1] == rel_path:
  177. self.player.play()
  178. else:
  179. url = QUrl.fromLocalFile(path.join(self.base_dir, rel_path))
  180. content = QMediaContent(url)
  181. self.player.setMedia(content)
  182. self.player.play()
  183. def update_position(self) -> None:
  184. media = self.player.media()
  185. if media.isNull():
  186. return
  187. playing_path = path.split(media.canonicalUrl().toString())[1]
  188. for label_construct in self.position_labels:
  189. if label_construct.rel_path == playing_path:
  190. old_text = label_construct.label.text()
  191. old_text = old_text[old_text.find(" / ") :]
  192. secs = self.player.position() // 1000
  193. mins = secs // 60
  194. secs %= 60
  195. label_construct.label.setText(f"{mins:02}:{secs:02}{old_text}")
  196. def stop_player(self, rel_path: str) -> None:
  197. media = self.player.media()
  198. if media.isNull():
  199. return
  200. if path.split(media.canonicalUrl().toString())[1] == rel_path:
  201. self.player.stop()
  202. self.update_position()
  203. def seek_by(self, rel_path: str, seek_by_milis) -> None:
  204. media = self.player.media()
  205. if media.isNull():
  206. return
  207. if path.split(media.canonicalUrl().toString())[1] == rel_path:
  208. position = self.player.position()
  209. self.player.setPosition(position + seek_by_milis)
  210. self.update_position()
  211. def seek_fwd_10secs(self, rel_path: str) -> None:
  212. self.seek_by(rel_path, 10000)
  213. def seek_bwd_10secs(self, rel_path: str) -> None:
  214. self.seek_by(rel_path, -10000)
  215. def pause_player(self, rel_path: str) -> None:
  216. media = self.player.media()
  217. if media.isNull():
  218. return
  219. if path.split(media.canonicalUrl().toString())[1] == rel_path:
  220. self.player.pause()
  221. def get_scroll_area_layout(self):
  222. scroll_area = QScrollArea()
  223. scroll_area.setWidgetResizable(True)
  224. self.master_layout.addWidget(scroll_area)
  225. scroll_content = QWidget()
  226. scroll_area.setWidget(scroll_content)
  227. scroll_area_layout = QVBoxLayout(scroll_content)
  228. return scroll_area_layout
  229. def get_player_button(self, icon_name: str) -> QPushButton:
  230. stop_button = QPushButton("")
  231. stop_button.setMinimumSize(QSize(40, 40))
  232. stop_button.setMaximumSize(QSize(40, 40))
  233. pixmapi = getattr(QStyle, icon_name)
  234. icon = self.style().standardIcon(pixmapi) # pyright: ignore
  235. stop_button.setIcon(icon)
  236. return stop_button
  237. def accept(self) -> None:
  238. for check_box_construct in self.check_buttons:
  239. if check_box_construct.check_box.isChecked():
  240. self.chosen_sheets.append(check_box_construct.rel_path)
  241. super().accept()
  242. def get_wav_relative_path_from_cue_sheet(
  243. self, sheet_relative_path: str
  244. ) -> str:
  245. full_path = path.join(self.base_dir, sheet_relative_path)
  246. try:
  247. with open(
  248. full_path,
  249. mode="r",
  250. encoding="utf-8-sig",
  251. ) as cachefile_reader:
  252. cachefile_content = cachefile_reader.readlines()
  253. first_line = cachefile_content[0].strip()
  254. if not match(r"^FILE \".+\" WAVE$", first_line):
  255. raise CustomException("invalid first cue sheet line")
  256. full_path_found = first_line[first_line.find('"') + 1 :]
  257. full_path_found = full_path_found[: full_path_found.rfind('"')]
  258. return path.split(full_path_found)[1]
  259. except (
  260. FileNotFoundError,
  261. PermissionError,
  262. IOError,
  263. IndexError,
  264. CustomException,
  265. ) as error:
  266. QMessageBox.critical(
  267. self,
  268. "Error",
  269. f"Could not parse cue sheet: '{full_path}', Reason: {error}",
  270. )
  271. sys.exit(1)