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

Observable Preferences S (LastExportPath and Cleanups in JabRefPreferences and Globals) #9493

Merged
merged 6 commits into from
Dec 24, 2022
Merged
Show file tree
Hide file tree
Changes from 5 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
49 changes: 21 additions & 28 deletions src/main/java/org/jabref/cli/ArgumentProcessor.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
import org.jabref.logic.exporter.Exporter;
import org.jabref.logic.exporter.ExporterFactory;
import org.jabref.logic.exporter.SavePreferences;
import org.jabref.logic.exporter.TemplateExporter;
import org.jabref.logic.exporter.XmpPdfExporter;
import org.jabref.logic.importer.FetcherException;
import org.jabref.logic.importer.ImportException;
Expand All @@ -40,7 +39,6 @@
import org.jabref.logic.importer.WebFetchers;
import org.jabref.logic.importer.fileformat.BibtexParser;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.layout.LayoutFormatterPreferences;
import org.jabref.logic.net.URLDownload;
import org.jabref.logic.search.DatabaseSearcher;
import org.jabref.logic.search.SearchQuery;
Expand Down Expand Up @@ -74,10 +72,11 @@ public class ArgumentProcessor {
private boolean noGUINeeded;

public ArgumentProcessor(String[] args, Mode startupMode, PreferencesService preferencesService) throws org.apache.commons.cli.ParseException {
cli = new JabRefCLI(args);
this.cli = new JabRefCLI(args);
this.startupMode = startupMode;
this.preferencesService = preferencesService;
parserResults = processArguments();

this.parserResults = processArguments();
}

/**
Expand Down Expand Up @@ -186,7 +185,7 @@ private List<ParserResult> processArguments() {
}

if ((startupMode == Mode.INITIAL_START) && cli.isHelp()) {
JabRefCLI.printUsage();
JabRefCLI.printUsage(preferencesService);
noGUINeeded = true;
return Collections.emptyList();
}
Expand Down Expand Up @@ -399,14 +398,18 @@ private boolean exportMatches(List<ParserResult> loaded) {
}

// export new database
Optional<Exporter> exporter = Globals.exportFactory.getExporterByName(formatName);
ExporterFactory exporterFactory = ExporterFactory.create(
preferencesService,
Globals.entryTypesManager,
Globals.journalAbbreviationRepository);
Optional<Exporter> exporter = exporterFactory.getExporterByName(formatName);
if (exporter.isEmpty()) {
System.err.println(Localization.lang("Unknown export format") + ": " + formatName);
} else {
// We have an TemplateExporter instance:
try {
System.out.println(Localization.lang("Exporting") + ": " + data[1]);
exporter.get().export(databaseContext, Path.of(data[1]), matches);
exporter.get().export(databaseContext, Path.of(data[1]), matches, Collections.emptyList());
} catch (Exception ex) {
System.err.println(Localization.lang("Could not export file") + " '" + data[1] + "': "
+ Throwables.getStackTraceAsString(ex));
Expand Down Expand Up @@ -561,23 +564,27 @@ private void exportFile(List<ParserResult> loaded, String[] data) {
// format to the given file.
ParserResult pr = loaded.get(loaded.size() - 1);

// Set the global variable for this database's file directory before exporting,
// so formatters can resolve linked files correctly.
// (This is an ugly hack!)
Path path = pr.getPath().get().toAbsolutePath();
BibDatabaseContext databaseContext = pr.getDatabaseContext();
databaseContext.setDatabasePath(path);
Globals.prefs.fileDirForDatabase = databaseContext
List<Path> fileDirForDatabase = databaseContext
.getFileDirectories(preferencesService.getFilePreferences());
System.out.println(Localization.lang("Exporting") + ": " + data[0]);
Optional<Exporter> exporter = Globals.exportFactory.getExporterByName(data[1]);
ExporterFactory exporterFactory = ExporterFactory.create(
preferencesService,
Globals.entryTypesManager,
Globals.journalAbbreviationRepository);
Optional<Exporter> exporter = exporterFactory.getExporterByName(data[1]);
if (exporter.isEmpty()) {
System.err.println(Localization.lang("Unknown export format") + ": " + data[1]);
} else {
// We have an exporter:
try {
exporter.get().export(pr.getDatabaseContext(), Path.of(data[0]),
pr.getDatabaseContext().getDatabase().getEntries());
exporter.get().export(
pr.getDatabaseContext(),
Path.of(data[0]),
pr.getDatabaseContext().getDatabase().getEntries(),
fileDirForDatabase);
} catch (Exception ex) {
System.err.println(Localization.lang("Could not export file") + " '" + data[0] + "': "
+ Throwables.getStackTraceAsString(ex));
Expand All @@ -591,20 +598,6 @@ private void importPreferences() {
preferencesService.importPreferences(Path.of(cli.getPreferencesImport()));
Globals.entryTypesManager.addCustomOrModifiedTypes(preferencesService.getBibEntryTypes(BibDatabaseMode.BIBTEX),
preferencesService.getBibEntryTypes(BibDatabaseMode.BIBLATEX));
List<TemplateExporter> customExporters =
preferencesService.getCustomExportFormats(Globals.journalAbbreviationRepository);
LayoutFormatterPreferences layoutPreferences =
preferencesService.getLayoutFormatterPreferences(Globals.journalAbbreviationRepository);
SavePreferences savePreferences = preferencesService.getSavePreferencesForExport();
XmpPreferences xmpPreferences = preferencesService.getXmpPreferences();
BibDatabaseMode bibDatabaseMode = preferencesService.getGeneralPreferences().getDefaultBibDatabaseMode();
Globals.exportFactory = ExporterFactory.create(
customExporters,
layoutPreferences,
savePreferences,
xmpPreferences,
bibDatabaseMode,
Globals.entryTypesManager);
} catch (JabRefException ex) {
LOGGER.error("Cannot import preferences", ex);
}
Expand Down
45 changes: 34 additions & 11 deletions src/main/java/org/jabref/cli/JabRefCLI.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,22 @@
import java.util.List;

import org.jabref.gui.Globals;
import org.jabref.logic.exporter.Exporter;
import org.jabref.logic.exporter.ExporterFactory;
import org.jabref.logic.l10n.Localization;
import org.jabref.preferences.PreferencesService;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JabRefCLI {
private static final int WIDTH = 100; // Number of characters per line before a line break must be added.
private static final String WRAPPED_LINE_PREFIX = ""; // If a line break is added, this prefix will be inserted at the beginning of the next line

private static final int WIDTH = 100; // Number of characters per line
private static final Logger LOGGER = LoggerFactory.getLogger(JabRefCLI.class);
private final CommandLine cl;
private final List<String> leftOver;

Expand Down Expand Up @@ -47,10 +48,6 @@ public boolean isBlank() {
return cl.hasOption("blank");
}

public boolean isLoadSession() {
return cl.hasOption("loads");
}

public boolean isDisableGui() {
return cl.hasOption("nogui");
}
Expand Down Expand Up @@ -291,14 +288,19 @@ public void displayVersion() {
System.out.println(getVersionInfo());
}

public static void printUsage() {
public static void printUsage(PreferencesService preferencesService) {
String header = "";

String importFormats = Globals.IMPORT_FORMAT_READER.getImportFormatList();
String importFormatsList = String.format("%s:%n%s%n", Localization.lang("Available import formats"), importFormats);

String outFormats = Globals.exportFactory.getExportersAsString(70, 20, "");
String outFormatsList = String.format("%s: %s%n", Localization.lang("Available export formats"), outFormats);
ExporterFactory exporterFactory = ExporterFactory.create(
preferencesService,
Globals.entryTypesManager,
Globals.journalAbbreviationRepository);
String outFormatsIntro = Localization.lang("Available export formats");
String outFormats = wrapStringList(exporterFactory.getExporters().stream().map(Exporter::getId).toList(), outFormatsIntro.length());
String outFormatsList = String.format("%s: %s%n", outFormatsIntro, outFormats);

String footer = '\n' + importFormatsList + outFormatsList + "\nPlease report issues at https://github.com/JabRef/jabref/issues.";

Expand All @@ -313,4 +315,25 @@ private String getVersionInfo() {
public List<String> getLeftOver() {
return leftOver;
}

/**
* Creates and wraps a multi-line and colon-seperated string from a List of Strings.
*/
protected static String wrapStringList(List<String> list, int firstLineIntroLength) {
StringBuilder builder = new StringBuilder();
int lastBreak = -firstLineIntroLength;

for (String line : list) {
if (((builder.length() + 2 + line.length()) - lastBreak) > WIDTH) {
builder.append(",\n");
lastBreak = builder.length();
builder.append(WRAPPED_LINE_PREFIX);
} else if (builder.length() > 0) {
builder.append(", ");
}
builder.append(line);
}

return builder.toString();
}
}
10 changes: 1 addition & 9 deletions src/main/java/org/jabref/cli/Launcher.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@

import org.jabref.gui.Globals;
import org.jabref.gui.MainApplication;
import org.jabref.logic.exporter.ExporterFactory;
import org.jabref.logic.journals.JournalAbbreviationLoader;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.net.ProxyAuthenticator;
Expand Down Expand Up @@ -78,7 +77,7 @@ public static void main(String[] args) {
MainApplication.main(argumentProcessor.getParserResults(), argumentProcessor.isBlank(), preferences, ARGUMENTS);
} catch (ParseException e) {
LOGGER.error("Problem parsing arguments", e);
JabRefCLI.printUsage();
JabRefCLI.printUsage(preferences);
}
} catch (Exception ex) {
LOGGER.error("Unexpected exception", ex);
Expand Down Expand Up @@ -151,13 +150,6 @@ private static void applyPreferences(PreferencesService preferences) {
Globals.entryTypesManager.addCustomOrModifiedTypes(
preferences.getBibEntryTypes(BibDatabaseMode.BIBTEX),
preferences.getBibEntryTypes(BibDatabaseMode.BIBLATEX));
Globals.exportFactory = ExporterFactory.create(
preferences.getCustomExportFormats(Globals.journalAbbreviationRepository),
preferences.getLayoutFormatterPreferences(Globals.journalAbbreviationRepository),
preferences.getSavePreferencesForExport(),
preferences.getXmpPreferences(),
preferences.getGeneralPreferences().getDefaultBibDatabaseMode(),
Globals.entryTypesManager);

// Initialize protected terms loader
Globals.protectedTermsLoader = new ProtectedTermsLoader(preferences.getProtectedTermsPreferences());
Expand Down
2 changes: 0 additions & 2 deletions src/main/java/org/jabref/gui/Globals.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
import org.jabref.gui.util.DefaultFileUpdateMonitor;
import org.jabref.gui.util.DefaultTaskExecutor;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.exporter.ExporterFactory;
import org.jabref.logic.importer.ImportFormatReader;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.logic.protectedterms.ProtectedTermsLoader;
Expand Down Expand Up @@ -71,7 +70,6 @@ public class Globals {
*/
public static ProtectedTermsLoader protectedTermsLoader;

public static ExporterFactory exportFactory;
public static CountingUndoManager undoManager = new CountingUndoManager();
public static BibEntryTypesManager entryTypesManager = new BibEntryTypesManager();

Expand Down
2 changes: 1 addition & 1 deletion src/main/java/org/jabref/gui/JabRefFrame.java
Original file line number Diff line number Diff line change
Expand Up @@ -789,7 +789,7 @@ private MenuBar createMenu() {
factory.createMenuItem(StandardActions.COPY_KEY_AND_TITLE, new CopyMoreAction(StandardActions.COPY_KEY_AND_TITLE, dialogService, stateManager, Globals.getClipboardManager(), prefs)),
factory.createMenuItem(StandardActions.COPY_KEY_AND_LINK, new CopyMoreAction(StandardActions.COPY_KEY_AND_LINK, dialogService, stateManager, Globals.getClipboardManager(), prefs)),
factory.createMenuItem(StandardActions.COPY_CITATION_PREVIEW, new CopyCitationAction(CitationStyleOutputFormat.HTML, dialogService, stateManager, Globals.getClipboardManager(), Globals.TASK_EXECUTOR, prefs.getPreviewPreferences())),
factory.createMenuItem(StandardActions.EXPORT_SELECTED_TO_CLIPBOARD, new ExportToClipboardAction(dialogService, Globals.exportFactory, stateManager, Globals.getClipboardManager(), Globals.TASK_EXECUTOR, prefs))),
factory.createMenuItem(StandardActions.EXPORT_SELECTED_TO_CLIPBOARD, new ExportToClipboardAction(dialogService, stateManager, Globals.getClipboardManager(), Globals.TASK_EXECUTOR, prefs))),

factory.createMenuItem(StandardActions.PASTE, new EditAction(StandardActions.PASTE, this, stateManager)),

Expand Down
29 changes: 10 additions & 19 deletions src/main/java/org/jabref/gui/exporter/ExportCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,8 @@
import org.jabref.gui.util.FileFilterConverter;
import org.jabref.logic.exporter.Exporter;
import org.jabref.logic.exporter.ExporterFactory;
import org.jabref.logic.exporter.SavePreferences;
import org.jabref.logic.exporter.TemplateExporter;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.layout.LayoutFormatterPreferences;
import org.jabref.logic.util.io.FileUtil;
import org.jabref.logic.xmp.XmpPreferences;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.preferences.PreferencesService;
Expand Down Expand Up @@ -71,18 +67,15 @@ public ExportCommand(ExportMethod exportMethod,

@Override
public void execute() {
List<TemplateExporter> customExporters = preferences.getCustomExportFormats(Globals.journalAbbreviationRepository);
LayoutFormatterPreferences layoutPreferences = preferences.getLayoutFormatterPreferences(Globals.journalAbbreviationRepository);
SavePreferences savePreferences = preferences.getSavePreferencesForExport();
XmpPreferences xmpPreferences = preferences.getXmpPreferences();

// Get list of exporters and sort before adding to file dialog
List<Exporter> exporters = Globals.exportFactory.getExporters().stream()
.sorted(Comparator.comparing(Exporter::getName))
.collect(Collectors.toList());
ExporterFactory exporterFactory = ExporterFactory.create(
preferences,
Globals.entryTypesManager,
Globals.journalAbbreviationRepository);
List<Exporter> exporters = exporterFactory.getExporters().stream()
.sorted(Comparator.comparing(Exporter::getName))
.collect(Collectors.toList());

Globals.exportFactory = ExporterFactory.create(customExporters, layoutPreferences, savePreferences,
xmpPreferences, preferences.getGeneralPreferences().getDefaultBibDatabaseMode(), Globals.entryTypesManager);
FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
.addExtensionFilter(FileFilterConverter.exporterToExtensionFilter(exporters))
.withDefaultExtension(preferences.getImportExportPreferences().getLastExportExtension())
Expand Down Expand Up @@ -111,10 +104,7 @@ private void export(Path file, FileChooser.ExtensionFilter selectedExtensionFilt
.orElse(Collections.emptyList());
}

// Set the global variable for this database's file directory before exporting,
// so formatters can resolve linked files correctly.
// (This is an ugly hack!)
Globals.prefs.fileDirForDatabase = stateManager.getActiveDatabase()
List<Path> fileDirForDatabase = stateManager.getActiveDatabase()
.map(db -> db.getFileDirectories(preferences.getFilePreferences()))
.orElse(List.of(preferences.getFilePreferences().getWorkingDirectory()));

Expand All @@ -129,7 +119,8 @@ private void export(Path file, FileChooser.ExtensionFilter selectedExtensionFilt
.wrap(() -> {
format.export(stateManager.getActiveDatabase().get(),
file,
finEntries);
finEntries,
fileDirForDatabase);
return null; // can not use BackgroundTask.wrap(Runnable) because Runnable.run() can't throw Exceptions
})
.onSuccess(save -> {
Expand Down
Loading