Skip to content

Commit

Permalink
Fixes #6357: File directory
Browse files Browse the repository at this point in the history
Bug was introduced in 1b03f03.
  • Loading branch information
tobiasdiez committed Apr 29, 2020
1 parent 7219e36 commit 79e5106
Show file tree
Hide file tree
Showing 19 changed files with 197 additions and 276 deletions.
2 changes: 1 addition & 1 deletion src/main/java/org/jabref/gui/actions/ActionHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public static BooleanExpression isFilePresentForSelectedEntry(StateManager state
return Bindings.createBooleanBinding(() -> {
List<LinkedFile> files = stateManager.getSelectedEntries().get(0).getFiles();
if ((files.size() > 0) && stateManager.getActiveDatabase().isPresent()) {
Optional<Path> filename = FileHelper.expandFilename(
Optional<Path> filename = FileHelper.find(
stateManager.getActiveDatabase().get(),
files.get(0).getLink(),
preferencesService.getFilePreferences());
Expand Down
15 changes: 5 additions & 10 deletions src/main/java/org/jabref/gui/desktop/JabRefDesktop.java
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,12 @@ public static void openExternalViewer(BibDatabaseContext databaseContext, String
Field field = initialField;
if (StandardField.PS.equals(field) || StandardField.PDF.equals(field)) {
// Find the default directory for this field type:
List<String> dir = databaseContext.getFileDirectories(field, Globals.prefs.getFilePreferences());
List<Path> directories = databaseContext.getFileDirectoriesAsPaths(Globals.prefs.getFilePreferences());

Optional<Path> file = FileHelper.expandFilename(link, dir);
Optional<Path> file = FileHelper.find(link, directories);

// Check that the file exists:
if (!file.isPresent() || !Files.exists(file.get())) {
if (file.isEmpty() || !Files.exists(file.get())) {
throw new IOException("File not found (" + field + "): '" + link + "'.");
}
link = file.get().toAbsolutePath().toString();
Expand Down Expand Up @@ -126,21 +126,16 @@ public static boolean openExternalFileAnyFormat(final BibDatabaseContext databas
return true;
}

Optional<Path> file = FileHelper.expandFilename(databaseContext, link, Globals.prefs.getFilePreferences());
Optional<Path> file = FileHelper.find(databaseContext, link, Globals.prefs.getFilePreferences());
if (file.isPresent() && Files.exists(file.get())) {
// Open the file:
String filePath = file.get().toString();
openExternalFilePlatformIndependent(type, filePath);
return true;
} else {
// No file matched the name, try to open it directly using the given app
openExternalFilePlatformIndependent(type, link);
return true;
}
}

public static boolean openExternalFileAnyFormat(Path file, final BibDatabaseContext databaseContext, final Optional<ExternalFileType> type) throws IOException {
return openExternalFileAnyFormat(databaseContext, file.toString(), type);
return true;
}

private static void openExternalFilePlatformIndependent(Optional<ExternalFileType> fileType, String filePath)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ public LinkedFileViewModel(LinkedFile linkedFile,
if (linkedFile.isOnlineLink()) {
return true;
} else {
Optional<Path> path = FileHelper.expandFilename(databaseContext, link, filePreferences);
Optional<Path> path = FileHelper.find(databaseContext, link, filePreferences);
return path.isPresent() && Files.exists(path.get());
}
},
Expand Down Expand Up @@ -192,7 +192,7 @@ public void open() {
public void openFolder() {
try {
if (!linkedFile.isOnlineLink()) {
Optional<Path> resolvedPath = FileHelper.expandFilename(
Optional<Path> resolvedPath = FileHelper.find(
databaseContext,
linkedFile.getLink(),
filePreferences);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ private void setExternalFileTypeByExtension(String link) {
public void openBrowseDialog() {
String fileText = link.get();

Optional<Path> file = FileHelper.expandFilename(database, fileText, preferences.getFilePreferences());
Optional<Path> file = FileHelper.find(database, fileText, preferences.getFilePreferences());

Path workingDir = file.orElse(preferences.getWorkingDir());
String fileName = Paths.get(fileText).getFileName().toString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@
import org.jabref.gui.DialogService;
import org.jabref.gui.util.DirectoryDialogConfiguration;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.metadata.FilePreferences;
import org.jabref.preferences.JabRefPreferences;
import org.jabref.preferences.NewLineSeparator;

Expand Down Expand Up @@ -87,7 +85,7 @@ public void setValues() {
selectedNewLineSeparatorProperty.setValue(preferences.getNewLineSeparator());
alwaysReformatBibProperty.setValue(preferences.getBoolean(JabRefPreferences.REFORMAT_FILE_ON_SAVE_AND_EXPORT));

mainFileDirProperty.setValue(preferences.getAsOptional(StandardField.FILE.getName() + FilePreferences.DIR_SUFFIX).orElse(""));
mainFileDirProperty.setValue(preferences.getAsOptional(JabRefPreferences.MAIN_FILE_DIRECTORY).orElse(""));
useBibLocationAsPrimaryProperty.setValue(preferences.getBoolean(JabRefPreferences.BIB_LOC_AS_PRIMARY_DIR));
if (preferences.getBoolean(JabRefPreferences.AUTOLINK_USE_REG_EXP_SEARCH_KEY)) { // Flipped around
autolinkUseRegexProperty.setValue(true);
Expand Down Expand Up @@ -118,7 +116,7 @@ public void storeSettings() {
preferences.setNewLineSeparator(selectedNewLineSeparatorProperty.getValue());
preferences.putBoolean(JabRefPreferences.REFORMAT_FILE_ON_SAVE_AND_EXPORT, alwaysReformatBibProperty.getValue());

preferences.put(StandardField.FILE.getName() + FilePreferences.DIR_SUFFIX, mainFileDirProperty.getValue());
preferences.put(JabRefPreferences.MAIN_FILE_DIRECTORY, mainFileDirProperty.getValue());
preferences.putBoolean(JabRefPreferences.BIB_LOC_AS_PRIMARY_DIR, useBibLocationAsPrimaryProperty.getValue());
preferences.putBoolean(JabRefPreferences.AUTOLINK_USE_REG_EXP_SEARCH_KEY, autolinkUseRegexProperty.getValue());
preferences.putBoolean(JabRefPreferences.AUTOLINK_EXACT_KEY_ONLY, autolinkFileExactBibtexProperty.getValue());
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/org/jabref/logic/layout/format/FileLink.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.jabref.logic.layout.format;

import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

Expand Down Expand Up @@ -55,7 +56,7 @@ public String format(String field) {
// ugly hack, the export routine has set a global variable before
// starting the export, which contains the database's file directory:
if (prefs.getFileDirForDatabase() == null) {
dirs = prefs.getGeneratedDirForDatabase();
dirs = Collections.singletonList(prefs.getMainFileDirectory());
} else {
dirs = prefs.getFileDirForDatabase();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,16 @@

public class FileLinkPreferences {

private final List<String> generatedDirForDatabase;
private final String mainFileDirectory;
private final List<String> fileDirForDatabase;
public FileLinkPreferences(List<String> generatedDirForDatabase, List<String> fileDirForDatabase) {
this.generatedDirForDatabase = generatedDirForDatabase;

public FileLinkPreferences(String mainFileDirectory, List<String> fileDirForDatabase) {
this.mainFileDirectory = mainFileDirectory;
this.fileDirForDatabase = fileDirForDatabase;
}

public List<String> getGeneratedDirForDatabase() {
return generatedDirForDatabase;
public String getMainFileDirectory() {
return mainFileDirectory;
}

public List<String> getFileDirForDatabase() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
Expand Down Expand Up @@ -201,7 +202,7 @@ public String format(String field) {
// ugly hack, the export routine has set a global variable before
// starting the export, which contains the database's file directory:
if ((prefs.getFileDirForDatabase() == null) || prefs.getFileDirForDatabase().isEmpty()) {
dirs = prefs.getGeneratedDirForDatabase();
dirs = Collections.singletonList(prefs.getMainFileDirectory());
} else {
dirs = prefs.getFileDirForDatabase();
}
Expand Down
107 changes: 42 additions & 65 deletions src/main/java/org/jabref/model/database/BibDatabaseContext.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package org.jabref.model.database;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
Expand All @@ -14,8 +13,6 @@
import org.jabref.model.database.shared.DatabaseLocation;
import org.jabref.model.database.shared.DatabaseSynchronizer;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.metadata.FilePreferences;
import org.jabref.model.metadata.MetaData;

Expand Down Expand Up @@ -107,63 +104,34 @@ public boolean isBiblatexMode() {
return getMode() == BibDatabaseMode.BIBLATEX;
}

public List<Path> getFileDirectoriesAsPaths(FilePreferences preferences) {
// Filter for empty string, as this would be expanded to the jar-directory with Paths.get()
return getFileDirectories(preferences).stream()
.filter(s -> !s.isEmpty())
.map(Paths::get)
.map(Path::toAbsolutePath)
.map(Path::normalize)
.collect(Collectors.toList());
}

/**
* @deprecated use {@link #getFileDirectoriesAsPaths(FilePreferences)} instead
*/
@Deprecated
public List<String> getFileDirectories(FilePreferences preferences) {
return getFileDirectories(StandardField.FILE, preferences);
}

/**
* Returns the first existing file directory from {@link #getFileDirectories(FilePreferences)}
*
* @param preferences The FilePreferences
* @return Optional of Path
*/
public Optional<Path> getFirstExistingFileDir(FilePreferences preferences) {
return getFileDirectoriesAsPaths(preferences).stream().filter(Files::exists).findFirst();
}

/**
* Look up the directories set up for the given field type for this database. If no directory is set up, return that
* defined in global preferences. There can be up to three directory definitions for these files: the database's
* metadata can specify a general directory and/or a user-specific directory or the preferences can specify one. <p>
* The settings are prioritized in the following order and the first defined setting is used:
* Look up the directories set up for this database.
* There can be up to three directory definitions for these files: the database's
* metadata can specify a general directory and/or a user-specific directory, or the preferences can specify one.
* <p>
* The settings are prioritized in the following order, and the first defined setting is used:
* <ol>
* <li>metadata</li>
* <li>user-specific directory</li>
* <li>user-specific metadata directory</li>
* <li>general metadata directory</li>
* <li>preferences directory</li>
* <li>BIB file directory</li>
* </ol>
*
* @param field The field
* @param preferences The fileDirectory preferences
* @return The default directory for this field type.
*/
public List<String> getFileDirectories(Field field, FilePreferences preferences) {
List<String> fileDirs = new ArrayList<>();
public List<Path> getFileDirectoriesAsPaths(FilePreferences preferences) {
List<Path> fileDirs = new ArrayList<>();

// 1. metadata user-specific directory
// 1. Metadata user-specific directory
metaData.getUserFileDirectory(preferences.getUser())
.ifPresent(userFileDirectory -> fileDirs.add(getFileDirectoryPath(userFileDirectory)));

// 2. metadata general directory
// 2. Metadata general directory
metaData.getDefaultFileDirectory()
.ifPresent(metaDataDirectory -> fileDirs.add(getFileDirectoryPath(metaDataDirectory)));

// 3. preferences directory
preferences.getFileDirectory(field).ifPresent(path -> fileDirs.add(path.toAbsolutePath().toString()));
// 3. Preferences directory
preferences.getFileDirectory().ifPresent(fileDirs::add);

// 4. BIB file directory
getDatabasePath().ifPresent(dbPath -> {
Expand All @@ -173,38 +141,47 @@ public List<String> getFileDirectories(Field field, FilePreferences preferences)
parentPath = Paths.get(System.getProperty("user.dir"));
}
Objects.requireNonNull(parentPath, "BibTeX database parent path is null");
String parentDir = parentPath.toAbsolutePath().toString();

// Check if we should add it as primary file dir (first in the list) or not:
if (preferences.isBibLocationAsPrimary()) {
fileDirs.add(0, parentDir);
fileDirs.add(0, parentPath);
} else {
fileDirs.add(parentDir);
fileDirs.add(parentPath);
}
});

return fileDirs;
return fileDirs.stream().map(Path::toAbsolutePath).collect(Collectors.toList());
}

/**
* Returns the first existing file directory from {@link #getFileDirectories(FilePreferences)}
*
* @param preferences The FilePreferences
* @return Optional of Path
*/
public Optional<Path> getFirstExistingFileDir(FilePreferences preferences) {
return getFileDirectoriesAsPaths(preferences).stream().filter(Files::exists).findFirst();
}

private String getFileDirectoryPath(String directoryName) {
String dir = directoryName;
/**
* @deprecated use {@link #getFileDirectoriesAsPaths(FilePreferences)} instead
*/
@Deprecated
public List<String> getFileDirectories(FilePreferences preferences) {
return getFileDirectoriesAsPaths(preferences).stream()
.map(directory -> directory.toAbsolutePath().toString())
.collect(Collectors.toList());
}

private Path getFileDirectoryPath(String directoryName) {
Path directory = Path.of(directoryName);
// If this directory is relative, we try to interpret it as relative to
// the file path of this BIB file:
Optional<Path> databaseFile = getDatabasePath();
if (!new File(dir).isAbsolute() && databaseFile.isPresent()) {
Path relDir;
if (".".equals(dir)) {
// if dir is only "current" directory, just use its parent (== real current directory) as path
relDir = databaseFile.get().getParent();
} else {
relDir = databaseFile.get().getParent().resolve(dir);
}
// If this directory actually exists, it is very likely that the
// user wants us to use it:
if (Files.exists(relDir)) {
dir = relDir.toString();
}
if (!directory.isAbsolute() && databaseFile.isPresent()) {
return databaseFile.get().getParent().resolve(directory).normalize();
}
return dir;
return directory;
}

public DatabaseSynchronizer getDBMSSynchronizer() {
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/org/jabref/model/entry/LinkedFile.java
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ public Optional<Path> findIn(List<Path> directories) {
return Optional.empty();
}
} else {
return FileHelper.expandFilenameAsPath(link.get(), directories);
return FileHelper.find(link.get(), directories);
}
} catch (InvalidPathException ex) {
return Optional.empty();
Expand Down
8 changes: 4 additions & 4 deletions src/main/java/org/jabref/model/groups/TexGroup.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,12 @@ public class TexGroup extends AbstractGroup implements FileUpdateListener {

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

private Path filePath;
private final Path filePath;
private Set<String> keysUsedInAux = null;
private final FileUpdateMonitor fileMonitor;
private AuxParser auxParser;
private final AuxParser auxParser;
private final MetaData metaData;
private String user;
private final String user;

TexGroup(String name, GroupHierarchyType context, Path filePath, AuxParser auxParser, FileUpdateMonitor fileMonitor, MetaData metaData, String user) {
super(name, context);
Expand Down Expand Up @@ -126,7 +126,7 @@ private Path relativize(Path path) {

private Path expandPath(Path path) {
List<Path> fileDirectories = getFileDirectoriesAsPaths();
return FileHelper.expandFilenameAsPath(path.toString(), fileDirectories).orElse(path);
return FileHelper.find(path.toString(), fileDirectories).orElse(path);
}

private List<Path> getFileDirectoriesAsPaths() {
Expand Down
Loading

0 comments on commit 79e5106

Please sign in to comment.