gui.py 13 KB

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