Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Revert "Process CLI arguments before starting gui" #9257

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,6 @@

"onCreateCommand": "gradle assemble",

// Forward the noVNC port (desktop-lite: https://github.com/devcontainers/features/tree/main/src/desktop-lite)
"forwardPorts": [6080],

// Need to connect as root otherwise we run into issues with gradle.
// default option is "vscode". More info: https://aka.ms/vscode-remote/containers/non-root.
"remoteUser": "root",
Expand Down
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ java {
}

application {
mainClass.set('org.jabref.cli.Launcher')
mainClass.set('org.jabref.gui.JabRefLauncher')
mainModule.set('org.jabref')
}

Expand Down
10 changes: 10 additions & 0 deletions src/main/java/org/jabref/gui/JabRefLauncher.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package org.jabref.gui;

/**
* JabRef launcher: This just starts JabRefMain. It is there because to have the name consistent to other Java applications.
*/
public class JabRefLauncher {
public static void main(String[] args) {
JabRefMain.main(args);
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package org.jabref.cli;
package org.jabref.gui;

import java.io.File;
import java.io.IOException;
Expand All @@ -9,8 +9,13 @@
import java.util.Comparator;
import java.util.Map;

import org.jabref.gui.Globals;
import org.jabref.gui.MainApplication;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.stage.Stage;

import org.jabref.cli.ArgumentProcessor;
import org.jabref.cli.JabRefCLI;
import org.jabref.gui.openoffice.OOBibBaseConnect;
import org.jabref.gui.remote.JabRefMessageHandler;
import org.jabref.logic.exporter.ExporterFactory;
import org.jabref.logic.journals.JournalAbbreviationLoader;
Expand All @@ -37,72 +42,40 @@
import org.tinylog.configuration.Configuration;

/**
* The main entry point for the JabRef application.
* <p>
* It has two main functions:
* - Handle the command line arguments
* - Start the JavaFX application (if not in cli mode)
* JabRef's main class to process command line options and to start the UI
*/
public class Launcher {
public class JabRefMain extends Application {
private static Logger LOGGER;

private static String[] arguments;

public static void main(String[] args) {
addLogToDisk();
try {
// Init preferences
final JabRefPreferences preferences = JabRefPreferences.getInstance();
Globals.prefs = preferences;
PreferencesMigrations.runMigrations();

// Early exit in case another instance is already running
if (!handleMultipleAppInstances(args, preferences)) {
return;
}

// Init rest of preferences
configureProxy(preferences.getProxyPreferences());
configureSSL(preferences.getSSLPreferences());
applyPreferences(preferences);
clearOldSearchIndices();

try {
// Process arguments
ArgumentProcessor argumentProcessor = new ArgumentProcessor(args, ArgumentProcessor.Mode.INITIAL_START,
preferences);
if (argumentProcessor.shouldShutDown()) {
LOGGER.debug("JabRef shut down after processing command line arguments");
return;
}
arguments = args;
launch(arguments);
}

MainApplication.create(argumentProcessor.getParserResults(), argumentProcessor.isBlank(), preferences);
} catch (ParseException e) {
LOGGER.error("Problem parsing arguments", e);
JabRefCLI.printUsage();
}
} catch (Exception ex) {
LOGGER.error("Unexpected exception", ex);
}
private static void initializeLogger() {
LOGGER = LoggerFactory.getLogger(JabRefMain.class);
}

/**
* This needs to be called as early as possible. After the first log write, it
* is not possible to alter
* This needs to be called as early as possible. After the first log write, it is not possible to alter
* the log configuration programmatically anymore.
*/
private static void addLogToDisk() {
Path directory = Path.of(AppDirsFactory.getInstance().getUserLogDir(
"jabref",
new BuildInfo().version.toString(),
"org.jabref"));
"jabref",
new BuildInfo().version.toString(),
"org.jabref"));
try {
Files.createDirectories(directory);
} catch (IOException e) {
initializeLogger();
LOGGER.error("Could not create log directory {}", directory, e);
return;
}
// The "Shared File Writer" is explained at
// https://tinylog.org/v2/configuration/#shared-file-writer
// The "Shared File Writer" is explained at https://tinylog.org/v2/configuration/#shared-file-writer
Map<String, String> configuration = Map.of(
"writerFile", "shared file",
"writerFile.level", "info",
Expand All @@ -113,8 +86,55 @@ private static void addLogToDisk() {
initializeLogger();
}

private static void initializeLogger() {
LOGGER = LoggerFactory.getLogger(MainApplication.class);
@Override
public void start(Stage mainStage) {
try {
FallbackExceptionHandler.installExceptionHandler();

// Init preferences
final JabRefPreferences preferences = JabRefPreferences.getInstance();
Globals.prefs = preferences;
// Perform migrations
PreferencesMigrations.runMigrations();

configureProxy(preferences.getProxyPreferences());

configureSSL(preferences.getSSLPreferences());

Globals.startBackgroundTasks();

applyPreferences(preferences);

clearOldSearchIndices();

try {
// Process arguments
ArgumentProcessor argumentProcessor = new ArgumentProcessor(arguments, ArgumentProcessor.Mode.INITIAL_START, preferences);
// Check for running JabRef
if (!handleMultipleAppInstances(arguments, preferences) || argumentProcessor.shouldShutDown()) {
Platform.exit();
return;
}

// If not, start GUI
new JabRefGUI(mainStage, argumentProcessor.getParserResults(), argumentProcessor.isBlank(), preferences);
} catch (ParseException e) {
LOGGER.error("Problem parsing arguments", e);

JabRefCLI.printUsage();
Platform.exit();
}
} catch (Exception ex) {
LOGGER.error("Unexpected exception", ex);
Platform.exit();
}
}

@Override
public void stop() {
OOBibBaseConnect.closeOfficeConnection();
Globals.stopBackgroundTasks();
Globals.shutdownThreadPools();
}

private static boolean handleMultipleAppInstances(String[] args, PreferencesService preferences) {
Expand All @@ -123,8 +143,7 @@ private static boolean handleMultipleAppInstances(String[] args, PreferencesServ
// Try to contact already running JabRef
RemoteClient remoteClient = new RemoteClient(remotePreferences.getPort());
if (remoteClient.ping()) {
// We are not alone, there is already a server out there, send command line
// arguments to other instance
// We are not alone, there is already a server out there, send command line arguments to other instance
if (remoteClient.sendCommandLineArguments(args)) {
// So we assume it's all taken care of, and quit.
LOGGER.info(Localization.lang("Arguments passed on to running JabRef instance. Shutting down."));
Expand All @@ -134,17 +153,15 @@ private static boolean handleMultipleAppInstances(String[] args, PreferencesServ
}
} else {
// We are alone, so we start the server
Globals.REMOTE_LISTENER.openAndStart(new JabRefMessageHandler(), remotePreferences.getPort(),
preferences);
Globals.REMOTE_LISTENER.openAndStart(new JabRefMessageHandler(), remotePreferences.getPort(), preferences);
}
}
return true;
}

private static void applyPreferences(PreferencesService preferences) {
// Read list(s) of journal names and abbreviations
Globals.journalAbbreviationRepository = JournalAbbreviationLoader
.loadRepository(preferences.getJournalAbbreviationPreferences());
Globals.journalAbbreviationRepository = JournalAbbreviationLoader.loadRepository(preferences.getJournalAbbreviationPreferences());

// Build list of Import and Export formats
Globals.IMPORT_FORMAT_READER.resetImportFormats(
Expand Down Expand Up @@ -191,13 +208,12 @@ private static void clearOldSearchIndices() {

try (DirectoryStream<Path> stream = Files.newDirectoryStream(appData)) {
for (Path path : stream) {
if (Files.isDirectory(path) && !path.toString().endsWith("ssl") && path.toString().contains("lucene")
&& !path.equals(currentIndexPath)) {
if (Files.isDirectory(path) && !path.toString().endsWith("ssl") && path.toString().contains("lucene") && !path.equals(currentIndexPath)) {
LOGGER.info("Deleting out-of-date fulltext search index at {}.", path);
Files.walk(path)
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
}
}
} catch (IOException e) {
Expand Down
41 changes: 0 additions & 41 deletions src/main/java/org/jabref/gui/MainApplication.java

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
import org.jabref.gui.ClipBoardManager;
import org.jabref.gui.DialogService;
import org.jabref.gui.desktop.JabRefDesktop;
import org.jabref.gui.util.BindingsHelper;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.logging.LogMessages;
import org.jabref.logic.util.BuildInfo;
Expand All @@ -26,7 +25,6 @@
import org.slf4j.LoggerFactory;

public class ErrorConsoleViewModel extends AbstractViewModel {

private static final Logger LOGGER = LoggerFactory.getLogger(ErrorConsoleViewModel.class);

private final DialogService dialogService;
Expand All @@ -38,7 +36,7 @@ public ErrorConsoleViewModel(DialogService dialogService, ClipBoardManager clipB
this.dialogService = Objects.requireNonNull(dialogService);
this.clipBoardManager = Objects.requireNonNull(clipBoardManager);
this.buildInfo = Objects.requireNonNull(buildInfo);
ObservableList<LogEventViewModel> eventViewModels = EasyBind.map(BindingsHelper.forUI(LogMessages.getInstance().getMessages()), LogEventViewModel::new);
ObservableList<LogEventViewModel> eventViewModels = EasyBind.map(LogMessages.getInstance().getMessages(), LogEventViewModel::new);
allMessagesData = new ReadOnlyListWrapper<>(eventViewModels);
}

Expand Down
3 changes: 2 additions & 1 deletion src/main/java/org/jabref/gui/logging/GuiWriter.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import java.util.EnumSet;
import java.util.Map;

import org.jabref.gui.util.DefaultTaskExecutor;
import org.jabref.logic.logging.LogMessages;

import org.tinylog.core.LogEntry;
Expand All @@ -28,7 +29,7 @@ public Collection<LogEntryValue> getRequiredLogEntryValues() {

@Override
public void write(LogEntry logEntry) throws Exception {
LogMessages.getInstance().add(logEntry);
DefaultTaskExecutor.runInJavaFXThread(() -> LogMessages.getInstance().add(logEntry));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ public X509Certificate getCertificate(String alias) {
*/
public static void createTruststoreFileIfNotExist(Path storePath) {
try {
LOGGER.debug("Trust store path: {}", storePath.toAbsolutePath());
LOGGER.info("Trust store path: {}", storePath.toAbsolutePath());
Path storeResourcePath = Path.of(TrustStoreManager.class.getResource("/ssl/truststore.jks").toURI());
Files.createDirectories(storePath.getParent());
if (Files.notExists(storePath)) {
Expand Down
28 changes: 28 additions & 0 deletions src/test/java/org/jabref/testutils/TestUtils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package org.jabref.testutils;

import org.jabref.gui.JabRefGUI;
import org.jabref.gui.JabRefMain;

public class TestUtils {

private static final String PATH_TO_TEST_BIBTEX = "src/test/resources/org/jabref/bibtexFiles/test.bib";

/**
* Initialize JabRef. Can be cleaned up with {@link TestUtils#closeJabRef()}
*
* @see TestUtils#closeJabRef()
*/
public static void initJabRef() {
String[] args = {"-p", " ", TestUtils.PATH_TO_TEST_BIBTEX};
JabRefMain.main(args);
}

/**
* Closes the current instance of JabRef.
*/
public static void closeJabRef() {
if (JabRefGUI.getMainFrame() != null) {
// TODO
}
}
}