gui.py 11 KB

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