gui.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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 AudioSourceFileType, ChosenAudio, get_wave_duration_in_secs
  41. from utils import CustomException, 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_sheet_path: str
  50. abs_wave_path: str
  51. check_box: QCheckBox
  52. class RadioButtonDialog(QDialog): # pylint: disable=too-few-public-methods
  53. def __init__(self, options: list[str], window_title: str):
  54. super().__init__()
  55. self.setWindowTitle(window_title)
  56. self.master_layout = QVBoxLayout(self)
  57. scroll_area_layout = self.get_scroll_area_layout()
  58. self.radio_button_group = QButtonGroup(self)
  59. self.chosen = ""
  60. for num, item in enumerate(options):
  61. radio_button = QRadioButton(item)
  62. if num == 0:
  63. radio_button.setChecked(True)
  64. self.radio_button_group.addButton(radio_button)
  65. scroll_area_layout.addWidget(radio_button)
  66. ok_button = QPushButton("OK")
  67. ok_button.clicked.connect(self.accept)
  68. self.master_layout.addWidget(ok_button)
  69. def get_scroll_area_layout(self):
  70. scroll_area = QScrollArea()
  71. scroll_area.setWidgetResizable(True)
  72. self.master_layout.addWidget(scroll_area)
  73. scroll_content = QWidget()
  74. scroll_area.setWidget(scroll_content)
  75. scroll_area_layout = QVBoxLayout(scroll_content)
  76. return scroll_area_layout
  77. def accept(self):
  78. selected_button = self.radio_button_group.checkedButton()
  79. if selected_button:
  80. self.chosen = selected_button.text()
  81. # QMessageBox.information(
  82. # self, "Selection", f"You selected: {selected_button.text()}"
  83. # )
  84. super().accept()
  85. else:
  86. QMessageBox.warning(
  87. self,
  88. "No Selection",
  89. "Please select an option before proceeding.",
  90. )
  91. class WaveAndSheetPreviewChooserGUI(
  92. QDialog
  93. ): # pylint: disable=too-few-public-methods
  94. def __init__(
  95. self,
  96. base_dir: str,
  97. options: list[str],
  98. window_title: str,
  99. source_type: AudioSourceFileType,
  100. ) -> None:
  101. super().__init__()
  102. self.base_dir = base_dir
  103. self.setWindowTitle(window_title)
  104. self.master_layout = QVBoxLayout(self)
  105. scroll_area_layout = self.get_scroll_area_layout()
  106. self.check_buttons = []
  107. self.player = QMediaPlayer()
  108. self.chosen_audios = []
  109. self.position_labels = []
  110. for num, item in enumerate(options):
  111. if source_type is AudioSourceFileType.WAVE:
  112. rel_wave_path = item
  113. else:
  114. rel_wave_path = self.get_wav_relative_path_from_cue_sheet(item)
  115. abs_wave_path = path.join(base_dir, rel_wave_path)
  116. if source_type is AudioSourceFileType.WAVE:
  117. check_box = QCheckBox(
  118. f"Segment {(num+1):0{const.CD_RECORD_FILENAME_ZFILL}}"
  119. )
  120. else:
  121. check_box = QCheckBox(item)
  122. if num == 0 and source_type is AudioSourceFileType.CUESHEET:
  123. check_box.setChecked(True)
  124. button_layout = QHBoxLayout()
  125. check_box_construct = CheckBoxConstruct(
  126. item, abs_wave_path, check_box
  127. )
  128. self.check_buttons.append(check_box_construct)
  129. button_layout.addWidget(check_box)
  130. play_button = self.get_player_button("SP_MediaPlay")
  131. play_button.setToolTip("Play CD Preview")
  132. play_button.clicked.connect(
  133. lambda _, x=rel_wave_path: self.play_audio(x)
  134. )
  135. pause_button = self.get_player_button("SP_MediaPause")
  136. pause_button.setToolTip("Pause CD Preview")
  137. pause_button.clicked.connect(
  138. lambda _, x=rel_wave_path: self.pause_player(x)
  139. )
  140. stop_button = self.get_player_button("SP_MediaStop")
  141. stop_button.setToolTip("Stop CD Preview")
  142. stop_button.clicked.connect(
  143. lambda _, x=rel_wave_path: self.stop_player(x)
  144. )
  145. seek_bwd_button = self.get_player_button("SP_MediaSeekBackward")
  146. seek_bwd_button.setToolTip("Seek 10 seconds backwards")
  147. seek_bwd_button.clicked.connect(
  148. lambda _, x=rel_wave_path: self.seek_bwd_10secs(x)
  149. )
  150. seek_fwd_button = self.get_player_button("SP_MediaSeekForward")
  151. seek_fwd_button.setToolTip("Seek 10 seconds forwards")
  152. seek_fwd_button.clicked.connect(
  153. lambda _, x=rel_wave_path: self.seek_fwd_10secs(x)
  154. )
  155. button_layout.addWidget(play_button)
  156. button_layout.addWidget(pause_button)
  157. button_layout.addWidget(stop_button)
  158. button_layout.addWidget(seek_bwd_button)
  159. button_layout.addWidget(seek_fwd_button)
  160. time_label = self.get_initial_time_label(abs_wave_path)
  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 get_initial_time_label(self, abs_wave_path):
  172. secs = get_wave_duration_in_secs(abs_wave_path)
  173. mins = secs // 60
  174. secs %= 60
  175. time_label = QLabel(f"00:00 / {mins:02}:{secs:02}")
  176. return time_label
  177. def play_audio(self, rel_path: str) -> None:
  178. if self.player.state() == QMediaPlayer.PausedState: # pyright: ignore
  179. media = self.player.media()
  180. if media.isNull():
  181. return
  182. if path.split(media.canonicalUrl().toString())[1] == rel_path:
  183. self.player.play()
  184. else:
  185. url = QUrl.fromLocalFile(path.join(self.base_dir, rel_path))
  186. content = QMediaContent(url)
  187. self.player.setMedia(content)
  188. self.player.play()
  189. def update_position(self) -> None:
  190. media = self.player.media()
  191. if media.isNull():
  192. return
  193. playing_path = path.split(media.canonicalUrl().toString())[1]
  194. for label_construct in self.position_labels:
  195. if label_construct.rel_path == playing_path:
  196. old_text = label_construct.label.text()
  197. old_text = old_text[old_text.find(" / ") :]
  198. secs = self.player.position() // 1000
  199. mins = secs // 60
  200. secs %= 60
  201. label_construct.label.setText(f"{mins:02}:{secs:02}{old_text}")
  202. def stop_player(self, rel_path: str) -> None:
  203. media = self.player.media()
  204. if media.isNull():
  205. return
  206. if path.split(media.canonicalUrl().toString())[1] == rel_path:
  207. self.player.stop()
  208. self.update_position()
  209. def seek_by(self, rel_path: str, seek_by_milis) -> None:
  210. media = self.player.media()
  211. if media.isNull():
  212. return
  213. if path.split(media.canonicalUrl().toString())[1] == rel_path:
  214. position = self.player.position()
  215. self.player.setPosition(position + seek_by_milis)
  216. self.update_position()
  217. def seek_fwd_10secs(self, rel_path: str) -> None:
  218. self.seek_by(rel_path, 10000)
  219. def seek_bwd_10secs(self, rel_path: str) -> None:
  220. self.seek_by(rel_path, -10000)
  221. def pause_player(self, rel_path: str) -> None:
  222. media = self.player.media()
  223. if media.isNull():
  224. return
  225. if path.split(media.canonicalUrl().toString())[1] == rel_path:
  226. self.player.pause()
  227. def get_scroll_area_layout(self):
  228. scroll_area = QScrollArea()
  229. scroll_area.setWidgetResizable(True)
  230. self.master_layout.addWidget(scroll_area)
  231. scroll_content = QWidget()
  232. scroll_area.setWidget(scroll_content)
  233. scroll_area_layout = QVBoxLayout(scroll_content)
  234. return scroll_area_layout
  235. def get_player_button(self, icon_name: str) -> QPushButton:
  236. stop_button = QPushButton("")
  237. stop_button.setMinimumSize(QSize(40, 40))
  238. stop_button.setMaximumSize(QSize(40, 40))
  239. pixmapi = getattr(QStyle, icon_name)
  240. icon = self.style().standardIcon(pixmapi) # pyright: ignore
  241. stop_button.setIcon(icon)
  242. return stop_button
  243. def accept(self) -> None:
  244. for check_box_construct in self.check_buttons:
  245. if check_box_construct.check_box.isChecked():
  246. self.chosen_audios.append(
  247. ChosenAudio(
  248. check_box_construct.rel_sheet_path,
  249. check_box_construct.abs_wave_path,
  250. )
  251. )
  252. super().accept()
  253. def get_wav_relative_path_from_cue_sheet(
  254. self, sheet_relative_path: str
  255. ) -> str:
  256. full_path = path.join(self.base_dir, sheet_relative_path)
  257. try:
  258. with open(
  259. full_path,
  260. mode="r",
  261. encoding="utf-8-sig",
  262. ) as cachefile_reader:
  263. cachefile_content = cachefile_reader.readlines()
  264. first_line = cachefile_content[0].strip()
  265. if not match(r"^FILE \".+\" WAVE$", first_line):
  266. raise CustomException("invalid first cue sheet line")
  267. full_path_found = first_line[first_line.find('"') + 1 :]
  268. full_path_found = full_path_found[: full_path_found.rfind('"')]
  269. return path.split(full_path_found)[1]
  270. except (
  271. FileNotFoundError,
  272. PermissionError,
  273. IOError,
  274. IndexError,
  275. CustomException,
  276. ) as error:
  277. QMessageBox.critical(
  278. self,
  279. "Error",
  280. f"Could not parse cue sheet: '{full_path}', Reason: {error}",
  281. )
  282. sys.exit(1)
  283. @dataclass
  284. class ArchiveTypeStrings:
  285. archive_type_plural: str
  286. action_to_choose: str
  287. action_ing_form: str
  288. def choose_cd_day() -> list[str]:
  289. strings = ArchiveTypeStrings("CD's", "CD day to Burn", "Burning CD for day")
  290. return choose_archive_day(strings)
  291. def choose_sermon_day() -> list[str]:
  292. strings = ArchiveTypeStrings(
  293. "Sermons", "Sermon day to upload", "Uploading Sermon for day"
  294. )
  295. return choose_archive_day(strings)
  296. def choose_archive_day(strings: ArchiveTypeStrings) -> list[str]:
  297. # pylint: disable=unused-variable
  298. app = QApplication([])
  299. try:
  300. dirs = sorted(listdir(const.CD_RECORD_OUTPUT_BASEDIR))
  301. dirs.reverse()
  302. if not dirs:
  303. return [
  304. f"Did not find any {strings.archive_type_plural} in: "
  305. + f"{const.CD_RECORD_OUTPUT_BASEDIR}.",
  306. "",
  307. ]
  308. dialog = RadioButtonDialog(
  309. dirs, "Choose a " + f"{strings.action_to_choose}"
  310. )
  311. if dialog.exec_() == QDialog.Accepted:
  312. log(f"{strings.action_ing_form} for day: {dialog.chosen}")
  313. return ["", dialog.chosen]
  314. return ["ignore", ""]
  315. except (FileNotFoundError, PermissionError, IOError):
  316. pass
  317. return [
  318. f"Failed to access directory: {const.CD_RECORD_OUTPUT_BASEDIR}.",
  319. "",
  320. ]