Skip to content

Commit

Permalink
Fix architecture gui/logic (#11729)
Browse files Browse the repository at this point in the history
* Refine JavaDoc

* Add TODOs

Co-authored-by: Carl Christian Snethlage <50491877+calixtus@users.noreply.github.com>

* Fix typos

* Reoder settings

* Fix arch flaw

Co-authored-by: Christoph <siedlerkiller@gmail.com>
Co-authored-by: Carl Christian Snethlage <50491877+calixtus@users.noreply.github.com>

* Fix checkstyle and formatting

* Make BackgroundTask independent from UI

* Move BackgroundTask from gui to logic

Co-authored-by: Christoph <siedlerkiller@gmail.com>

* protected -> public

Co-authored-by: Christoph <siedlerkiller@gmail.com>

* Move CurrentThreadTaskExecutor from gui to logic

Co-authored-by: Christoph <siedlerkiller@gmail.com>

* protected/package private -> public

Co-authored-by: Christoph <siedlerkiller@gmail.com>

* Fix formatting

* Make ArchitectureTest "real"

* Fix typo in "cancelled"

Co-authored-by: Christoph <siedlerkiller@gmail.com>

* Fix JavaDoc

* Move execute(JavaFX Task) down to UiTaskExecutor

Co-authored-by: Christoph <siedlerkiller@gmail.com>

* Fixed an exception when searching for unlinked files.

Co-authored-by: Christoph <siedlerkiller@gmail.com>

* Fix CHANGELOG

* Move TaskExecutor from gui to logic

Co-authored-by: Christoph <siedlerkiller@gmail.com>

* Fix more checkstyle

* Introduce NotifcationService

Also:

- Move openAiChat from AiService (logic) to GroupTree (gui)

* move unlinked files filter to logic

* Inline JabRefDesktop.get*Directory() (to avoid dependency to gui from logic)

* move search display mode enum

* Introduce "Directories"

* Remove unused variables

* Move ChatHistoryService to UI

* move fallback exception handler to logic and add consumer for thread execution

* remove dialog service from logic class

* Route ChatHistoryService correctly

* Do not do architecture tests for test classes

* remove dialog service in test

* Fix checkstyle

* Sort and shelve preferences objects

* Fix CHANGELOG

* Checkstyle imports

* Refactor NativeDesktop

- Integrate OS into NativeDesktop
- Integrate JabRefDesktop into NativeDesktop

* Compile fix

* Introduce OS (and move things from NativeDesktop)

* Move FilePreferences to logic

Co-authored-by: Carl Christian Snethlage <50491877+calixtus@users.noreply.github.com>

* Fix imports

* More optimize imports...

* One more...

* Move externalFileTypes from FilePreferences to ExternalApplicationPreferences

* Adapt classes to new structure of ExternalApplicatoinPreferences

Co-authored-by: Carl Christian Snethlage <50491877+calixtus@users.noreply.github.com>

* Move MrDlibPreferences

* Move AutoCompleteFirstNameMode to logic.preferences

* Move detectProgramPath to OS

* Rename "PreferenceService" to "Preferences"

* Adapt name of factory

* Move class - we do it differently in main JabRef

* Move Preferences to logic (to prepare split up in gui / non-gui)

* Infrastructore for gui / non-gui

* Rename Preferences to CliPreferences

* Fix names - begin to move getEntryEditorPreferences()

* Rename GuiPreferences to CoreGuiPreferences

* Fix CliPreferences - GuiPreferences

* Move constants

* Move "getMergeDialogPreferences()" to GuiPreferences

* Make LinkedFile independent from Gui

* Push down AutoCompletePreferences

* Pull down CoreGuiPreferences and Workspace preferences

* Fix empty line

* Push getUnlinkedFilesDialogPreferences() down

* Push down ExternalApplicationsPreferences

* Adapt code

* fix imports

* fix more imports

* checkstyle

* fix more imports

* rewrite

* Fix imports

* Push down SidePanePreferences

* Adapt code

* Fix variable location

* Push down GroupsPreferences

* Adapt classes

* Push down getSpecialFieldsPreferences()

* Adapt code

* Push down PreviewPreferences

* Adapt code

* Push down PushToApplicationPreferences

* Push down NameDisplayPreferences

* ADapt code

* Push down main table preference, main table column preferences, and search dialog column preferences

* Push down KeyBindingsRepository

* Add warning if file could not be deleted

* Remove some calls to NativeDesktop

* Remove NativeDesktop from JabRefCliPreferences

* Introduce constants (and migrations may be accessed by GUI)

* Fix wrong logger

* Relax migrations

* Move PreferencesFilter to gui

* Move LuceneIndexer to logic

* Remove preferences package from tests

* Fix imports

* Fix checkstyle

* Fix compile error

* Fix logger

* Add workaround

* Discard changes to src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestOnlyRequiredFields.xml

* Discard changes to src/test/resources/org/jabref/logic/exporter/ModsExportFormatTestAllFields.xml

* Reset *.xml to main

* Creaate LastFilesOpenedPreferences

* Re-activate code for Server

* NativeDesktop use is not restricted

* Fix architecture test

---------

Co-authored-by: Carl Christian Snethlage <50491877+calixtus@users.noreply.github.com>
Co-authored-by: Christoph <siedlerkiller@gmail.com>
  • Loading branch information
3 people authored Sep 15, 2024
1 parent 67ca174 commit 7c958e7
Show file tree
Hide file tree
Showing 572 changed files with 5,406 additions and 5,192 deletions.
4 changes: 2 additions & 2 deletions docs/code-howtos/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ JabRef stores files relative to one of [multiple possible directories](https://d
The convert the relative path to an absolute one, there is the `find` method in `FileUtil`:

```java
org.jabref.logic.util.io.FileUtil.find(org.jabref.model.database.BibDatabaseContext, java.lang.String, org.jabref.preferences.FilePreferences)
org.jabref.logic.util.io.FileUtil.find(org.jabref.model.database.BibDatabaseContext, java.lang.String, org.jabref.logic.FilePreferences)
```

`String path` Can be the files name or a relative path to it. The Preferences should only be directly accessed in the GUI. For the usage in logic pass them as parameter
Expand All @@ -59,7 +59,7 @@ When adding a file to a library, the path should be stored relative to "the best
This is implemented in `FileUtil`:

```java
org.jabref.logic.util.io.FileUtil.relativize(java.nio.file.Path, org.jabref.model.database.BibDatabaseContext, org.jabref.preferences.FilePreferences)
org.jabref.logic.util.io.FileUtil.relativize(java.nio.file.Path, org.jabref.model.database.BibDatabaseContext, org.jabref.logic.FilePreferences)
```

## Setting a Directory for a .bib File
Expand Down
12 changes: 6 additions & 6 deletions src/jmh/java/org/jabref/benchmarks/Benchmarks.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@
import org.jabref.logic.importer.fileformat.BibtexParser;
import org.jabref.logic.layout.format.HTMLChars;
import org.jabref.logic.layout.format.LatexToUnicodeFormatter;
import org.jabref.logic.util.OS;
import org.jabref.logic.os.OS;
import org.jabref.logic.preferences.CliPreferences;
import org.jabref.logic.preferences.JabRefCliPreferences;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.database.BibDatabaseMode;
Expand All @@ -29,8 +31,6 @@
import org.jabref.model.groups.KeywordGroup;
import org.jabref.model.groups.WordKeywordGroup;
import org.jabref.model.metadata.MetaData;
import org.jabref.preferences.JabRefPreferences;
import org.jabref.preferences.PreferencesService;

import com.airhacks.afterburner.injection.Injector;
import org.openjdk.jmh.Main;
Expand All @@ -52,7 +52,7 @@ public class Benchmarks {

@Setup
public void init() throws Exception {
Injector.setModelOrService(PreferencesService.class, JabRefPreferences.getInstance());
Injector.setModelOrService(CliPreferences.class, JabRefCliPreferences.getInstance());

Random randomizer = new Random();
for (int i = 0; i < 1000; i++) {
Expand Down Expand Up @@ -89,8 +89,8 @@ private StringWriter getOutputWriter() throws IOException {

@Benchmark
public ParserResult parse() throws IOException {
PreferencesService preferencesService = Injector.instantiateModelOrService(PreferencesService.class);
BibtexParser parser = new BibtexParser(preferencesService.getImportFormatPreferences());
CliPreferences preferences = Injector.instantiateModelOrService(CliPreferences.class);
BibtexParser parser = new BibtexParser(preferences.getImportFormatPreferences());
return parser.parse(new StringReader(bibtexString));
}

Expand Down
17 changes: 10 additions & 7 deletions src/main/java/org/jabref/Launcher.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
import org.jabref.cli.ArgumentProcessor;
import org.jabref.cli.JabRefCLI;
import org.jabref.gui.JabRefGUI;
import org.jabref.gui.preferences.GuiPreferences;
import org.jabref.gui.preferences.JabRefGuiPreferences;
import org.jabref.gui.util.DefaultDirectoryMonitor;
import org.jabref.gui.util.DefaultFileUpdateMonitor;
import org.jabref.logic.UiCommand;
Expand All @@ -24,18 +26,17 @@
import org.jabref.logic.net.ProxyRegisterer;
import org.jabref.logic.net.ssl.SSLPreferences;
import org.jabref.logic.net.ssl.TrustStoreManager;
import org.jabref.logic.preferences.CliPreferences;
import org.jabref.logic.protectedterms.ProtectedTermsLoader;
import org.jabref.logic.remote.RemotePreferences;
import org.jabref.logic.remote.client.RemoteClient;
import org.jabref.logic.util.BuildInfo;
import org.jabref.logic.util.Directories;
import org.jabref.logic.util.HeadlessExecutorService;
import org.jabref.logic.util.OS;
import org.jabref.migrations.PreferencesMigrations;
import org.jabref.model.entry.BibEntryTypesManager;
import org.jabref.model.util.DirectoryMonitor;
import org.jabref.model.util.FileUpdateMonitor;
import org.jabref.preferences.JabRefPreferences;
import org.jabref.preferences.PreferencesService;

import com.airhacks.afterburner.injection.Injector;
import org.apache.commons.cli.ParseException;
Expand All @@ -61,8 +62,9 @@ public static void main(String[] args) {
Injector.setModelOrService(BuildInfo.class, new BuildInfo());

// Initialize preferences
final JabRefPreferences preferences = JabRefPreferences.getInstance();
Injector.setModelOrService(PreferencesService.class, preferences);
final JabRefGuiPreferences preferences = JabRefGuiPreferences.getInstance();
Injector.setModelOrService(CliPreferences.class, preferences);
Injector.setModelOrService(GuiPreferences.class, preferences);

// Early exit in case another instance is already running
if (!handleMultipleAppInstances(args, preferences.getRemotePreferences())) {
Expand Down Expand Up @@ -95,6 +97,7 @@ public static void main(String[] args) {
args,
ArgumentProcessor.Mode.INITIAL_START,
preferences,
preferences,
fileUpdateMonitor,
entryTypesManager);
argumentProcessor.processArguments();
Expand Down Expand Up @@ -137,7 +140,7 @@ private static void initLogging(String[] args) {
}

// addLogToDisk
Path directory = OS.getNativeDesktop().getLogDirectory();
Path directory = Directories.getLogDirectory();
try {
Files.createDirectories(directory);
} catch (IOException e) {
Expand Down Expand Up @@ -204,7 +207,7 @@ private static void configureSSL(SSLPreferences sslPreferences) {
}

private static void clearOldSearchIndices() {
Path currentIndexPath = OS.getNativeDesktop().getFulltextIndexBaseDirectory();
Path currentIndexPath = Directories.getFulltextIndexBaseDirectory();
Path appData = currentIndexPath.getParent();

try {
Expand Down
81 changes: 44 additions & 37 deletions src/main/java/org/jabref/cli/ArgumentProcessor.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
import java.util.prefs.BackingStoreException;

import org.jabref.gui.externalfiles.AutoSetFileLinksUtil;
import org.jabref.gui.util.CurrentThreadTaskExecutor;
import org.jabref.gui.preferences.GuiPreferences;
import org.jabref.logic.FilePreferences;
import org.jabref.logic.JabRefException;
import org.jabref.logic.UiCommand;
import org.jabref.logic.bibtex.FieldPreferences;
Expand All @@ -41,9 +42,12 @@
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.net.URLDownload;
import org.jabref.logic.os.OS;
import org.jabref.logic.preferences.CliPreferences;
import org.jabref.logic.search.DatabaseSearcher;
import org.jabref.logic.search.SearchPreferences;
import org.jabref.logic.shared.prefs.SharedDatabasePreferences;
import org.jabref.logic.util.OS;
import org.jabref.logic.util.CurrentThreadTaskExecutor;
import org.jabref.logic.util.io.FileUtil;
import org.jabref.logic.xmp.XmpPreferences;
import org.jabref.model.database.BibDatabase;
Expand All @@ -55,9 +59,6 @@
import org.jabref.model.strings.StringUtil;
import org.jabref.model.util.DummyFileUpdateMonitor;
import org.jabref.model.util.FileUpdateMonitor;
import org.jabref.preferences.FilePreferences;
import org.jabref.preferences.PreferencesService;
import org.jabref.preferences.SearchPreferences;

import com.airhacks.afterburner.injection.Injector;
import com.google.common.base.Throwables;
Expand All @@ -73,7 +74,8 @@ public enum Mode { INITIAL_START, REMOTE_START }

private final Mode startupMode;

private final PreferencesService preferencesService;
private final CliPreferences cliPreferences;
private final GuiPreferences guiPreferences;
private final FileUpdateMonitor fileUpdateMonitor;
private final BibEntryTypesManager entryTypesManager;

Expand All @@ -83,16 +85,20 @@ public enum Mode { INITIAL_START, REMOTE_START }
/**
* First call the constructor, then call {@link #processArguments()}.
* Afterward, you can access the {@link #getUiCommands()}.
*
* @implNote both cli and gui preferences are passed to make the dependency to GUI parts explicit
*/
public ArgumentProcessor(String[] args,
Mode startupMode,
PreferencesService preferencesService,
CliPreferences cliPreferences,
GuiPreferences guiPreferences,
FileUpdateMonitor fileUpdateMonitor,
BibEntryTypesManager entryTypesManager)
throws org.apache.commons.cli.ParseException {
this.cli = new JabRefCLI(args);
this.startupMode = startupMode;
this.preferencesService = preferencesService;
this.cliPreferences = cliPreferences;
this.guiPreferences = guiPreferences;
this.fileUpdateMonitor = fileUpdateMonitor;
this.entryTypesManager = entryTypesManager;
}
Expand Down Expand Up @@ -166,9 +172,9 @@ private Optional<ParserResult> importFile(String importArguments) {
private Optional<ParserResult> importFile(Path file, String importFormat) {
try {
ImportFormatReader importFormatReader = new ImportFormatReader(
preferencesService.getImporterPreferences(),
preferencesService.getImportFormatPreferences(),
preferencesService.getCitationKeyPatternPreferences(),
cliPreferences.getImporterPreferences(),
cliPreferences.getImportFormatPreferences(),
cliPreferences.getCitationKeyPatternPreferences(),
fileUpdateMonitor
);

Expand Down Expand Up @@ -200,7 +206,7 @@ public void processArguments() {
}

if ((startupMode == Mode.INITIAL_START) && cli.isHelp()) {
JabRefCLI.printUsage(preferencesService);
JabRefCLI.printUsage(cliPreferences);
guiNeeded = false;
return;
}
Expand Down Expand Up @@ -249,11 +255,11 @@ public void processArguments() {
if (!loaded.isEmpty()) {
writeMetadataToPdf(loaded,
cli.getWriteMetadataToPdf(),
preferencesService.getXmpPreferences(),
preferencesService.getFilePreferences(),
preferencesService.getLibraryPreferences().getDefaultBibDatabaseMode(),
cliPreferences.getXmpPreferences(),
cliPreferences.getFilePreferences(),
cliPreferences.getLibraryPreferences().getDefaultBibDatabaseMode(),
Injector.instantiateModelOrService(BibEntryTypesManager.class),
preferencesService.getFieldPreferences(),
cliPreferences.getFieldPreferences(),
Injector.instantiateModelOrService(JournalAbbreviationRepository.class),
cli.isWriteXmpToPdf() || cli.isWriteMetadataToPdf(),
cli.isEmbedBibFileInPdf() || cli.isWriteMetadataToPdf());
Expand All @@ -271,7 +277,7 @@ public void processArguments() {

if (cli.isPreferencesExport()) {
try {
preferencesService.exportPreferences(Path.of(cli.getPreferencesExport()));
cliPreferences.exportPreferences(Path.of(cli.getPreferencesExport()));
} catch (JabRefException ex) {
LOGGER.error("Cannot export preferences", ex);
}
Expand Down Expand Up @@ -456,13 +462,13 @@ private boolean exportMatches(List<ParserResult> loaded) {
ParserResult pr = loaded.getLast();
BibDatabaseContext databaseContext = pr.getDatabaseContext();

SearchPreferences searchPreferences = preferencesService.getSearchPreferences();
SearchPreferences searchPreferences = cliPreferences.getSearchPreferences();
SearchQuery query = new SearchQuery(searchTerm, searchPreferences.getSearchFlags());

List<BibEntry> matches;
try {
// extract current thread task executor from luceneManager
matches = new DatabaseSearcher(query, databaseContext, new CurrentThreadTaskExecutor(), preferencesService.getFilePreferences()).getMatches();
matches = new DatabaseSearcher(query, databaseContext, new CurrentThreadTaskExecutor(), cliPreferences.getFilePreferences()).getMatches();
} catch (IOException e) {
LOGGER.error("Error occurred when searching", e);
return false;
Expand Down Expand Up @@ -494,7 +500,7 @@ private boolean exportMatches(List<ParserResult> loaded) {
} else {
// export new database
ExporterFactory exporterFactory = ExporterFactory.create(
preferencesService,
cliPreferences,
Injector.instantiateModelOrService(BibEntryTypesManager.class));
Optional<Exporter> exporter = exporterFactory.getExporterByName(formatName);
if (exporter.isEmpty()) {
Expand Down Expand Up @@ -554,7 +560,7 @@ private List<ParserResult> importAndOpenFiles() {
try {
pr = OpenDatabase.loadDatabase(
Path.of(aLeftOver),
preferencesService.getImportFormatPreferences(),
cliPreferences.getImportFormatPreferences(),
fileUpdateMonitor);
// In contrast to org.jabref.gui.LibraryTab.onDatabaseLoadingSucceed, we do not execute OpenDatabaseAction.performPostOpenActions(result, dialogService);
} catch (IOException ex) {
Expand Down Expand Up @@ -594,7 +600,7 @@ private List<ParserResult> importAndOpenFiles() {
}

if (!cli.isBlank() && cli.isBibtexImport()) {
importBibtexToOpenBase(cli.getBibtexImport(), preferencesService.getImportFormatPreferences()).ifPresent(loaded::add);
importBibtexToOpenBase(cli.getBibtexImport(), cliPreferences.getImportFormatPreferences()).ifPresent(loaded::add);
}

return loaded;
Expand Down Expand Up @@ -630,12 +636,12 @@ private void saveDatabase(BibDatabase newBase, String subName) {
try (AtomicFileWriter fileWriter = new AtomicFileWriter(Path.of(subName), StandardCharsets.UTF_8)) {
BibWriter bibWriter = new BibWriter(fileWriter, OS.NEWLINE);
SelfContainedSaveConfiguration saveConfiguration = (SelfContainedSaveConfiguration) new SelfContainedSaveConfiguration()
.withReformatOnSave(preferencesService.getLibraryPreferences().shouldAlwaysReformatOnSave());
.withReformatOnSave(cliPreferences.getLibraryPreferences().shouldAlwaysReformatOnSave());
BibDatabaseWriter databaseWriter = new BibtexDatabaseWriter(
bibWriter,
saveConfiguration,
preferencesService.getFieldPreferences(),
preferencesService.getCitationKeyPatternPreferences(),
cliPreferences.getFieldPreferences(),
cliPreferences.getCitationKeyPatternPreferences(),
entryTypesManager);
databaseWriter.saveDatabase(new BibDatabaseContext(newBase));

Expand Down Expand Up @@ -671,10 +677,10 @@ private void exportFile(List<ParserResult> loaded, String[] data) {
BibDatabaseContext databaseContext = parserResult.getDatabaseContext();
databaseContext.setDatabasePath(path);
List<Path> fileDirForDatabase = databaseContext
.getFileDirectories(preferencesService.getFilePreferences());
.getFileDirectories(cliPreferences.getFilePreferences());
System.out.println(Localization.lang("Exporting %0", data[0]));
ExporterFactory exporterFactory = ExporterFactory.create(
preferencesService,
cliPreferences,
Injector.instantiateModelOrService(BibEntryTypesManager.class));
Optional<Exporter> exporter = exporterFactory.getExporterByName(data[1]);
if (exporter.isEmpty()) {
Expand All @@ -697,8 +703,8 @@ private void exportFile(List<ParserResult> loaded, String[] data) {

private void importPreferences() {
try {
preferencesService.importPreferences(Path.of(cli.getPreferencesImport()));
Injector.setModelOrService(BibEntryTypesManager.class, preferencesService.getCustomEntryTypesRepository());
cliPreferences.importPreferences(Path.of(cli.getPreferencesImport()));
Injector.setModelOrService(BibEntryTypesManager.class, cliPreferences.getCustomEntryTypesRepository());
} catch (JabRefException ex) {
LOGGER.error("Cannot import preferences", ex);
}
Expand All @@ -708,7 +714,7 @@ private void resetPreferences(String value) {
if ("all".equals(value.trim())) {
try {
System.out.println(Localization.lang("Setting all preferences to default values."));
preferencesService.clear();
cliPreferences.clear();
new SharedDatabasePreferences().clear();
} catch (BackingStoreException e) {
System.err.println(Localization.lang("Unable to clear preferences."));
Expand All @@ -718,7 +724,7 @@ private void resetPreferences(String value) {
String[] keys = value.split(",");
for (String key : keys) {
try {
preferencesService.deleteKey(key.trim());
cliPreferences.deleteKey(key.trim());
System.out.println(Localization.lang("Resetting preference key '%0'", key.trim()));
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
Expand All @@ -734,11 +740,12 @@ private void automaticallySetFileLinks(List<ParserResult> loaded) {
parserResult.getDatabaseContext().getDatabasePath()
.map(Path::getFileName)
.map(Path::toString).orElse("UNKNOWN"));

AutoSetFileLinksUtil util = new AutoSetFileLinksUtil(
parserResult.getDatabaseContext(),
preferencesService.getFilePreferences(),
preferencesService.getAutoLinkPreferences());
guiPreferences.getExternalApplicationsPreferences(),
cliPreferences.getFilePreferences(),
cliPreferences.getAutoLinkPreferences());

util.linkAssociatedFiles(database.getEntries(), (linkedFile, bibEntry) -> bibEntry.addFile(linkedFile));
}
Expand All @@ -752,7 +759,7 @@ private void regenerateCitationKeys(List<ParserResult> loaded) {

CitationKeyGenerator keyGenerator = new CitationKeyGenerator(
parserResult.getDatabaseContext(),
preferencesService.getCitationKeyPatternPreferences());
cliPreferences.getCitationKeyPatternPreferences());
for (BibEntry entry : database.getEntries()) {
keyGenerator.generateAndSetKey(entry);
}
Expand All @@ -777,8 +784,8 @@ private Optional<ParserResult> fetch(String fetchCommand) {
String query = split[1];

Set<SearchBasedFetcher> fetchers = WebFetchers.getSearchBasedFetchers(
preferencesService.getImportFormatPreferences(),
preferencesService.getImporterPreferences());
cliPreferences.getImportFormatPreferences(),
cliPreferences.getImporterPreferences());
Optional<SearchBasedFetcher> selectedFetcher = fetchers.stream()
.filter(fetcher -> fetcher.getName().equalsIgnoreCase(engine))
.findFirst();
Expand Down
Loading

0 comments on commit 7c958e7

Please sign in to comment.