gui.py 11 KB

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