Skip to content

Commit

Permalink
Introduce OS (and move things from NativeDesktop)
Browse files Browse the repository at this point in the history
  • Loading branch information
koppor committed Sep 8, 2024
1 parent fb80e7d commit 5572342
Show file tree
Hide file tree
Showing 63 changed files with 574 additions and 554 deletions.
4 changes: 2 additions & 2 deletions src/jmh/java/org/jabref/benchmarks/Benchmarks.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import java.util.List;
import java.util.Random;

import org.jabref.gui.desktop.os.NativeDesktop;
import org.jabref.logic.bibtex.FieldPreferences;
import org.jabref.logic.citationkeypattern.CitationKeyPatternPreferences;
import org.jabref.logic.exporter.BibWriter;
Expand All @@ -17,6 +16,7 @@
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.os.OS;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.database.BibDatabaseMode;
Expand Down Expand Up @@ -76,7 +76,7 @@ public void init() throws Exception {

private StringWriter getOutputWriter() throws IOException {
StringWriter outputWriter = new StringWriter();
BibWriter bibWriter = new BibWriter(outputWriter, NativeDesktop.NEWLINE);
BibWriter bibWriter = new BibWriter(outputWriter, OS.NEWLINE);
BibtexDatabaseWriter databaseWriter = new BibtexDatabaseWriter(
bibWriter,
mock(SelfContainedSaveConfiguration.class),
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/org/jabref/cli/ArgumentProcessor.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
import java.util.Set;
import java.util.prefs.BackingStoreException;

import org.jabref.gui.desktop.os.NativeDesktop;
import org.jabref.gui.FilePreferences;
import org.jabref.gui.externalfiles.AutoSetFileLinksUtil;
import org.jabref.logic.JabRefException;
Expand Down Expand Up @@ -42,6 +41,7 @@
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.search.DatabaseSearcher;
import org.jabref.logic.search.SearchPreferences;
import org.jabref.logic.shared.prefs.SharedDatabasePreferences;
Expand Down Expand Up @@ -140,7 +140,7 @@ private Optional<ParserResult> importFile(String importArguments) {
return Optional.empty();
}
} else {
if (NativeDesktop.WINDOWS) {
if (OS.WINDOWS) {
file = Path.of(address);
} else {
file = Path.of(address.replace("~", System.getProperty("user.home")));
Expand Down Expand Up @@ -628,7 +628,7 @@ private void saveDatabase(BibDatabase newBase, String subName) {
try {
System.out.println(Localization.lang("Saving") + ": " + subName);
try (AtomicFileWriter fileWriter = new AtomicFileWriter(Path.of(subName), StandardCharsets.UTF_8)) {
BibWriter bibWriter = new BibWriter(fileWriter, NativeDesktop.NEWLINE);
BibWriter bibWriter = new BibWriter(fileWriter, OS.NEWLINE);
SelfContainedSaveConfiguration saveConfiguration = (SelfContainedSaveConfiguration) new SelfContainedSaveConfiguration()
.withReformatOnSave(preferencesService.getLibraryPreferences().shouldAlwaysReformatOnSave());
BibDatabaseWriter databaseWriter = new BibtexDatabaseWriter(
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/org/jabref/cli/JabRefCLI.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@

import javafx.util.Pair;

import org.jabref.gui.desktop.os.NativeDesktop;
import org.jabref.logic.exporter.ExporterFactory;
import org.jabref.logic.importer.ImportFormatReader;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.os.OS;
import org.jabref.logic.util.BuildInfo;
import org.jabref.model.entry.BibEntryTypesManager;
import org.jabref.model.strings.StringUtil;
Expand Down Expand Up @@ -366,7 +366,7 @@ protected static String alignStringTable(List<Pair<String, String>> table) {

sb.append(STRING_TABLE_DELIMITER);
sb.append(pair.getValue());
sb.append(NativeDesktop.NEWLINE);
sb.append(OS.NEWLINE);
}

return sb.toString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;

import org.jabref.gui.desktop.os.NativeDesktop;
import org.jabref.gui.preview.PreviewViewer;
import org.jabref.logic.bibtex.BibEntryWriter;
import org.jabref.logic.bibtex.FieldPreferences;
import org.jabref.logic.bibtex.FieldWriter;
import org.jabref.logic.exporter.BibWriter;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.os.OS;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.database.BibDatabaseMode;
import org.jabref.model.entry.BibEntry;
Expand Down Expand Up @@ -65,7 +65,7 @@ public TabPane getPreviewWithSourceTab(BibEntry entry, BibDatabaseContext bibDat

private String getSourceString(BibEntry entry, BibDatabaseMode type, FieldPreferences fieldPreferences, BibEntryTypesManager entryTypesManager) throws IOException {
StringWriter writer = new StringWriter();
BibWriter bibWriter = new BibWriter(writer, NativeDesktop.NEWLINE);
BibWriter bibWriter = new BibWriter(writer, OS.NEWLINE);
FieldWriter fieldWriter = FieldWriter.buildIgnoreHashes(fieldPreferences);
new BibEntryWriter(fieldWriter, entryTypesManager).write(entry, bibWriter, type);
return writer.toString();
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/org/jabref/gui/copyfiles/CopyFilesTask.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@

import javafx.concurrent.Task;

import org.jabref.gui.desktop.os.NativeDesktop;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.os.OS;
import org.jabref.logic.util.io.FileUtil;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
Expand Down Expand Up @@ -123,7 +123,7 @@ protected List<CopyFilesResultItemViewModel> call() throws InterruptedException,
private void writeLogMessage(Path newFile, BufferedWriter bw, String logMessage) {
try {
bw.write(logMessage + ": " + newFile);
bw.write(NativeDesktop.NEWLINE);
bw.write(OS.NEWLINE);
} catch (IOException e) {
LOGGER.error("error writing log file", e);
}
Expand Down
83 changes: 14 additions & 69 deletions src/main/java/org/jabref/gui/desktop/os/NativeDesktop.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
Expand All @@ -24,6 +22,7 @@
import org.jabref.gui.frame.ExternalApplicationsPreferences;
import org.jabref.logic.importer.util.IdentifierParser;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.os.OS;
import org.jabref.logic.util.Directories;
import org.jabref.logic.util.io.FileUtil;
import org.jabref.model.database.BibDatabaseContext;
Expand All @@ -32,14 +31,9 @@
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.identifier.DOI;
import org.jabref.model.entry.identifier.Identifier;
import org.jabref.model.strings.StringUtil;
import org.jabref.preferences.PreferencesService;

import com.airhacks.afterburner.injection.Injector;
import com.github.javakeyring.BackendNotSupportedException;
import com.github.javakeyring.Keyring;
import com.github.javakeyring.PasswordAccessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.jabref.model.entry.field.StandardField.PDF;
Expand All @@ -56,23 +50,15 @@
* <p>
* See http://stackoverflow.com/questions/18004150/desktop-api-is-not-supported-on-the-current-platform for more implementation hints.
* http://docs.oracle.com/javase/7/docs/api/java/awt/Desktop.html cannot be used as we don't want to rely on AWT
*
* For non-GUI things, see {@link org.jabref.logic.os.OS}.
*/
@AllowedToUseAwt("Because of moveToTrash() is not available elsewhere.")
public abstract class NativeDesktop {
// No LOGGER may be initialized directly
// Otherwise, org.jabref.Launcher.addLogToDisk will fail, because tinylog's properties are frozen

public static final String NEWLINE = System.lineSeparator();
public static final String APP_DIR_APP_NAME = "jabref";
public static final String APP_DIR_APP_AUTHOR = "org.jabref";
private static final Logger LOGGER = LoggerFactory.getLogger(NativeDesktop.class);

private static final Pattern REMOTE_LINK_PATTERN = Pattern.compile("[a-z]+://.*");
// https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/SystemUtils.html
private static final String OS_NAME = System.getProperty("os.name", "unknown").toLowerCase(Locale.ROOT);
public static final boolean OS_X = OS_NAME.startsWith("mac");
public static final boolean WINDOWS = OS_NAME.startsWith("win");
public static final boolean LINUX = OS_NAME.startsWith("linux");

/**
* Open a http/pdf/ps viewer for the given link string.
Expand Down Expand Up @@ -144,18 +130,18 @@ public static void openExternalViewer(BibDatabaseContext databaseContext,
try {
get().openFile(link, PS.getName(), preferencesService.getFilePreferences());
} catch (IOException e) {
LOGGER.error("An error occurred on the command: {}", link, e);
LoggerFactory.getLogger(NativeDesktop.class).error("An error occurred on the command: {}", link, e);
}
}
case PDF -> {
try {
get().openFile(link, PDF.getName(), preferencesService.getFilePreferences());
} catch (IOException e) {
LOGGER.error("An error occurred on the command: {}", link, e);
LoggerFactory.getLogger(NativeDesktop.class).error("An error occurred on the command: {}", link, e);
}
}
case null, default ->
LOGGER.info("Message: currently only PDF, PS and HTML files can be opened by double clicking");
LoggerFactory.getLogger(NativeDesktop.class).info("Message: currently only PDF, PS and HTML files can be opened by double clicking");
}
}

Expand Down Expand Up @@ -250,7 +236,7 @@ public static void openFolderAndSelectFile(Path fileLink,
String absolutePath = fileLink.toAbsolutePath().getParent().toString();
String command = externalApplicationsPreferences.getCustomFileBrowserCommand();
if (command.isEmpty()) {
LOGGER.info("No custom file browser command defined");
LoggerFactory.getLogger(NativeDesktop.class).info("No custom file browser command defined");
get().openFolderAndSelectFile(fileLink);
return;
}
Expand Down Expand Up @@ -278,7 +264,7 @@ public static void openConsole(Path file, PreferencesService preferencesService,
command = command.trim();
if (command.isEmpty()) {
get().openConsole(absolutePath, dialogService);
LOGGER.info("Preference for custom terminal is empty. Using default terminal.");
LoggerFactory.getLogger(NativeDesktop.class).info("Preference for custom terminal is empty. Using default terminal.");
return;
}
executeCommand(command, absolutePath, dialogService);
Expand All @@ -291,14 +277,14 @@ private static void executeCommand(String command, String absolutePath, DialogSe
// replace the placeholder if used
command = command.replace("%DIR", absolutePath);

LOGGER.info("Executing command \"{}\"...", command);
LoggerFactory.getLogger(NativeDesktop.class).info("Executing command \"{}\"...", command);
dialogService.notify(Localization.lang("Executing command \"%0\"...", command));

String[] subcommands = command.split(" ");
try {
new ProcessBuilder(subcommands).start();
} catch (IOException exception) {
LOGGER.error("Error during command execution", exception);
LoggerFactory.getLogger(NativeDesktop.class).error("Error during command execution", exception);
dialogService.notify(Localization.lang("Error occurred while executing the command \"%0\".", command));
}
}
Expand Down Expand Up @@ -328,7 +314,7 @@ public static void openBrowserShowPopup(String url, DialogService dialogService,
} catch (IOException exception) {
ClipBoardManager clipBoardManager = Injector.instantiateModelOrService(ClipBoardManager.class);
clipBoardManager.setContent(url);
LOGGER.error("Could not open browser", exception);
LoggerFactory.getLogger(NativeDesktop.class).error("Could not open browser", exception);
String couldNotOpenBrowser = Localization.lang("Could not open browser.");
String openManually = Localization.lang("Please open %0 manually.", url);
String copiedToClipboard = Localization.lang("The link has been copied to the clipboard.");
Expand All @@ -338,38 +324,16 @@ public static void openBrowserShowPopup(String url, DialogService dialogService,
}

public static NativeDesktop get() {
if (WINDOWS) {
if (OS.WINDOWS) {
return new Windows();
} else if (OS_X) {
} else if (OS.OS_X) {
return new OSX();
} else if (LINUX) {
} else if (OS.LINUX) {
return new Linux();
}
return new DefaultDesktop();
}

public static boolean isKeyringAvailable() {
try (Keyring keyring = Keyring.create()) {
keyring.setPassword("JabRef", "keyringTest", "keyringTest");
if (!"keyringTest".equals(keyring.getPassword("JabRef", "keyringTest"))) {
return false;
}
keyring.deletePassword("JabRef", "keyringTest");
} catch (
BackendNotSupportedException ex) {
LoggerFactory.getLogger(NativeDesktop.class).warn("Credential store not supported.");
return false;
} catch (
PasswordAccessException ex) {
LoggerFactory.getLogger(NativeDesktop.class).warn("Password storage in credential store failed.");
return false;
} catch (Exception ex) {
LoggerFactory.getLogger(NativeDesktop.class).warn("Connection to credential store failed");
return false;
}
return true;
}

public abstract void openFile(String filePath, String fileType, FilePreferences filePreferences) throws IOException;

/**
Expand Down Expand Up @@ -407,25 +371,6 @@ public Path getDefaultFileChooserDirectory() {
return documents;
}

public String getHostName() {
String hostName;
// Following code inspired by https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/SystemUtils.html#getHostName--
// See also https://stackoverflow.com/a/20793241/873282
hostName = System.getenv("HOSTNAME");
if (StringUtil.isBlank(hostName)) {
hostName = System.getenv("COMPUTERNAME");
}
if (StringUtil.isBlank(hostName)) {
try {
hostName = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
LoggerFactory.getLogger(NativeDesktop.class).info("Hostname not found. Using \"localhost\" as fallback.", e);
hostName = "localhost";
}
}
return hostName;
}

/**
* Moves the given file to the trash.
*
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/org/jabref/gui/edit/CopyMoreAction.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@
import org.jabref.gui.actions.ActionHelper;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.actions.StandardActions;
import org.jabref.gui.desktop.os.NativeDesktop;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.layout.Layout;
import org.jabref.logic.layout.LayoutHelper;
import org.jabref.logic.os.OS;
import org.jabref.logic.push.CitationCommandString;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
Expand Down Expand Up @@ -248,9 +248,9 @@ private void copyKeyAndLink() {
}
String url = entry.getField(StandardField.URL).orElse("");
keyAndLink.append(url.isEmpty() ? key : "<a href=\"%s\">%s</a>".formatted(url, key));
keyAndLink.append(NativeDesktop.NEWLINE);
keyAndLink.append(OS.NEWLINE);
fallbackString.append(url.isEmpty() ? key : "%s - %s".formatted(key, url));
fallbackString.append(NativeDesktop.NEWLINE);
fallbackString.append(OS.NEWLINE);
}

clipBoardManager.setHtmlContent(keyAndLink.toString(), fallbackString.toString());
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/org/jabref/gui/entryeditor/SourceTab.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
import org.jabref.gui.actions.ActionFactory;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.actions.StandardActions;
import org.jabref.gui.desktop.os.NativeDesktop;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.keyboard.CodeAreaKeyBindings;
import org.jabref.gui.keyboard.KeyBindingRepository;
Expand All @@ -43,6 +42,7 @@
import org.jabref.logic.importer.ParserResult;
import org.jabref.logic.importer.fileformat.BibtexParser;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.os.OS;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.database.BibDatabaseMode;
Expand Down Expand Up @@ -140,7 +140,7 @@ private void highlightSearchPattern() {

private String getSourceString(BibEntry entry, BibDatabaseMode type, FieldPreferences fieldPreferences) throws IOException {
StringWriter writer = new StringWriter();
BibWriter bibWriter = new BibWriter(writer, NativeDesktop.NEWLINE);
BibWriter bibWriter = new BibWriter(writer, OS.NEWLINE);
FieldWriter fieldWriter = FieldWriter.buildIgnoreHashes(fieldPreferences);
new BibEntryWriter(fieldWriter, entryTypesManager).write(entry, bibWriter, type);
return writer.toString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@

import org.jabref.gui.AbstractViewModel;
import org.jabref.gui.ClipBoardManager;
import org.jabref.gui.desktop.os.NativeDesktop;
import org.jabref.gui.util.UiTaskExecutor;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.os.OS;
import org.jabref.logic.pdf.FileAnnotationCache;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.pdf.FileAnnotation;
Expand Down Expand Up @@ -121,7 +121,7 @@ public void copyCurrentAnnotation() {
if (null == getCurrentAnnotation()) {
return;
}
StringJoiner sj = new StringJoiner("," + NativeDesktop.NEWLINE);
StringJoiner sj = new StringJoiner("," + OS.NEWLINE);
sj.add(Localization.lang("Author") + ": " + getCurrentAnnotation().getAuthor());
sj.add(Localization.lang("Date") + ": " + getCurrentAnnotation().getDate());
sj.add(Localization.lang("Page") + ": " + getCurrentAnnotation().getPage());
Expand Down
Loading

0 comments on commit 5572342

Please sign in to comment.