gui.py 11 KB

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