gui.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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, listdir
  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 audio import SermonSegment
  41. from utils import CustomException, get_wave_duration_in_secs, log
  42. import config as const
  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)
  272. class SegmentChooser(QDialog): # pylint: disable=too-few-public-methods
  273. def __init__(
  274. self, base_dir: str, options: list[SermonSegment], window_title: str
  275. ) -> None:
  276. super().__init__()
  277. self.base_dir = base_dir
  278. self.setWindowTitle(window_title)
  279. self.master_layout = QVBoxLayout(self)
  280. scroll_area_layout = self.get_scroll_area_layout()
  281. self.check_buttons = []
  282. self.player = QMediaPlayer()
  283. self.chosen_sheets = []
  284. self.position_labels = []
  285. for num, item in enumerate(options):
  286. rel_wave_path = self.get_wav_relative_path_from_cue_sheet(item)
  287. check_box = QCheckBox(item)
  288. if num == 0:
  289. check_box.setChecked(True)
  290. button_layout = QHBoxLayout()
  291. check_box_construct = CheckBoxConstruct(item, check_box)
  292. self.check_buttons.append(check_box_construct)
  293. button_layout.addWidget(check_box)
  294. play_button = self.get_player_button("SP_MediaPlay")
  295. play_button.setToolTip("Play CD Preview")
  296. play_button.clicked.connect(
  297. lambda _, x=rel_wave_path: self.play_audio(x)
  298. )
  299. pause_button = self.get_player_button("SP_MediaPause")
  300. pause_button.setToolTip("Pause CD Preview")
  301. pause_button.clicked.connect(
  302. lambda _, x=rel_wave_path: self.pause_player(x)
  303. )
  304. stop_button = self.get_player_button("SP_MediaStop")
  305. stop_button.setToolTip("Stop CD Preview")
  306. stop_button.clicked.connect(
  307. lambda _, x=rel_wave_path: self.stop_player(x)
  308. )
  309. seek_bwd_button = self.get_player_button("SP_MediaSeekBackward")
  310. seek_bwd_button.setToolTip("Seek 10 seconds backwards")
  311. seek_bwd_button.clicked.connect(
  312. lambda _, x=rel_wave_path: self.seek_bwd_10secs(x)
  313. )
  314. seek_fwd_button = self.get_player_button("SP_MediaSeekForward")
  315. seek_fwd_button.setToolTip("Seek 10 seconds forwards")
  316. seek_fwd_button.clicked.connect(
  317. lambda _, x=rel_wave_path: self.seek_fwd_10secs(x)
  318. )
  319. button_layout.addWidget(play_button)
  320. button_layout.addWidget(pause_button)
  321. button_layout.addWidget(stop_button)
  322. button_layout.addWidget(seek_bwd_button)
  323. button_layout.addWidget(seek_fwd_button)
  324. secs = get_wave_duration_in_secs(path.join(base_dir, rel_wave_path))
  325. mins = secs // 60
  326. secs %= 60
  327. time_label = QLabel(f"00:00 / {mins:02}:{secs:02}")
  328. label_construct = LabelConstruct(rel_wave_path, time_label)
  329. self.position_labels.append(label_construct)
  330. button_layout.addWidget(time_label)
  331. timer = QTimer(self)
  332. timer.timeout.connect(self.update_position)
  333. timer.start(1000)
  334. scroll_area_layout.addLayout(button_layout)
  335. ok_button = QPushButton("OK")
  336. ok_button.clicked.connect(self.accept)
  337. self.master_layout.addWidget(ok_button)
  338. def play_audio(self, rel_path: str) -> None:
  339. if self.player.state() == QMediaPlayer.PausedState: # pyright: ignore
  340. media = self.player.media()
  341. if media.isNull():
  342. return
  343. if path.split(media.canonicalUrl().toString())[1] == rel_path:
  344. self.player.play()
  345. else:
  346. url = QUrl.fromLocalFile(path.join(self.base_dir, rel_path))
  347. content = QMediaContent(url)
  348. self.player.setMedia(content)
  349. self.player.play()
  350. def update_position(self) -> None:
  351. media = self.player.media()
  352. if media.isNull():
  353. return
  354. playing_path = path.split(media.canonicalUrl().toString())[1]
  355. for label_construct in self.position_labels:
  356. if label_construct.rel_path == playing_path:
  357. old_text = label_construct.label.text()
  358. old_text = old_text[old_text.find(" / ") :]
  359. secs = self.player.position() // 1000
  360. mins = secs // 60
  361. secs %= 60
  362. label_construct.label.setText(f"{mins:02}:{secs:02}{old_text}")
  363. def stop_player(self, rel_path: str) -> None:
  364. media = self.player.media()
  365. if media.isNull():
  366. return
  367. if path.split(media.canonicalUrl().toString())[1] == rel_path:
  368. self.player.stop()
  369. self.update_position()
  370. def seek_by(self, rel_path: str, seek_by_milis) -> None:
  371. media = self.player.media()
  372. if media.isNull():
  373. return
  374. if path.split(media.canonicalUrl().toString())[1] == rel_path:
  375. position = self.player.position()
  376. self.player.setPosition(position + seek_by_milis)
  377. self.update_position()
  378. def seek_fwd_10secs(self, rel_path: str) -> None:
  379. self.seek_by(rel_path, 10000)
  380. def seek_bwd_10secs(self, rel_path: str) -> None:
  381. self.seek_by(rel_path, -10000)
  382. def pause_player(self, rel_path: str) -> None:
  383. media = self.player.media()
  384. if media.isNull():
  385. return
  386. if path.split(media.canonicalUrl().toString())[1] == rel_path:
  387. self.player.pause()
  388. def get_scroll_area_layout(self):
  389. scroll_area = QScrollArea()
  390. scroll_area.setWidgetResizable(True)
  391. self.master_layout.addWidget(scroll_area)
  392. scroll_content = QWidget()
  393. scroll_area.setWidget(scroll_content)
  394. scroll_area_layout = QVBoxLayout(scroll_content)
  395. return scroll_area_layout
  396. def get_player_button(self, icon_name: str) -> QPushButton:
  397. stop_button = QPushButton("")
  398. stop_button.setMinimumSize(QSize(40, 40))
  399. stop_button.setMaximumSize(QSize(40, 40))
  400. pixmapi = getattr(QStyle, icon_name)
  401. icon = self.style().standardIcon(pixmapi) # pyright: ignore
  402. stop_button.setIcon(icon)
  403. return stop_button
  404. def accept(self) -> None:
  405. for check_box_construct in self.check_buttons:
  406. if check_box_construct.check_box.isChecked():
  407. self.chosen_sheets.append(check_box_construct.rel_path)
  408. super().accept()
  409. def get_wav_relative_path_from_cue_sheet(
  410. self, sheet_relative_path: str
  411. ) -> str:
  412. full_path = path.join(self.base_dir, sheet_relative_path)
  413. try:
  414. with open(
  415. full_path,
  416. mode="r",
  417. encoding="utf-8-sig",
  418. ) as cachefile_reader:
  419. cachefile_content = cachefile_reader.readlines()
  420. first_line = cachefile_content[0].strip()
  421. if not match(r"^FILE \".+\" WAVE$", first_line):
  422. raise CustomException("invalid first cue sheet line")
  423. full_path_found = first_line[first_line.find('"') + 1 :]
  424. full_path_found = full_path_found[: full_path_found.rfind('"')]
  425. return path.split(full_path_found)[1]
  426. except (
  427. FileNotFoundError,
  428. PermissionError,
  429. IOError,
  430. IndexError,
  431. CustomException,
  432. ) as error:
  433. QMessageBox.critical(
  434. self,
  435. "Error",
  436. f"Could not parse cue sheet: '{full_path}', Reason: {error}",
  437. )
  438. sys.exit(1)
  439. @dataclass
  440. class ArchiveTypeStrings:
  441. archive_type_plural: str
  442. action_to_choose: str
  443. action_ing_form: str
  444. def choose_cd_day() -> list[str]:
  445. strings = ArchiveTypeStrings("CD's", "CD day to Burn", "Burning CD for day")
  446. return choose_archive_day(strings)
  447. def choose_sermon_day() -> list[str]:
  448. strings = ArchiveTypeStrings(
  449. "Sermons", "Sermon day to upload", "Uploading Sermon for day"
  450. )
  451. return choose_archive_day(strings)
  452. def choose_archive_day(strings: ArchiveTypeStrings) -> list[str]:
  453. # pylint: disable=unused-variable
  454. app = QApplication([])
  455. try:
  456. dirs = sorted(listdir(const.CD_RECORD_OUTPUT_BASEDIR))
  457. dirs.reverse()
  458. if not dirs:
  459. return [
  460. f"Did not find any {strings.archive_type_plural} in: "
  461. + f"{const.CD_RECORD_OUTPUT_BASEDIR}.",
  462. "",
  463. ]
  464. dialog = RadioButtonDialog(
  465. dirs, "Choose a " + f"{strings.action_to_choose}"
  466. )
  467. if dialog.exec_() == QDialog.Accepted:
  468. log(f"{strings.action_ing_form} for day: {dialog.chosen}")
  469. return ["", dialog.chosen]
  470. return ["ignore", ""]
  471. except (FileNotFoundError, PermissionError, IOError):
  472. pass
  473. return [
  474. f"Failed to access directory: {const.CD_RECORD_OUTPUT_BASEDIR}.",
  475. "",
  476. ]