Repository navigation
Expand file tree
/
Copy pathStudio.java
More file actions
1264 lines (1098 loc) · 45.8 KB
/
Copy pathStudio.java
File metadata and controls
1264 lines (1098 loc) · 45.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) AudioManager Project Contributors.
* SPDX-License-Identifier: Apache-2.0
*/
package audiomanager;
import audiomanager.core.AutoUpdater;
import audiomanager.core.BatchScheduler;
import audiomanager.core.ErrorReporter;
import audiomanager.core.ModelManager;
import audiomanager.core.TranslationService;
import audiomanager.ui.EulaDialog;
import audiomanager.ui.MainWindow;
import audiomanager.ui.OnboardingWizard;
import audiomanager.ui.ThemeManager;
import audiomanager.util.PreferenceManager;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.Properties;
/**
* Studio Audio Manager Application - Main entry point for the application.
*
* <p>This class serves as the JavaFX application launcher and the central
* singleton that manages application-wide state and dependencies. It handles:
* <ul>
* <li><b>Application lifecycle:</b> Startup, initialisation, and shutdown</li>
* <li><b>Resource resolution:</b> Locating bundled FFmpeg, Python, and Whisper</li>
* <li><b>Error handling:</b> Global exception handler setup</li>
* <li><b>Singleton access:</b> Provides a single instance for dependency lookup</li>
* <li><b>EULA check:</b> Displays End-User License Agreement on first run</li>
* <li><b>First-run onboarding:</b> Launches onboarding wizard for new users</li>
* <li><b>Translation service:</b> Initializes and wires translation for transcripts</li>
* </ul>
*
* @author AudioManager Project Contributors
* @version 4.0.0
* @see MainWindow
* @see PreferenceManager
* @see ErrorReporter
* @see TranslationService
*/
public class Studio extends Application {
ModelManager modelManager;
private static final Logger LOGGER = LoggerFactory.getLogger(Studio.class);
private static volatile Studio instance;
/**
* Returns the singleton instance of the Studio application.
*
* @return the Studio instance, or {@code null} if not initialised
*/
public static Studio getInstance() {
return instance;
}
private AutoUpdater autoUpdater;
private ErrorReporter errorReporter;
private BatchScheduler batchScheduler;
private TranslationService translationService;
private PreferenceManager prefManager;
private MainWindow mainWindow;
// Bundled resource paths
private String appDir;
private String ffmpegPath;
private String whisperPython;
private String whisperEnv;
private static final String OS_NAME = System.getProperty("os.name", "").toLowerCase();
private static final boolean IS_WINDOWS = OS_NAME.contains("win");
private static final boolean IS_MAC = OS_NAME.contains("mac") || OS_NAME.contains("darwin");
/**
* Returns the executable name with the appropriate extension for the current OS.
*
* @param baseName the base name of the executable (e.g., "ffmpeg")
* @return the executable name with extension (e.g., "ffmpeg.exe" on Windows)
*/
private static String exeName(String baseName) {
return IS_WINDOWS ? baseName + ".exe" : baseName;
}
/**
* Returns the relative path to the Python executable in a virtual environment.
*
* @return the relative path (e.g., "Scripts/python.exe" on Windows)
*/
private static Path venvPythonRelativePath() {
return IS_WINDOWS ? Paths.get("Scripts", "python.exe") : Paths.get("bin", "python3");
}
/**
* Returns the relative path to the bin directory in a virtual environment.
*
* @return the relative path (e.g., "Scripts" on Windows)
*/
private static Path venvBinRelativePath() {
return IS_WINDOWS ? Paths.get("Scripts") : Paths.get("bin");
}
/**
* Returns the relative path to the site-packages directory in a virtual environment.
*
* @param envRoot the root directory of the virtual environment
* @return the relative path to site-packages
*/
private static Path venvSitePackagesRelativePath(Path envRoot) {
if (IS_WINDOWS) {
return Paths.get("Lib", "site-packages");
}
Path libDir = envRoot.resolve("lib");
if (Files.isDirectory(libDir)) {
try (var stream = Files.list(libDir)) {
Path pythonVersionDir = stream
.filter(p -> Files.isDirectory(p) && p.getFileName().toString().startsWith("python3"))
.findFirst()
.orElse(null);
if (pythonVersionDir != null) {
return envRoot.relativize(pythonVersionDir.resolve("site-packages"));
}
} catch (IOException ignored) {
// Fall through
}
}
return Paths.get("lib", "python3", "site-packages");
}
/**
* Initialises the application before the JavaFX stage is created.
*
* <p>This method:
* <ol>
* <li>Sets the singleton instance</li>
* <li>Initialises bundled paths</li>
* <li>Creates the model manager</li>
* <li>Initialises error reporting</li>
* <li>Initialises auto-updater</li>
* <li>Initialises batch scheduler</li>
* <li>Initialises translation service</li>
* <li>Verifies WhisperX installation</li>
* <li>Sets up global exception handling</li>
* </ol>
*
* @throws Exception if initialisation fails
*/
@Override
public void init() throws Exception {
super.init();
instance = this;
try {
initializeBundledPaths();
} catch (Exception e) {
LOGGER.warn("Bundled runtime path resolution failed ({}); falling back to system PATH.", e.getMessage(), e);
appDir = ".";
ffmpegPath = "ffmpeg";
whisperPython = "python";
whisperEnv = null;
}
this.modelManager = new ModelManager();
// Initialize error reporter EARLY so it can catch startup errors
initializeErrorReporter();
// Initialize auto updater
initializeAutoUpdater();
// Initialize batch scheduler
initializeBatchScheduler();
// Initialize translation service
initializeTranslationService();
// Verify WhisperX installation during app startup
boolean modelsAvailable = verifyWhisperXInstallation();
if (!modelsAvailable) {
LOGGER.warn("WhisperX models not available at startup. They will be downloaded on first use.");
} else {
LOGGER.info("WhisperX models verified and ready at startup");
}
LOGGER.info("Initializing Studio Audio Manager v4.0.0");
// Configure logging if needed
configureLogging();
// Set up global exception handler
setupGlobalExceptionHandler();
}
/**
* Starts the JavaFX application.
*
* <p>This method:
* <ol>
* <li>Initialises the preference manager</li>
* <li>Shows the EULA if not already accepted</li>
* <li>Checks for code signing verification</li>
* <li>Checks for pending updates</li>
* <li>Runs first-run onboarding if needed</li>
* <li>Checks for updates in the background</li>
* <li>Creates and initialises the main window</li>
* <li>Wires the translation service to the batch processor</li>
* </ol>
*
* @param primaryStage the primary stage for the JavaFX application
*/
@Override
public void start(Stage primaryStage) {
try {
LOGGER.info("Starting application...");
// Initialize preference manager
prefManager = new PreferenceManager(Studio.class);
LOGGER.debug("Preference manager initialized");
// ========== EULA CHECK ==========
// Show EULA if not accepted
if (!EulaDialog.isEulaAccepted(prefManager)) {
LOGGER.info("EULA not accepted - showing dialog");
EulaDialog eulaDialog = new EulaDialog();
boolean accepted = eulaDialog.showAndWait();
if (accepted) {
EulaDialog.markEulaAccepted(prefManager);
LOGGER.info("EULA accepted by user");
} else {
LOGGER.info("EULA declined - exiting application");
Platform.exit();
return;
}
}
// ========== END EULA CHECK ==========
// ========== CODE SIGNING VERIFICATION ==========
// Check if application is verified as code-signed
if (prefManager.isCodeSigned()) {
LOGGER.info("Application is verified as code-signed");
} else {
LOGGER.info("Application is not verified as code-signed - running in unsigned mode");
}
// ========== END CODE SIGNING VERIFICATION ==========
// Check if we just installed an update
checkRestartAfterUpdate();
// ===== UPDATED: Run first-run onboarding if needed =====
// This will show the enhanced OnboardingWizard on first run
runFirstRunOnboardingIfNeeded();
// Check for updates in background
checkForUpdatesInBackground();
// Create and initialize main window
mainWindow = new MainWindow(primaryStage, prefManager);
mainWindow.initialize();
// Wire translation service to batch processor
wireTranslationServiceToBatchProcessor();
LOGGER.info("Application started successfully");
// Show model status in UI if needed
Platform.runLater(this::showModelStatusInUI);
} catch (Exception e) {
LOGGER.error("Fatal error during application startup", e);
if (errorReporter != null && errorReporter.isEnabled()) {
errorReporter.reportErrorSync(e, "Application startup");
}
showErrorAndExit("Startup Error",
"Failed to initialize application",
e);
}
}
/**
* Called when the application is shutting down.
*
* <p>This method saves preferences, shuts down the batch scheduler,
* and performs other cleanup tasks.</p>
*/
@Override
public void stop() {
LOGGER.info("Application shutdown initiated");
try {
if (prefManager != null) {
prefManager.flush();
LOGGER.debug("Preferences saved");
}
if (batchScheduler != null) {
batchScheduler.shutdown();
LOGGER.debug("Batch scheduler shutdown");
}
if (autoUpdater != null) {
LOGGER.debug("Auto updater shutdown");
}
if (translationService != null) {
LOGGER.debug("Translation service shutdown");
}
LOGGER.info("Application shutdown complete");
super.stop();
} catch (Exception e) {
LOGGER.error("Error during application shutdown", e);
}
}
// ========== BUNDLED PATHS ==========
/**
* Initialises paths to bundled resources (FFmpeg, Python, Whisper).
*
* <p>This method reads system properties for paths and falls back to
* bundled resources when available.</p>
*/
private void initializeBundledPaths() {
appDir = System.getProperty("app.dir", ".");
ffmpegPath = System.getProperty("ffmpeg.path", "ffmpeg");
whisperPython = System.getProperty("whisper.python", "python");
whisperEnv = System.getProperty("whisper.env", ".");
LOGGER.info("Application directory: {}", appDir);
LOGGER.info("FFmpeg path: {}", ffmpegPath);
LOGGER.info("Whisper Python: {}", whisperPython);
LOGGER.info("Whisper environment: {}", whisperEnv);
validateBundledPaths();
}
/**
* Validates bundled paths and falls back to system resources when needed.
*/
private void validateBundledPaths() {
boolean ffmpegPathWasExplicitlyConfigured = System.getProperty("ffmpeg.path") != null;
Path ffmpeg = Paths.get(ffmpegPath);
if (!Files.exists(ffmpeg)) {
if (ffmpegPathWasExplicitlyConfigured) {
LOGGER.warn("FFmpeg not found at configured path: {}", ffmpegPath);
} else {
LOGGER.debug("No bundled FFmpeg path configured; will resolve \"ffmpeg\" via system PATH.");
}
Path bundledFFmpeg = getAppDirectory().resolve("ffmpeg").resolve(exeName("ffmpeg"));
if (Files.exists(bundledFFmpeg)) {
ffmpegPath = bundledFFmpeg.toString();
LOGGER.info("Using bundled FFmpeg: {}", ffmpegPath);
} else {
ffmpegPath = "ffmpeg";
LOGGER.info("Using system FFmpeg (PATH): {}", ffmpegPath);
}
} else {
LOGGER.info("FFmpeg found at: {}", ffmpegPath);
}
boolean pythonPathWasExplicitlyConfigured = System.getProperty("whisper.python") != null;
Path python = Paths.get(whisperPython);
if (!Files.exists(python)) {
if (pythonPathWasExplicitlyConfigured) {
LOGGER.warn("Whisper Python not found at configured path: {}", whisperPython);
} else {
LOGGER.debug("No bundled Whisper Python path configured; will resolve \"python\" via system PATH.");
}
Path bundledPython = getAppDirectory().resolve("whisper_env").resolve(venvPythonRelativePath());
if (Files.exists(bundledPython)) {
whisperPython = bundledPython.toString();
whisperEnv = getAppDirectory().resolve("whisper_env").toString();
LOGGER.info("Using bundled Whisper Python: {}", whisperPython);
LOGGER.info("Using bundled Whisper environment: {}", whisperEnv);
} else {
whisperPython = "python";
LOGGER.info("Using system Python: {}", whisperPython);
whisperEnv = null;
}
} else {
LOGGER.info("Whisper Python found at: {}", whisperPython);
}
if (whisperEnv != null) {
Path envDir = Paths.get(whisperEnv);
if (!Files.exists(envDir)) {
LOGGER.warn("Whisper environment not found at: {}", whisperEnv);
Path pythonPath = Paths.get(whisperPython);
if (pythonPath.getNameCount() > 3) {
Path inferredEnv = pythonPath.getParent().getParent();
if (Files.exists(inferredEnv)) {
whisperEnv = inferredEnv.toString();
LOGGER.info("Inferred Whisper environment: {}", whisperEnv);
}
}
} else {
LOGGER.info("Whisper environment found at: {}", whisperEnv);
}
}
}
/**
* Returns the application directory path.
*
* @return the application directory
*/
private Path getAppDirectory() {
try {
var codeSource = Studio.class.getProtectionDomain().getCodeSource();
if (codeSource == null || codeSource.getLocation() == null) {
LOGGER.warn("Could not determine application directory, using current directory");
return Paths.get(".");
}
String path = codeSource.getLocation().toURI().getPath();
if (path.startsWith("/") && path.contains(":")) {
path = path.substring(1);
}
Path jarPath = Paths.get(path);
return jarPath.getParent();
} catch (URISyntaxException | RuntimeException e) {
LOGGER.warn("Could not determine application directory, using current directory", e);
return Paths.get(".");
}
}
// ========== PUBLIC GETTERS ==========
/**
* Returns the path to the FFmpeg executable.
*
* @return the FFmpeg path
*/
public Path getFFmpegPath() {
return Paths.get(ffmpegPath);
}
/**
* Returns the path to the Whisper Python executable.
*
* @return the Python path
*/
public Path getWhisperPython() {
return Paths.get(whisperPython);
}
/**
* Returns the path to the Whisper environment.
*
* @return the environment path, or {@code null} if not available
*/
public Path getWhisperEnv() {
return whisperEnv != null ? Paths.get(whisperEnv) : null;
}
/**
* Creates a ProcessBuilder for an FFmpeg command.
*
* @param args the FFmpeg arguments
* @return a ProcessBuilder configured with FFmpeg
*/
public ProcessBuilder createFFmpegProcess(String... args) {
java.util.List<String> command = new java.util.ArrayList<>();
command.add(ffmpegPath);
command.addAll(java.util.Arrays.asList(args));
LOGGER.debug("FFmpeg command: {}", String.join(" ", command));
return new ProcessBuilder(command);
}
/**
* Creates a ProcessBuilder for a Whisper command.
*
* @param args the Whisper arguments
* @return a ProcessBuilder configured with Whisper
*/
public ProcessBuilder createWhisperProcess(String... args) {
java.util.List<String> command = new java.util.ArrayList<>();
command.add(whisperPython);
command.add("-m");
command.add("whisperx");
command.addAll(java.util.Arrays.asList(args));
LOGGER.debug("Whisper command: {}", String.join(" ", command));
ProcessBuilder pb = new ProcessBuilder(command);
if (whisperEnv != null) {
Path envPath = Paths.get(whisperEnv);
if (Files.exists(envPath)) {
String pathEnv = System.getenv("PATH");
String binDir = envPath.resolve(venvBinRelativePath()).toString();
pb.environment().put("PATH",
binDir +
java.io.File.pathSeparator +
(pathEnv != null ? pathEnv : ""));
pb.directory(envPath.toFile());
}
}
return pb;
}
/**
* Returns whether FFmpeg is available.
*
* @return {@code true} if FFmpeg is available
*/
public boolean isFFmpegAvailable() {
Path ffmpeg = Paths.get(ffmpegPath);
return Files.exists(ffmpeg) && Files.isExecutable(ffmpeg);
}
/**
* Returns whether Whisper is available.
*
* @return {@code true} if Whisper is available
*/
public boolean isWhisperAvailable() {
Path python = Paths.get(whisperPython);
return Files.exists(python) && Files.isExecutable(python);
}
/**
* Returns the FFmpeg path as a string.
*
* @return the FFmpeg path
*/
public String getFfmpegPath() {
return ffmpegPath;
}
/**
* Returns the Whisper Python path as a string.
*
* @return the Python path
*/
public String getWhisperPythonPath() {
return whisperPython;
}
/**
* Returns the Whisper environment path as a string.
*
* @return the environment path, or {@code null} if not available
*/
public String getWhisperEnvPath() {
return whisperEnv;
}
/**
* Returns the error reporter.
*
* @return the error reporter instance
*/
public ErrorReporter getErrorReporter() {
return errorReporter;
}
/**
* Returns the batch scheduler.
*
* @return the batch scheduler instance
*/
public BatchScheduler getBatchScheduler() {
return batchScheduler;
}
/**
* Returns the auto updater.
*
* @return the auto updater instance
*/
public AutoUpdater getAutoUpdater() {
return autoUpdater;
}
/**
* Returns the preference manager.
*
* @return the preference manager instance
*/
public PreferenceManager getPreferenceManager() {
return prefManager;
}
/**
* Returns the application version string.
*
* @return the version string (e.g., "4.0.0")
*/
public String getAppVersion() {
try {
String version = System.getProperty("app.version");
if (version == null || version.isEmpty()) {
version = getClass().getPackage().getImplementationVersion();
}
if (version == null || version.isEmpty()) {
version = "4.0.0";
}
return version;
} catch (Exception e) {
return "4.0.0";
}
}
/**
* Returns the translation service.
*
* @return the translation service instance, or {@code null} if not configured
*/
public TranslationService getTranslationService() {
return translationService;
}
/**
* Returns whether translation is available.
*
* @return {@code true} if a translation service is configured
*/
public boolean isTranslationAvailable() {
return translationService != null;
}
// ========== INITIALIZATION METHODS ==========
/**
* Initialises the error reporter.
*/
private void initializeErrorReporter() {
String version = getAppVersion();
errorReporter = new ErrorReporter(version);
if (prefManager != null) {
boolean consent = prefManager.getBoolean("error.reporting.enabled", false);
errorReporter.setEnabled(consent);
}
LOGGER.info("Error reporter initialized (enabled: {})", errorReporter.isEnabled());
}
/**
* Initialises the auto updater.
*/
private void initializeAutoUpdater() {
autoUpdater = new AutoUpdater();
autoUpdater.setCallback(new AutoUpdater.UpdateCheckCallback() {
@Override
public void onUpdateAvailable(AutoUpdater.UpdateInfo update) {
LOGGER.info("Update available: version {}", update.version);
Platform.runLater(() -> showUpdateAvailableDialog(update));
}
@Override
public void onNoUpdateAvailable() {
LOGGER.debug("No update available");
}
@Override
public void onCheckFailed(String error) {
LOGGER.warn("Update check failed: {}", error);
}
@Override
public void onDownloadProgress(double progress) {
LOGGER.debug("Update download progress: {}%", (int) (progress * 100));
}
@Override
public void onUpdateInstalled() {
LOGGER.info("Update installed successfully");
Platform.runLater(() -> showUpdateInstalledDialog());
}
});
LOGGER.info("Auto updater initialized");
}
/**
* Initialises the batch scheduler.
*/
private void initializeBatchScheduler() {
batchScheduler = new BatchScheduler();
batchScheduler.setOnBatchStart(() -> {
LOGGER.info("Scheduled batch starting...");
Platform.runLater(() -> {
if (mainWindow != null) {
mainWindow.showStatusMessage("Scheduled batch is starting...");
}
});
});
batchScheduler.setOnBatchComplete(() -> {
LOGGER.info("Scheduled batch completed");
Platform.runLater(() -> {
if (mainWindow != null) {
mainWindow.showStatusMessage("Scheduled batch completed!");
}
});
});
LOGGER.info("Batch scheduler initialized");
}
/**
* Initialises the translation service.
*/
private void initializeTranslationService() {
String endpoint = "https://libretranslate.com/translate";
String apiKey = null;
String propEndpoint = System.getProperty("translation.endpoint");
if (propEndpoint != null && !propEndpoint.isBlank()) {
endpoint = propEndpoint;
}
String propApiKey = System.getProperty("translation.api_key");
if (propApiKey != null && !propApiKey.isBlank()) {
apiKey = propApiKey;
}
if (endpoint != null && !endpoint.isBlank() && !endpoint.equals("none")) {
translationService = new TranslationService(endpoint, apiKey);
LOGGER.info("🌐 Translation service initialized with endpoint: {}", endpoint);
if (apiKey != null && !apiKey.isBlank()) {
LOGGER.info("🌐 Translation API key configured (length: {})", apiKey.length());
}
} else {
LOGGER.info("🌐 Translation service disabled - no endpoint configured");
translationService = null;
}
}
/**
* Wires the translation service to the batch processor.
*/
private void wireTranslationServiceToBatchProcessor() {
if (mainWindow == null) {
LOGGER.warn("🌐 MainWindow not available - translation service not wired");
return;
}
var batchProcessor = mainWindow.getBatchProcessor();
if (batchProcessor == null) {
LOGGER.warn("🌐 BatchProcessor not available - translation service not wired");
return;
}
if (translationService != null) {
batchProcessor.setTranslationService(translationService);
LOGGER.info("🌐 Translation service wired to BatchProcessor");
String targetLang = prefManager != null
? prefManager.getString("translation.target_language", "es")
: "es";
LOGGER.info("🌐 Default translation target language: {}", targetLang);
} else {
LOGGER.info("🌐 Translation service not available - skipping wiring");
}
}
/**
* Reloads the translation service configuration.
*/
public void reloadTranslationService() {
LOGGER.info("🌐 Reloading translation service...");
if (prefManager != null) {
String endpoint = prefManager.getString("translation.endpoint",
"https://libretranslate.com/translate");
String apiKey = prefManager.getString("translation.api_key", null);
if (endpoint != null && !endpoint.isBlank() && !endpoint.equals("none")) {
translationService = new TranslationService(endpoint, apiKey);
LOGGER.info("🌐 Translation service reloaded with endpoint: {}", endpoint);
} else {
translationService = null;
LOGGER.info("🌐 Translation service disabled");
}
}
wireTranslationServiceToBatchProcessor();
}
/**
* Sets up the global exception handler for uncaught exceptions.
*/
private void setupGlobalExceptionHandler() {
Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> {
LOGGER.error("Uncaught exception in thread: {}", thread.getName(), throwable);
if (errorReporter != null && errorReporter.isEnabled()) {
errorReporter.reportErrorSync(throwable, "Uncaught in thread: " + thread.getName());
}
Platform.runLater(() -> {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Unexpected Error");
alert.setHeaderText("Something went wrong");
alert.setContentText("An unexpected error occurred.\n\n" +
"The application will continue running.\n" +
"If this persists, please restart the application.");
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
throwable.printStackTrace(pw);
String exceptionText = sw.toString();
TextArea textArea = new TextArea(exceptionText);
textArea.setEditable(false);
textArea.setWrapText(true);
textArea.setMaxWidth(Double.MAX_VALUE);
textArea.setMaxHeight(Double.MAX_VALUE);
javafx.scene.layout.GridPane expContent = new javafx.scene.layout.GridPane();
expContent.setMaxWidth(Double.MAX_VALUE);
expContent.add(new Label("Exception details:"), 0, 0);
expContent.add(textArea, 0, 1);
alert.getDialogPane().setExpandableContent(expContent);
alert.showAndWait();
});
});
LOGGER.info("Global exception handler configured");
}
// ========== UPDATE METHODS ==========
/**
* Checks if a restart is needed after an update.
*/
private void checkRestartAfterUpdate() {
if (AutoUpdater.isRestartRequired()) {
LOGGER.info("Update was installed - showing restart notification");
Platform.runLater(() -> {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Update Installed");
alert.setHeaderText("AudioManager has been updated!");
alert.setContentText("The update has been installed successfully.\n\n" +
"Please restart the application to use the new version.");
alert.getButtonTypes().setAll(ButtonType.OK);
alert.showAndWait();
});
}
}
/**
* Checks for updates in the background.
*/
private void checkForUpdatesInBackground() {
if (autoUpdater == null) {
LOGGER.debug("Auto updater not initialized - skipping update check");
return;
}
String version = getAppVersion();
LOGGER.debug("Checking for updates (version: {})", version);
new Thread(() -> {
try {
autoUpdater.checkForUpdates(version);
} catch (Exception e) {
LOGGER.warn("Background update check failed: {}", e.getMessage());
}
}, "AutoUpdater-Check").start();
}
/**
* Shows the update available dialog.
*
* @param update the update information
*/
private void showUpdateAvailableDialog(AutoUpdater.UpdateInfo update) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Update Available");
alert.setHeaderText("Version " + update.version + " is now available");
String content = "A new version of AudioManager is available.\n\n";
if (update.releaseNotes != null && !update.releaseNotes.isEmpty()) {
content += "Release Notes:\n" + update.releaseNotes + "\n\n";
}
content += "Download size: " + formatFileSize(update.sizeBytes);
if (update.isCritical) {
content += "\n\n⚠️ This is a critical update - please install it as soon as possible.";
}
alert.setContentText(content);
ButtonType downloadBtn = new ButtonType("Download & Install");
ButtonType laterBtn = new ButtonType("Later");
ButtonType skipBtn = new ButtonType("Skip This Version");
alert.getButtonTypes().setAll(downloadBtn, laterBtn, skipBtn);
alert.showAndWait().ifPresent(response -> {
if (response == downloadBtn) {
downloadAndInstallUpdate(update);
} else if (response == skipBtn) {
if (prefManager != null) {
prefManager.putString("update.skipped.version", update.version);
}
}
});
}
/**
* Downloads and installs an update with progress reporting.
*
* @param update the update information
*/
private void downloadAndInstallUpdate(AutoUpdater.UpdateInfo update) {
Dialog<Void> progressDialog = new Dialog<>();
progressDialog.setTitle("Downloading Update");
progressDialog.setHeaderText("Downloading version " + update.version);
progressDialog.setResizable(true);
ProgressBar progressBar = new ProgressBar(-1);
progressBar.setPrefWidth(400);
progressBar.setMaxWidth(Double.MAX_VALUE);
Label progressLabel = new Label("Starting download...");
VBox content = new VBox(10);
content.setPadding(new Insets(20));
content.getChildren().addAll(progressLabel, progressBar);
progressDialog.getDialogPane().setContent(content);
ButtonType cancelButton = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);
progressDialog.getDialogPane().getButtonTypes().add(cancelButton);
final Dialog<Void> finalDialog = progressDialog;
autoUpdater.setCallback(new AutoUpdater.UpdateCheckCallback() {
@Override
public void onUpdateAvailable(AutoUpdater.UpdateInfo info) {
}
@Override
public void onNoUpdateAvailable() {
}
@Override
public void onCheckFailed(String error) {
}
@Override
public void onDownloadProgress(double progress) {
Platform.runLater(() -> {
if (progress >= 0 && progress <= 1.0) {
progressBar.setProgress(progress);
progressLabel.setText("Downloading... " + (int) (progress * 100) + "%");
} else {
progressBar.setProgress(-1);
progressLabel.setText("Preparing download...");
}
});
}
@Override
public void onUpdateInstalled() {
Platform.runLater(() -> {
finalDialog.close();
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Update Installed");
alert.setHeaderText("Update installed successfully!");
alert.setContentText("Please restart AudioManager to use the new version.");
alert.showAndWait();
});
}
});
finalDialog.setOnCloseRequest(event -> {
LOGGER.info("Update download cancelled by user");
});
Thread downloadThread = new Thread(() -> {
try {
boolean success = autoUpdater.downloadAndInstallUpdate(update).get();
if (!success) {
Platform.runLater(() -> {
finalDialog.close();