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 E (FilePreferences) #8165

Merged
merged 6 commits into from
Oct 19, 2021
Merged
Show file tree
Hide file tree
Changes from 4 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
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package org.jabref.gui.importer;

import java.io.File;
import java.util.List;
import java.util.Optional;

Expand Down Expand Up @@ -28,8 +27,8 @@
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.BibEntryTypesManager;
import org.jabref.model.entry.LinkedFile;
import org.jabref.model.util.FileUpdateMonitor;
import org.jabref.preferences.FilePreferences;
import org.jabref.preferences.PreferencesService;

import org.slf4j.Logger;
Expand Down Expand Up @@ -138,13 +137,11 @@ public void importEntries(List<BibEntry> entriesToImport, boolean shouldDownload
}

// Remember the selection in the dialog
FilePreferences filePreferences = preferences.getFilePreferences()
.withShouldDownloadLinkedFiles(shouldDownloadFiles);
preferences.storeFilePreferences(filePreferences);
preferences.getFilePreferences().setDownloadLinkedFiles(shouldDownloadFiles);

if (shouldDownloadFiles) {
for (BibEntry bibEntry : entriesToImport) {
bibEntry.getFiles().stream().filter(file -> file.isOnlineLink()).forEach(linkedFile ->
bibEntry.getFiles().stream().filter(LinkedFile::isOnlineLink).forEach(linkedFile ->
new LinkedFileViewModel(
linkedFile,
bibEntry,
Expand All @@ -159,7 +156,7 @@ public void importEntries(List<BibEntry> entriesToImport, boolean shouldDownload
new DatabaseMerger(preferences.getKeywordDelimiter()).mergeStrings(databaseContext.getDatabase(), parserResult.getDatabase());
new DatabaseMerger(preferences.getKeywordDelimiter()).mergeMetaData(databaseContext.getMetaData(),
parserResult.getMetaData(),
parserResult.getFile().map(File::getName).orElse("unknown"),
parserResult.getPath().map(path -> path.getFileName().toString()).orElse("unknown"),
parserResult.getDatabase().getEntries());

JabRefGUI.getMainFrame().getCurrentLibraryTab().markBaseChanged();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,6 @@
text="%When downloading files, or moving linked files to the file directory, prefer the BIB file location rather than the file directory set above"/>
</tooltip>
</CheckBox>
<CheckBox fx:id="searchFilesOnOpen" text="%When opening file link, search for matching file if no link is defined"/>
<CheckBox fx:id="openBrowseOnCreate" text="%Automatically open browse dialog when creating new file link"/>
<Label styleClass="sectionHeader" text="%Autolink files"/>
<RadioButton fx:id="autolinkFileStartsBibtex" text="%Autolink files with names starting with the citation key"
toggleGroup="$autolinkToggleGroup"/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,6 @@ public class LinkedFilesTab extends AbstractPreferenceTabView<LinkedFilesTabView
@FXML private RadioButton autolinkFileExactBibtex;
@FXML private RadioButton autolinkUseRegex;
@FXML private TextField autolinkRegexKey;
@FXML private CheckBox searchFilesOnOpen;
@FXML private CheckBox openBrowseOnCreate;

@FXML private ComboBox<String> fileNamePattern;
@FXML private TextField fileDirectoryPattern;
Expand Down Expand Up @@ -59,8 +57,6 @@ public void initialize() {
autolinkUseRegex.selectedProperty().bindBidirectional(viewModel.autolinkUseRegexProperty());
autolinkRegexKey.textProperty().bindBidirectional(viewModel.autolinkRegexKeyProperty());
autolinkRegexKey.disableProperty().bind(autolinkUseRegex.selectedProperty().not());
searchFilesOnOpen.selectedProperty().bindBidirectional(viewModel.searchFilesOnOpenProperty());
openBrowseOnCreate.selectedProperty().bindBidirectional(viewModel.openBrowseOnCreateProperty());
fileNamePattern.valueProperty().bindBidirectional(viewModel.fileNamePatternProperty());
fileNamePattern.itemsProperty().bind(viewModel.defaultFileNamePatternsProperty());
fileDirectoryPattern.textProperty().bindBidirectional(viewModel.fileDirectoryPatternProperty());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,6 @@ public class LinkedFilesTabViewModel implements PreferenceTabViewModel {
private final BooleanProperty autolinkFileExactBibtexProperty = new SimpleBooleanProperty();
private final BooleanProperty autolinkUseRegexProperty = new SimpleBooleanProperty();
private final StringProperty autolinkRegexKeyProperty = new SimpleStringProperty("");
private final BooleanProperty searchFilesOnOpenProperty = new SimpleBooleanProperty();
private final BooleanProperty openBrowseOnCreateProperty = new SimpleBooleanProperty();
private final ListProperty<String> defaultFileNamePatternsProperty =
new SimpleListProperty<>(FXCollections.observableArrayList(FilePreferences.DEFAULT_FILENAME_PATTERNS));
private final StringProperty fileNamePatternProperty = new SimpleStringProperty();
Expand All @@ -44,13 +42,13 @@ public class LinkedFilesTabViewModel implements PreferenceTabViewModel {

private final DialogService dialogService;
private final PreferencesService preferences;
private final FilePreferences initialFilePreferences;
private final FilePreferences filePreferences;
private final AutoLinkPreferences initialAutoLinkPreferences;

public LinkedFilesTabViewModel(DialogService dialogService, PreferencesService preferences) {
this.dialogService = dialogService;
this.preferences = preferences;
this.initialFilePreferences = preferences.getFilePreferences();
this.filePreferences = preferences.getFilePreferences();
this.initialAutoLinkPreferences = preferences.getAutoLinkPreferences();

mainFileDirValidator = new FunctionBasedValidator<>(
Expand All @@ -76,10 +74,10 @@ public LinkedFilesTabViewModel(DialogService dialogService, PreferencesService p
@Override
public void setValues() {
// External files preferences / Attached files preferences / File preferences
mainFileDirectoryProperty.setValue(initialFilePreferences.getFileDirectory().orElse(Path.of("")).toString());
useBibLocationAsPrimaryProperty.setValue(initialFilePreferences.shouldStoreFilesRelativeToBib());
fileNamePatternProperty.setValue(initialFilePreferences.getFileNamePattern());
fileDirectoryPatternProperty.setValue(initialFilePreferences.getFileDirectoryPattern());
mainFileDirectoryProperty.setValue(filePreferences.getFileDirectory().orElse(Path.of("")).toString());
useBibLocationAsPrimaryProperty.setValue(filePreferences.shouldStoreFilesRelativeToBibFile());
fileNamePatternProperty.setValue(filePreferences.getFileNamePattern());
fileDirectoryPatternProperty.setValue(filePreferences.getFileDirectoryPattern());

// Autolink preferences
switch (initialAutoLinkPreferences.getCitationKeyDependency()) {
Expand All @@ -94,13 +92,11 @@ public void setValues() {
@Override
public void storeSettings() {
// External files preferences / Attached files preferences / File preferences
preferences.storeFilePreferences(new FilePreferences(
initialFilePreferences.getUser(),
mainFileDirectoryProperty.getValue(),
useBibLocationAsPrimaryProperty.getValue(),
fileNamePatternProperty.getValue(),
fileDirectoryPatternProperty.getValue(),
initialFilePreferences.shouldDownloadLinkedFiles())); // set in ImportEntriesViewModel
filePreferences.setMainFileDirectory(mainFileDirectoryProperty.getValue());
filePreferences.setStoreFilesRelativeToBibFile(useBibLocationAsPrimaryProperty.getValue());
filePreferences.setFileNamePattern(fileNamePatternProperty.getValue());
filePreferences.setFileDirectoryPattern(fileDirectoryPatternProperty.getValue());
filePreferences.setDownloadLinkedFiles(filePreferences.shouldDownloadLinkedFiles()); // set in ImportEntriesViewModel

// Autolink preferences
AutoLinkPreferences.CitationKeyDependency citationKeyDependency = AutoLinkPreferences.CitationKeyDependency.START;
Expand Down Expand Up @@ -165,14 +161,6 @@ public StringProperty autolinkRegexKeyProperty() {
return autolinkRegexKeyProperty;
}

public BooleanProperty searchFilesOnOpenProperty() {
return searchFilesOnOpenProperty;
}

public BooleanProperty openBrowseOnCreateProperty() {
return openBrowseOnCreateProperty;
}

public ListProperty<String> defaultFileNamePatternsProperty() {
return defaultFileNamePatternsProperty;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,14 +180,14 @@ public UnknownFormatImport importUnknownFormat(Path filePath, FileUpdateMonitor

try {
UnknownFormatImport unknownFormatImport = importUnknownFormat(importer -> importer.importDatabase(filePath, importFormatPreferences.getEncoding()), importer -> importer.isRecognizedFormat(filePath, importFormatPreferences.getEncoding()));
unknownFormatImport.parserResult.setFile(filePath.toFile());
unknownFormatImport.parserResult.setPath(filePath);
return unknownFormatImport;
} catch (ImportException e) {
// If all importers fail, try to read the file as BibTeX
try {
ParserResult parserResult = OpenDatabase.loadDatabase(filePath, importFormatPreferences, fileMonitor);
if (parserResult.getDatabase().hasEntries() || !parserResult.getDatabase().hasNoStrings()) {
parserResult.setFile(filePath.toFile());
parserResult.setPath(filePath);
return new UnknownFormatImport(ImportFormatReader.BIBTEX_FORMAT, parserResult);
} else {
throw new ImportException(Localization.lang("Could not find a suitable import format."));
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/org/jabref/logic/importer/Importer.java
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ public ParserResult importDatabase(Path filePath, Charset encoding) throws IOExc
try (BufferedReader bufferedReader = getReader(filePath, encoding)) {
ParserResult parserResult = importDatabase(bufferedReader);
parserResult.getMetaData().setEncoding(encoding);
parserResult.setFile(filePath.toFile());
parserResult.setPath(filePath);

// Make sure the mode is always set
if (parserResult.getMetaData().getMode().isEmpty()) {
Expand Down
14 changes: 2 additions & 12 deletions src/main/java/org/jabref/logic/importer/ParserResult.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package org.jabref.logic.importer;

import java.io.File;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
Expand Down Expand Up @@ -96,17 +95,8 @@ public Optional<Path> getPath() {
return Optional.ofNullable(file);
}

/**
* @return the file object of the database file
* @deprecated use {@link #getPath()}} instead
*/
@Deprecated
public Optional<File> getFile() {
return Optional.ofNullable(file).map(Path::toFile);
}

public void setFile(File f) {
file = f.toPath();
public void setPath(Path path) {
file = path;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ public List<Path> getFileDirectories(FilePreferences preferences) {
preferences.getFileDirectory().ifPresent(fileDirs::add);

// 4. BIB file directory
if (preferences.shouldStoreFilesRelativeToBib()) {
if (preferences.shouldStoreFilesRelativeToBibFile()) {
getDatabasePath().ifPresent(dbPath -> {
Path parentPath = dbPath.getParent();
if (parentPath == null) {
Expand Down Expand Up @@ -221,7 +221,7 @@ public Path getFulltextIndexPath() {
Path appData = getFulltextIndexBasePath();

if (getDatabasePath().isPresent()) {
LOGGER.info("Index path for {} is {}", getDatabasePath().get(), appData.toString());
LOGGER.info("Index path for {} is {}", getDatabasePath().get(), appData);
return appData.resolve(String.valueOf(this.getDatabasePath().get().hashCode()));
}

Expand Down
92 changes: 66 additions & 26 deletions src/main/java/org/jabref/preferences/FilePreferences.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,63 +3,103 @@
import java.nio.file.Path;
import java.util.Optional;

import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;

import org.jabref.model.strings.StringUtil;

public class FilePreferences {

public static final String[] DEFAULT_FILENAME_PATTERNS = new String[] {"[bibtexkey]", "[bibtexkey] - [title]"};

private final String user;
private final String mainFileDirectory;
private final boolean shouldStoreFilesRelativeToBibFile;
private final String fileNamePattern;
private final String fileDirPattern;
private boolean shouldDownloadLinkedFiles;
private final StringProperty user = new SimpleStringProperty();
private final SimpleStringProperty mainFileDirectory = new SimpleStringProperty();
private final BooleanProperty storeFilesRelativeToBibFile = new SimpleBooleanProperty();
private final StringProperty fileNamePattern = new SimpleStringProperty();
private final StringProperty fileDirectoryPattern = new SimpleStringProperty();
private final BooleanProperty downloadLinkedFiles = new SimpleBooleanProperty();

public FilePreferences(String user,
String mainFileDirectory,
boolean shouldStoreFilesRelativeToBibFile,
boolean storeFilesRelativeToBibFile,
String fileNamePattern,
String fileDirPattern,
boolean shouldDownloadLinkedFiles) {
this.user = user;
this.mainFileDirectory = mainFileDirectory;
this.shouldStoreFilesRelativeToBibFile = shouldStoreFilesRelativeToBibFile;
this.fileNamePattern = fileNamePattern;
this.fileDirPattern = fileDirPattern;
this.shouldDownloadLinkedFiles = shouldDownloadLinkedFiles;
String fileDirectoryPattern,
boolean downloadLinkedFiles) {
this.user.setValue(user);
this.mainFileDirectory.setValue(mainFileDirectory);
this.storeFilesRelativeToBibFile.setValue(storeFilesRelativeToBibFile);
this.fileNamePattern.setValue(fileNamePattern);
this.fileDirectoryPattern.setValue(fileDirectoryPattern);
this.downloadLinkedFiles.setValue(downloadLinkedFiles);
}

public String getUser() {
return user;
public String getUser() { // Read only
return user.getValue();
}

public Optional<Path> getFileDirectory() {
if (StringUtil.isBlank(mainFileDirectory)) {
if (StringUtil.isBlank(mainFileDirectory.getValue())) {
return Optional.empty();
} else {
return Optional.of(Path.of(mainFileDirectory));
return Optional.of(Path.of(mainFileDirectory.getValue()));
}
}

public boolean shouldStoreFilesRelativeToBib() {
return shouldStoreFilesRelativeToBibFile;
public StringProperty mainFileDirectoryProperty() {
return mainFileDirectory;
}

public void setMainFileDirectory(String mainFileDirectory) {
this.mainFileDirectory.set(mainFileDirectory);
}

public boolean shouldStoreFilesRelativeToBibFile() {
return storeFilesRelativeToBibFile.get();
}

public BooleanProperty storeFilesRelativeToBibFileProperty() {
return storeFilesRelativeToBibFile;
}

public void setStoreFilesRelativeToBibFile(boolean shouldStoreFilesRelativeToBibFile) {
this.storeFilesRelativeToBibFile.set(shouldStoreFilesRelativeToBibFile);
}

public String getFileNamePattern() {
return fileNamePattern.get();
}

public StringProperty fileNamePatternProperty() {
return fileNamePattern;
}

public void setFileNamePattern(String fileNamePattern) {
this.fileNamePattern.set(fileNamePattern);
}

public String getFileDirectoryPattern() {
return fileDirPattern;
return fileDirectoryPattern.get();
}

public StringProperty fileDirectoryPatternProperty() {
return fileDirectoryPattern;
}

public void setFileDirectoryPattern(String fileDirectoryPattern) {
this.fileDirectoryPattern.set(fileDirectoryPattern);
}

public boolean shouldDownloadLinkedFiles() {
return shouldDownloadLinkedFiles;
return downloadLinkedFiles.get();
}

public BooleanProperty downloadLinkedFilesProperty() {
return downloadLinkedFiles;
}

public FilePreferences withShouldDownloadLinkedFiles(boolean newShouldDownloadLinkedFiles) {
this.shouldDownloadLinkedFiles = newShouldDownloadLinkedFiles;
return this;
public void setDownloadLinkedFiles(boolean shouldDownloadLinkedFiles) {
this.downloadLinkedFiles.set(shouldDownloadLinkedFiles);
}
}
25 changes: 15 additions & 10 deletions src/main/java/org/jabref/preferences/JabRefPreferences.java
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,7 @@ public class JabRefPreferences implements PreferencesService {
private ProtectedTermsPreferences protectedTermsPreferences;
private MrDlibPreferences mrDlibPreferences;
private EntryEditorPreferences entryEditorPreferences;
private FilePreferences filePreferences;

// The constructor is made private to enforce this as a singleton class:
private JabRefPreferences() {
Expand Down Expand Up @@ -2179,22 +2180,26 @@ public void setWorkingDirectory(Path directory) {

@Override
public FilePreferences getFilePreferences() {
return new FilePreferences(
if (Objects.nonNull(filePreferences)) {
return filePreferences;
}

filePreferences = new FilePreferences(
getUser(),
get(MAIN_FILE_DIRECTORY),
getBoolean(STORE_RELATIVE_TO_BIB),
get(IMPORT_FILENAMEPATTERN),
get(IMPORT_FILEDIRPATTERN),
getBoolean(DOWNLOAD_LINKED_FILES));
}
getBoolean(DOWNLOAD_LINKED_FILES)
);

@Override
public void storeFilePreferences(FilePreferences preferences) {
put(MAIN_FILE_DIRECTORY, preferences.getFileDirectory().map(Path::toString).orElse(""));
putBoolean(STORE_RELATIVE_TO_BIB, preferences.shouldStoreFilesRelativeToBib());
put(IMPORT_FILENAMEPATTERN, preferences.getFileNamePattern());
put(IMPORT_FILEDIRPATTERN, preferences.getFileDirectoryPattern());
putBoolean(DOWNLOAD_LINKED_FILES, preferences.shouldDownloadLinkedFiles());
EasyBind.subscribe(filePreferences.mainFileDirectoryProperty(), newValue -> put(MAIN_FILE_DIRECTORY, filePreferences.getFileDirectory().map(Path::toString).orElse("")));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Subscripe runs the lambda immediately, which leads to an unnecessary write of the preferences. Easybind.listen should be used instead. https://github.com/tobiasdiez/EasyBind#subscribe-to-values

EasyBind.subscribe(filePreferences.storeFilesRelativeToBibFileProperty(), newValue -> putBoolean(STORE_RELATIVE_TO_BIB, newValue));
EasyBind.subscribe(filePreferences.fileNamePatternProperty(), newValue -> put(IMPORT_FILENAMEPATTERN, newValue));
EasyBind.subscribe(filePreferences.fileDirectoryPatternProperty(), newValue -> put(IMPORT_FILEDIRPATTERN, newValue));
EasyBind.subscribe(filePreferences.downloadLinkedFilesProperty(), newValue -> putBoolean(DOWNLOAD_LINKED_FILES, newValue));

return filePreferences;
}

@Override
Expand Down
2 changes: 0 additions & 2 deletions src/main/java/org/jabref/preferences/PreferencesService.java
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,6 @@ public interface PreferencesService {

FilePreferences getFilePreferences();

void storeFilePreferences(FilePreferences filePreferences);

FieldWriterPreferences getFieldWriterPreferences();

FileHistory getFileHistory();
Expand Down
Loading