This commit is contained in:
oitsjustjose 2025-03-30 14:37:22 -05:00
commit a8f88df4b7
4 changed files with 213 additions and 129 deletions

View file

@ -1,9 +1,10 @@
import platform
import sys
from multiprocessing import Process
from pathlib import Path
from typing import Callable
from typing import Callable, List
from PySide6.QtCore import QThread
from PySide6.QtCore import QObject, Signal
from PySide6.QtGui import QIcon
from PySide6.QtWidgets import (
QApplication,
@ -25,31 +26,116 @@ from src.processor import FolderProcessor
APP_ID = "com.oitsjustjose.drum-track-converter"
class DataBackend:
def __init__(self):
# Variables for the actual processing flow
self.input_dir: str = ""
self.output_dir: str = ""
self.model_name: str = list(MODEL_CHOICES.values())[0]
self.worker: Worker = None
self._child_proc: Process = None
class MainWindow(QMainWindow):
def __init__(self, icon: QIcon):
def __init__(self):
super().__init__()
self.setWindowIcon(icon)
# Widgets that we'll want to set throughout the runtime
# Widgets that we'll want to set & mutate throughout the runtime
self.start_button: QPushButton = None
self.logging_region: QTextEdit = None
self.interactive_elements: List[QWidget] = list()
self.setWindowTitle("Drum Track Converter by oitsjustjose")
self.__setup_layout()
self.__center()
# Set fixed size only once we've established the contents of the window
self.setMaximumSize(self.size())
# Handle data separately from the GUI
self.data_backend = DataBackend()
# Variables for the actual processing flow
self.input_dir: str = ""
self.output_dir: str = ""
self.model_name: str = list(MODEL_CHOICES.values())[0]
self._thread: OffThreadProcessor = None
def on_input_clicked(self, button_ref: QPushButton):
"""Sets the output directory to the selected value from a QFileDialog
Mutates the button_ref's text to reflect the selected folder
If Input and Output are set, enables the Start button
Args:
button_ref (QPushButton): A reference to the button pressed
"""
self.input_dir = QFileDialog.getExistingDirectory(None, "Select Input Folder")
self.__common_io_clicked(button_ref, self.input_dir)
def on_output_clicked(self, button_ref: QPushButton):
"""Sets the output directory to the selected value from a QFileDialog
Mutates the button_ref's text to reflect the selected folder
If Input and Output are set, enables the Start button
Args:
button_ref (QPushButton): A reference to the button pressed
"""
self.output_dir = QFileDialog.getExistingDirectory(None, "Select Output Folder")
self.__common_io_clicked(button_ref, self.output_dir)
def on_model_changed(self, model_display_name: str) -> None:
"""Sets the model_name to the new model_name based on the display name
Args:
model_display_name (str): The display name of the model
"""
self.model_name = MODEL_CHOICES[model_display_name]
def on_start_clicked(self):
"""Passes through basic assertions, spins up thread to process files from the input and output params"""
if not (self.input_dir and self.output_dir):
return
self.logging_region.setVisible(True)
[x.setEnabled(False) for x in self.interactive_elements]
self.worker = Worker(
FolderProcessor(
self.input_dir,
self.output_dir,
self.model_name,
GuiOutput(self),
)
)
self.worker.finished.connect(self.on_done)
self._child_proc = Process(target=self.worker.run)
self._child_proc.start()
def on_done(self, message: str):
# Reset State
self._child_proc.join(0)
self.worker.finished.disconnect()
self.worker = None
self.logging_region.append(message)
self.start_button.setText("Start")
[x.setEnabled(False) for x in self.interactive_elements]
def stop(self):
"""Stops the working thread (if it's been started) at its soonest convenience..."""
if self._child_proc:
self._child_proc.terminate()
self._child_proc.join(0)
"""~~Hidden / private methods~~"""
def __get_state__(self) -> dict:
state = self.__dict__.copy()
# TODO: delete any unpicklable entries
# del state['f'] --
return state
def __setstate__(self, state: dict):
self.__dict__.update(state)
# TODO: restore any unpicklable entries
# self.f = # manual parsing
def __center(self) -> None:
"""Centers the window to the middle of the Screen"""
# Center window
frame_geo = self.frameGeometry()
center = self.screen().availableGeometry().center()
frame_geo.moveCenter(center)
@ -65,12 +151,21 @@ class MainWindow(QMainWindow):
def __setup_children(self):
"""Sets up the children of the main window element using [nested] HBox and VBox layouts"""
# Start Button
self.start_button = QPushButton("Start")
self.start_button.setEnabled(False)
self.start_button.adjustSize()
self.start_button.clicked.connect(self.on_start_clicked)
# These should stay in the same order as intended visually, so smaller index = closer to top.
# These elements will all be disabled/enabled as the process starts & stops
self.interactive_elements = [
self.__make_io_buttons(),
self.__make_model_combobox(),
self.start_button,
]
# Logging region appears automatically
self.logging_region = QTextEdit()
self.logging_region.setReadOnly(True)
@ -78,9 +173,7 @@ class MainWindow(QMainWindow):
self.logging_region.setLineWrapMode(QTextEdit.LineWrapMode.NoWrap)
# Add all children to the parent layout
self.layout.addWidget(self.__make_io_buttons())
self.layout.addWidget(self.__make_model_combobox())
self.layout.addWidget(self.start_button)
[self.layout.addWidget(x) for x in self.interactive_elements]
self.layout.addWidget(self.logging_region)
def __make_io_buttons(self) -> QWidget:
@ -184,86 +277,23 @@ class MainWindow(QMainWindow):
enabled = bool(self.input_dir and self.output_dir)
self.start_button.setEnabled(enabled)
def on_input_clicked(self, button_ref: QPushButton):
"""Sets the output directory to the selected value from a QFileDialog
Mutates the button_ref's text to reflect the selected folder
If Input and Output are set, enables the Start button
Args:
button_ref (QPushButton): A reference to the button pressed
"""
self.input_dir = QFileDialog.getExistingDirectory(None, "Select Input Folder")
self.__common_io_clicked(button_ref, self.input_dir)
class Worker(QObject):
finished = Signal(str, name="on_worker_finished")
def on_output_clicked(self, button_ref: QPushButton):
"""Sets the output directory to the selected value from a QFileDialog
Mutates the button_ref's text to reflect the selected folder
If Input and Output are set, enables the Start button
def __init__(self, processor: FolderProcessor):
super().__init__()
self.processor = processor
Args:
button_ref (QPushButton): A reference to the button pressed
"""
self.output_dir = QFileDialog.getExistingDirectory(None, "Select Output Folder")
self.__common_io_clicked(button_ref, self.output_dir)
def __reduce__(self):
return (Worker, (self.processor,))
def on_model_changed(self, model_display_name: str) -> None:
"""Sets the model_name to the new model_name based on the display name
Args:
model_display_name (str): The display name of the model
"""
self.model_name = MODEL_CHOICES[model_display_name]
def on_start_clicked(self):
"""Passes through basic assertions, spins up thread to process files from the input and output params"""
assert bool(self.input_dir and self.output_dir)
# Only join once we're good to go again, there's really no harm in keeping the other thread around
if self._thread and not self._thread.isRunning():
self._thread.join()
self._thread = None
self.start_button.setEnabled(False)
self.start_button.setText("Processing...")
self.logging_region.setVisible(True)
self._thread = OffThreadProcessor(self)
self._thread.start()
def stop_thread(self):
"""Stops the working thread (if it's been started) at its soonest convenience..."""
if not self._thread:
return
self._thread.stop()
self._thread.deleteLater()
self._thread = None
class OffThreadProcessor(QThread):
def __init__(self, parent: MainWindow):
super().__init__(parent)
self.main_window: MainWindow = parent
self.setTerminationEnabled(True)
self.gui_output = GuiOutput(self.main_window)
self.processor = FolderProcessor(
parent.input_dir, parent.output_dir, self.gui_output, parent.model_name
)
def run(self) -> None:
def run(self):
try:
self.processor.process_directory()
# All of this occurs here instead of on_start_clicked to keep the main GUI from being blocked on the join
self.main_window.logging_region.append("✅ Done!")
self.main_window.start_button.setText("Start")
self.main_window.start_button.setEnabled(True)
self.finished.emit("✅ Done!")
except Exception as e:
self.processor.msg_interface.error(f"Failed: {e}")
def stop(self) -> None:
self.terminate()
self.finished.emit(f"Failed: {e}")
class GuiOutput(MessageInterface):
@ -299,10 +329,10 @@ def main() -> None:
icon.addFile("assets/icon.ico")
app.setWindowIcon(icon)
window = MainWindow(icon)
window = MainWindow()
window.show()
exit_code = app.exec()
window.stop_thread()
window.stop()
sys.exit(exit_code)