"""
Main entry point for the JD-Xi Editor application.
This module sets up the application environment, including logging, MIDI message listening,
and application window initialization. It also manages the application's lifecycle,
from initialization to event loop execution.
Functions:
midi_callback(msg): Callback function for handling incoming MIDI messages.
listen_midi(port_name, callback): Listens for MIDI messages on the specified port
and triggers the provided callback function.
setup_logging(): Configures logging for the application, including console and file
logging with rotation.
main(): Main entry point to initialize and run the JD-Xi Editor application,
set up the window, and handle MIDI message listening.
"""
import cProfile
import io
import logging
import os
import platform
import pstats
import sys
from pathlib import Path
from decologr import setup_logging
from PySide6.QtCore import QLocale, QSettings, QTranslator
from PySide6.QtGui import QColor, QIcon, QPixmap, Qt
from PySide6.QtWidgets import (
QApplication,
QFrame,
QHBoxLayout,
QLabel,
QSplashScreen,
QVBoxLayout,
)
import jdxi_editor.bundle_imports # noqa: F401 fluidsynth, sounddevice, lilypond
from jdxi_editor.core.jdxi import JDXi
from jdxi_editor.log.message import log_message
from jdxi_editor.project import __organization_name__, __program__, __version__
from jdxi_editor.resources import resource_path
from jdxi_editor.ui.style import JDXiUIDimensions
from jdxi_editor.ui.widgets.digital.title import DigitalTitle
from jdxi_editor.ui.widgets.indicator.startup_sequencer import StartupSequencer
from jdxi_editor.ui.widgets.editor.helper import create_icon_label_with_pixmap
from jdxi_editor.ui.windows.jdxi.instrument import JDXiInstrument
from jdxi_editor.utils.profiling_decorator import profiling_decorator
os.environ["QT_LOGGING_RULES"] = "qt.qpa.fonts=false"
[docs]
def load_translations(app: QApplication) -> bool:
"""Load Qt .qm translation files for the current locale (e.g. en_GB for 'Bar' instead of 'Measure').
Place .qm files in jdxi_editor/i18n/ or in resources/translations/. Returns True if a translator was installed.
"""
locale_name = QLocale().name() # e.g. "en_GB", "en_US", "de_DE"
base_name = f"jdxi_editor_{locale_name}"
for search_dir in (
Path(__file__).parent / "i18n",
Path(resource_path(os.path.join("resources", "translations"))),
Path(__file__).parent.parent / "i18n",
):
qm_path = search_dir / f"{base_name}.qm"
if qm_path.exists():
translator = QTranslator(app)
if translator.load(str(qm_path)):
app.installTranslator(translator)
return True
return False
@profiling_decorator() # Profile is logged and printed when main() returns (after you close the app)
[docs]
def main() -> None:
"""Main entry point for the JD-Xi Editor application."""
try:
# --- Set up logging first
settings = QSettings(__organization_name__, __program__)
# one log file per start, in ~/.jdxi_editor/logs, kept two weeks
from jdxi_editor.log_files import (
LOG_KEEP_DAYS,
apply_log_level,
prune_logs,
saved_level,
)
pruned = prune_logs()
logger = setup_logging(use_rich=False, project_name="jdxi_editor") # @@@
apply_log_level(saved_level(settings), logger) # Preferences: log level
if pruned:
logger.info(f"Deleted {pruned} log files older than {LOG_KEEP_DAYS} days")
# --- Create application
app = QApplication(sys.argv)
# --- Preferences › Text size (nothing at Normal)
from jdxi_editor.ui import text_size
text_size.install(app)
# --- Garbage collection on the main thread only (see main_thread_gc)
from jdxi_editor.ui import main_thread_gc
main_thread_gc.install(app)
from jdxi_editor.ui.widgets.digital.base import load_lcd_font
load_lcd_font()
# --- Load translations for current locale (e.g. en_GB -> "Bar" / "Bars")
load_translations(app)
# --- Set application metadata
app.setApplicationName(__program__)
app.setApplicationVersion(__version__)
app.setOrganizationName("mabsoft")
app.setOrganizationDomain("com.mabsoft")
app.setStyleSheet(
"""
QTabWidget::tab-bar {
alignment: center;
}
"""
)
logger.debug("Application initialized")
# --- Set application icon
icon_locations = [
# Installed package, app bundle or repository checkout
Path(resource_path(os.path.join("resources", "jdxi_icon.png"))),
]
icon_found = False
for icon_path in icon_locations:
if icon_path.exists():
app.setWindowIcon(QIcon(str(icon_path)))
log_message(f"Loaded icon from {icon_path}")
icon_found = True
break
if not icon_found:
logging.warning(
f"Icon not found in any of: {[str(p) for p in icon_locations]}"
)
# --- Create address fallback icon only for windows, not macOS
if platform.system() == "Windows":
icon = QIcon()
pixmap = QPixmap(128, 128)
pixmap.fill(QColor("#2897B7")) # Use the app's theme color
icon.addPixmap(pixmap)
app.setWindowIcon(icon)
log_message("Using fallback icon")
splash, progress_bar, status_label = setup_splash_screen(app)
# --- Update splash screen with initial progress
status_label.setText("Initializing MIDI subsystem…")
progress_bar.setValue(10)
app.processEvents()
# --- The user's own skins (~/.jdxi_editor/skins/*.toml), before the
# window builds its JDXiSkin menu and wears the remembered skin
from jdxi_editor.ui.style.user_skins import load_user_skins
load_user_skins()
# --- Create window and pass splash screen components
window = JDXiInstrument(
splash=splash, progress_bar=progress_bar, status_label=status_label
)
# --- Finalize splash screen (every step lit)
progress_bar.setValue(100)
app.processEvents()
splash.finish(window)
window.show()
# --- Start event loop
return app.exec()
except Exception as ex:
logging.exception(f"Fatal error {ex} occurred")
raise
[docs]
def setup_splash_screen(
app: QApplication,
) -> tuple[QSplashScreen, StartupSequencer, DigitalTitle]:
"""Setup and digital a professional application splash screen with rotating status text.
Returns:
tuple: (splash_screen, progress_bar, status_label) for updating progress
"""
splash = QSplashScreen()
# Need to use the screen center to digital the splash screen
# In Qt 6, QApplication.desktop() was removed, use QScreen instead
screen = app.primaryScreen()
if screen:
screen_geometry = screen.availableGeometry()
screen_center = screen_geometry.center()
splash.move(
int(screen_center.x() - JDXiUIDimensions.SPLASH.WIDTH / 2),
int(screen_center.y() - JDXiUIDimensions.SPLASH.HEIGHT / 2),
)
splash.setWindowFlags(
Qt.SplashScreen | Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint
)
splash.setFixedSize(JDXiUIDimensions.SPLASH.WIDTH, JDXiUIDimensions.SPLASH.HEIGHT)
splash.setStyleSheet(
"""
QSplashScreen { background-color: #111111; border: 1px solid #2c2c2c; }
QLabel#TitleLabel { color: #f3f3f3; font-size: 28px; font-weight: 600; letter-spacing: 1px; }
QLabel#SubtitleLabel { color: #bbbbbb; font-size: 14px; }
QLabel#StatusLabel { color: #88ccff; font-size: 18px; font-style: italic; font-weight: 500; }
QLabel#CreditLabel { color: #888888; font-size: 10px; }
QLabel#NoticeLabel { color: #d06a10; font-size: 11px; }
QFrame#Card {
background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #1c1c1c, stop:1 #0f0f0f);
border-radius: 14px; border: 1px solid #2a2a2a;
}
QFrame#StartupSequencer { background: transparent; }
"""
)
root = QVBoxLayout(splash)
root.setContentsMargins(20, 20, 20, 20)
root.setSpacing(10)
# --- Content container (so we can overlay the title on top)
content = QFrame()
content.setObjectName("Card")
content_layout = QVBoxLayout(content)
content_layout.setContentsMargins(0, 0, 0, 0)
content_layout.setSpacing(10)
# --- Logo on the left; title and trademark notice on the right
image_path = resource_path((Path("resources") / "JDXI-Editor_logo_640.png"))
pixmap = QPixmap(image_path)
if not pixmap.isNull():
pixmap = pixmap.scaled(
JDXiUIDimensions.SPLASH.IMAGE_WIDTH,
JDXiUIDimensions.SPLASH.IMAGE_HEIGHT,
Qt.KeepAspectRatio,
Qt.SmoothTransformation,
)
logo = create_icon_label_with_pixmap(pixmap)
title = DigitalTitle(__program__, show_upper_text=False)
title.setObjectName("TitleLabel")
title.setStyleSheet(JDXi.UI.Style.INSTRUMENT_TITLE_LABEL)
notice = QLabel(
"'Roland' and 'JD-Xi' are trademarks of the Roland Corporation "
"in the United States and/or other countries.\n\n"
"This app is an independent, unofficial companion tool for the "
"Roland JD-Xi synthesizer. It is not affiliated with, endorsed by, "
"or sponsored by Roland Corporation in any way.\n\n"
"All product names, trademarks, and logos are the property of "
"their respective owners."
)
notice.setObjectName("NoticeLabel")
notice.setWordWrap(True)
side_layout = QVBoxLayout()
side_layout.setContentsMargins(0, 12, 12, 0)
side_layout.setSpacing(16)
side_layout.addWidget(title)
side_layout.addWidget(notice)
side_layout.addStretch()
header_layout = QHBoxLayout()
header_layout.setSpacing(16)
header_layout.addWidget(logo)
header_layout.addLayout(side_layout, 1)
content_layout.addLayout(header_layout)
# --- 16 step startup sequencer
progress_bar = StartupSequencer() # fills the card's width
content_layout.addWidget(progress_bar)
# --- Rotating status label
status_label = DigitalTitle("Starting...")
status_label.setObjectName("StatusLabel")
content_layout.addWidget(status_label)
# --- Footer credits
credits = QLabel(
f"{__program__} • Version {__version__}\n"
"Developed by mabsoft.com — Inspired by modern instrument editors"
)
credits.setObjectName("CreditLabel")
credits.setAlignment(Qt.AlignCenter)
content_layout.addWidget(credits)
root.addWidget(content)
splash.show()
splash.raise_()
splash.activateWindow()
# Return splash screen components for updating progress
return splash, progress_bar, status_label
if __name__ == "__main__":
try:
profiling = True
if profiling:
profiler = cProfile.Profile()
profiler.enable()
exit_code = main()
if profiling:
profiler.disable()
s = io.StringIO()
sortby = "cumtime" # or 'tottime'
ps = pstats.Stats(profiler, stream=s).sort_stats(sortby)
ps.print_stats(50) # Top 50 entries
print(s.getvalue())
sys.exit(exit_code)
except Exception as ex:
print(f"Application crashed: {str(ex)}") # Fallback if logging fails
logging.exception("Application crashed")
sys.exit(1)