gui.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. # Copyright © 2024 Noah Vogt <noah@noahvogt.com>
  2. # This program is free software: you can redistribute it and/or modify
  3. # it under the terms of the GNU General Public License as published by
  4. # the Free Software Foundation, either version 3 of the License, or
  5. # (at your option) any later version.
  6. # This program is distributed in the hope that it will be useful,
  7. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  9. # GNU General Public License for more details.
  10. # You should have received a copy of the GNU General Public License
  11. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  12. import sys
  13. from os import path
  14. from re import match
  15. from dataclasses import dataclass
  16. from PyQt5.QtWidgets import ( # pylint: disable=no-name-in-module
  17. QApplication,
  18. QDialog,
  19. QVBoxLayout,
  20. QHBoxLayout,
  21. QStyle,
  22. QLabel,
  23. QRadioButton,
  24. QCheckBox,
  25. QPushButton,
  26. QMessageBox,
  27. QButtonGroup,
  28. QScrollArea,
  29. QWidget,
  30. )
  31. from PyQt5.QtMultimedia import ( # pylint: disable=no-name-in-module
  32. QMediaPlayer,
  33. QMediaContent,
  34. )
  35. from PyQt5.QtCore import ( # pylint: disable=no-name-in-module
  36. QSize,
  37. QUrl,
  38. QTimer,
  39. )
  40. from utils import CustomException, get_wave_duration_in_secs, SermonSegment
  41. @dataclass
  42. class LabelConstruct:
  43. rel_path: str
  44. label: QLabel
  45. @dataclass
  46. class CheckBoxConstruct:
  47. rel_path: str
  48. check_box: QCheckBox
  49. # pylint: disable=too-few-public-methods
  50. class InfoMsgBox:
  51. def __init__(self, icon: QMessageBox.Icon, title: str, text: str) -> None:
  52. self.app = QApplication([])
  53. self.title = title
  54. self.text = text
  55. self.icon = icon
  56. self.show_msg_box()
  57. self.app.exec_()
  58. def show_msg_box(self):
  59. self.message_box = QMessageBox()
  60. self.message_box.setIcon(self.icon)
  61. self.message_box.setWindowTitle(self.title)
  62. self.message_box.setText(self.text)
  63. self.message_box.show()
  64. class RadioButtonDialog(QDialog): # pylint: disable=too-few-public-methods
  65. def __init__(self, options: list[str], window_title: str):
  66. super().__init__()
  67. self.setWindowTitle(window_title)
  68. self.master_layout = QVBoxLayout(self)
  69. scroll_area_layout = self.get_scroll_area_layout()
  70. self.radio_button_group = QButtonGroup(self)
  71. self.chosen = ""
  72. for num, item in enumerate(options):
  73. radio_button = QRadioButton(item)
  74. if num == 0:
  75. radio_button.setChecked(True)
  76. self.radio_button_group.addButton(radio_button)
  77. scroll_area_layout.addWidget(radio_button)
  78. ok_button = QPushButton("OK")
  79. ok_button.clicked.connect(self.accept)
  80. self.master_layout.addWidget(ok_button)
  81. def get_scroll_area_layout(self):
  82. scroll_area = QScrollArea()
  83. scroll_area.setWidgetResizable(True)
  84. self.master_layout.addWidget(scroll_area)
  85. scroll_content = QWidget()
  86. scroll_area.setWidget(scroll_content)
  87. scroll_area_layout = QVBoxLayout(scroll_content)
  88. return scroll_area_layout
  89. def accept(self):
  90. selected_button = self.radio_button_group.checkedButton()
  91. if selected_button:
  92. self.chosen = selected_button.text()
  93. # QMessageBox.information(
  94. # self, "Selection", f"You selected: {selected_button.text()}"
  95. # )
  96. super().accept()
  97. else:
  98. QMessageBox.warning(
  99. self,
  100. "No Selection",
  101. "Please select an option before proceeding.",
  102. )
  103. class SheetAndPreviewChooser(QDialog): # pylint: disable=too-few-public-methods
  104. def __init__(
  105. self, base_dir: str, options: list[str], window_title: str
  106. ) -> None:
  107. super().__init__()
  108. self.base_dir = base_dir
  109. self.setWindowTitle(window_title)
  110. self.master_layout = QVBoxLayout(self)
  111. scroll_area_layout = self.get_scroll_area_layout()
  112. self.check_buttons = []
  113. self.player = QMediaPlayer()
  114. self.chosen_sheets = []
  115. self.position_labels = []
  116. for num, item in enumerate(options):
  117. rel_wave_path = self.get_wav_relative_path_from_cue_sheet(item)
  118. check_box = QCheckBox(item)
  119. if num == 0:
  120. check_box.setChecked(True)
  121. button_layout = QHBoxLayout()
  122. check_box_construct = CheckBoxConstruct(item, check_box)
  123. self.check_buttons.append(check_box_construct)
  124. button_layout.addWidget(check_box)
  125. play_button = self.get_player_button("SP_MediaPlay")
  126. play_button.setToolTip("Play CD Preview")
  127. play_button.clicked.connect(
  128. lambda _, x=rel_wave_path: self.play_audio(x)
  129. )
  130. pause_button = self.get_player_button("SP_MediaPause")
  131. pause_button.setToolTip("Pause CD Preview")
  132. pause_button.clicked.connect(
  133. lambda _, x=rel_wave_path: self.pause_player(x)
  134. )
  135. stop_button = self.get_player_button("SP_MediaStop")
  136. stop_button.setToolTip("Stop CD Preview")
  137. stop_button.clicked.connect(
  138. lambda _, x=rel_wave_path: self.stop_player(x)
  139. )
  140. seek_bwd_button = self.get_player_button("SP_MediaSeekBackward")
  141. seek_bwd_button.setToolTip("Seek 10 seconds backwards")
  142. seek_bwd_button.clicked.connect(
  143. lambda _, x=rel_wave_path: self.seek_bwd_10secs(x)
  144. )
  145. seek_fwd_button = self.get_player_button("SP_MediaSeekForward")
  146. seek_fwd_button.setToolTip("Seek 10 seconds forwards")
  147. seek_fwd_button.clicked.connect(
  148. lambda _, x=rel_wave_path: self.seek_fwd_10secs(x)
  149. )
  150. button_layout.addWidget(play_button)
  151. button_layout.addWidget(pause_button)
  152. button_layout.addWidget(stop_button)
  153. button_layout.addWidget(seek_bwd_button)
  154. button_layout.addWidget(seek_fwd_button)
  155. secs = get_wave_duration_in_secs(path.join(base_dir, rel_wave_path))
  156. mins = secs // 60
  157. secs %= 60
  158. time_label = QLabel(f"00:00 / {mins:02}:{secs:02}")
  159. label_construct = LabelConstruct(rel_wave_path, time_label)
  160. self.position_labels.append(label_construct)
  161. button_layout.addWidget(time_label)
  162. timer = QTimer(self)
  163. timer.timeout.connect(self.update_position)
  164. timer.start(1000)
  165. scroll_area_layout.addLayout(button_layout)
  166. ok_button = QPushButton("OK")
  167. ok_button.clicked.connect(self.accept)
  168. self.master_layout.addWidget(ok_button)
  169. def play_audio(self, rel_path: str) -> None:
  170. if self.player.state() == QMediaPlayer.PausedState: # pyright: ignore
  171. media = self.player.media()
  172. if media.isNull():
  173. return
  174. if path.split(media.canonicalUrl().toString())[1] == rel_path:
  175. self.player.play()
  176. else:
  177. url = QUrl.fromLocalFile(path.join(self.base_dir, rel_path))
  178. content = QMediaContent(url)
  179. self.player.setMedia(content)
  180. self.player.play()
  181. def update_position(self) -> None:
  182. media = self.player.media()
  183. if media.isNull():
  184. return
  185. playing_path = path.split(media.canonicalUrl().toString())[1]
  186. for label_construct in self.position_labels:
  187. if label_construct.rel_path == playing_path:
  188. old_text = label_construct.label.text()
  189. old_text = old_text[old_text.find(" / ") :]
  190. secs = self.player.position() // 1000
  191. mins = secs // 60
  192. secs %= 60
  193. label_construct.label.setText(f"{mins:02}:{secs:02}{old_text}")
  194. def stop_player(self, rel_path: str) -> None:
  195. media = self.player.media()
  196. if media.isNull():
  197. return
  198. if path.split(media.canonicalUrl().toString())[1] == rel_path:
  199. self.player.stop()
  200. self.update_position()
  201. def seek_by(self, rel_path: str, seek_by_milis) -> None:
  202. media = self.player.media()
  203. if media.isNull():
  204. return
  205. if path.split(media.canonicalUrl().toString())[1] == rel_path:
  206. position = self.player.position()
  207. self.player.setPosition(position + seek_by_milis)
  208. self.update_position()
  209. def seek_fwd_10secs(self, rel_path: str) -> None:
  210. self.seek_by(rel_path, 10000)
  211. def seek_bwd_10secs(self, rel_path: str) -> None:
  212. self.seek_by(rel_path, -10000)
  213. def pause_player(self, rel_path: str) -> None:
  214. media = self.player.media()
  215. if media.isNull():
  216. return
  217. if path.split(media.canonicalUrl().toString())[1] == rel_path:
  218. self.player.pause()
  219. def get_scroll_area_layout(self):
  220. scroll_area = QScrollArea()
  221. scroll_area.setWidgetResizable(True)
  222. self.master_layout.addWidget(scroll_area)
  223. scroll_content = QWidget()
  224. scroll_area.setWidget(scroll_content)
  225. scroll_area_layout = QVBoxLayout(scroll_content)
  226. return scroll_area_layout
  227. def get_player_button(self, icon_name: str) -> QPushButton:
  228. stop_button = QPushButton("")
  229. stop_button.setMinimumSize(QSize(40, 40))
  230. stop_button.setMaximumSize(QSize(40, 40))
  231. pixmapi = getattr(QStyle, icon_name)
  232. icon = self.style().standardIcon(pixmapi) # pyright: ignore
  233. stop_button.setIcon(icon)
  234. return stop_button
  235. def accept(self) -> None:
  236. for check_box_construct in self.check_buttons:
  237. if check_box_construct.check_box.isChecked():
  238. self.chosen_sheets.append(check_box_construct.rel_path)
  239. super().accept()
  240. def get_wav_relative_path_from_cue_sheet(
  241. self, sheet_relative_path: str
  242. ) -> str:
  243. full_path = path.join(self.base_dir, sheet_relative_path)
  244. try:
  245. with open(
  246. full_path,
  247. mode="r",
  248. encoding="utf-8-sig",
  249. ) as cachefile_reader:
  250. cachefile_content = cachefile_reader.readlines()
  251. first_line = cachefile_content[0].strip()
  252. if not match(r"^FILE \".+\" WAVE$", first_line):
  253. raise CustomException("invalid first cue sheet line")
  254. full_path_found = first_line[first_line.find('"') + 1 :]
  255. full_path_found = full_path_found[: full_path_found.rfind('"')]
  256. return path.split(full_path_found)[1]
  257. except (
  258. FileNotFoundError,
  259. PermissionError,
  260. IOError,
  261. IndexError,
  262. CustomException,
  263. ) as error:
  264. QMessageBox.critical(
  265. self,
  266. "Error",
  267. f"Could not parse cue sheet: '{full_path}', Reason: {error}",
  268. )
  269. sys.exit(1)
  270. class SegmentChooser(QDialog): # pylint: disable=too-few-public-methods
  271. def __init__(
  272. self, base_dir: str, options: list[SermonSegment], window_title: str
  273. ) -> None:
  274. super().__init__()
  275. self.base_dir = base_dir
  276. self.setWindowTitle(window_title)
  277. self.master_layout = QVBoxLayout(self)
  278. scroll_area_layout = self.get_scroll_area_layout()
  279. self.check_buttons = []
  280. self.player = QMediaPlayer()
  281. self.chosen_sheets = []
  282. self.position_labels = []
  283. for num, item in enumerate(options):
  284. rel_wave_path = self.get_wav_relative_path_from_cue_sheet(item)
  285. check_box = QCheckBox(item)
  286. if num == 0:
  287. check_box.setChecked(True)
  288. button_layout = QHBoxLayout()
  289. check_box_construct = CheckBoxConstruct(item, check_box)
  290. self.check_buttons.append(check_box_construct)
  291. button_layout.addWidget(check_box)
  292. play_button = self.get_player_button("SP_MediaPlay")
  293. play_button.setToolTip("Play CD Preview")
  294. play_button.clicked.connect(
  295. lambda _, x=rel_wave_path: self.play_audio(x)
  296. )
  297. pause_button = self.get_player_button("SP_MediaPause")
  298. pause_button.setToolTip("Pause CD Preview")
  299. pause_button.clicked.connect(
  300. lambda _, x=rel_wave_path: self.pause_player(x)
  301. )
  302. stop_button = self.get_player_button("SP_MediaStop")
  303. stop_button.setToolTip("Stop CD Preview")
  304. stop_button.clicked.connect(
  305. lambda _, x=rel_wave_path: self.stop_player(x)
  306. )
  307. seek_bwd_button = self.get_player_button("SP_MediaSeekBackward")
  308. seek_bwd_button.setToolTip("Seek 10 seconds backwards")
  309. seek_bwd_button.clicked.connect(
  310. lambda _, x=rel_wave_path: self.seek_bwd_10secs(x)
  311. )
  312. seek_fwd_button = self.get_player_button("SP_MediaSeekForward")
  313. seek_fwd_button.setToolTip("Seek 10 seconds forwards")
  314. seek_fwd_button.clicked.connect(
  315. lambda _, x=rel_wave_path: self.seek_fwd_10secs(x)
  316. )
  317. button_layout.addWidget(play_button)
  318. button_layout.addWidget(pause_button)
  319. button_layout.addWidget(stop_button)
  320. button_layout.addWidget(seek_bwd_button)
  321. button_layout.addWidget(seek_fwd_button)
  322. secs = get_wave_duration_in_secs(path.join(base_dir, rel_wave_path))
  323. mins = secs // 60
  324. secs %= 60
  325. time_label = QLabel(f"00:00 / {mins:02}:{secs:02}")
  326. label_construct = LabelConstruct(rel_wave_path, time_label)
  327. self.position_labels.append(label_construct)
  328. button_layout.addWidget(time_label)
  329. timer = QTimer(self)
  330. timer.timeout.connect(self.update_position)
  331. timer.start(1000)
  332. scroll_area_layout.addLayout(button_layout)
  333. ok_button = QPushButton("OK")
  334. ok_button.clicked.connect(self.accept)
  335. self.master_layout.addWidget(ok_button)
  336. def play_audio(self, rel_path: str) -> None:
  337. if self.player.state() == QMediaPlayer.PausedState: # pyright: ignore
  338. media = self.player.media()
  339. if media.isNull():
  340. return
  341. if path.split(media.canonicalUrl().toString())[1] == rel_path:
  342. self.player.play()
  343. else:
  344. url = QUrl.fromLocalFile(path.join(self.base_dir, rel_path))
  345. content = QMediaContent(url)
  346. self.player.setMedia(content)
  347. self.player.play()
  348. def update_position(self) -> None:
  349. media = self.player.media()
  350. if media.isNull():
  351. return
  352. playing_path = path.split(media.canonicalUrl().toString())[1]
  353. for label_construct in self.position_labels:
  354. if label_construct.rel_path == playing_path:
  355. old_text = label_construct.label.text()
  356. old_text = old_text[old_text.find(" / ") :]
  357. secs = self.player.position() // 1000
  358. mins = secs // 60
  359. secs %= 60
  360. label_construct.label.setText(f"{mins:02}:{secs:02}{old_text}")
  361. def stop_player(self, rel_path: str) -> None:
  362. media = self.player.media()
  363. if media.isNull():
  364. return
  365. if path.split(media.canonicalUrl().toString())[1] == rel_path:
  366. self.player.stop()
  367. self.update_position()
  368. def seek_by(self, rel_path: str, seek_by_milis) -> None:
  369. media = self.player.media()
  370. if media.isNull():
  371. return
  372. if path.split(media.canonicalUrl().toString())[1] == rel_path:
  373. position = self.player.position()
  374. self.player.setPosition(position + seek_by_milis)
  375. self.update_position()
  376. def seek_fwd_10secs(self, rel_path: str) -> None:
  377. self.seek_by(rel_path, 10000)
  378. def seek_bwd_10secs(self, rel_path: str) -> None:
  379. self.seek_by(rel_path, -10000)
  380. def pause_player(self, rel_path: str) -> None:
  381. media = self.player.media()
  382. if media.isNull():
  383. return
  384. if path.split(media.canonicalUrl().toString())[1] == rel_path:
  385. self.player.pause()
  386. def get_scroll_area_layout(self):
  387. scroll_area = QScrollArea()
  388. scroll_area.setWidgetResizable(True)
  389. self.master_layout.addWidget(scroll_area)
  390. scroll_content = QWidget()
  391. scroll_area.setWidget(scroll_content)
  392. scroll_area_layout = QVBoxLayout(scroll_content)
  393. return scroll_area_layout
  394. def get_player_button(self, icon_name: str) -> QPushButton:
  395. stop_button = QPushButton("")
  396. stop_button.setMinimumSize(QSize(40, 40))
  397. stop_button.setMaximumSize(QSize(40, 40))
  398. pixmapi = getattr(QStyle, icon_name)
  399. icon = self.style().standardIcon(pixmapi) # pyright: ignore
  400. stop_button.setIcon(icon)
  401. return stop_button
  402. def accept(self) -> None:
  403. for check_box_construct in self.check_buttons:
  404. if check_box_construct.check_box.isChecked():
  405. self.chosen_sheets.append(check_box_construct.rel_path)
  406. super().accept()
  407. def get_wav_relative_path_from_cue_sheet(
  408. self, sheet_relative_path: str
  409. ) -> str:
  410. full_path = path.join(self.base_dir, sheet_relative_path)
  411. try:
  412. with open(
  413. full_path,
  414. mode="r",
  415. encoding="utf-8-sig",
  416. ) as cachefile_reader:
  417. cachefile_content = cachefile_reader.readlines()
  418. first_line = cachefile_content[0].strip()
  419. if not match(r"^FILE \".+\" WAVE$", first_line):
  420. raise CustomException("invalid first cue sheet line")
  421. full_path_found = first_line[first_line.find('"') + 1 :]
  422. full_path_found = full_path_found[: full_path_found.rfind('"')]
  423. return path.split(full_path_found)[1]
  424. except (
  425. FileNotFoundError,
  426. PermissionError,
  427. IOError,
  428. IndexError,
  429. CustomException,
  430. ) as error:
  431. QMessageBox.critical(
  432. self,
  433. "Error",
  434. f"Could not parse cue sheet: '{full_path}', Reason: {error}",
  435. )
  436. sys.exit(1)