repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
|---|---|---|---|---|---|---|
null |
jabref-main/src/main/java/org/jabref/gui/shared/SharedDatabaseLoginDialogViewModel.java
|
package org.jabref.gui.shared;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.GeneralSecurityException;
import java.sql.SQLException;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.ButtonType;
import org.jabref.gui.AbstractViewModel;
import org.jabref.gui.DialogService;
import org.jabref.gui.Globals;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.LibraryTab;
import org.jabref.gui.exporter.SaveDatabaseAction;
import org.jabref.gui.help.HelpAction;
import org.jabref.gui.util.FileDialogConfiguration;
import org.jabref.gui.util.FileFilterConverter;
import org.jabref.logic.help.HelpFile;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.shared.DBMSConnectionProperties;
import org.jabref.logic.shared.DBMSConnectionPropertiesBuilder;
import org.jabref.logic.shared.DBMSType;
import org.jabref.logic.shared.DatabaseLocation;
import org.jabref.logic.shared.DatabaseNotSupportedException;
import org.jabref.logic.shared.exception.InvalidDBMSConnectionPropertiesException;
import org.jabref.logic.shared.prefs.SharedDatabasePreferences;
import org.jabref.logic.shared.security.Password;
import org.jabref.logic.util.StandardFileType;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.util.FileUpdateMonitor;
import org.jabref.preferences.PreferencesService;
import com.tobiasdiez.easybind.EasyBind;
import de.saxsys.mvvmfx.utils.validation.CompositeValidator;
import de.saxsys.mvvmfx.utils.validation.FunctionBasedValidator;
import de.saxsys.mvvmfx.utils.validation.ValidationMessage;
import de.saxsys.mvvmfx.utils.validation.ValidationStatus;
import de.saxsys.mvvmfx.utils.validation.Validator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SharedDatabaseLoginDialogViewModel extends AbstractViewModel {
private static final Logger LOGGER = LoggerFactory.getLogger(SharedDatabaseLoginDialogViewModel.class);
private final ObjectProperty<DBMSType> selectedDBMSType = new SimpleObjectProperty<>(DBMSType.values()[0]);
private final StringProperty database = new SimpleStringProperty("");
private final StringProperty host = new SimpleStringProperty("");
private final StringProperty port = new SimpleStringProperty("");
private final StringProperty user = new SimpleStringProperty("");
private final StringProperty password = new SimpleStringProperty("");
private final StringProperty folder = new SimpleStringProperty("");
private final BooleanProperty autosave = new SimpleBooleanProperty();
private final BooleanProperty rememberPassword = new SimpleBooleanProperty();
private final BooleanProperty loading = new SimpleBooleanProperty();
private final StringProperty keystore = new SimpleStringProperty("");
private final BooleanProperty useSSL = new SimpleBooleanProperty();
private final StringProperty keyStorePasswordProperty = new SimpleStringProperty("");
private final StringProperty serverTimezone = new SimpleStringProperty("");
private final JabRefFrame frame;
private final DialogService dialogService;
private final PreferencesService preferencesService;
private final SharedDatabasePreferences sharedDatabasePreferences = new SharedDatabasePreferences();
private final FileUpdateMonitor fileUpdateMonitor;
private final Validator databaseValidator;
private final Validator hostValidator;
private final Validator portValidator;
private final Validator userValidator;
private final Validator folderValidator;
private final Validator keystoreValidator;
private final CompositeValidator formValidator;
public SharedDatabaseLoginDialogViewModel(JabRefFrame frame,
DialogService dialogService,
PreferencesService preferencesService,
FileUpdateMonitor fileUpdateMonitor) {
this.frame = frame;
this.dialogService = dialogService;
this.preferencesService = preferencesService;
this.fileUpdateMonitor = fileUpdateMonitor;
EasyBind.subscribe(selectedDBMSType, selected -> port.setValue(Integer.toString(selected.getDefaultPort())));
Predicate<String> notEmpty = input -> (input != null) && !input.trim().isEmpty();
Predicate<String> fileExists = input -> Files.exists(Path.of(input));
Predicate<String> notEmptyAndfilesExist = notEmpty.and(fileExists);
databaseValidator = new FunctionBasedValidator<>(database, notEmpty, ValidationMessage.error(Localization.lang("Required field \"%0\" is empty.", Localization.lang("Library"))));
hostValidator = new FunctionBasedValidator<>(host, notEmpty, ValidationMessage.error(Localization.lang("Required field \"%0\" is empty.", Localization.lang("Port"))));
portValidator = new FunctionBasedValidator<>(port, notEmpty, ValidationMessage.error(Localization.lang("Required field \"%0\" is empty.", Localization.lang("Host"))));
userValidator = new FunctionBasedValidator<>(user, notEmpty, ValidationMessage.error(Localization.lang("Required field \"%0\" is empty.", Localization.lang("User"))));
folderValidator = new FunctionBasedValidator<>(folder, notEmptyAndfilesExist, ValidationMessage.error(Localization.lang("Please enter a valid file path.")));
keystoreValidator = new FunctionBasedValidator<>(keystore, notEmptyAndfilesExist, ValidationMessage.error(Localization.lang("Please enter a valid file path.")));
formValidator = new CompositeValidator();
formValidator.addValidators(databaseValidator, hostValidator, portValidator, userValidator);
applyPreferences();
}
public boolean openDatabase() {
DBMSConnectionProperties connectionProperties = new DBMSConnectionPropertiesBuilder()
.setType(selectedDBMSType.getValue())
.setHost(host.getValue())
.setPort(Integer.parseInt(port.getValue()))
.setDatabase(database.getValue())
.setUser(user.getValue())
.setPassword(password.getValue())
.setUseSSL(useSSL.getValue())
// Authorize client to retrieve RSA server public key when serverRsaPublicKeyFile is not set (for sha256_password and caching_sha2_password authentication password)
.setAllowPublicKeyRetrieval(true)
.setKeyStore(keystore.getValue())
.setServerTimezone(serverTimezone.getValue())
.createDBMSConnectionProperties();
setupKeyStore();
return openSharedDatabase(connectionProperties);
}
private void setupKeyStore() {
System.setProperty("javax.net.ssl.trustStore", keystore.getValue());
System.setProperty("javax.net.ssl.trustStorePassword", keyStorePasswordProperty.getValue());
System.setProperty("javax.net.debug", "ssl");
}
private boolean openSharedDatabase(DBMSConnectionProperties connectionProperties) {
if (isSharedDatabaseAlreadyPresent(connectionProperties)) {
dialogService.showWarningDialogAndWait(Localization.lang("Shared database connection"),
Localization.lang("You are already connected to a database using entered connection details."));
return true;
}
if (autosave.get()) {
Path localFilePath = Path.of(folder.getValue());
if (Files.exists(localFilePath) && !Files.isDirectory(localFilePath)) {
boolean overwriteFilePressed = dialogService.showConfirmationDialogAndWait(Localization.lang("Existing file"),
Localization.lang("'%0' exists. Overwrite file?", localFilePath.getFileName().toString()),
Localization.lang("Overwrite file"),
Localization.lang("Cancel"));
if (!overwriteFilePressed) {
return true;
}
}
}
loading.set(true);
try {
SharedDatabaseUIManager manager = new SharedDatabaseUIManager(frame, preferencesService, fileUpdateMonitor);
LibraryTab libraryTab = manager.openNewSharedDatabaseTab(connectionProperties);
setPreferences();
if (!folder.getValue().isEmpty() && autosave.get()) {
try {
new SaveDatabaseAction(libraryTab, preferencesService, Globals.entryTypesManager).saveAs(Path.of(folder.getValue()));
} catch (Throwable e) {
LOGGER.error("Error while saving the database", e);
}
}
return true;
} catch (SQLException | InvalidDBMSConnectionPropertiesException exception) {
frame.getDialogService().showErrorDialogAndWait(Localization.lang("Connection error"), exception);
} catch (DatabaseNotSupportedException exception) {
ButtonType openHelp = new ButtonType("Open Help", ButtonData.OTHER);
Optional<ButtonType> result = dialogService.showCustomButtonDialogAndWait(AlertType.INFORMATION,
Localization.lang("Migration help information"),
Localization.lang("Entered database has obsolete structure and is no longer supported.")
+ "\n" +
Localization.lang("Click help to learn about the migration of pre-3.6 databases.")
+ "\n" +
Localization.lang("However, a new database was created alongside the pre-3.6 one."),
ButtonType.OK, openHelp);
result.filter(btn -> btn.equals(openHelp)).ifPresent(btn -> new HelpAction(HelpFile.SQL_DATABASE_MIGRATION, dialogService).execute());
result.filter(btn -> btn.equals(ButtonType.OK)).ifPresent(btn -> openSharedDatabase(connectionProperties));
}
loading.set(false);
return false;
}
private void setPreferences() {
sharedDatabasePreferences.setType(selectedDBMSType.getValue().toString());
sharedDatabasePreferences.setHost(host.getValue());
sharedDatabasePreferences.setPort(port.getValue());
sharedDatabasePreferences.setName(database.getValue());
sharedDatabasePreferences.setUser(user.getValue());
sharedDatabasePreferences.setUseSSL(useSSL.getValue());
sharedDatabasePreferences.setKeystoreFile(keystore.getValue());
sharedDatabasePreferences.setServerTimezone(serverTimezone.getValue());
if (rememberPassword.get()) {
try {
sharedDatabasePreferences.setPassword(new Password(password.getValue(), user.getValue()).encrypt());
} catch (GeneralSecurityException | UnsupportedEncodingException e) {
LOGGER.error("Could not store the password due to encryption problems.", e);
}
} else {
sharedDatabasePreferences.clearPassword(); // for the case that the password is already set
}
sharedDatabasePreferences.setRememberPassword(rememberPassword.get());
sharedDatabasePreferences.setFolder(folder.getValue());
sharedDatabasePreferences.setAutosave(autosave.get());
}
/**
* Fetches possibly saved data and configures the control elements respectively.
*/
private void applyPreferences() {
Optional<String> sharedDatabaseType = sharedDatabasePreferences.getType();
Optional<String> sharedDatabaseHost = sharedDatabasePreferences.getHost();
Optional<String> sharedDatabasePort = sharedDatabasePreferences.getPort();
Optional<String> sharedDatabaseName = sharedDatabasePreferences.getName();
Optional<String> sharedDatabaseUser = sharedDatabasePreferences.getUser();
Optional<String> sharedDatabasePassword = sharedDatabasePreferences.getPassword();
boolean sharedDatabaseRememberPassword = sharedDatabasePreferences.getRememberPassword();
Optional<String> sharedDatabaseFolder = sharedDatabasePreferences.getFolder();
boolean sharedDatabaseAutosave = sharedDatabasePreferences.getAutosave();
Optional<String> sharedDatabaseKeystoreFile = sharedDatabasePreferences.getKeyStoreFile();
if (sharedDatabaseType.isPresent()) {
Optional<DBMSType> dbmsType = DBMSType.fromString(sharedDatabaseType.get());
dbmsType.ifPresent(selectedDBMSType::set);
}
sharedDatabaseHost.ifPresent(host::set);
sharedDatabasePort.ifPresent(port::set);
sharedDatabaseName.ifPresent(database::set);
sharedDatabaseUser.ifPresent(user::set);
sharedDatabaseKeystoreFile.ifPresent(keystore::set);
useSSL.setValue(sharedDatabasePreferences.isUseSSL());
if (sharedDatabasePassword.isPresent() && sharedDatabaseUser.isPresent()) {
try {
password.setValue(new Password(sharedDatabasePassword.get().toCharArray(), sharedDatabaseUser.get()).decrypt());
} catch (GeneralSecurityException | UnsupportedEncodingException e) {
LOGGER.error("Could not read the password due to decryption problems.", e);
}
}
rememberPassword.set(sharedDatabaseRememberPassword);
sharedDatabaseFolder.ifPresent(folder::set);
autosave.set(sharedDatabaseAutosave);
}
private boolean isSharedDatabaseAlreadyPresent(DBMSConnectionProperties connectionProperties) {
List<LibraryTab> panels = frame.getLibraryTabs();
return panels.parallelStream().anyMatch(panel -> {
BibDatabaseContext context = panel.getBibDatabaseContext();
return (context.getLocation() == DatabaseLocation.SHARED) &&
connectionProperties.equals(context.getDBMSSynchronizer().getConnectionProperties());
});
}
public void showSaveDbToFileDialog() {
FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
.addExtensionFilter(StandardFileType.BIBTEX_DB)
.withDefaultExtension(StandardFileType.BIBTEX_DB)
.withInitialDirectory(preferencesService.getFilePreferences().getWorkingDirectory())
.build();
Optional<Path> exportPath = dialogService.showFileSaveDialog(fileDialogConfiguration);
exportPath.ifPresent(path -> folder.setValue(path.toString()));
}
public void showOpenKeystoreFileDialog() {
FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
.addExtensionFilter(FileFilterConverter.ANY_FILE)
.addExtensionFilter(StandardFileType.JAVA_KEYSTORE)
.withDefaultExtension(StandardFileType.JAVA_KEYSTORE)
.withInitialDirectory(preferencesService.getFilePreferences().getWorkingDirectory())
.build();
Optional<Path> keystorePath = dialogService.showFileOpenDialog(fileDialogConfiguration);
keystorePath.ifPresent(path -> keystore.setValue(path.toString()));
}
public StringProperty databaseproperty() {
return database;
}
public StringProperty hostProperty() {
return host;
}
public StringProperty portProperty() {
return port;
}
public StringProperty userProperty() {
return user;
}
public StringProperty passwordProperty() {
return password;
}
public BooleanProperty autosaveProperty() {
return autosave;
}
public BooleanProperty rememberPasswordProperty() {
return rememberPassword;
}
public StringProperty folderProperty() {
return folder;
}
public StringProperty keyStoreProperty() {
return keystore;
}
public StringProperty keyStorePasswordProperty() {
return keyStorePasswordProperty;
}
public BooleanProperty useSSLProperty() {
return useSSL;
}
public ObjectProperty<DBMSType> selectedDbmstypeProperty() {
return selectedDBMSType;
}
public BooleanProperty loadingProperty() {
return loading;
}
public ValidationStatus dbValidation() {
return databaseValidator.getValidationStatus();
}
public ValidationStatus hostValidation() {
return hostValidator.getValidationStatus();
}
public ValidationStatus portValidation() {
return portValidator.getValidationStatus();
}
public ValidationStatus userValidation() {
return userValidator.getValidationStatus();
}
public ValidationStatus folderValidation() {
return folderValidator.getValidationStatus();
}
public ValidationStatus keystoreValidation() {
return keystoreValidator.getValidationStatus();
}
public ValidationStatus formValidation() {
return formValidator.getValidationStatus();
}
public StringProperty serverTimezoneProperty() {
return serverTimezone;
}
}
| 17,558
| 44.965969
| 186
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/shared/SharedDatabaseUIManager.java
|
package org.jabref.gui.shared;
import java.sql.SQLException;
import java.util.Objects;
import java.util.Optional;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.ButtonType;
import org.jabref.gui.DialogService;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.LibraryTab;
import org.jabref.gui.entryeditor.EntryEditor;
import org.jabref.gui.exporter.SaveDatabaseAction;
import org.jabref.gui.mergeentries.EntriesMergeResult;
import org.jabref.gui.mergeentries.MergeEntriesDialog;
import org.jabref.gui.undo.UndoableRemoveEntries;
import org.jabref.logic.importer.ParserResult;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.shared.DBMSConnection;
import org.jabref.logic.shared.DBMSConnectionProperties;
import org.jabref.logic.shared.DBMSSynchronizer;
import org.jabref.logic.shared.DatabaseNotSupportedException;
import org.jabref.logic.shared.DatabaseSynchronizer;
import org.jabref.logic.shared.event.ConnectionLostEvent;
import org.jabref.logic.shared.event.SharedEntriesNotPresentEvent;
import org.jabref.logic.shared.event.UpdateRefusedEvent;
import org.jabref.logic.shared.exception.InvalidDBMSConnectionPropertiesException;
import org.jabref.logic.shared.exception.NotASharedDatabaseException;
import org.jabref.logic.shared.prefs.SharedDatabasePreferences;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.util.FileUpdateMonitor;
import org.jabref.preferences.PreferencesService;
import com.google.common.eventbus.Subscribe;
public class SharedDatabaseUIManager {
private final JabRefFrame jabRefFrame;
private DatabaseSynchronizer dbmsSynchronizer;
private final DialogService dialogService;
private final PreferencesService preferencesService;
private final FileUpdateMonitor fileUpdateMonitor;
public SharedDatabaseUIManager(JabRefFrame jabRefFrame, PreferencesService preferencesService, FileUpdateMonitor fileUpdateMonitor) {
this.jabRefFrame = jabRefFrame;
this.dialogService = jabRefFrame.getDialogService();
this.preferencesService = preferencesService;
this.fileUpdateMonitor = fileUpdateMonitor;
}
@Subscribe
public void listen(ConnectionLostEvent connectionLostEvent) {
ButtonType reconnect = new ButtonType(Localization.lang("Reconnect"), ButtonData.YES);
ButtonType workOffline = new ButtonType(Localization.lang("Work offline"), ButtonData.NO);
ButtonType closeLibrary = new ButtonType(Localization.lang("Close library"), ButtonData.CANCEL_CLOSE);
Optional<ButtonType> answer = dialogService.showCustomButtonDialogAndWait(AlertType.WARNING,
Localization.lang("Connection lost"),
Localization.lang("The connection to the server has been terminated."),
reconnect,
workOffline,
closeLibrary);
if (answer.isPresent()) {
if (answer.get().equals(reconnect)) {
jabRefFrame.closeCurrentTab();
dialogService.showCustomDialogAndWait(new SharedDatabaseLoginDialogView(jabRefFrame));
} else if (answer.get().equals(workOffline)) {
connectionLostEvent.getBibDatabaseContext().convertToLocalDatabase();
jabRefFrame.getLibraryTabs().forEach(tab -> tab.updateTabTitle(tab.isModified()));
jabRefFrame.getDialogService().notify(Localization.lang("Working offline."));
}
} else {
jabRefFrame.closeCurrentTab();
}
}
@Subscribe
public void listen(UpdateRefusedEvent updateRefusedEvent) {
jabRefFrame.getDialogService().notify(Localization.lang("Update refused."));
BibEntry localBibEntry = updateRefusedEvent.getLocalBibEntry();
BibEntry sharedBibEntry = updateRefusedEvent.getSharedBibEntry();
String message = Localization.lang("Update could not be performed due to existing change conflicts.") + "\r\n" +
Localization.lang("You are not working on the newest version of BibEntry.") + "\r\n" +
Localization.lang("Shared version: %0", String.valueOf(sharedBibEntry.getSharedBibEntryData().getVersion())) + "\r\n" +
Localization.lang("Local version: %0", String.valueOf(localBibEntry.getSharedBibEntryData().getVersion())) + "\r\n" +
Localization.lang("Press \"Merge entries\" to merge the changes and resolve this problem.") + "\r\n" +
Localization.lang("Canceling this operation will leave your changes unsynchronized.");
ButtonType merge = new ButtonType(Localization.lang("Merge entries"), ButtonBar.ButtonData.YES);
Optional<ButtonType> response = dialogService.showCustomButtonDialogAndWait(AlertType.CONFIRMATION, Localization.lang("Update refused"), message, ButtonType.CANCEL, merge);
if (response.isPresent() && response.get().equals(merge)) {
MergeEntriesDialog dialog = new MergeEntriesDialog(localBibEntry, sharedBibEntry, preferencesService.getBibEntryPreferences());
dialog.setTitle(Localization.lang("Update refused"));
Optional<BibEntry> mergedEntry = dialogService.showCustomDialogAndWait(dialog).map(EntriesMergeResult::mergedEntry);
mergedEntry.ifPresent(mergedBibEntry -> {
mergedBibEntry.getSharedBibEntryData().setSharedID(sharedBibEntry.getSharedBibEntryData().getSharedID());
mergedBibEntry.getSharedBibEntryData().setVersion(sharedBibEntry.getSharedBibEntryData().getVersion());
dbmsSynchronizer.synchronizeSharedEntry(mergedBibEntry);
dbmsSynchronizer.synchronizeLocalDatabase();
});
}
}
@Subscribe
public void listen(SharedEntriesNotPresentEvent event) {
LibraryTab libraryTab = jabRefFrame.getCurrentLibraryTab();
EntryEditor entryEditor = libraryTab.getEntryEditor();
libraryTab.getUndoManager().addEdit(new UndoableRemoveEntries(libraryTab.getDatabase(), event.getBibEntries()));
if (Objects.nonNull(entryEditor) && (event.getBibEntries().contains(entryEditor.getEntry()))) {
dialogService.showInformationDialogAndWait(Localization.lang("Shared entry is no longer present"),
Localization.lang("The entry you currently work on has been deleted on the shared side.")
+ "\n"
+ Localization.lang("You can restore the entry using the \"Undo\" operation."));
libraryTab.closeBottomPane();
}
}
/**
* Opens a new shared database tab with the given {@link DBMSConnectionProperties}.
*
* @param dbmsConnectionProperties Connection data
* @return BasePanel which also used by {@link SaveDatabaseAction}
*/
public LibraryTab openNewSharedDatabaseTab(DBMSConnectionProperties dbmsConnectionProperties)
throws SQLException, DatabaseNotSupportedException, InvalidDBMSConnectionPropertiesException {
BibDatabaseContext bibDatabaseContext = new BibDatabaseContext();
bibDatabaseContext.setMode(preferencesService.getLibraryPreferences().getDefaultBibDatabaseMode());
DBMSSynchronizer synchronizer = new DBMSSynchronizer(
bibDatabaseContext,
preferencesService.getBibEntryPreferences().getKeywordSeparator(),
preferencesService.getCitationKeyPatternPreferences().getKeyPattern(),
fileUpdateMonitor);
bibDatabaseContext.convertToSharedDatabase(synchronizer);
dbmsSynchronizer = bibDatabaseContext.getDBMSSynchronizer();
dbmsSynchronizer.openSharedDatabase(new DBMSConnection(dbmsConnectionProperties));
dbmsSynchronizer.registerListener(this);
jabRefFrame.getDialogService().notify(Localization.lang("Connection to %0 server established.", dbmsConnectionProperties.getType().toString()));
return jabRefFrame.addTab(bibDatabaseContext, true);
}
public void openSharedDatabaseFromParserResult(ParserResult parserResult)
throws SQLException, DatabaseNotSupportedException, InvalidDBMSConnectionPropertiesException,
NotASharedDatabaseException {
Optional<String> sharedDatabaseIDOptional = parserResult.getDatabase().getSharedDatabaseID();
if (sharedDatabaseIDOptional.isEmpty()) {
throw new NotASharedDatabaseException();
}
String sharedDatabaseID = sharedDatabaseIDOptional.get();
DBMSConnectionProperties dbmsConnectionProperties = new DBMSConnectionProperties(new SharedDatabasePreferences(sharedDatabaseID));
BibDatabaseContext bibDatabaseContext = new BibDatabaseContext();
bibDatabaseContext.setMode(preferencesService.getLibraryPreferences().getDefaultBibDatabaseMode());
DBMSSynchronizer synchronizer = new DBMSSynchronizer(
bibDatabaseContext,
preferencesService.getBibEntryPreferences().getKeywordSeparator(),
preferencesService.getCitationKeyPatternPreferences().getKeyPattern(),
fileUpdateMonitor);
bibDatabaseContext.convertToSharedDatabase(synchronizer);
bibDatabaseContext.getDatabase().setSharedDatabaseID(sharedDatabaseID);
bibDatabaseContext.setDatabasePath(parserResult.getDatabaseContext().getDatabasePath().orElse(null));
dbmsSynchronizer = bibDatabaseContext.getDBMSSynchronizer();
dbmsSynchronizer.openSharedDatabase(new DBMSConnection(dbmsConnectionProperties));
dbmsSynchronizer.registerListener(this);
parserResult.setDatabaseContext(bibDatabaseContext);
jabRefFrame.getDialogService().notify(Localization.lang("Connection to %0 server established.", dbmsConnectionProperties.getType().toString()));
}
}
| 9,971
| 52.042553
| 180
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/sidepane/GroupsSidePaneComponent.java
|
package org.jabref.gui.sidepane;
import javafx.scene.control.Button;
import org.jabref.gui.DialogService;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.groups.GroupModeViewModel;
import org.jabref.gui.groups.GroupViewMode;
import org.jabref.gui.groups.GroupsPreferences;
import org.jabref.gui.icon.IconTheme;
import org.jabref.logic.l10n.Localization;
import com.tobiasdiez.easybind.EasyBind;
public class GroupsSidePaneComponent extends SidePaneComponent {
private final GroupsPreferences groupsPreferences;
private final DialogService dialogService;
private final Button intersectionUnionToggle = IconTheme.JabRefIcons.GROUP_INTERSECTION.asButton();
public GroupsSidePaneComponent(SimpleCommand closeCommand,
SimpleCommand moveUpCommand,
SimpleCommand moveDownCommand,
SidePaneContentFactory contentFactory,
GroupsPreferences groupsPreferences,
DialogService dialogService) {
super(SidePaneType.GROUPS, closeCommand, moveUpCommand, moveDownCommand, contentFactory);
this.groupsPreferences = groupsPreferences;
this.dialogService = dialogService;
setupIntersectionUnionToggle();
EasyBind.subscribe(groupsPreferences.groupViewModeProperty(), mode -> {
GroupModeViewModel modeViewModel = new GroupModeViewModel(mode);
intersectionUnionToggle.setGraphic(modeViewModel.getUnionIntersectionGraphic());
intersectionUnionToggle.setTooltip(modeViewModel.getUnionIntersectionTooltip());
});
}
private void setupIntersectionUnionToggle() {
addExtraButtonToHeader(intersectionUnionToggle, 0);
intersectionUnionToggle.setOnAction(event -> new ToggleUnionIntersectionAction().execute());
}
private class ToggleUnionIntersectionAction extends SimpleCommand {
@Override
public void execute() {
GroupViewMode mode = groupsPreferences.getGroupViewMode();
if (mode == GroupViewMode.UNION) {
groupsPreferences.setGroupViewMode(GroupViewMode.INTERSECTION);
dialogService.notify(Localization.lang("Group view mode set to intersection"));
} else if (mode == GroupViewMode.INTERSECTION) {
groupsPreferences.setGroupViewMode(GroupViewMode.UNION);
dialogService.notify(Localization.lang("Group view mode set to union"));
}
}
}
}
| 2,583
| 42.79661
| 103
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/sidepane/SidePane.java
|
package org.jabref.gui.sidepane;
import java.util.HashMap;
import java.util.Map;
import javax.swing.undo.UndoManager;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.collections.ListChangeListener;
import javafx.scene.layout.VBox;
import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.preferences.PreferencesService;
public class SidePane extends VBox {
private final SidePaneViewModel viewModel;
private final PreferencesService preferencesService;
private final StateManager stateManager;
// These bindings need to be stored, otherwise they are garbage collected
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
private final Map<SidePaneType, BooleanBinding> visibleBindings = new HashMap<>();
public SidePane(PreferencesService preferencesService,
JournalAbbreviationRepository abbreviationRepository,
TaskExecutor taskExecutor,
DialogService dialogService,
StateManager stateManager,
UndoManager undoManager) {
this.stateManager = stateManager;
this.preferencesService = preferencesService;
this.viewModel = new SidePaneViewModel(preferencesService, abbreviationRepository, stateManager, taskExecutor, dialogService, undoManager);
stateManager.getVisibleSidePaneComponents().addListener((ListChangeListener<SidePaneType>) c -> updateView());
updateView();
}
private void updateView() {
getChildren().clear();
for (SidePaneType type : stateManager.getVisibleSidePaneComponents()) {
SidePaneComponent view = viewModel.getSidePaneComponent(type);
getChildren().add(view);
}
}
public BooleanBinding paneVisibleBinding(SidePaneType pane) {
BooleanBinding visibility = Bindings.createBooleanBinding(
() -> stateManager.getVisibleSidePaneComponents().contains(pane),
stateManager.getVisibleSidePaneComponents());
visibleBindings.put(pane, visibility);
return visibility;
}
public SimpleCommand getToggleCommandFor(SidePaneType sidePane) {
return new TogglePaneAction(stateManager, sidePane, preferencesService.getSidePanePreferences());
}
public SidePaneComponent getSidePaneComponent(SidePaneType type) {
return viewModel.getSidePaneComponent(type);
}
}
| 2,639
| 38.402985
| 147
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/sidepane/SidePaneComponent.java
|
package org.jabref.gui.sidepane;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.groups.GroupTreeView;
import org.jabref.gui.icon.IconTheme;
import org.jabref.logic.l10n.Localization;
public class SidePaneComponent extends BorderPane {
private final SidePaneType sidePaneType;
private final SimpleCommand closeCommand;
private final SimpleCommand moveUpCommand;
private final SimpleCommand moveDownCommand;
private final SidePaneContentFactory contentFactory;
private HBox buttonContainer;
public SidePaneComponent(SidePaneType sidePaneType,
SimpleCommand closeCommand,
SimpleCommand moveUpCommand,
SimpleCommand moveDownCommand,
SidePaneContentFactory contentFactory) {
this.sidePaneType = sidePaneType;
this.closeCommand = closeCommand;
this.moveUpCommand = moveUpCommand;
this.moveDownCommand = moveDownCommand;
this.contentFactory = contentFactory;
initialize();
}
private void initialize() {
getStyleClass().add("sidePaneComponent");
setTop(createHeaderView());
setCenter(contentFactory.create(sidePaneType));
VBox.setVgrow(this, sidePaneType == SidePaneType.GROUPS ? Priority.ALWAYS : Priority.NEVER);
}
private Node createHeaderView() {
Button closeButton = IconTheme.JabRefIcons.CLOSE.asButton();
closeButton.setTooltip(new Tooltip(Localization.lang("Hide panel")));
closeButton.setOnAction(e -> closeCommand.execute());
Button upButton = IconTheme.JabRefIcons.UP.asButton();
upButton.setTooltip(new Tooltip(Localization.lang("Move panel up")));
upButton.setOnAction(e -> moveUpCommand.execute());
Button downButton = IconTheme.JabRefIcons.DOWN.asButton();
downButton.setTooltip(new Tooltip(Localization.lang("Move panel down")));
downButton.setOnAction(e -> moveDownCommand.execute());
this.buttonContainer = new HBox();
buttonContainer.getChildren().addAll(upButton, downButton, closeButton);
Label label = new Label(sidePaneType.getTitle());
BorderPane headerView = new BorderPane();
headerView.setLeft(label);
headerView.setRight(buttonContainer);
headerView.getStyleClass().add("sidePaneComponentHeader");
return headerView;
}
protected void addExtraButtonToHeader(Button button, int position) {
this.buttonContainer.getChildren().add(position, button);
}
public void requestFocus() {
for (Node child : getChildren()) {
if (child instanceof GroupTreeView groupTreeView) {
groupTreeView.requestFocusGroupTree();
break;
}
}
}
}
| 3,125
| 35.776471
| 100
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/sidepane/SidePaneContentFactory.java
|
package org.jabref.gui.sidepane;
import javax.swing.undo.UndoManager;
import javafx.scene.Node;
import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.groups.GroupTreeView;
import org.jabref.gui.importer.fetcher.WebSearchPaneView;
import org.jabref.gui.openoffice.OpenOfficePanel;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.preferences.PreferencesService;
public class SidePaneContentFactory {
private final PreferencesService preferences;
private final JournalAbbreviationRepository abbreviationRepository;
private final TaskExecutor taskExecutor;
private final DialogService dialogService;
private final StateManager stateManager;
private final UndoManager undoManager;
public SidePaneContentFactory(PreferencesService preferences,
JournalAbbreviationRepository abbreviationRepository,
TaskExecutor taskExecutor,
DialogService dialogService,
StateManager stateManager,
UndoManager undoManager) {
this.preferences = preferences;
this.abbreviationRepository = abbreviationRepository;
this.taskExecutor = taskExecutor;
this.dialogService = dialogService;
this.stateManager = stateManager;
this.undoManager = undoManager;
}
public Node create(SidePaneType sidePaneType) {
return switch (sidePaneType) {
case GROUPS -> new GroupTreeView(
taskExecutor,
stateManager,
preferences,
dialogService);
case OPEN_OFFICE -> new OpenOfficePanel(
preferences,
preferences.getKeyBindingRepository(),
abbreviationRepository,
taskExecutor,
dialogService,
stateManager,
undoManager).getContent();
case WEB_SEARCH -> new WebSearchPaneView(
preferences,
dialogService,
stateManager);
};
}
}
| 2,287
| 37.133333
| 87
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/sidepane/SidePaneType.java
|
package org.jabref.gui.sidepane;
import org.jabref.gui.actions.Action;
import org.jabref.gui.actions.StandardActions;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.icon.JabRefIcon;
import org.jabref.logic.l10n.Localization;
/**
* Definition of all possible components in the side pane.
*/
public enum SidePaneType {
OPEN_OFFICE("OpenOffice/LibreOffice", IconTheme.JabRefIcons.FILE_OPENOFFICE, StandardActions.TOOGLE_OO),
WEB_SEARCH(Localization.lang("Web search"), IconTheme.JabRefIcons.WWW, StandardActions.TOGGLE_WEB_SEARCH),
GROUPS(Localization.lang("Groups"), IconTheme.JabRefIcons.TOGGLE_GROUPS, StandardActions.TOGGLE_GROUPS);
private final String title;
private final JabRefIcon icon;
private final Action toggleAction;
SidePaneType(String title, JabRefIcon icon, Action toggleAction) {
this.title = title;
this.icon = icon;
this.toggleAction = toggleAction;
}
public String getTitle() {
return title;
}
public JabRefIcon getIcon() {
return icon;
}
public Action getToggleAction() {
return toggleAction;
}
}
| 1,142
| 28.307692
| 110
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/sidepane/SidePaneViewModel.java
|
package org.jabref.gui.sidepane;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;
import javax.swing.undo.UndoManager;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import org.jabref.gui.AbstractViewModel;
import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.preferences.PreferencesService;
import org.jabref.preferences.SidePanePreferences;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SidePaneViewModel extends AbstractViewModel {
private static final Logger LOGGER = LoggerFactory.getLogger(SidePaneViewModel.class);
private final Map<SidePaneType, SidePaneComponent> sidePaneComponentLookup = new HashMap<>();
private final PreferencesService preferencesService;
private final StateManager stateManager;
private final SidePaneContentFactory sidePaneContentFactory;
private final DialogService dialogService;
public SidePaneViewModel(PreferencesService preferencesService,
JournalAbbreviationRepository abbreviationRepository,
StateManager stateManager,
TaskExecutor taskExecutor,
DialogService dialogService,
UndoManager undoManager) {
this.preferencesService = preferencesService;
this.stateManager = stateManager;
this.dialogService = dialogService;
this.sidePaneContentFactory = new SidePaneContentFactory(
preferencesService,
abbreviationRepository,
taskExecutor,
dialogService,
stateManager,
undoManager);
preferencesService.getSidePanePreferences().visiblePanes().forEach(this::show);
getPanes().addListener((ListChangeListener<? super SidePaneType>) change -> {
while (change.next()) {
if (change.wasAdded()) {
preferencesService.getSidePanePreferences().visiblePanes().add(change.getAddedSubList().get(0));
} else if (change.wasRemoved()) {
preferencesService.getSidePanePreferences().visiblePanes().remove(change.getRemoved().get(0));
}
}
});
}
protected SidePaneComponent getSidePaneComponent(SidePaneType pane) {
SidePaneComponent sidePaneComponent = sidePaneComponentLookup.get(pane);
if (sidePaneComponent == null) {
sidePaneComponent = switch (pane) {
case GROUPS -> new GroupsSidePaneComponent(
new ClosePaneAction(pane),
new MoveUpAction(pane),
new MoveDownAction(pane),
sidePaneContentFactory,
preferencesService.getGroupsPreferences(),
dialogService);
case WEB_SEARCH, OPEN_OFFICE -> new SidePaneComponent(pane,
new ClosePaneAction(pane),
new MoveUpAction(pane),
new MoveDownAction(pane),
sidePaneContentFactory);
};
sidePaneComponentLookup.put(pane, sidePaneComponent);
}
return sidePaneComponent;
}
/**
* Stores the current configuration of visible panes in the preferences, so that we show panes at the preferred
* position next time.
*/
private void updatePreferredPositions() {
Map<SidePaneType, Integer> preferredPositions = new HashMap<>(preferencesService.getSidePanePreferences()
.getPreferredPositions());
IntStream.range(0, getPanes().size()).forEach(i -> preferredPositions.put(getPanes().get(i), i));
preferencesService.getSidePanePreferences().setPreferredPositions(preferredPositions);
}
public void moveUp(SidePaneType pane) {
if (getPanes().contains(pane)) {
int currentPosition = getPanes().indexOf(pane);
if (currentPosition > 0) {
int newPosition = currentPosition - 1;
swap(getPanes(), currentPosition, newPosition);
updatePreferredPositions();
} else {
LOGGER.debug("SidePaneComponent is already at the bottom");
}
} else {
LOGGER.warn("SidePaneComponent {} not visible", pane.getTitle());
}
}
public void moveDown(SidePaneType pane) {
if (getPanes().contains(pane)) {
int currentPosition = getPanes().indexOf(pane);
if (currentPosition < (getPanes().size() - 1)) {
int newPosition = currentPosition + 1;
swap(getPanes(), currentPosition, newPosition);
updatePreferredPositions();
} else {
LOGGER.debug("SidePaneComponent {} is already at the top", pane.getTitle());
}
} else {
LOGGER.warn("SidePaneComponent {} not visible", pane.getTitle());
}
}
private void show(SidePaneType pane) {
if (!getPanes().contains(pane)) {
getPanes().add(pane);
getPanes().sort(new PreferredIndexSort(preferencesService.getSidePanePreferences()));
} else {
LOGGER.warn("SidePaneComponent {} not visible", pane.getTitle());
}
}
private ObservableList<SidePaneType> getPanes() {
return stateManager.getVisibleSidePaneComponents();
}
private <T> void swap(ObservableList<T> observableList, int i, int j) {
List<T> placeholder = new ArrayList<>(observableList);
Collections.swap(placeholder, i, j);
observableList.sort(Comparator.comparingInt(placeholder::indexOf));
}
/**
* Helper class for sorting visible side panes based on their preferred position.
*/
protected static class PreferredIndexSort implements Comparator<SidePaneType> {
private final Map<SidePaneType, Integer> preferredPositions;
public PreferredIndexSort(SidePanePreferences sidePanePreferences) {
this.preferredPositions = sidePanePreferences.getPreferredPositions();
}
@Override
public int compare(SidePaneType type1, SidePaneType type2) {
int pos1 = preferredPositions.getOrDefault(type1, 0);
int pos2 = preferredPositions.getOrDefault(type2, 0);
return Integer.compare(pos1, pos2);
}
}
private class MoveUpAction extends SimpleCommand {
private final SidePaneType toMoveUpPane;
public MoveUpAction(SidePaneType toMoveUpPane) {
this.toMoveUpPane = toMoveUpPane;
}
@Override
public void execute() {
moveUp(toMoveUpPane);
}
}
private class MoveDownAction extends SimpleCommand {
private final SidePaneType toMoveDownPane;
public MoveDownAction(SidePaneType toMoveDownPane) {
this.toMoveDownPane = toMoveDownPane;
}
@Override
public void execute() {
moveDown(toMoveDownPane);
}
}
public class ClosePaneAction extends SimpleCommand {
private final SidePaneType toClosePane;
public ClosePaneAction(SidePaneType toClosePane) {
this.toClosePane = toClosePane;
}
@Override
public void execute() {
stateManager.getVisibleSidePaneComponents().remove(toClosePane);
}
}
}
| 7,896
| 37.149758
| 116
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/sidepane/TogglePaneAction.java
|
package org.jabref.gui.sidepane;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.preferences.SidePanePreferences;
public class TogglePaneAction extends SimpleCommand {
private final StateManager stateManager;
private final SidePaneType pane;
private final SidePanePreferences sidePanePreferences;
public TogglePaneAction(StateManager stateManager, SidePaneType pane, SidePanePreferences sidePanePreferences) {
this.stateManager = stateManager;
this.pane = pane;
this.sidePanePreferences = sidePanePreferences;
}
@Override
public void execute() {
if (!stateManager.getVisibleSidePaneComponents().contains(pane)) {
stateManager.getVisibleSidePaneComponents().add(pane);
stateManager.getVisibleSidePaneComponents().sort(new SidePaneViewModel.PreferredIndexSort(sidePanePreferences));
} else {
stateManager.getVisibleSidePaneComponents().remove(pane);
}
}
}
| 1,025
| 35.642857
| 124
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/slr/EditExistingStudyAction.java
|
package org.jabref.gui.slr;
import java.io.IOException;
import java.nio.file.Path;
import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.ActionHelper;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.logic.crawler.StudyRepository;
import org.jabref.logic.crawler.StudyYamlParser;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.study.Study;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class EditExistingStudyAction extends SimpleCommand {
private static final Logger LOGGER = LoggerFactory.getLogger(EditExistingStudyAction.class);
private final DialogService dialogService;
private final StateManager stateManager;
public EditExistingStudyAction(DialogService dialogService, StateManager stateManager) {
this.dialogService = dialogService;
this.stateManager = stateManager;
this.executable.bind(ActionHelper.needsStudyDatabase(stateManager));
}
@Override
public void execute() {
// The action works on the current library
// This library has to be determined
if (stateManager.getActiveDatabase().isEmpty() || !stateManager.getActiveDatabase().get().isStudy()) {
return;
}
BibDatabaseContext bibDatabaseContext = stateManager.getActiveDatabase().get();
// The action can only be called on an existing AND saved study library
// The saving is ensured at creation of a study library
// Thus, this check is only existing to check this assumption
if (bibDatabaseContext.getDatabasePath().isEmpty()) {
LOGGER.error("Library path is not available");
return;
}
Path databasePath = bibDatabaseContext.getDatabasePath().get();
Path studyDirectory = databasePath.getParent();
Study study;
try {
study = new StudyYamlParser().parseStudyYamlFile(studyDirectory.resolve(StudyRepository.STUDY_DEFINITION_FILE_NAME));
} catch (IOException e) {
dialogService.showErrorDialogAndWait(Localization.lang("Error opening file"), e);
return;
}
// When the dialog returns, the study.yml file is updated (or kept unmodified at Cancel)
dialogService.showCustomDialogAndWait(new ManageStudyDefinitionView(study, studyDirectory));
}
}
| 2,446
| 37.234375
| 129
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/slr/ExistingStudySearchAction.java
|
package org.jabref.gui.slr;
import java.io.IOException;
import java.nio.file.Path;
import org.jabref.gui.DialogService;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.ActionHelper;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.importer.actions.OpenDatabaseAction;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.crawler.Crawler;
import org.jabref.logic.git.SlrGitHandler;
import org.jabref.logic.importer.ParseException;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntryTypesManager;
import org.jabref.model.util.FileUpdateMonitor;
import org.jabref.preferences.PreferencesService;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ExistingStudySearchAction extends SimpleCommand {
private static final Logger LOGGER = LoggerFactory.getLogger(ExistingStudySearchAction.class);
protected final DialogService dialogService;
protected Path studyDirectory;
protected final PreferencesService preferencesService;
protected final StateManager stateManager;
private final FileUpdateMonitor fileUpdateMonitor;
private final TaskExecutor taskExecutor;
private final JabRefFrame frame;
private final OpenDatabaseAction openDatabaseAction;
/**
* @param frame Required to close the tab before the study is updated
* @param openDatabaseAction Required to open the tab after the study is exectued
*/
public ExistingStudySearchAction(
JabRefFrame frame,
OpenDatabaseAction openDatabaseAction,
DialogService dialogService,
FileUpdateMonitor fileUpdateMonitor,
TaskExecutor taskExecutor,
PreferencesService preferencesService,
StateManager stateManager) {
this(frame,
openDatabaseAction,
dialogService,
fileUpdateMonitor,
taskExecutor,
preferencesService,
stateManager,
false);
}
protected ExistingStudySearchAction(
JabRefFrame frame,
OpenDatabaseAction openDatabaseAction,
DialogService dialogService,
FileUpdateMonitor fileUpdateMonitor,
TaskExecutor taskExecutor,
PreferencesService preferencesService,
StateManager stateManager,
boolean isNew) {
this.frame = frame;
this.openDatabaseAction = openDatabaseAction;
this.dialogService = dialogService;
this.fileUpdateMonitor = fileUpdateMonitor;
this.taskExecutor = taskExecutor;
this.preferencesService = preferencesService;
this.stateManager = stateManager;
if (!isNew) {
this.executable.bind(ActionHelper.needsStudyDatabase(stateManager));
}
}
@Override
public void execute() {
if (stateManager.getActiveDatabase().isEmpty()) {
LOGGER.error("Database is not present, even if it should");
return;
}
BibDatabaseContext bibDatabaseContext = stateManager.getActiveDatabase().get();
if (bibDatabaseContext.getDatabasePath().isEmpty()) {
LOGGER.error("Database path is not present, even if it should");
return;
}
this.studyDirectory = bibDatabaseContext.getDatabasePath().get().getParent();
crawl();
}
protected void crawl() {
try {
crawlPreparation(this.studyDirectory);
} catch (IOException | GitAPIException e) {
dialogService.showErrorDialogAndWait(Localization.lang("Study repository could not be created"), e);
return;
}
final Crawler crawler;
try {
crawler = new Crawler(
this.studyDirectory,
new SlrGitHandler(this.studyDirectory),
preferencesService,
new BibEntryTypesManager(),
fileUpdateMonitor);
} catch (IOException | ParseException e) {
LOGGER.error("Error during reading of study definition file.", e);
dialogService.showErrorDialogAndWait(Localization.lang("Error during reading of study definition file."), e);
return;
}
dialogService.notify(Localization.lang("Searching..."));
BackgroundTask.wrap(() -> {
crawler.performCrawl();
return 0; // Return any value to make this a callable instead of a runnable. This allows throwing exceptions.
})
.onFailure(e -> {
LOGGER.error("Error during persistence of crawling results.");
dialogService.showErrorDialogAndWait(Localization.lang("Error during persistence of crawling results."), e);
})
.onSuccess(unused -> {
dialogService.notify(Localization.lang("Finished Searching"));
openDatabaseAction.openFile(Path.of(this.studyDirectory.toString(), Crawler.FILENAME_STUDY_RESULT_BIB));
})
.executeWith(taskExecutor);
}
/**
* Hook for setting up the crawl phase (e.g., initialization the repository)
*/
protected void crawlPreparation(Path studyRepositoryRoot) throws IOException, GitAPIException {
// Do nothing with the repository as repository is already setup
// The user focused an SLR
// We hard close the tab
// Future work: Properly close the tab (with saving, ...)
frame.closeCurrentTab();
}
}
| 5,886
| 37.730263
| 135
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/slr/ManageStudyDefinitionView.java
|
package org.jabref.gui.slr;
import java.nio.file.Path;
import java.util.Optional;
import java.util.StringJoiner;
import java.util.function.Consumer;
import javafx.beans.binding.Bindings;
import javafx.beans.property.SimpleStringProperty;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.input.KeyCode;
import javafx.scene.input.MouseButton;
import org.jabref.gui.DialogService;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.theme.ThemeManager;
import org.jabref.gui.util.BaseDialog;
import org.jabref.gui.util.DirectoryDialogConfiguration;
import org.jabref.gui.util.ValueTableCellFactory;
import org.jabref.gui.util.ViewModelTableRowFactory;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.study.Study;
import org.jabref.preferences.PreferencesService;
import com.airhacks.afterburner.views.ViewLoader;
import jakarta.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class controls the user interface of the study definition management dialog. The UI elements and their layout
* are defined in the FXML file.
*/
public class ManageStudyDefinitionView extends BaseDialog<SlrStudyAndDirectory> {
private static final Logger LOGGER = LoggerFactory.getLogger(ManageStudyDefinitionView.class);
@FXML private TextField studyTitle;
@FXML private TextField addAuthor;
@FXML private TextField addResearchQuestion;
@FXML private TextField addQuery;
@FXML private TextField studyDirectory;
@FXML private Button selectStudyDirectory;
@FXML private ButtonType saveSurveyButtonType;
@FXML private Label helpIcon;
@FXML private TableView<String> authorTableView;
@FXML private TableColumn<String, String> authorsColumn;
@FXML private TableColumn<String, String> authorsActionColumn;
@FXML private TableView<String> questionTableView;
@FXML private TableColumn<String, String> questionsColumn;
@FXML private TableColumn<String, String> questionsActionColumn;
@FXML private TableView<String> queryTableView;
@FXML private TableColumn<String, String> queriesColumn;
@FXML private TableColumn<String, String> queriesActionColumn;
@FXML private TableView<StudyCatalogItem> catalogTable;
@FXML private TableColumn<StudyCatalogItem, Boolean> catalogEnabledColumn;
@FXML private TableColumn<StudyCatalogItem, String> catalogColumn;
@Inject private DialogService dialogService;
@Inject private PreferencesService prefs;
@Inject private ThemeManager themeManager;
private ManageStudyDefinitionViewModel viewModel;
// not present if new study is created;
// present if existing study is edited
private final Optional<Study> study;
// Either the proposed directory (on new study creation)
// or the "real" directory of the study
private final Path pathToStudyDataDirectory;
/**
* This is used to create a new study
*
* @param pathToStudyDataDirectory This directory is proposed in the file chooser
*/
public ManageStudyDefinitionView(Path pathToStudyDataDirectory) {
this.pathToStudyDataDirectory = pathToStudyDataDirectory;
this.setTitle("Define study parameters");
this.study = Optional.empty();
ViewLoader.view(this)
.load()
.setAsDialogPane(this);
setupSaveSurveyButton(false);
themeManager.updateFontStyle(getDialogPane().getScene());
}
/**
* This is used to edit an existing study.
*
* @param study the study to edit
* @param studyDirectory the directory of the study
*/
public ManageStudyDefinitionView(Study study, Path studyDirectory) {
this.pathToStudyDataDirectory = studyDirectory;
this.setTitle(Localization.lang("Manage study definition"));
this.study = Optional.of(study);
ViewLoader.view(this)
.load()
.setAsDialogPane(this);
setupSaveSurveyButton(true);
themeManager.updateFontStyle(getDialogPane().getScene());
}
private void setupSaveSurveyButton(boolean isEdit) {
Button saveSurveyButton = (Button) this.getDialogPane().lookupButton(saveSurveyButtonType);
if (!isEdit) {
saveSurveyButton.setText(Localization.lang("Start survey"));
}
saveSurveyButton.disableProperty().bind(Bindings.or(Bindings.or(Bindings.or(Bindings.or(
Bindings.isEmpty(viewModel.getQueries()),
Bindings.isEmpty(viewModel.getCatalogs())),
Bindings.isEmpty(viewModel.getAuthors())),
viewModel.getTitle().isEmpty()),
viewModel.getDirectory().isEmpty()));
setResultConverter(button -> {
if (button == saveSurveyButtonType) {
return viewModel.saveStudy();
}
// Cancel button will return null
return null;
});
}
@FXML
private void initialize() {
if (study.isEmpty()) {
viewModel = new ManageStudyDefinitionViewModel(
prefs.getImportFormatPreferences(),
prefs.getImporterPreferences(),
dialogService);
} else {
viewModel = new ManageStudyDefinitionViewModel(
study.get(),
pathToStudyDataDirectory,
prefs.getImportFormatPreferences(),
prefs.getImporterPreferences(),
dialogService);
// The directory of the study cannot be changed
studyDirectory.setEditable(false);
selectStudyDirectory.setDisable(true);
}
// Listen whether any catalogs are removed from selection -> Add back to the catalog selector
studyTitle.textProperty().bindBidirectional(viewModel.titleProperty());
studyDirectory.textProperty().bindBidirectional(viewModel.getDirectory());
initAuthorTab();
initQuestionsTab();
initQueriesTab();
initCatalogsTab();
}
private void initAuthorTab() {
setupCommonPropertiesForTables(addAuthor, this::addAuthor, authorsColumn, authorsActionColumn);
setupCellFactories(authorsColumn, authorsActionColumn, viewModel::deleteAuthor);
authorTableView.setItems(viewModel.getAuthors());
}
private void initQuestionsTab() {
setupCommonPropertiesForTables(addResearchQuestion, this::addResearchQuestion, questionsColumn, questionsActionColumn);
setupCellFactories(questionsColumn, questionsActionColumn, viewModel::deleteQuestion);
questionTableView.setItems(viewModel.getResearchQuestions());
}
private void initQueriesTab() {
setupCommonPropertiesForTables(addQuery, this::addQuery, queriesColumn, queriesActionColumn);
setupCellFactories(queriesColumn, queriesActionColumn, viewModel::deleteQuery);
queryTableView.setItems(viewModel.getQueries());
// TODO: Keep until PR #7279 is merged
helpIcon.setTooltip(new Tooltip(new StringJoiner("\n")
.add(Localization.lang("Query terms are separated by spaces."))
.add(Localization.lang("All query terms are joined using the logical AND, and OR operators") + ".")
.add(Localization.lang("If the sequence of terms is relevant wrap them in double quotes") + "(\").")
.add(Localization.lang("An example:") + " rain AND (clouds OR drops) AND \"precipitation distribution\"")
.toString()));
}
private void initCatalogsTab() {
new ViewModelTableRowFactory<StudyCatalogItem>()
.withOnMouseClickedEvent((entry, event) -> {
if (event.getButton() == MouseButton.PRIMARY) {
entry.setEnabled(!entry.isEnabled());
}
})
.install(catalogTable);
catalogColumn.setReorderable(false);
catalogColumn.setCellFactory(TextFieldTableCell.forTableColumn());
catalogEnabledColumn.setResizable(false);
catalogEnabledColumn.setReorderable(false);
catalogEnabledColumn.setCellFactory(CheckBoxTableCell.forTableColumn(catalogEnabledColumn));
catalogEnabledColumn.setCellValueFactory(param -> param.getValue().enabledProperty());
catalogColumn.setEditable(false);
catalogColumn.setCellValueFactory(param -> param.getValue().nameProperty());
catalogTable.setItems(viewModel.getCatalogs());
}
private void setupCommonPropertiesForTables(Node addControl,
Runnable addAction,
TableColumn<?, String> contentColumn,
TableColumn<?, String> actionColumn) {
addControl.setOnKeyPressed(event -> {
if (event.getCode() == KeyCode.ENTER) {
addAction.run();
}
});
contentColumn.setReorderable(false);
contentColumn.setCellFactory(TextFieldTableCell.forTableColumn());
actionColumn.setReorderable(false);
actionColumn.setResizable(false);
}
private void setupCellFactories(TableColumn<String, String> contentColumn,
TableColumn<String, String> actionColumn,
Consumer<String> removeAction) {
contentColumn.setCellValueFactory(param -> new SimpleStringProperty(param.getValue()));
actionColumn.setCellValueFactory(param -> new SimpleStringProperty(param.getValue()));
new ValueTableCellFactory<String, String>()
.withGraphic(item -> IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode())
.withTooltip(name -> Localization.lang("Remove"))
.withOnMouseClickedEvent(item -> evt ->
removeAction.accept(item))
.install(actionColumn);
}
@FXML
private void addAuthor() {
viewModel.addAuthor(addAuthor.getText());
addAuthor.setText("");
}
@FXML
private void addResearchQuestion() {
viewModel.addResearchQuestion(addResearchQuestion.getText());
addResearchQuestion.setText("");
}
@FXML
private void addQuery() {
viewModel.addQuery(addQuery.getText());
addQuery.setText("");
}
@FXML
public void selectStudyDirectory() {
DirectoryDialogConfiguration directoryDialogConfiguration = new DirectoryDialogConfiguration.Builder()
.withInitialDirectory(pathToStudyDataDirectory)
.build();
viewModel.setStudyDirectory(dialogService.showDirectorySelectionDialog(directoryDialogConfiguration));
}
}
| 11,278
| 38.714789
| 127
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/slr/ManageStudyDefinitionViewModel.java
|
package org.jabref.gui.slr;
import java.io.IOException;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javafx.beans.property.Property;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.jabref.gui.DialogService;
import org.jabref.logic.crawler.StudyRepository;
import org.jabref.logic.crawler.StudyYamlParser;
import org.jabref.logic.git.GitHandler;
import org.jabref.logic.importer.ImportFormatPreferences;
import org.jabref.logic.importer.ImporterPreferences;
import org.jabref.logic.importer.SearchBasedFetcher;
import org.jabref.logic.importer.WebFetchers;
import org.jabref.logic.importer.fetcher.ACMPortalFetcher;
import org.jabref.logic.importer.fetcher.CompositeSearchBasedFetcher;
import org.jabref.logic.importer.fetcher.DBLPFetcher;
import org.jabref.logic.importer.fetcher.IEEE;
import org.jabref.logic.importer.fetcher.SpringerFetcher;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.study.Study;
import org.jabref.model.study.StudyDatabase;
import org.jabref.model.study.StudyQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class provides a model for managing study definitions.
* To visualize the model one can bind the properties to UI elements.
*/
public class ManageStudyDefinitionViewModel {
private static final Logger LOGGER = LoggerFactory.getLogger(ManageStudyDefinitionViewModel.class);
private static final Set<String> DEFAULT_SELECTION = Set.of(
ACMPortalFetcher.FETCHER_NAME,
IEEE.FETCHER_NAME,
SpringerFetcher.FETCHER_NAME,
DBLPFetcher.FETCHER_NAME);
private final StringProperty title = new SimpleStringProperty();
private final ObservableList<String> authors = FXCollections.observableArrayList();
private final ObservableList<String> researchQuestions = FXCollections.observableArrayList();
private final ObservableList<String> queries = FXCollections.observableArrayList();
private final ObservableList<StudyCatalogItem> databases = FXCollections.observableArrayList();
// Hold the complement of databases for the selector
private final SimpleStringProperty directory = new SimpleStringProperty();
private final DialogService dialogService;
/**
* Constructor for a new study
*/
public ManageStudyDefinitionViewModel(ImportFormatPreferences importFormatPreferences,
ImporterPreferences importerPreferences,
DialogService dialogService) {
databases.addAll(WebFetchers.getSearchBasedFetchers(importFormatPreferences, importerPreferences)
.stream()
.map(SearchBasedFetcher::getName)
// The user wants to select specific fetchers
// The fetcher summarizing ALL fetchers can be emulated by selecting ALL fetchers (which happens rarely when doing an SLR)
.filter(name -> !name.equals(CompositeSearchBasedFetcher.FETCHER_NAME))
.map(name -> {
boolean enabled = DEFAULT_SELECTION.contains(name);
return new StudyCatalogItem(name, enabled);
})
.toList());
this.dialogService = Objects.requireNonNull(dialogService);
}
/**
* Constructor for an existing study
*
* @param study The study to initialize the UI from
* @param studyDirectory The path where the study resides
*/
public ManageStudyDefinitionViewModel(Study study,
Path studyDirectory,
ImportFormatPreferences importFormatPreferences,
ImporterPreferences importerPreferences,
DialogService dialogService) {
// copy the content of the study object into the UI fields
authors.addAll(Objects.requireNonNull(study).getAuthors());
title.setValue(study.getTitle());
researchQuestions.addAll(study.getResearchQuestions());
queries.addAll(study.getQueries().stream().map(StudyQuery::getQuery).toList());
List<StudyDatabase> studyDatabases = study.getDatabases();
databases.addAll(WebFetchers.getSearchBasedFetchers(importFormatPreferences, importerPreferences)
.stream()
.map(SearchBasedFetcher::getName)
// The user wants to select specific fetchers
// The fetcher summarizing ALL fetchers can be emulated by selecting ALL fetchers (which happens rarely when doing an SLR)
.filter(name -> !name.equals(CompositeSearchBasedFetcher.FETCHER_NAME))
.map(name -> {
boolean enabled = studyDatabases.contains(new StudyDatabase(name, true));
return new StudyCatalogItem(name, enabled);
})
.toList());
this.directory.set(Objects.requireNonNull(studyDirectory).toString());
this.dialogService = Objects.requireNonNull(dialogService);
}
public StringProperty getTitle() {
return title;
}
public StringProperty getDirectory() {
return directory;
}
public ObservableList<String> getAuthors() {
return authors;
}
public ObservableList<String> getResearchQuestions() {
return researchQuestions;
}
public ObservableList<String> getQueries() {
return queries;
}
public ObservableList<StudyCatalogItem> getCatalogs() {
return databases;
}
public void addAuthor(String author) {
if (author.isBlank()) {
return;
}
authors.add(author);
}
public void addResearchQuestion(String researchQuestion) {
if (researchQuestion.isBlank() || researchQuestions.contains(researchQuestion)) {
return;
}
researchQuestions.add(researchQuestion);
}
public void addQuery(String query) {
if (query.isBlank()) {
return;
}
queries.add(query);
}
public SlrStudyAndDirectory saveStudy() {
Study study = new Study(
authors,
title.getValueSafe(),
researchQuestions,
queries.stream().map(StudyQuery::new).collect(Collectors.toList()),
databases.stream().map(studyDatabaseItem -> new StudyDatabase(studyDatabaseItem.getName(), studyDatabaseItem.isEnabled())).filter(StudyDatabase::isEnabled).collect(Collectors.toList()));
Path studyDirectory;
final String studyDirectoryAsString = directory.getValueSafe();
try {
studyDirectory = Path.of(studyDirectoryAsString);
} catch (InvalidPathException e) {
LOGGER.error("Invalid path was provided: {}", studyDirectoryAsString);
dialogService.notify(Localization.lang("Unable to write to %0.", studyDirectoryAsString));
// We do not assume another path - we return that there is an invalid object.
return null;
}
Path studyDefinitionFile = studyDirectory.resolve(StudyRepository.STUDY_DEFINITION_FILE_NAME);
try {
new StudyYamlParser().writeStudyYamlFile(study, studyDefinitionFile);
} catch (IOException e) {
LOGGER.error("Could not write study file {}", studyDefinitionFile, e);
dialogService.notify(Localization.lang("Please enter a valid file path.") +
": " + studyDirectoryAsString);
// We do not assume another path - we return that there is an invalid object.
return null;
}
try {
new GitHandler(studyDirectory).createCommitOnCurrentBranch("Update study definition", false);
} catch (Exception e) {
LOGGER.error("Could not commit study definition file in directory {}", studyDirectory, e);
dialogService.notify(Localization.lang("Please enter a valid file path.") +
": " + studyDirectory);
// We continue nevertheless as the directory itself could be valid
}
return new SlrStudyAndDirectory(study, studyDirectory);
}
public Property<String> titleProperty() {
return title;
}
public void setStudyDirectory(Optional<Path> studyRepositoryRoot) {
getDirectory().setValue(studyRepositoryRoot.map(Path::toString).orElseGet(() -> getDirectory().getValueSafe()));
}
public void deleteAuthor(String item) {
authors.remove(item);
}
public void deleteQuestion(String item) {
researchQuestions.remove(item);
}
public void deleteQuery(String item) {
queries.remove(item);
}
}
| 9,464
| 41.828054
| 202
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/slr/SlrStudyAndDirectory.java
|
package org.jabref.gui.slr;
import java.nio.file.Path;
import java.util.Objects;
import org.jabref.model.study.Study;
public class SlrStudyAndDirectory {
private final Study study;
private final Path studyDirectory;
public SlrStudyAndDirectory(Study study, Path studyDirectory) {
this.study = Objects.requireNonNull(study);
this.studyDirectory = Objects.requireNonNull(studyDirectory);
}
public Path getStudyDirectory() {
return studyDirectory;
}
public Study getStudy() {
return study;
}
}
| 561
| 21.48
| 69
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/slr/StartNewStudyAction.java
|
package org.jabref.gui.slr;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Optional;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.StateManager;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.crawler.StudyRepository;
import org.jabref.logic.crawler.StudyYamlParser;
import org.jabref.logic.git.GitHandler;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.study.Study;
import org.jabref.model.util.FileUpdateMonitor;
import org.jabref.preferences.PreferencesService;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Used to start a new study:
* <ol>
* <li>Let the user input meta data for the study.</li>
* <li>Let JabRef do the crawling afterwards.</li>
* </ol>
*
* Needs to inherit {@link ExistingStudySearchAction}, because that action implements the real crawling.
*
* There is the hook {@link StartNewStudyAction#crawlPreparation(Path)}, which is used by {@link ExistingStudySearchAction#crawl()}.
*/
public class StartNewStudyAction extends ExistingStudySearchAction {
private static final Logger LOGGER = LoggerFactory.getLogger(StartNewStudyAction.class);
Study newStudy;
public StartNewStudyAction(JabRefFrame frame,
FileUpdateMonitor fileUpdateMonitor,
TaskExecutor taskExecutor,
PreferencesService preferencesService,
StateManager stateManager) {
super(frame,
frame.getOpenDatabaseAction(),
frame.getDialogService(),
fileUpdateMonitor,
taskExecutor,
preferencesService,
stateManager,
true);
}
@Override
protected void crawlPreparation(Path studyRepositoryRoot) throws IOException, GitAPIException {
StudyYamlParser studyYAMLParser = new StudyYamlParser();
studyYAMLParser.writeStudyYamlFile(newStudy, studyRepositoryRoot.resolve(StudyRepository.STUDY_DEFINITION_FILE_NAME));
// When execution reaches this point, the user created a new study.
// The GitHandler is already called to initialize the repository with one single commit "Initial commit".
// The "Initial commit" should also contain the created YAML.
// Thus, we append to that commit.
new GitHandler(studyRepositoryRoot).createCommitOnCurrentBranch("Initial commit", true);
}
@Override
public void execute() {
Optional<SlrStudyAndDirectory> studyAndDirectory = dialogService.showCustomDialogAndWait(
new ManageStudyDefinitionView(preferencesService.getFilePreferences().getWorkingDirectory()));
if (studyAndDirectory.isEmpty()) {
return;
}
if (studyAndDirectory.get().getStudyDirectory().toString().isBlank()) {
LOGGER.error("Study directory is blank");
// This branch probably is never taken
// Thus, we re-use existing localization
dialogService.showErrorDialogAndWait(Localization.lang("Must not be empty!"));
return;
}
studyDirectory = studyAndDirectory.get().getStudyDirectory();
// set variable for #setupRepository
// setupRepository() is called at crawl()
newStudy = studyAndDirectory.get().getStudy();
crawl();
}
}
| 3,471
| 38.011236
| 132
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/slr/StudyCatalogItem.java
|
package org.jabref.gui.slr;
import java.util.Objects;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import org.jabref.model.study.StudyDatabase;
/**
* View representation of {@link StudyDatabase}
*/
public class StudyCatalogItem {
private final StringProperty name;
private final BooleanProperty enabled;
public StudyCatalogItem(String name, boolean enabled) {
this.name = new SimpleStringProperty(Objects.requireNonNull(name));
this.enabled = new SimpleBooleanProperty(enabled);
}
public String getName() {
return name.getValue();
}
public void setName(String name) {
this.name.setValue(name);
}
public StringProperty nameProperty() {
return name;
}
public boolean isEnabled() {
return enabled.getValue();
}
public void setEnabled(boolean enabled) {
this.enabled.setValue(enabled);
}
public BooleanProperty enabledProperty() {
return enabled;
}
@Override
public String toString() {
return "StudyCatalogItem{" +
"name=" + name.get() +
", enabled=" + enabled.get() +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
StudyCatalogItem that = (StudyCatalogItem) o;
return Objects.equals(getName(), that.getName()) && Objects.equals(isEnabled(), that.isEnabled());
}
@Override
public int hashCode() {
return Objects.hash(getName(), isEnabled());
}
}
| 1,806
| 23.753425
| 106
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/specialfields/SpecialFieldAction.java
|
package org.jabref.gui.specialfields;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import javax.swing.undo.UndoManager;
import org.jabref.gui.DialogService;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.ActionHelper;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.undo.NamedCompound;
import org.jabref.gui.undo.UndoableFieldChange;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.UpdateField;
import org.jabref.model.FieldChange;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.SpecialField;
import org.jabref.preferences.PreferencesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SpecialFieldAction extends SimpleCommand {
private static final Logger LOGGER = LoggerFactory.getLogger(SpecialFieldAction.class);
private final JabRefFrame frame;
private final SpecialField specialField;
private final String value;
private final boolean nullFieldIfValueIsTheSame;
private final String undoText;
private final DialogService dialogService;
private final PreferencesService preferencesService;
private final UndoManager undoManager;
private final StateManager stateManager;
/**
* @param nullFieldIfValueIsTheSame - false also causes that doneTextPattern has two place holders %0 for the value and %1 for the sum of entries
*/
public SpecialFieldAction(JabRefFrame frame,
SpecialField specialField,
String value,
boolean nullFieldIfValueIsTheSame,
String undoText,
DialogService dialogService,
PreferencesService preferencesService,
UndoManager undoManager,
StateManager stateManager) {
this.frame = frame;
this.specialField = specialField;
this.value = value;
this.nullFieldIfValueIsTheSame = nullFieldIfValueIsTheSame;
this.undoText = undoText;
this.dialogService = dialogService;
this.preferencesService = preferencesService;
this.undoManager = undoManager;
this.stateManager = stateManager;
this.executable.bind(ActionHelper.needsEntriesSelected(stateManager));
}
@Override
public void execute() {
try {
List<BibEntry> bes = stateManager.getSelectedEntries();
if ((bes == null) || bes.isEmpty()) {
return;
}
NamedCompound ce = new NamedCompound(undoText);
List<BibEntry> besCopy = new ArrayList<>(bes);
for (BibEntry bibEntry : besCopy) {
// if (value==null) and then call nullField has been omitted as updatefield also handles value==null
Optional<FieldChange> change = UpdateField.updateField(bibEntry, specialField, value, nullFieldIfValueIsTheSame);
change.ifPresent(fieldChange -> ce.addEdit(new UndoableFieldChange(fieldChange)));
}
ce.end();
if (ce.hasEdits()) {
frame.getCurrentLibraryTab().getUndoManager().addEdit(ce);
frame.getCurrentLibraryTab().markBaseChanged();
frame.getCurrentLibraryTab().updateEntryEditorIfShowing();
String outText;
if (nullFieldIfValueIsTheSame || value == null) {
outText = getTextDone(specialField, Integer.toString(bes.size()));
} else {
outText = getTextDone(specialField, value, Integer.toString(bes.size()));
}
dialogService.notify(outText);
}
// if user does not change anything with his action, we do not do anything either, even no output message
} catch (Throwable ex) {
LOGGER.error("Problem setting special fields", ex);
}
}
private String getTextDone(SpecialField field, String... params) {
Objects.requireNonNull(params);
SpecialFieldViewModel viewModel = new SpecialFieldViewModel(field, preferencesService, undoManager);
if (field.isSingleValueField() && (params.length == 1) && (params[0] != null)) {
// Single value fields can be toggled only
return Localization.lang("Toggled '%0' for %1 entries", viewModel.getLocalization(), params[0]);
} else if (!field.isSingleValueField() && (params.length == 2) && (params[0] != null) && (params[1] != null)) {
// setting a multi value special field - the setted value is displayed, too
String[] allParams = {viewModel.getLocalization(), params[0], params[1]};
return Localization.lang("Set '%0' to '%1' for %2 entries", allParams);
} else if (!field.isSingleValueField() && (params.length == 1) && (params[0] != null)) {
// clearing a multi value specialfield
return Localization.lang("Cleared '%0' for %1 entries", viewModel.getLocalization(), params[0]);
} else {
// invalid usage
LOGGER.info("Creation of special field status change message failed: illegal argument combination.");
return "";
}
}
}
| 5,407
| 43.327869
| 149
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/specialfields/SpecialFieldMenuItemFactory.java
|
package org.jabref.gui.specialfields;
import java.util.function.Function;
import javax.swing.undo.UndoManager;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import org.jabref.gui.DialogService;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.ActionFactory;
import org.jabref.model.entry.field.SpecialField;
import org.jabref.model.entry.field.SpecialFieldValue;
import org.jabref.preferences.PreferencesService;
import de.saxsys.mvvmfx.utils.commands.Command;
public class SpecialFieldMenuItemFactory {
public static MenuItem getSpecialFieldSingleItem(SpecialField field,
ActionFactory factory,
JabRefFrame frame,
DialogService dialogService,
PreferencesService preferencesService,
UndoManager undoManager,
StateManager stateManager) {
SpecialFieldValueViewModel specialField = new SpecialFieldValueViewModel(field.getValues().get(0));
MenuItem menuItem = factory.createMenuItem(specialField.getAction(),
new SpecialFieldViewModel(field, preferencesService, undoManager)
.getSpecialFieldAction(field.getValues().get(0), frame, dialogService, stateManager));
menuItem.visibleProperty().bind(preferencesService.getSpecialFieldsPreferences().specialFieldsEnabledProperty());
return menuItem;
}
public static Menu createSpecialFieldMenu(SpecialField field,
ActionFactory factory,
JabRefFrame frame,
DialogService dialogService,
PreferencesService preferencesService,
UndoManager undoManager,
StateManager stateManager) {
return createSpecialFieldMenu(field, factory, preferencesService, undoManager, specialField ->
new SpecialFieldViewModel(field, preferencesService, undoManager)
.getSpecialFieldAction(specialField.getValue(), frame, dialogService, stateManager));
}
public static Menu createSpecialFieldMenu(SpecialField field,
ActionFactory factory,
PreferencesService preferencesService,
UndoManager undoManager,
Function<SpecialFieldValueViewModel, Command> commandFactory) {
SpecialFieldViewModel viewModel = new SpecialFieldViewModel(field, preferencesService, undoManager);
Menu menu = factory.createMenu(viewModel.getAction());
for (SpecialFieldValue Value : field.getValues()) {
SpecialFieldValueViewModel valueViewModel = new SpecialFieldValueViewModel(Value);
menu.getItems().add(factory.createMenuItem(valueViewModel.getAction(), commandFactory.apply(valueViewModel)));
}
menu.visibleProperty().bind(preferencesService.getSpecialFieldsPreferences().specialFieldsEnabledProperty());
return menu;
}
}
| 3,494
| 51.954545
| 122
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/specialfields/SpecialFieldValueViewModel.java
|
package org.jabref.gui.specialfields;
import java.util.Objects;
import java.util.Optional;
import org.jabref.gui.actions.Action;
import org.jabref.gui.actions.StandardActions;
import org.jabref.gui.icon.JabRefIcon;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.entry.field.SpecialFieldValue;
public class SpecialFieldValueViewModel {
private final SpecialFieldValue value;
public SpecialFieldValueViewModel(SpecialFieldValue value) {
Objects.requireNonNull(value);
this.value = value;
}
public SpecialFieldValue getValue() {
return value;
}
public Optional<JabRefIcon> getIcon() {
return getAction().getIcon();
}
public String getMenuString() {
return getAction().getText();
}
public String getToolTipText() {
return switch (value) {
case PRINTED -> Localization.lang("Toggle print status");
case CLEAR_PRIORITY -> Localization.lang("No priority information");
case PRIORITY_HIGH -> Localization.lang("Priority high");
case PRIORITY_MEDIUM -> Localization.lang("Priority medium");
case PRIORITY_LOW -> Localization.lang("Priority low");
case QUALITY_ASSURED -> Localization.lang("Toggle quality assured");
case CLEAR_RANK -> Localization.lang("No rank information");
case RANK_1 -> Localization.lang("One star");
case RANK_2 -> Localization.lang("Two stars");
case RANK_3 -> Localization.lang("Three stars");
case RANK_4 -> Localization.lang("Four stars");
case RANK_5 -> Localization.lang("Five stars");
case CLEAR_READ_STATUS -> Localization.lang("No read status information");
case READ -> Localization.lang("Read status read");
case SKIMMED -> Localization.lang("Read status skimmed");
case RELEVANT -> Localization.lang("Toggle relevance");
};
}
public Action getAction() {
return switch (value) {
case PRINTED -> StandardActions.TOGGLE_PRINTED;
case CLEAR_PRIORITY -> StandardActions.CLEAR_PRIORITY;
case PRIORITY_HIGH -> StandardActions.PRIORITY_HIGH;
case PRIORITY_MEDIUM -> StandardActions.PRIORITY_MEDIUM;
case PRIORITY_LOW -> StandardActions.PRIORITY_LOW;
case QUALITY_ASSURED -> StandardActions.QUALITY_ASSURED;
case CLEAR_RANK -> StandardActions.CLEAR_RANK;
case RANK_1 -> StandardActions.RANK_1;
case RANK_2 -> StandardActions.RANK_2;
case RANK_3 -> StandardActions.RANK_3;
case RANK_4 -> StandardActions.RANK_4;
case RANK_5 -> StandardActions.RANK_5;
case CLEAR_READ_STATUS -> StandardActions.CLEAR_READ_STATUS;
case READ -> StandardActions.READ;
case SKIMMED -> StandardActions.SKIMMED;
case RELEVANT -> StandardActions.RELEVANT;
};
}
}
| 2,992
| 38.906667
| 86
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/specialfields/SpecialFieldViewModel.java
|
package org.jabref.gui.specialfields;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.swing.undo.UndoManager;
import org.jabref.gui.DialogService;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.Action;
import org.jabref.gui.actions.StandardActions;
import org.jabref.gui.icon.JabRefIcon;
import org.jabref.gui.undo.UndoableFieldChange;
import org.jabref.logic.util.UpdateField;
import org.jabref.model.FieldChange;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.SpecialField;
import org.jabref.model.entry.field.SpecialFieldValue;
import org.jabref.preferences.PreferencesService;
public class SpecialFieldViewModel {
private final SpecialField field;
private final PreferencesService preferencesService;
private final UndoManager undoManager;
public SpecialFieldViewModel(SpecialField field, PreferencesService preferencesService, UndoManager undoManager) {
this.field = Objects.requireNonNull(field);
this.preferencesService = Objects.requireNonNull(preferencesService);
this.undoManager = Objects.requireNonNull(undoManager);
}
public SpecialField getField() {
return field;
}
public SpecialFieldAction getSpecialFieldAction(SpecialFieldValue value,
JabRefFrame frame,
DialogService dialogService,
StateManager stateManager) {
return new SpecialFieldAction(
frame,
field,
value.getFieldValue().orElse(null),
// if field contains only one value, it has to be nulled, as another setting does not empty the field
field.getValues().size() == 1,
getLocalization(),
dialogService,
preferencesService,
undoManager,
stateManager);
}
public JabRefIcon getIcon() {
return getAction().getIcon().orElse(null);
}
public String getLocalization() {
return getAction().getText();
}
public Action getAction() {
return switch (field) {
case PRINTED -> StandardActions.PRINTED;
case PRIORITY -> StandardActions.PRIORITY;
case QUALITY -> StandardActions.QUALITY;
case RANKING -> StandardActions.RANKING;
case READ_STATUS -> StandardActions.READ_STATUS;
case RELEVANCE -> StandardActions.RELEVANCE;
};
}
public JabRefIcon getEmptyIcon() {
return getIcon();
}
public List<SpecialFieldValueViewModel> getValues() {
return field.getValues().stream()
.map(SpecialFieldValueViewModel::new)
.collect(Collectors.toList());
}
public void setSpecialFieldValue(BibEntry bibEntry, SpecialFieldValue value) {
Optional<FieldChange> change = UpdateField.updateField(bibEntry, getField(), value.getFieldValue().orElse(null), getField().isSingleValueField());
change.ifPresent(fieldChange -> undoManager.addEdit(new UndoableFieldChange(fieldChange)));
}
public void toggle(BibEntry entry) {
setSpecialFieldValue(entry, getField().getValues().get(0));
}
}
| 3,429
| 34.729167
| 154
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/specialfields/SpecialFieldsPreferences.java
|
package org.jabref.gui.specialfields;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
public class SpecialFieldsPreferences {
public static final int COLUMN_RANKING_WIDTH = 5 * 16; // Width of Ranking Icon Column
private final BooleanProperty specialFieldsEnabled;
public SpecialFieldsPreferences(boolean specialFieldsEnabled) {
this.specialFieldsEnabled = new SimpleBooleanProperty(specialFieldsEnabled);
}
public boolean isSpecialFieldsEnabled() {
return specialFieldsEnabled.getValue();
}
public BooleanProperty specialFieldsEnabledProperty() {
return specialFieldsEnabled;
}
public void setSpecialFieldsEnabled(boolean specialFieldsEnabled) {
this.specialFieldsEnabled.set(specialFieldsEnabled);
}
}
| 834
| 28.821429
| 90
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/texparser/CitationsDisplay.java
|
package org.jabref.gui.texparser;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.Node;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.util.ViewModelListCellFactory;
import org.jabref.model.strings.LatexToUnicodeAdapter;
import org.jabref.model.texparser.Citation;
public class CitationsDisplay extends ListView<Citation> {
private final ObjectProperty<Path> basePath;
public CitationsDisplay() {
this.basePath = new SimpleObjectProperty<>(null);
new ViewModelListCellFactory<Citation>().withGraphic(this::getDisplayGraphic)
.withTooltip(this::getDisplayTooltip)
.install(this);
this.getStyleClass().add("citationsList");
}
public ObjectProperty<Path> basePathProperty() {
return basePath;
}
private Node getDisplayGraphic(Citation item) {
if (basePath.get() == null) {
basePath.set(item.getPath().getRoot());
}
Node citationIcon = IconTheme.JabRefIcons.LATEX_COMMENT.getGraphicNode();
Text contextText = new Text(LatexToUnicodeAdapter.format(item.getContext()));
contextText.wrappingWidthProperty().bind(this.widthProperty().subtract(85));
HBox contextBox = new HBox(8, citationIcon, contextText);
contextBox.getStyleClass().add("contextBox");
Label fileNameLabel = new Label(String.format("%s", basePath.get().relativize(item.getPath())));
fileNameLabel.setGraphic(IconTheme.JabRefIcons.LATEX_FILE.getGraphicNode());
Label positionLabel = new Label(String.format("(%s:%s-%s)", item.getLine(), item.getColStart(), item.getColEnd()));
positionLabel.setGraphic(IconTheme.JabRefIcons.LATEX_LINE.getGraphicNode());
HBox dataBox = new HBox(5, fileNameLabel, positionLabel);
return new VBox(contextBox, dataBox);
}
private Tooltip getDisplayTooltip(Citation item) {
String line = item.getLineText();
int start = item.getColStart();
int end = item.getColEnd();
List<Text> texts = new ArrayList<>(3);
// Text before the citation.
if (start > 0) {
texts.add(new Text(line.substring(0, start)));
}
// Citation text (highlighted).
Text citation = new Text(line.substring(start, end));
citation.getStyleClass().setAll("tooltip-text-bold");
texts.add(citation);
// Text after the citation.
if (end < line.length()) {
texts.add(new Text(line.substring(end)));
}
Tooltip tooltip = new Tooltip();
tooltip.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
tooltip.setGraphic(new TextFlow(texts.toArray(new Text[0])));
tooltip.setMaxHeight(10);
tooltip.setMinWidth(200);
tooltip.maxWidthProperty().bind(this.widthProperty().subtract(85));
tooltip.setWrapText(true);
return tooltip;
}
}
| 3,411
| 35.297872
| 123
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/texparser/ParseLatexAction.java
|
package org.jabref.gui.texparser;
import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.ActionHelper;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.model.database.BibDatabaseContext;
import com.airhacks.afterburner.injection.Injector;
public class ParseLatexAction extends SimpleCommand {
private final StateManager stateManager;
public ParseLatexAction(StateManager stateManager) {
this.stateManager = stateManager;
executable.bind(ActionHelper.needsDatabase(stateManager));
}
@Override
public void execute() {
DialogService dialogService = Injector.instantiateModelOrService(DialogService.class);
BibDatabaseContext database = stateManager.getActiveDatabase().orElseThrow(NullPointerException::new);
dialogService.showCustomDialogAndWait(new ParseLatexDialogView(database));
}
}
| 917
| 33
| 110
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/texparser/ParseLatexDialogView.java
|
package org.jabref.gui.texparser;
import javafx.beans.binding.Bindings;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.CheckBoxTreeItem;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TextField;
import org.jabref.gui.DialogService;
import org.jabref.gui.theme.ThemeManager;
import org.jabref.gui.util.BaseDialog;
import org.jabref.gui.util.ControlHelper;
import org.jabref.gui.util.FileNodeViewModel;
import org.jabref.gui.util.IconValidationDecorator;
import org.jabref.gui.util.RecursiveTreeItem;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.gui.util.ViewModelTreeCellFactory;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.util.FileUpdateMonitor;
import org.jabref.preferences.PreferencesService;
import com.airhacks.afterburner.views.ViewLoader;
import com.tobiasdiez.easybind.EasyBind;
import de.saxsys.mvvmfx.utils.validation.visualization.ControlsFxVisualizer;
import jakarta.inject.Inject;
import org.controlsfx.control.CheckTreeView;
public class ParseLatexDialogView extends BaseDialog<Void> {
private final BibDatabaseContext databaseContext;
private final ControlsFxVisualizer validationVisualizer;
@FXML private TextField latexDirectoryField;
@FXML private Button browseButton;
@FXML private Button searchButton;
@FXML private ProgressIndicator progressIndicator;
@FXML private CheckTreeView<FileNodeViewModel> fileTreeView;
@FXML private Button selectAllButton;
@FXML private Button unselectAllButton;
@FXML private ButtonType parseButtonType;
@Inject private DialogService dialogService;
@Inject private TaskExecutor taskExecutor;
@Inject private PreferencesService preferencesService;
@Inject private FileUpdateMonitor fileMonitor;
@Inject private ThemeManager themeManager;
private ParseLatexDialogViewModel viewModel;
public ParseLatexDialogView(BibDatabaseContext databaseContext) {
this.databaseContext = databaseContext;
this.validationVisualizer = new ControlsFxVisualizer();
setTitle(Localization.lang("Search for citations in LaTeX files..."));
ViewLoader.view(this).load().setAsDialogPane(this);
ControlHelper.setAction(parseButtonType, getDialogPane(), event -> viewModel.parseButtonClicked());
Button parseButton = (Button) getDialogPane().lookupButton(parseButtonType);
parseButton.disableProperty().bind(viewModel.noFilesFoundProperty().or(
Bindings.isEmpty(viewModel.getCheckedFileList())));
themeManager.updateFontStyle(getDialogPane().getScene());
}
@FXML
private void initialize() {
viewModel = new ParseLatexDialogViewModel(databaseContext, dialogService, taskExecutor, preferencesService, fileMonitor);
fileTreeView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
fileTreeView.showRootProperty().bindBidirectional(viewModel.successfulSearchProperty());
fileTreeView.rootProperty().bind(EasyBind.map(viewModel.rootProperty(), fileNode ->
new RecursiveTreeItem<>(fileNode, FileNodeViewModel::getChildren)));
new ViewModelTreeCellFactory<FileNodeViewModel>()
.withText(FileNodeViewModel::getDisplayText)
.install(fileTreeView);
EasyBind.subscribe(fileTreeView.rootProperty(), root -> {
((CheckBoxTreeItem<FileNodeViewModel>) root).setSelected(true);
root.setExpanded(true);
EasyBind.bindContent(viewModel.getCheckedFileList(), fileTreeView.getCheckModel().getCheckedItems());
});
latexDirectoryField.textProperty().bindBidirectional(viewModel.latexFileDirectoryProperty());
validationVisualizer.setDecoration(new IconValidationDecorator());
validationVisualizer.initVisualization(viewModel.latexDirectoryValidation(), latexDirectoryField);
browseButton.disableProperty().bindBidirectional(viewModel.searchInProgressProperty());
searchButton.disableProperty().bind(viewModel.latexDirectoryValidation().validProperty().not());
selectAllButton.disableProperty().bindBidirectional(viewModel.noFilesFoundProperty());
unselectAllButton.disableProperty().bindBidirectional(viewModel.noFilesFoundProperty());
progressIndicator.visibleProperty().bindBidirectional(viewModel.searchInProgressProperty());
}
@FXML
private void browseButtonClicked() {
viewModel.browseButtonClicked();
}
@FXML
private void searchButtonClicked() {
viewModel.searchButtonClicked();
}
@FXML
private void selectAll() {
fileTreeView.getCheckModel().checkAll();
}
@FXML
private void unselectAll() {
fileTreeView.getCheckModel().clearChecks();
}
}
| 4,964
| 41.801724
| 129
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/texparser/ParseLatexDialogViewModel.java
|
package org.jabref.gui.texparser;
import java.io.IOException;
import java.nio.file.FileSystemException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ReadOnlyListWrapper;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.TreeItem;
import org.jabref.gui.AbstractViewModel;
import org.jabref.gui.DialogService;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.gui.util.DirectoryDialogConfiguration;
import org.jabref.gui.util.FileNodeViewModel;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.texparser.DefaultLatexParser;
import org.jabref.logic.texparser.TexBibEntriesResolver;
import org.jabref.logic.util.io.FileUtil;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.util.FileUpdateMonitor;
import org.jabref.preferences.PreferencesService;
import de.saxsys.mvvmfx.utils.validation.FunctionBasedValidator;
import de.saxsys.mvvmfx.utils.validation.ValidationMessage;
import de.saxsys.mvvmfx.utils.validation.ValidationStatus;
import de.saxsys.mvvmfx.utils.validation.Validator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ParseLatexDialogViewModel extends AbstractViewModel {
private static final Logger LOGGER = LoggerFactory.getLogger(ParseLatexDialogViewModel.class);
private static final String TEX_EXT = ".tex";
private final BibDatabaseContext databaseContext;
private final DialogService dialogService;
private final TaskExecutor taskExecutor;
private final PreferencesService preferencesService;
private final FileUpdateMonitor fileMonitor;
private final StringProperty latexFileDirectory;
private final Validator latexDirectoryValidator;
private final ObjectProperty<FileNodeViewModel> root;
private final ObservableList<TreeItem<FileNodeViewModel>> checkedFileList;
private final BooleanProperty noFilesFound;
private final BooleanProperty searchInProgress;
private final BooleanProperty successfulSearch;
public ParseLatexDialogViewModel(BibDatabaseContext databaseContext,
DialogService dialogService,
TaskExecutor taskExecutor,
PreferencesService preferencesService,
FileUpdateMonitor fileMonitor) {
this.databaseContext = databaseContext;
this.dialogService = dialogService;
this.taskExecutor = taskExecutor;
this.preferencesService = preferencesService;
this.fileMonitor = fileMonitor;
this.latexFileDirectory = new SimpleStringProperty(databaseContext.getMetaData().getLatexFileDirectory(preferencesService.getFilePreferences().getUserAndHost())
.orElse(FileUtil.getInitialDirectory(databaseContext, preferencesService.getFilePreferences().getWorkingDirectory()))
.toAbsolutePath().toString());
this.root = new SimpleObjectProperty<>();
this.checkedFileList = FXCollections.observableArrayList();
this.noFilesFound = new SimpleBooleanProperty(true);
this.searchInProgress = new SimpleBooleanProperty(false);
this.successfulSearch = new SimpleBooleanProperty(false);
Predicate<String> isDirectory = path -> Path.of(path).toFile().isDirectory();
latexDirectoryValidator = new FunctionBasedValidator<>(latexFileDirectory, isDirectory,
ValidationMessage.error(Localization.lang("Please enter a valid file path.")));
}
public StringProperty latexFileDirectoryProperty() {
return latexFileDirectory;
}
public ValidationStatus latexDirectoryValidation() {
return latexDirectoryValidator.getValidationStatus();
}
public ObjectProperty<FileNodeViewModel> rootProperty() {
return root;
}
public ObservableList<TreeItem<FileNodeViewModel>> getCheckedFileList() {
return new ReadOnlyListWrapper<>(checkedFileList);
}
public BooleanProperty noFilesFoundProperty() {
return noFilesFound;
}
public BooleanProperty searchInProgressProperty() {
return searchInProgress;
}
public BooleanProperty successfulSearchProperty() {
return successfulSearch;
}
public void browseButtonClicked() {
DirectoryDialogConfiguration directoryDialogConfiguration = new DirectoryDialogConfiguration.Builder()
.withInitialDirectory(Path.of(latexFileDirectory.get())).build();
dialogService.showDirectorySelectionDialog(directoryDialogConfiguration).ifPresent(selectedDirectory -> {
latexFileDirectory.set(selectedDirectory.toAbsolutePath().toString());
preferencesService.getFilePreferences().setWorkingDirectory(selectedDirectory.toAbsolutePath());
});
}
/**
* Run a recursive search in a background task.
*/
public void searchButtonClicked() {
BackgroundTask.wrap(() -> searchDirectory(Path.of(latexFileDirectory.get())))
.onRunning(() -> {
root.set(null);
noFilesFound.set(true);
searchInProgress.set(true);
successfulSearch.set(false);
})
.onFinished(() -> searchInProgress.set(false))
.onSuccess(newRoot -> {
root.set(newRoot);
noFilesFound.set(false);
successfulSearch.set(true);
})
.onFailure(this::handleFailure)
.executeWith(taskExecutor);
}
private void handleFailure(Exception exception) {
final boolean permissionProblem = (exception instanceof IOException) && (exception.getCause() instanceof FileSystemException) && exception.getCause().getMessage().endsWith("Operation not permitted");
if (permissionProblem) {
dialogService.showErrorDialogAndWait(String.format(Localization.lang("JabRef does not have permission to access %s"), exception.getCause().getMessage()));
} else {
dialogService.showErrorDialogAndWait(exception);
}
}
private FileNodeViewModel searchDirectory(Path directory) throws IOException {
if ((directory == null) || !directory.toFile().isDirectory()) {
throw new IOException(String.format("Invalid directory for searching: %s", directory));
}
FileNodeViewModel parent = new FileNodeViewModel(directory);
Map<Boolean, List<Path>> fileListPartition;
try (Stream<Path> filesStream = Files.list(directory)) {
fileListPartition = filesStream.collect(Collectors.partitioningBy(path -> path.toFile().isDirectory()));
} catch (IOException e) {
LOGGER.error(String.format("%s while searching files: %s", e.getClass().getName(), e.getMessage()));
return parent;
}
List<Path> subDirectories = fileListPartition.get(true);
List<Path> files = fileListPartition.get(false)
.stream()
.filter(path -> path.toString().endsWith(TEX_EXT))
.collect(Collectors.toList());
int fileCount = 0;
for (Path subDirectory : subDirectories) {
FileNodeViewModel subRoot = searchDirectory(subDirectory);
if (!subRoot.getChildren().isEmpty()) {
fileCount += subRoot.getFileCount();
parent.getChildren().add(subRoot);
}
}
parent.setFileCount(files.size() + fileCount);
parent.getChildren().addAll(files.stream()
.map(FileNodeViewModel::new)
.collect(Collectors.toList()));
return parent;
}
/**
* Parse all checked files in a background task.
*/
public void parseButtonClicked() {
List<Path> fileList = checkedFileList.stream()
.map(item -> item.getValue().getPath())
.filter(path -> path.toFile().isFile())
.collect(Collectors.toList());
if (fileList.isEmpty()) {
LOGGER.warn("There are no valid files checked");
return;
}
TexBibEntriesResolver entriesResolver = new TexBibEntriesResolver(
databaseContext.getDatabase(),
preferencesService.getLibraryPreferences(),
preferencesService.getImportFormatPreferences(),
fileMonitor);
BackgroundTask.wrap(() -> entriesResolver.resolve(new DefaultLatexParser().parse(fileList)))
.onRunning(() -> searchInProgress.set(true))
.onFinished(() -> searchInProgress.set(false))
.onSuccess(result -> dialogService.showCustomDialogAndWait(
new ParseLatexResultView(result, databaseContext, Path.of(latexFileDirectory.get()))))
.onFailure(dialogService::showErrorDialogAndWait)
.executeWith(taskExecutor);
}
}
| 9,992
| 44.422727
| 207
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/texparser/ParseLatexResultView.java
|
package org.jabref.gui.texparser;
import java.nio.file.Path;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ListView;
import javafx.scene.text.Text;
import org.jabref.gui.theme.ThemeManager;
import org.jabref.gui.util.BaseDialog;
import org.jabref.gui.util.ControlHelper;
import org.jabref.gui.util.ViewModelListCellFactory;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.texparser.LatexBibEntriesResolverResult;
import com.airhacks.afterburner.views.ViewLoader;
import com.tobiasdiez.easybind.EasyBind;
import jakarta.inject.Inject;
public class ParseLatexResultView extends BaseDialog<Void> {
private final LatexBibEntriesResolverResult resolverResult;
private final BibDatabaseContext databaseContext;
private final Path basePath;
@FXML private ListView<ReferenceViewModel> referenceListView;
@FXML private CitationsDisplay citationsDisplay;
@FXML private ButtonType importButtonType;
@Inject private ThemeManager themeManager;
private ParseLatexResultViewModel viewModel;
public ParseLatexResultView(LatexBibEntriesResolverResult resolverResult, BibDatabaseContext databaseContext, Path basePath) {
this.resolverResult = resolverResult;
this.databaseContext = databaseContext;
this.basePath = basePath;
setTitle(Localization.lang("LaTeX Citations Search Results"));
ViewLoader.view(this).load().setAsDialogPane(this);
ControlHelper.setAction(importButtonType, getDialogPane(), event -> {
viewModel.importButtonClicked();
close();
});
Button importButton = (Button) getDialogPane().lookupButton(importButtonType);
importButton.disableProperty().bind(viewModel.importButtonDisabledProperty());
themeManager.updateFontStyle(getDialogPane().getScene());
}
@FXML
private void initialize() {
viewModel = new ParseLatexResultViewModel(resolverResult, databaseContext);
referenceListView.setItems(viewModel.getReferenceList());
referenceListView.getSelectionModel().selectFirst();
new ViewModelListCellFactory<ReferenceViewModel>()
.withGraphic(reference -> {
Text referenceText = new Text(reference.getDisplayText());
if (reference.isHighlighted()) {
referenceText.setStyle("-fx-fill: -fx-accent");
}
return referenceText;
})
.install(referenceListView);
EasyBind.subscribe(referenceListView.getSelectionModel().selectedItemProperty(),
viewModel::activeReferenceChanged);
citationsDisplay.basePathProperty().set(basePath);
citationsDisplay.setItems(viewModel.getCitationListByReference());
}
}
| 2,941
| 37.710526
| 130
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/texparser/ParseLatexResultViewModel.java
|
package org.jabref.gui.texparser;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ReadOnlyListWrapper;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.jabref.gui.AbstractViewModel;
import org.jabref.gui.DialogService;
import org.jabref.gui.importer.ImportEntriesDialog;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.logic.importer.ParserResult;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.texparser.Citation;
import org.jabref.model.texparser.LatexBibEntriesResolverResult;
import com.airhacks.afterburner.injection.Injector;
public class ParseLatexResultViewModel extends AbstractViewModel {
private final LatexBibEntriesResolverResult resolverResult;
private final BibDatabaseContext databaseContext;
private final ObservableList<ReferenceViewModel> referenceList;
private final ObservableList<Citation> citationList;
private final BooleanProperty importButtonDisabled;
public ParseLatexResultViewModel(LatexBibEntriesResolverResult resolverResult, BibDatabaseContext databaseContext) {
this.resolverResult = resolverResult;
this.databaseContext = databaseContext;
this.referenceList = FXCollections.observableArrayList();
this.citationList = FXCollections.observableArrayList();
Set<String> newEntryKeys = resolverResult.getNewEntries().stream().map(entry -> entry.getCitationKey().orElse("")).collect(Collectors.toSet());
for (Map.Entry<String, Collection<Citation>> entry : resolverResult.getCitations().asMap().entrySet()) {
String key = entry.getKey();
referenceList.add(new ReferenceViewModel(key, newEntryKeys.contains(key), entry.getValue()));
}
this.importButtonDisabled = new SimpleBooleanProperty(referenceList.stream().noneMatch(ReferenceViewModel::isHighlighted));
}
public ObservableList<ReferenceViewModel> getReferenceList() {
return new ReadOnlyListWrapper<>(referenceList);
}
public ObservableList<Citation> getCitationListByReference() {
return new ReadOnlyListWrapper<>(citationList);
}
public BooleanProperty importButtonDisabledProperty() {
return importButtonDisabled;
}
/**
* Update the citation list depending on the selected reference.
*/
public void activeReferenceChanged(ReferenceViewModel reference) {
if (reference == null) {
citationList.clear();
} else {
citationList.setAll(reference.getCitationList());
}
}
/**
* Search and import unknown references from associated BIB files.
*/
public void importButtonClicked() {
DialogService dialogService = Injector.instantiateModelOrService(DialogService.class);
ImportEntriesDialog dialog = new ImportEntriesDialog(databaseContext, BackgroundTask.wrap(() -> new ParserResult(resolverResult.getNewEntries())));
dialog.setTitle(Localization.lang("Import entries from LaTeX files"));
dialogService.showCustomDialogAndWait(dialog);
}
}
| 3,337
| 39.707317
| 155
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/texparser/ReferenceViewModel.java
|
package org.jabref.gui.texparser;
import java.util.Collection;
import javafx.beans.property.ReadOnlyListWrapper;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.jabref.model.texparser.Citation;
public class ReferenceViewModel {
private final String entry;
private final boolean highlighted;
private final ObservableList<Citation> citationList;
public ReferenceViewModel(String entry, boolean highlighted, Collection<Citation> citationColl) {
this.entry = entry;
this.highlighted = highlighted;
this.citationList = FXCollections.observableArrayList();
citationList.setAll(citationColl);
}
public boolean isHighlighted() {
return highlighted;
}
public ObservableList<Citation> getCitationList() {
return new ReadOnlyListWrapper<>(citationList);
}
/**
* Return a string for displaying an entry key and its number of uses.
*/
public String getDisplayText() {
return String.format("%s (%s)", entry, citationList.size());
}
@Override
public String toString() {
return String.format("ReferenceViewModel{entry='%s', highlighted=%s, citationList=%s}",
this.entry,
this.highlighted,
this.citationList);
}
}
| 1,336
| 26.854167
| 101
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/theme/StyleSheet.java
|
package org.jabref.gui.theme;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.util.Optional;
import org.jabref.gui.JabRefFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
abstract class StyleSheet {
static final String DATA_URL_PREFIX = "data:text/css;charset=utf-8;base64,";
static final String EMPTY_WEBENGINE_CSS = DATA_URL_PREFIX;
private static final Logger LOGGER = LoggerFactory.getLogger(StyleSheet.class);
abstract URL getSceneStylesheet();
abstract String getWebEngineStylesheet();
Path getWatchPath() {
return null;
}
abstract void reload();
static Optional<StyleSheet> create(String name) {
Optional<URL> styleSheetUrl = Optional.ofNullable(JabRefFrame.class.getResource(name));
if (styleSheetUrl.isEmpty()) {
try {
styleSheetUrl = Optional.of(Path.of(name).toUri().toURL());
} catch (InvalidPathException e) {
LOGGER.warn("Cannot load additional css {} because it is an invalid path: {}", name, e.getLocalizedMessage());
} catch (MalformedURLException e) {
LOGGER.warn("Cannot load additional css url {} because it is a malformed url: {}", name, e.getLocalizedMessage());
}
}
if (styleSheetUrl.isEmpty()) {
try {
return Optional.of(new StyleSheetDataUrl(new URL(EMPTY_WEBENGINE_CSS)));
} catch (MalformedURLException e) {
return Optional.empty();
}
} else if ("file".equals(styleSheetUrl.get().getProtocol())) {
StyleSheet styleSheet = new StyleSheetFile(styleSheetUrl.get());
if (Files.isDirectory(styleSheet.getWatchPath())) {
LOGGER.warn("Failed to loadCannot load additional css {} because it is a directory.", styleSheet.getWatchPath());
return Optional.empty();
}
if (!Files.exists(styleSheet.getWatchPath())) {
LOGGER.warn("Cannot load additional css {} because the file does not exist.", styleSheet.getWatchPath());
// Should not return empty, since the user can create the file later.
}
return Optional.of(new StyleSheetFile(styleSheetUrl.get()));
} else {
return Optional.of(new StyleSheetResource(styleSheetUrl.get()));
}
}
@Override
public String toString() {
return "StyleSheet{" + getSceneStylesheet() + "}";
}
}
| 2,629
| 34.066667
| 130
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/theme/StyleSheetDataUrl.java
|
package org.jabref.gui.theme;
import java.net.URL;
public class StyleSheetDataUrl extends StyleSheet {
private final URL url;
private volatile String dataUrl;
StyleSheetDataUrl(URL url) {
this.url = url;
reload();
}
@Override
URL getSceneStylesheet() {
return url;
}
@Override
public String getWebEngineStylesheet() {
return dataUrl;
}
@Override
void reload() {
StyleSheetFile.getDataUrl(url).ifPresentOrElse(createdUrl -> dataUrl = createdUrl, () -> dataUrl = EMPTY_WEBENGINE_CSS);
}
@Override
public String toString() {
return "StyleSheet{" + getSceneStylesheet() + "}";
}
}
| 698
| 18.416667
| 128
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/theme/StyleSheetFile.java
|
package org.jabref.gui.theme;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
final class StyleSheetFile extends StyleSheet {
/**
* A size limit above which Theme will not attempt to keep a data-embedded URL in memory for the CSS.
*
* It's tolerable for CSS to exceed this limit; the functional benefit of the encoded CSS is in some edge
* case error handling. Specifically, having a reference to a data-embedded URL means that the Preview Viewer
* isn't impacted if the source CSS file is removed while the application is running.
*
* If the CSS is over this limit, then the user won't see any functional impact, as long as the file exists. Only if
* it becomes unavailable, might there be some impact. First, the Preview Viewer when created might not be themed.
* Second, there is a very small chance of uncaught exceptions. Theme makes a best effort to avoid this:
* it checks for CSS file existence before passing it to the Preview Viewer for theming. Still, as file existence
* checks are immediately out of date, it can't be perfectly ruled out.
*
* At the time of writing this comment:
*
* <ul>
* <li>src/main/java/org/jabref/gui/Base.css is 33k</li>
* <li>src/main/java/org/jabref/gui/Dark.css is 4k</li>
* <li>The dark custom theme in the Jabref documentation is 2k, see
* <a href="https://docs.jabref.org/advanced/custom-themes">Custom themes</a></li>
* </ul>
*
* So realistic custom themes will fit comfortably within 48k, even if they are modified copies of the base theme.
*
* Note that Base-64 encoding will increase the memory footprint of the URL by a third.
*/
static final int MAX_IN_MEMORY_CSS_LENGTH = 48000;
private static final Logger LOGGER = LoggerFactory.getLogger(StyleSheetFile.class);
private final URL url;
private final Path path;
private final AtomicReference<String> dataUrl = new AtomicReference<>();
StyleSheetFile(URL url) {
this.url = url;
this.path = Path.of(URI.create(url.toExternalForm()));
reload();
}
@Override
Path getWatchPath() {
return path;
}
@Override
void reload() {
getDataUrl(url).ifPresentOrElse(dataUrl::set, () -> dataUrl.set(""));
}
@Override
public URL getSceneStylesheet() {
if (!Files.exists(path)) {
LOGGER.warn("Cannot load additional css {} because the file does not exist.", path);
return null;
}
if (Files.isDirectory(path)) {
LOGGER.warn("Failed to loadCannot load additional css {} because it is a directory.", path);
return null;
}
return url;
}
/**
* This method allows callers to obtain the theme's additional stylesheet.
*
* @return the stylesheet location if there is an additional stylesheet present and available. The
* location will be a local URL. Typically it will be a {@code 'data:'} URL where the CSS is embedded. However for
* large themes it can be {@code 'file:'}.
*/
@Override
public String getWebEngineStylesheet() {
if (Strings.isNullOrEmpty(dataUrl.get())) {
reload();
}
if (Strings.isNullOrEmpty(dataUrl.get())) {
URL stylesheet = getSceneStylesheet();
return stylesheet == null ? "" : stylesheet.toExternalForm();
}
return dataUrl.get();
}
static Optional<String> getDataUrl(URL url) {
try {
URLConnection conn = url.openConnection();
conn.connect();
try (InputStream inputStream = conn.getInputStream()) {
byte[] data = inputStream.readNBytes(MAX_IN_MEMORY_CSS_LENGTH);
if (data.length < MAX_IN_MEMORY_CSS_LENGTH) {
String embeddedDataUrl = DATA_URL_PREFIX + Base64.getEncoder().encodeToString(data);
LOGGER.debug("Embedded css in data URL of length {}", embeddedDataUrl.length());
return Optional.of(embeddedDataUrl);
} else {
LOGGER.debug("Not embedding css in data URL as the length is >= {}", MAX_IN_MEMORY_CSS_LENGTH);
}
}
} catch (IOException e) {
LOGGER.warn("Could not load css url {}", url, e);
}
return Optional.empty();
}
@Override
public String toString() {
return "StyleSheet{" + getSceneStylesheet() + "}";
}
}
| 4,876
| 35.395522
| 120
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/theme/StyleSheetResource.java
|
package org.jabref.gui.theme;
import java.net.URL;
final class StyleSheetResource extends StyleSheet {
private final URL url;
StyleSheetResource(URL url) {
this.url = url;
}
@Override
URL getSceneStylesheet() {
return url;
}
@Override
public String getWebEngineStylesheet() {
return url.toExternalForm();
}
@Override
void reload() {
// nothing to do
}
@Override
public String toString() {
return "StyleSheet{" + getSceneStylesheet() + "}";
}
}
| 552
| 15.757576
| 58
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/theme/Theme.java
|
package org.jabref.gui.theme;
import java.util.Objects;
import java.util.Optional;
/**
* Represents one of three types of a css based Theme for JabRef:
* <p>
* The Default type of theme is the light theme (which is in fact the absence of any theme), the dark theme is currently
* the only embedded theme and the custom themes, that can be created by loading a proper css file.
*/
public class Theme {
public enum Type {
DEFAULT, EMBEDDED, CUSTOM
}
public static final String BASE_CSS = "Base.css";
public static final String EMBEDDED_DARK_CSS = "Dark.css";
private final Type type;
private final String name;
private final Optional<StyleSheet> additionalStylesheet;
public Theme(String name) {
Objects.requireNonNull(name);
if ("".equals(name) || BASE_CSS.equalsIgnoreCase(name)) {
this.additionalStylesheet = Optional.empty();
this.type = Type.DEFAULT;
this.name = "";
} else if (EMBEDDED_DARK_CSS.equalsIgnoreCase(name)) {
this.additionalStylesheet = StyleSheet.create(EMBEDDED_DARK_CSS);
if (this.additionalStylesheet.isPresent()) {
this.type = Type.EMBEDDED;
this.name = EMBEDDED_DARK_CSS;
} else {
this.type = Type.DEFAULT;
this.name = "";
}
} else {
this.additionalStylesheet = StyleSheet.create(name);
if (this.additionalStylesheet.isPresent()) {
this.type = Type.CUSTOM;
this.name = name;
} else {
this.type = Type.DEFAULT;
this.name = "";
}
}
}
public static Theme light() {
return new Theme("");
}
public static Theme dark() {
return new Theme(EMBEDDED_DARK_CSS);
}
public static Theme custom(String name) {
return new Theme(name);
}
/**
* @return the Theme type. Guaranteed to be non-null.
*/
public Type getType() {
return type;
}
/**
* Provides the name of the CSS, either for a built in theme, or for a raw, configured custom CSS location.
* This should be a file system path, but the raw string is
* returned even if it is not valid in some way. For this reason, the main use case for this getter is to
* storing or display the user preference, rather than to read and use the CSS file.
*
* @return the raw configured CSS location. Guaranteed to be non-null.
*/
public String getName() {
return name;
}
/**
* This method allows callers to obtain the theme's additional stylesheet.
*
* @return called with the stylesheet location if there is an additional stylesheet present and available. The
* location will be a local URL. Typically it will be a {@code 'data:'} URL where the CSS is embedded. However for
* large themes it can be {@code 'file:'}.
*/
public Optional<StyleSheet> getAdditionalStylesheet() {
return additionalStylesheet;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Theme that = (Theme) o;
return type == that.type && name.equals(that.name);
}
@Override
public int hashCode() {
return Objects.hash(type, name);
}
@Override
public String toString() {
return "Theme{" +
"type=" + type +
", name='" + name + '\'' +
'}';
}
}
| 3,669
| 29.583333
| 120
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/theme/ThemeManager.java
|
package org.jabref.gui.theme;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.function.Consumer;
import javafx.scene.Scene;
import javafx.scene.web.WebEngine;
import org.jabref.gui.util.DefaultTaskExecutor;
import org.jabref.model.util.FileUpdateListener;
import org.jabref.model.util.FileUpdateMonitor;
import org.jabref.preferences.WorkspacePreferences;
import com.tobiasdiez.easybind.EasyBind;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Installs and manages style files and provides live reloading. JabRef provides two inbuilt themes and a user
* customizable one: Light, Dark and Custom. The Light theme is basically the base.css theme. Every other theme is
* loaded as an addition to base.css.
* <p>
* For type Custom, Theme will protect against removal of the CSS file, degrading as gracefully as possible. If the file
* becomes unavailable while the application is running, some Scenes that have not yet had the CSS installed may not be
* themed. The PreviewViewer, which uses WebEngine, supports data URLs and so generally is not affected by removal of
* the file; however Theme package will not attempt to URL-encode large style sheets so as to protect memory usage (see
* {@link StyleSheetFile#MAX_IN_MEMORY_CSS_LENGTH}).
*
* @see <a href="https://docs.jabref.org/advanced/custom-themes">Custom themes</a> in the Jabref documentation.
*/
public class ThemeManager {
private static final Logger LOGGER = LoggerFactory.getLogger(ThemeManager.class);
private final WorkspacePreferences workspacePreferences;
private final FileUpdateMonitor fileUpdateMonitor;
private final Consumer<Runnable> updateRunner;
private final StyleSheet baseStyleSheet;
private Theme theme;
private Scene mainWindowScene;
private final Set<WebEngine> webEngines = Collections.newSetFromMap(new WeakHashMap<>());
public ThemeManager(WorkspacePreferences workspacePreferences,
FileUpdateMonitor fileUpdateMonitor,
Consumer<Runnable> updateRunner) {
this.workspacePreferences = Objects.requireNonNull(workspacePreferences);
this.fileUpdateMonitor = Objects.requireNonNull(fileUpdateMonitor);
this.updateRunner = Objects.requireNonNull(updateRunner);
this.baseStyleSheet = StyleSheet.create(Theme.BASE_CSS).get();
this.theme = workspacePreferences.getTheme();
// Watching base CSS only works in development and test scenarios, where the build system exposes the CSS as a
// file (e.g. for Gradle run task it will be in build/resources/main/org/jabref/gui/Base.css)
addStylesheetToWatchlist(this.baseStyleSheet, this::baseCssLiveUpdate);
baseCssLiveUpdate();
EasyBind.subscribe(workspacePreferences.themeProperty(), theme -> updateThemeSettings());
EasyBind.subscribe(workspacePreferences.shouldOverrideDefaultFontSizeProperty(), should -> updateFontSettings());
EasyBind.subscribe(workspacePreferences.mainFontSizeProperty(), size -> updateFontSettings());
}
private void updateThemeSettings() {
Theme newTheme = Objects.requireNonNull(workspacePreferences.getTheme());
if (newTheme.equals(theme)) {
LOGGER.info("Not updating theme because it hasn't changed");
} else {
theme.getAdditionalStylesheet().ifPresent(this::removeStylesheetFromWatchList);
}
this.theme = newTheme;
LOGGER.info("Theme set to {} with base css {}", newTheme, baseStyleSheet);
this.theme.getAdditionalStylesheet().ifPresent(
styleSheet -> addStylesheetToWatchlist(styleSheet, this::additionalCssLiveUpdate));
additionalCssLiveUpdate();
}
private void updateFontSettings() {
DefaultTaskExecutor.runInJavaFXThread(() -> updateRunner.accept(() -> getMainWindowScene().ifPresent(this::updateFontStyle)));
}
private void removeStylesheetFromWatchList(StyleSheet styleSheet) {
Path oldPath = styleSheet.getWatchPath();
if (oldPath != null) {
fileUpdateMonitor.removeListener(oldPath, this::additionalCssLiveUpdate);
LOGGER.info("No longer watch css {} for live updates", oldPath);
}
}
private void addStylesheetToWatchlist(StyleSheet styleSheet, FileUpdateListener updateMethod) {
Path watchPath = styleSheet.getWatchPath();
if (watchPath != null) {
try {
fileUpdateMonitor.addListenerForFile(watchPath, updateMethod);
LOGGER.info("Watching css {} for live updates", watchPath);
} catch (IOException e) {
LOGGER.warn("Cannot watch css path {} for live updates", watchPath, e);
}
}
}
private void baseCssLiveUpdate() {
baseStyleSheet.reload();
if (baseStyleSheet.getSceneStylesheet() == null) {
LOGGER.error("Base stylesheet does not exist.");
} else {
LOGGER.debug("Updating base CSS for main window scene");
}
DefaultTaskExecutor.runInJavaFXThread(() -> updateRunner.accept(this::updateBaseCss));
}
private void additionalCssLiveUpdate() {
final String newStyleSheetLocation = this.theme.getAdditionalStylesheet().map(styleSheet -> {
styleSheet.reload();
return styleSheet.getWebEngineStylesheet();
}).orElse("");
LOGGER.debug("Updating additional CSS for main window scene and {} web engines", webEngines.size());
DefaultTaskExecutor.runInJavaFXThread(() ->
updateRunner.accept(() -> {
updateAdditionalCss();
webEngines.forEach(webEngine -> {
// force refresh by unloading style sheet, if the location hasn't changed
if (newStyleSheetLocation.equals(webEngine.getUserStyleSheetLocation())) {
webEngine.setUserStyleSheetLocation(null);
}
webEngine.setUserStyleSheetLocation(newStyleSheetLocation);
});
})
);
}
private void updateBaseCss() {
getMainWindowScene().ifPresent(scene -> {
List<String> stylesheets = scene.getStylesheets();
if (!stylesheets.isEmpty()) {
stylesheets.remove(0);
}
stylesheets.add(0, baseStyleSheet.getSceneStylesheet().toExternalForm());
});
}
private void updateAdditionalCss() {
getMainWindowScene().ifPresent(scene -> scene.getStylesheets().setAll(List.of(
baseStyleSheet.getSceneStylesheet().toExternalForm(),
workspacePreferences.getTheme()
.getAdditionalStylesheet().map(styleSheet -> {
URL stylesheetUrl = styleSheet.getSceneStylesheet();
if (stylesheetUrl != null) {
return stylesheetUrl.toExternalForm();
} else {
return "";
}
})
.orElse("")
)));
}
/**
* Installs the base css file as a stylesheet in the given scene. Changes in the css file lead to a redraw of the
* scene using the new css file.
*
* @param mainWindowScene the scene to install the css into
*/
public void installCss(Scene mainWindowScene) {
Objects.requireNonNull(mainWindowScene, "scene is required");
updateRunner.accept(() -> {
this.mainWindowScene = mainWindowScene;
updateBaseCss();
updateAdditionalCss();
});
}
/**
* Installs the css file as a stylesheet in the given web engine. Changes in the css file lead to a redraw of the
* web engine using the new css file.
*
* @param webEngine the web engine to install the css into
*/
public void installCss(WebEngine webEngine) {
updateRunner.accept(() -> {
if (this.webEngines.add(webEngine)) {
webEngine.setUserStyleSheetLocation(this.theme.getAdditionalStylesheet().isPresent() ?
this.theme.getAdditionalStylesheet().get().getWebEngineStylesheet() : "");
}
});
}
/**
* Updates the font size settings of a scene. This method needs to be called from every custom dialog constructor,
* since javafx overwrites the style if applied before showing the dialog
*
* @param scene is the scene, the font size should be applied to
*/
public void updateFontStyle(Scene scene) {
if (workspacePreferences.shouldOverrideDefaultFontSize()) {
scene.getRoot().setStyle("-fx-font-size: " + workspacePreferences.getMainFontSize() + "pt;");
} else {
scene.getRoot().setStyle("-fx-font-size: " + workspacePreferences.getDefaultFontSize() + "pt;");
}
}
/**
* @return the currently active theme
*/
public Theme getActiveTheme() {
return this.theme;
}
public Optional<Scene> getMainWindowScene() {
return Optional.ofNullable(mainWindowScene);
}
}
| 9,592
| 40.528139
| 134
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/undo/AbstractUndoableJabRefEdit.java
|
package org.jabref.gui.undo;
import javax.swing.undo.AbstractUndoableEdit;
import org.jabref.logic.l10n.Localization;
public class AbstractUndoableJabRefEdit extends AbstractUndoableEdit {
@Override
public String getUndoPresentationName() {
return "<html>" + Localization.lang("Undo") + ": " + getPresentationName() + "</html>";
}
@Override
public String getRedoPresentationName() {
return "<html>" + Localization.lang("Redo") + ": " + getPresentationName() + "</html>";
}
}
| 520
| 26.421053
| 95
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/undo/CountingUndoManager.java
|
package org.jabref.gui.undo;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;
import javax.swing.undo.UndoableEdit;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.undo.AddUndoableActionEvent;
import org.jabref.logic.undo.UndoRedoEvent;
import com.google.common.eventbus.EventBus;
public class CountingUndoManager extends UndoManager {
private int unchangedPoint;
private int current;
private final EventBus eventBus = new EventBus();
@Override
public synchronized boolean addEdit(UndoableEdit edit) {
current++;
boolean returnvalue = super.addEdit(edit);
postAddUndoEvent();
return returnvalue;
}
@Override
public synchronized void undo() throws CannotUndoException {
super.undo();
current--;
postUndoRedoEvent();
}
@Override
public synchronized void redo() throws CannotUndoException {
super.redo();
current++;
postUndoRedoEvent();
}
public synchronized void markUnchanged() {
unchangedPoint = current;
}
public synchronized boolean hasChanged() {
return current != unchangedPoint;
}
public void registerListener(Object object) {
this.eventBus.register(object);
postUndoRedoEvent(); // Send event to trigger changes
}
public void unregisterListener(Object object) {
this.eventBus.unregister(object);
}
public void postUndoRedoEvent() {
boolean canRedo = this.canRedo();
boolean canUndo = this.canUndo();
eventBus.post(new UndoRedoEvent(canUndo, canUndo ? getUndoPresentationName() : Localization.lang("Undo"),
canRedo, canRedo ? getRedoPresentationName() : Localization.lang("Redo")));
}
private void postAddUndoEvent() {
boolean canRedo = this.canRedo();
boolean canUndo = this.canUndo();
eventBus.post(new AddUndoableActionEvent(canUndo, canUndo ? getUndoPresentationName() : Localization.lang("Undo"),
canRedo, canRedo ? getRedoPresentationName() : Localization.lang("Redo")));
}
}
| 2,150
| 28.465753
| 122
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/undo/NamedCompound.java
|
package org.jabref.gui.undo;
import javax.swing.undo.CompoundEdit;
import javax.swing.undo.UndoableEdit;
import org.jabref.logic.l10n.Localization;
public class NamedCompound extends CompoundEdit {
private final String name;
private boolean hasEdits;
public NamedCompound(String name) {
super();
this.name = name;
}
@Override
public boolean addEdit(UndoableEdit undoableEdit) {
hasEdits = true;
return super.addEdit(undoableEdit);
}
public boolean hasEdits() {
return hasEdits;
}
@Override
public String getUndoPresentationName() {
return "<html>" + Localization.lang("Undo") + ": " + name + "<ul>" + getPresentationName() + "</ul></html>";
}
@Override
public String getRedoPresentationName() {
return "<html>" + Localization.lang("Redo") + ": " + name + "<ul>" + getPresentationName() + "</ul></html>";
}
@Override
public String getPresentationName() {
StringBuilder sb = new StringBuilder();
for (UndoableEdit edit : edits) {
sb.append("<li>").append(edit.getPresentationName());
}
return sb.toString();
}
}
| 1,192
| 24.382979
| 116
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/undo/UndoRedoAction.java
|
package org.jabref.gui.undo;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import org.jabref.gui.DialogService;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.LibraryTab;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.ActionHelper;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.actions.StandardActions;
import org.jabref.logic.l10n.Localization;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class UndoRedoAction extends SimpleCommand {
private static final Logger LOGGER = LoggerFactory.getLogger(UndoRedoAction.class);
private final StandardActions action;
private final JabRefFrame frame;
private DialogService dialogService;
public UndoRedoAction(StandardActions action, JabRefFrame frame, DialogService dialogService, StateManager stateManager) {
this.action = action;
this.frame = frame;
this.dialogService = dialogService;
// ToDo: Rework the UndoManager to something like the following, if it had a property.
// this.executable.bind(frame.getCurrentBasePanel().getUndoManager().canUndo())
this.executable.bind(ActionHelper.needsDatabase(stateManager));
}
@Override
public void execute() {
LibraryTab libraryTab = frame.getCurrentLibraryTab();
if (action == StandardActions.UNDO) {
try {
libraryTab.getUndoManager().undo();
libraryTab.markBaseChanged();
dialogService.notify(Localization.lang("Undo"));
} catch (CannotUndoException ex) {
dialogService.notify(Localization.lang("Nothing to undo") + '.');
}
frame.getCurrentLibraryTab().markChangedOrUnChanged();
} else if (action == StandardActions.REDO) {
try {
libraryTab.getUndoManager().redo();
libraryTab.markBaseChanged();
dialogService.notify(Localization.lang("Redo"));
} catch (CannotRedoException ex) {
dialogService.notify(Localization.lang("Nothing to redo") + '.');
}
libraryTab.markChangedOrUnChanged();
} else {
LOGGER.debug("No undo/redo action: " + action.name());
}
}
}
| 2,327
| 35.952381
| 126
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/undo/UndoableChangeType.java
|
package org.jabref.gui.undo;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.FieldChange;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.types.EntryType;
import org.jabref.model.entry.types.EntryTypeFactory;
import org.jabref.model.strings.StringUtil;
/**
* This class represents the change of type for an entry.
*/
public class UndoableChangeType extends AbstractUndoableJabRefEdit {
private final EntryType oldType;
private final EntryType newType;
private final BibEntry entry;
public UndoableChangeType(FieldChange change) {
this(change.getEntry(), EntryTypeFactory.parse(change.getOldValue()), EntryTypeFactory.parse(change.getNewValue()));
}
public UndoableChangeType(BibEntry entry, EntryType oldType, EntryType newType) {
this.oldType = oldType;
this.newType = newType;
this.entry = entry;
}
@Override
public String getPresentationName() {
return Localization.lang("change type of entry %0 from %1 to %2",
StringUtil.boldHTML(entry.getCitationKey().orElse(Localization.lang("undefined"))),
StringUtil.boldHTML(oldType.getDisplayName(), Localization.lang("undefined")),
StringUtil.boldHTML(newType.getDisplayName()));
}
@Override
public void undo() {
super.undo();
entry.setType(oldType);
}
@Override
public void redo() {
super.redo();
entry.setType(newType);
}
}
| 1,506
| 30.395833
| 124
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/undo/UndoableFieldChange.java
|
package org.jabref.gui.undo;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.FieldChange;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.Field;
import org.jabref.model.strings.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class represents a change in any field value. The relevant
* information is the BibEntry, the field name, the old and the
* new value. Old/new values can be null.
*/
public class UndoableFieldChange extends AbstractUndoableJabRefEdit {
private static final Logger LOGGER = LoggerFactory.getLogger(UndoableFieldChange.class);
private final BibEntry entry;
private final Field field;
private final String oldValue;
private final String newValue;
public UndoableFieldChange(BibEntry entry, Field field, String oldValue, String newValue) {
this.entry = entry;
this.field = field;
this.oldValue = oldValue;
this.newValue = newValue;
}
public UndoableFieldChange(FieldChange change) {
this(change.getEntry(), change.getField(), change.getOldValue(), change.getNewValue());
}
@Override
public String getPresentationName() {
return Localization.lang("change field %0 of entry %1 from %2 to %3", StringUtil.boldHTML(field.getDisplayName()),
StringUtil.boldHTML(entry.getCitationKey().orElse(Localization.lang("undefined"))),
StringUtil.boldHTML(oldValue, Localization.lang("undefined")),
StringUtil.boldHTML(newValue, Localization.lang("undefined")));
}
@Override
public void undo() {
super.undo();
// Revert the change.
try {
if (oldValue == null) {
entry.clearField(field);
} else {
entry.setField(field, oldValue);
}
// this is the only exception explicitly thrown here
} catch (IllegalArgumentException ex) {
LOGGER.info("Cannot perform undo", ex);
}
}
@Override
public void redo() {
super.redo();
// Redo the change.
try {
if (newValue == null) {
entry.clearField(field);
} else {
entry.setField(field, newValue);
}
} catch (IllegalArgumentException ex) {
LOGGER.info("Cannot perform redo", ex);
}
}
}
| 2,438
| 30.269231
| 122
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/undo/UndoableInsertEntries.java
|
package org.jabref.gui.undo;
import java.util.Collections;
import java.util.List;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.strings.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class represents the removal of entries. The constructor needs
* references to the database, entries, and a boolean marked true if the undo
* is from a call to paste().
*/
public class UndoableInsertEntries extends AbstractUndoableJabRefEdit {
private static final Logger LOGGER = LoggerFactory.getLogger(UndoableInsertEntries.class);
private final BibDatabase database;
private final List<BibEntry> entries;
private final boolean paste;
public UndoableInsertEntries(BibDatabase database, BibEntry entry) {
this(database, Collections.singletonList(entry));
}
public UndoableInsertEntries(BibDatabase database, List<BibEntry> entries) {
this(database, entries, false);
}
public UndoableInsertEntries(BibDatabase database, List<BibEntry> entries, boolean paste) {
this.database = database;
this.entries = entries;
this.paste = paste;
}
@Override
public String getPresentationName() {
if (paste) {
if (entries.size() > 1) {
return Localization.lang("paste entries");
} else if (entries.size() == 1) {
return Localization.lang("paste entry %0",
StringUtil.boldHTML(entries.get(0).getCitationKey().orElse(Localization.lang("undefined"))));
} else {
return null;
}
} else {
if (entries.size() > 1) {
return Localization.lang("insert entries");
} else if (entries.size() == 1) {
return Localization.lang("insert entry %0",
StringUtil.boldHTML(entries.get(0).getCitationKey().orElse(Localization.lang("undefined"))));
} else {
return null;
}
}
}
@Override
public void undo() {
super.undo();
try {
database.removeEntries(entries);
} catch (Throwable ex) {
LOGGER.warn("Problem undoing `insert entries`", ex);
}
}
@Override
public void redo() {
super.redo();
database.insertEntries(entries);
}
}
| 2,477
| 29.975
| 117
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/undo/UndoableInsertString.java
|
package org.jabref.gui.undo;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.database.KeyCollisionException;
import org.jabref.model.entry.BibtexString;
import org.jabref.model.strings.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class UndoableInsertString extends AbstractUndoableJabRefEdit {
private static final Logger LOGGER = LoggerFactory.getLogger(UndoableInsertString.class);
private final BibDatabase base;
private final BibtexString string;
public UndoableInsertString(BibDatabase base, BibtexString string) {
this.base = base;
this.string = string;
}
@Override
public String getPresentationName() {
return Localization.lang("insert string %0", StringUtil.boldHTML(string.toString()));
}
@Override
public void undo() {
super.undo();
// Revert the change.
base.removeString(string.getId());
}
@Override
public void redo() {
super.redo();
// Redo the change.
try {
base.addString(string);
} catch (KeyCollisionException ex) {
LOGGER.warn("Problem to redo `insert entry`", ex);
}
}
}
| 1,266
| 24.857143
| 93
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/undo/UndoableKeyChange.java
|
package org.jabref.gui.undo;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.FieldChange;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.strings.StringUtil;
/**
* This class represents a change in any field value. The relevant
* information is the BibEntry, the field name, the old and the
* new value. Old/new values can be null.
*/
public class UndoableKeyChange extends AbstractUndoableJabRefEdit {
private final BibEntry entry;
private final String oldValue;
private final String newValue;
public UndoableKeyChange(FieldChange change) {
this(change.getEntry(), change.getOldValue(), change.getNewValue());
}
public UndoableKeyChange(BibEntry entry, String oldValue, String newValue) {
this.entry = entry;
this.oldValue = oldValue;
this.newValue = newValue;
}
@Override
public String getPresentationName() {
return Localization.lang("change key from %0 to %1",
StringUtil.boldHTML(oldValue, Localization.lang("undefined")),
StringUtil.boldHTML(newValue, Localization.lang("undefined")));
}
@Override
public void undo() {
super.undo();
entry.setCitationKey(oldValue);
}
@Override
public void redo() {
super.redo();
entry.setCitationKey(newValue);
}
}
| 1,369
| 27.541667
| 80
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/undo/UndoablePreambleChange.java
|
package org.jabref.gui.undo;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabase;
/**
* This class represents a change in any field value. The relevant information is the BibEntry, the field name, the old and the new value. Old/new values can be null.
*/
public class UndoablePreambleChange extends AbstractUndoableJabRefEdit {
private final BibDatabase base;
private final String oldValue;
private final String newValue;
public UndoablePreambleChange(BibDatabase base,
String oldValue, String newValue) {
this.base = base;
this.oldValue = oldValue;
this.newValue = newValue;
}
@Override
public String getPresentationName() {
return Localization.lang("change preamble");
}
@Override
public void undo() {
super.undo();
// Revert the change.
base.setPreamble(oldValue);
}
@Override
public void redo() {
super.redo();
// Redo the change.
base.setPreamble(newValue);
}
}
| 1,084
| 24.232558
| 166
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/undo/UndoableRemoveEntries.java
|
package org.jabref.gui.undo;
import java.util.Collections;
import java.util.List;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.event.EntriesEventSource;
import org.jabref.model.strings.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class represents the removal of entries. The constructor needs
* references to the database, the entries, and the map of open entry editors.
* TODO is this map still being used?
* The latter to be able to close the entry's editor if it is opened after
* an undo, and the removal is then undone.
*/
public class UndoableRemoveEntries extends AbstractUndoableJabRefEdit {
private static final Logger LOGGER = LoggerFactory.getLogger(UndoableRemoveEntries.class);
private final BibDatabase base;
private final List<BibEntry> entries;
private final boolean cut;
public UndoableRemoveEntries(BibDatabase base, BibEntry entry) {
this(base, Collections.singletonList(entry));
}
public UndoableRemoveEntries(BibDatabase base, List<BibEntry> entries) {
this(base, entries, false);
}
public UndoableRemoveEntries(BibDatabase base, List<BibEntry> entries, boolean cut) {
this.base = base;
this.entries = entries;
this.cut = cut;
}
@Override
public String getPresentationName() {
if (cut) {
if (entries.size() > 1) {
return Localization.lang("cut entries");
} else if (entries.size() == 1) {
return Localization.lang("cut entry %0",
StringUtil.boldHTML(entries.get(0).getCitationKey().orElse(Localization.lang("undefined"))));
} else {
return null;
}
} else {
if (entries.size() > 1) {
return Localization.lang("remove entries");
} else if (entries.size() == 1) {
return Localization.lang("remove entry %0",
StringUtil.boldHTML(entries.get(0).getCitationKey().orElse(Localization.lang("undefined"))));
} else {
return null;
}
}
}
@Override
public void undo() {
super.undo();
base.insertEntries(entries, EntriesEventSource.UNDO);
}
@Override
public void redo() {
super.redo();
// Redo the change.
try {
base.removeEntries(entries);
} catch (Throwable ex) {
LOGGER.warn("Problem to redo `remove entries`", ex);
}
}
}
| 2,660
| 30.678571
| 117
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/undo/UndoableRemoveString.java
|
package org.jabref.gui.undo;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.database.KeyCollisionException;
import org.jabref.model.entry.BibtexString;
import org.jabref.model.strings.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class UndoableRemoveString extends AbstractUndoableJabRefEdit {
private static final Logger LOGGER = LoggerFactory.getLogger(UndoableRemoveString.class);
private final BibDatabase base;
private final BibtexString string;
public UndoableRemoveString(BibDatabase base, BibtexString string) {
this.base = base;
this.string = string;
}
@Override
public String getPresentationName() {
return Localization.lang("remove string %0", StringUtil.boldHTML(string.toString()));
}
@Override
public void undo() {
super.undo();
// Revert the change.
try {
base.addString(string);
} catch (KeyCollisionException ex) {
LOGGER.warn("Problem to undo `remove string`", ex);
}
}
@Override
public void redo() {
super.redo();
// Redo the change.
base.removeString(string.getId());
}
}
| 1,264
| 26.5
| 93
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/undo/UndoableStringChange.java
|
package org.jabref.gui.undo;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.entry.BibtexString;
import org.jabref.model.strings.StringUtil;
public class UndoableStringChange extends AbstractUndoableJabRefEdit {
private final BibtexString string;
private final String oldValue;
private final String newValue;
private final boolean nameChange;
public UndoableStringChange(BibtexString string, boolean nameChange, String oldValue, String newValue) {
this.string = string;
this.oldValue = oldValue;
this.newValue = newValue;
this.nameChange = nameChange;
}
@Override
public String getPresentationName() {
return nameChange ? Localization.lang("change string name %0 to %1", StringUtil.boldHTML(oldValue),
StringUtil.boldHTML(newValue)) :
Localization.lang("change string content %0 to %1",
StringUtil.boldHTML(oldValue), StringUtil.boldHTML(newValue));
}
@Override
public void undo() {
super.undo();
// Revert the change.
if (nameChange) {
string.setName(oldValue);
} else {
string.setContent(oldValue);
}
}
@Override
public void redo() {
super.redo();
// Redo the change.
if (nameChange) {
string.setName(newValue);
} else {
string.setContent(newValue);
}
}
}
| 1,470
| 26.754717
| 108
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/BackgroundTask.java
|
package org.jabref.gui.util;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.concurrent.Task;
import javafx.scene.Node;
import org.jabref.gui.icon.IconTheme;
import org.jabref.logic.l10n.Localization;
import com.google.common.collect.ImmutableMap;
import com.tobiasdiez.easybind.EasyBind;
/**
* This class is essentially a wrapper around {@link Task}.
* We cannot use {@link Task} directly since it runs certain update notifications on the JavaFX thread,
* and so makes testing harder.
* We take the opportunity and implement a fluid interface.
*
* @param <V> type of the return value of the task
*/
public abstract class BackgroundTask<V> {
public static ImmutableMap<String, Node> iconMap = ImmutableMap.of(
Localization.lang("Downloading"), IconTheme.JabRefIcons.DOWNLOAD.getGraphicNode()
);
private Runnable onRunning;
private Consumer<V> onSuccess;
private Consumer<Exception> onException;
private Runnable onFinished;
private final BooleanProperty isCanceled = new SimpleBooleanProperty(false);
private final ObjectProperty<BackgroundProgress> progress = new SimpleObjectProperty<>(new BackgroundProgress(0, 0));
private final StringProperty message = new SimpleStringProperty("");
private final StringProperty title = new SimpleStringProperty(this.getClass().getSimpleName());
private final DoubleProperty workDonePercentage = new SimpleDoubleProperty(0);
private final BooleanProperty showToUser = new SimpleBooleanProperty(false);
private final BooleanProperty willBeRecoveredAutomatically = new SimpleBooleanProperty(false);
public BackgroundTask() {
workDonePercentage.bind(EasyBind.map(progress, BackgroundTask.BackgroundProgress::getWorkDonePercentage));
}
public static <V> BackgroundTask<V> wrap(Callable<V> callable) {
return new BackgroundTask<>() {
@Override
protected V call() throws Exception {
return callable.call();
}
};
}
public static BackgroundTask<Void> wrap(Runnable runnable) {
return new BackgroundTask<>() {
@Override
protected Void call() {
runnable.run();
return null;
}
};
}
private static <T> Consumer<T> chain(Runnable first, Consumer<T> second) {
if (first != null) {
if (second != null) {
return result -> {
first.run();
second.accept(result);
};
} else {
return result -> first.run();
}
} else {
return second;
}
}
public boolean isCanceled() {
return isCanceled.get();
}
public void cancel() {
this.isCanceled.set(true);
}
public BooleanProperty isCanceledProperty() {
return isCanceled;
}
public StringProperty messageProperty() {
return message;
}
public StringProperty titleProperty() {
return title;
}
public double getWorkDonePercentage() {
return workDonePercentage.get();
}
public DoubleProperty workDonePercentageProperty() {
return workDonePercentage;
}
public BackgroundProgress getProgress() {
return progress.get();
}
public ObjectProperty<BackgroundProgress> progressProperty() {
return progress;
}
public boolean showToUser() {
return showToUser.get();
}
public void showToUser(boolean show) {
showToUser.set(show);
}
public boolean willBeRecoveredAutomatically() {
return willBeRecoveredAutomatically.get();
}
public void willBeRecoveredAutomatically(boolean willBeRecoveredAutomatically) {
this.willBeRecoveredAutomatically.set(willBeRecoveredAutomatically);
}
/**
* Sets the {@link Runnable} that is invoked after the task is started.
*/
public BackgroundTask<V> onRunning(Runnable onRunning) {
this.onRunning = onRunning;
return this;
}
/**
* Sets the {@link Consumer} that is invoked after the task is successfully finished.
* The consumer always runs on the JavaFX thread.
*/
public BackgroundTask<V> onSuccess(Consumer<V> onSuccess) {
this.onSuccess = onSuccess;
return this;
}
protected abstract V call() throws Exception;
Runnable getOnRunning() {
return onRunning;
}
Consumer<V> getOnSuccess() {
return chain(onFinished, onSuccess);
}
Consumer<Exception> getOnException() {
return chain(onFinished, onException);
}
/**
* Sets the {@link Consumer} that is invoked after the task has failed with an exception.
* The consumer always runs on the JavaFX thread.
*/
public BackgroundTask<V> onFailure(Consumer<Exception> onException) {
this.onException = onException;
return this;
}
public Future<?> executeWith(TaskExecutor taskExecutor) {
return taskExecutor.execute(this);
}
public Future<?> scheduleWith(TaskExecutor taskExecutor, long delay, TimeUnit unit) {
return taskExecutor.schedule(this, delay, unit);
}
/**
* Sets the {@link Runnable} that is invoked after the task is finished, irrespectively if it was successful or
* failed with an error.
*/
public BackgroundTask<V> onFinished(Runnable onFinished) {
this.onFinished = onFinished;
return this;
}
/**
* Creates a {@link BackgroundTask} that first runs this task and based on the result runs a second task.
*
* @param nextTaskFactory the function that creates the new task
* @param <T> type of the return value of the second task
*/
public <T> BackgroundTask<T> then(Function<V, BackgroundTask<T>> nextTaskFactory) {
return new BackgroundTask<>() {
@Override
protected T call() throws Exception {
V result = BackgroundTask.this.call();
BackgroundTask<T> nextTask = nextTaskFactory.apply(result);
EasyBind.subscribe(nextTask.progressProperty(), this::updateProgress);
return nextTask.call();
}
};
}
/**
* Creates a {@link BackgroundTask} that first runs this task and based on the result runs a second task.
*
* @param nextOperation the function that performs the next operation
* @param <T> type of the return value of the second task
*/
public <T> BackgroundTask<T> thenRun(Function<V, T> nextOperation) {
return new BackgroundTask<>() {
@Override
protected T call() throws Exception {
V result = BackgroundTask.this.call();
BackgroundTask<T> nextTask = BackgroundTask.wrap(() -> nextOperation.apply(result));
EasyBind.subscribe(nextTask.progressProperty(), this::updateProgress);
return nextTask.call();
}
};
}
/**
* Creates a {@link BackgroundTask} that first runs this task and based on the result runs a second task.
*
* @param nextOperation the function that performs the next operation
*/
public BackgroundTask<Void> thenRun(Consumer<V> nextOperation) {
return new BackgroundTask<>() {
@Override
protected Void call() throws Exception {
V result = BackgroundTask.this.call();
BackgroundTask<Void> nextTask = BackgroundTask.wrap(() -> nextOperation.accept(result));
EasyBind.subscribe(nextTask.progressProperty(), this::updateProgress);
return nextTask.call();
}
};
}
protected void updateProgress(BackgroundProgress newProgress) {
progress.setValue(newProgress);
}
protected void updateProgress(double workDone, double max) {
updateProgress(new BackgroundProgress(workDone, max));
}
public void updateMessage(String newMessage) {
message.setValue(newMessage);
}
public BackgroundTask<V> withInitialMessage(String message) {
updateMessage(message);
return this;
}
public static Node getIcon(Task<?> task) {
return BackgroundTask.iconMap.getOrDefault(task.getTitle(), null);
}
static class BackgroundProgress {
private final double workDone;
private final double max;
public BackgroundProgress(double workDone, double max) {
this.workDone = workDone;
this.max = max;
}
public double getWorkDone() {
return workDone;
}
public double getMax() {
return max;
}
public double getWorkDonePercentage() {
if (max == 0) {
return 0;
} else {
return workDone / max;
}
}
}
}
| 9,523
| 30.746667
| 121
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/BaseDialog.java
|
package org.jabref.gui.util;
import java.util.Optional;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCode;
import javafx.stage.Stage;
import org.jabref.gui.Globals;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.keyboard.KeyBinding;
import org.jabref.gui.keyboard.KeyBindingRepository;
public class BaseDialog<T> extends Dialog<T> implements org.jabref.gui.Dialog<T> {
protected BaseDialog() {
getDialogPane().getScene().setOnKeyPressed(event -> {
KeyBindingRepository keyBindingRepository = Globals.getKeyPrefs();
if (keyBindingRepository.checkKeyCombinationEquality(KeyBinding.CLOSE, event)) {
close();
} else if (keyBindingRepository.checkKeyCombinationEquality(KeyBinding.DEFAULT_DIALOG_ACTION, event)) {
getDefaultButton().ifPresent(Button::fire);
}
// all buttons in base dialogs react on enter
if (event.getCode() == KeyCode.ENTER) {
if (event.getTarget() instanceof Button) {
((Button) event.getTarget()).fire();
event.consume();
}
}
});
setDialogIcon(IconTheme.getJabRefImage());
setResizable(true);
}
private Optional<Button> getDefaultButton() {
return Optional.ofNullable((Button) getDialogPane().lookupButton(getDefaultButtonType()));
}
private ButtonType getDefaultButtonType() {
return getDialogPane().getButtonTypes().stream()
.filter(buttonType -> buttonType.getButtonData().isDefaultButton())
.findFirst()
.orElse(ButtonType.OK);
}
private void setDialogIcon(Image image) {
Stage dialogWindow = (Stage) getDialogPane().getScene().getWindow();
dialogWindow.getIcons().add(image);
}
}
| 2,027
| 34.578947
| 115
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/BindingsHelper.java
|
package org.jabref.gui.util;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.binding.ObjectBinding;
import javafx.beans.binding.StringBinding;
import javafx.beans.property.ListProperty;
import javafx.beans.property.Property;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.MapChangeListener;
import javafx.collections.ObservableList;
import javafx.collections.ObservableMap;
import javafx.css.PseudoClass;
import javafx.scene.Node;
import com.tobiasdiez.easybind.EasyBind;
import com.tobiasdiez.easybind.PreboundBinding;
import com.tobiasdiez.easybind.Subscription;
/**
* Helper methods for javafx binding. Some methods are taken from https://bugs.openjdk.java.net/browse/JDK-8134679
*/
public class BindingsHelper {
private BindingsHelper() {
}
public static Subscription includePseudoClassWhen(Node node, PseudoClass pseudoClass, ObservableValue<? extends Boolean> condition) {
Consumer<Boolean> changePseudoClass = value -> node.pseudoClassStateChanged(pseudoClass, value);
Subscription subscription = EasyBind.subscribe(condition, changePseudoClass);
// Put the pseudo class there depending on the current value
changePseudoClass.accept(condition.getValue());
return subscription;
}
public static <T, U> ObservableList<U> map(ObservableValue<T> source, Function<T, List<U>> mapper) {
PreboundBinding<List<U>> binding = new PreboundBinding<>(source) {
@Override
protected List<U> computeValue() {
return mapper.apply(source.getValue());
}
};
ObservableList<U> list = FXCollections.observableArrayList();
binding.addListener((observable, oldValue, newValue) -> list.setAll(newValue));
return list;
}
/**
* Binds propertyA bidirectional to propertyB using the provided map functions to convert between them.
*/
public static <A, B> void bindBidirectional(Property<A> propertyA, Property<B> propertyB, Function<A, B> mapAtoB, Function<B, A> mapBtoA) {
Consumer<B> updateA = newValueB -> propertyA.setValue(mapBtoA.apply(newValueB));
Consumer<A> updateB = newValueA -> propertyB.setValue(mapAtoB.apply(newValueA));
bindBidirectional(propertyA, propertyB, updateA, updateB);
}
/**
* Binds propertyA bidirectional to propertyB while using updateB to update propertyB when propertyA changed.
*/
public static <A> void bindBidirectional(Property<A> propertyA, ObservableValue<A> propertyB, Consumer<A> updateB) {
bindBidirectional(propertyA, propertyB, propertyA::setValue, updateB);
}
/**
* Binds propertyA bidirectional to propertyB using updateB to update propertyB when propertyA changed and similar for updateA.
*/
public static <A, B> void bindBidirectional(ObservableValue<A> propertyA, ObservableValue<B> propertyB, Consumer<B> updateA, Consumer<A> updateB) {
final BidirectionalBinding<A, B> binding = new BidirectionalBinding<>(propertyA, propertyB, updateA, updateB);
// use updateB as initial source
updateA.accept(propertyB.getValue());
propertyA.addListener(binding.getChangeListenerA());
propertyB.addListener(binding.getChangeListenerB());
}
public static <A, B> void bindContentBidirectional(ObservableList<A> propertyA, ListProperty<B> propertyB, Consumer<ObservableList<B>> updateA, Consumer<List<A>> updateB) {
bindContentBidirectional(
propertyA,
(ObservableValue<ObservableList<B>>) propertyB,
updateA,
updateB);
}
public static <A, B> void bindContentBidirectional(ObservableList<A> propertyA, ObservableValue<B> propertyB, Consumer<B> updateA, Consumer<List<A>> updateB) {
final BidirectionalListBinding<A, B> binding = new BidirectionalListBinding<>(propertyA, propertyB, updateA, updateB);
// use property as initial source
updateA.accept(propertyB.getValue());
propertyA.addListener(binding);
propertyB.addListener(binding);
}
public static <A, B> void bindContentBidirectional(ListProperty<A> listProperty, Property<B> property, Function<List<A>, B> mapToB, Function<B, List<A>> mapToList) {
Consumer<B> updateList = newValueB -> listProperty.setAll(mapToList.apply(newValueB));
Consumer<List<A>> updateB = newValueList -> property.setValue(mapToB.apply(newValueList));
bindContentBidirectional(
listProperty,
property,
updateList,
updateB);
}
public static <A, V, B> void bindContentBidirectional(ObservableMap<A, V> propertyA, ObservableValue<B> propertyB, Consumer<B> updateA, Consumer<Map<A, V>> updateB) {
final BidirectionalMapBinding<A, V, B> binding = new BidirectionalMapBinding<>(propertyA, propertyB, updateA, updateB);
// use list as initial source
updateB.accept(propertyA);
propertyA.addListener(binding);
propertyB.addListener(binding);
}
public static <A, V, B> void bindContentBidirectional(ObservableMap<A, V> propertyA, Property<B> propertyB, Consumer<B> updateA, Function<Map<A, V>, B> mapToB) {
Consumer<Map<A, V>> updateB = newValueList -> propertyB.setValue(mapToB.apply(newValueList));
bindContentBidirectional(
propertyA,
propertyB,
updateA,
updateB);
}
public static <T> ObservableValue<T> constantOf(T value) {
return new ObjectBinding<>() {
@Override
protected T computeValue() {
return value;
}
};
}
public static ObservableValue<Boolean> constantOf(boolean value) {
return new BooleanBinding() {
@Override
protected boolean computeValue() {
return value;
}
};
}
public static ObservableValue<? extends String> emptyString() {
return new StringBinding() {
@Override
protected String computeValue() {
return "";
}
};
}
/**
* Returns a wrapper around the given list that posts changes on the JavaFX thread.
*/
public static <T> ObservableList<T> forUI(ObservableList<T> list) {
return new UiThreadList<>(list);
}
public static <T> ObservableValue<T> ifThenElse(ObservableValue<Boolean> condition, T value, T other) {
return EasyBind.map(condition, conditionValue -> {
if (conditionValue) {
return value;
} else {
return other;
}
});
}
/**
* Invokes {@code subscriber} for the every new value of {@code observable}, but not for the current value.
*
* @param observable observable value to subscribe to
* @param subscriber action to invoke for values of {@code observable}.
* @return a subscription that can be used to stop invoking subscriber for any further {@code observable} changes.
* @apiNote {@link EasyBind#subscribe(ObservableValue, Consumer)} is similar but also invokes the {@code subscriber} for the current value
*/
public static <T> Subscription subscribeFuture(ObservableValue<T> observable, Consumer<? super T> subscriber) {
ChangeListener<? super T> listener = (obs, oldValue, newValue) -> subscriber.accept(newValue);
observable.addListener(listener);
return () -> observable.removeListener(listener);
}
private static class BidirectionalBinding<A, B> {
private final ObservableValue<A> propertyA;
private final Consumer<B> updateA;
private final Consumer<A> updateB;
private boolean updating = false;
public BidirectionalBinding(ObservableValue<A> propertyA, ObservableValue<B> propertyB, Consumer<B> updateA, Consumer<A> updateB) {
this.propertyA = propertyA;
this.updateA = updateA;
this.updateB = updateB;
}
public ChangeListener<? super A> getChangeListenerA() {
return this::changedA;
}
public ChangeListener<? super B> getChangeListenerB() {
return this::changedB;
}
public void changedA(ObservableValue<? extends A> observable, A oldValue, A newValue) {
updateLocked(updateB, oldValue, newValue);
}
public void changedB(ObservableValue<? extends B> observable, B oldValue, B newValue) {
updateLocked(updateA, oldValue, newValue);
}
private <T> void updateLocked(Consumer<T> update, T oldValue, T newValue) {
if (!updating) {
try {
updating = true;
update.accept(newValue);
} finally {
updating = false;
}
}
}
}
private static class BidirectionalListBinding<A, B> implements ListChangeListener<A>, ChangeListener<B> {
private final ObservableList<A> listProperty;
private final ObservableValue<B> property;
private final Consumer<B> updateA;
private final Consumer<List<A>> updateB;
private boolean updating = false;
public BidirectionalListBinding(ObservableList<A> listProperty, ObservableValue<B> property, Consumer<B> updateA, Consumer<List<A>> updateB) {
this.listProperty = listProperty;
this.property = property;
this.updateA = updateA;
this.updateB = updateB;
}
@Override
public void changed(ObservableValue<? extends B> observable, B oldValue, B newValue) {
if (!updating) {
try {
updating = true;
updateA.accept(newValue);
} finally {
updating = false;
}
}
}
@Override
public void onChanged(Change<? extends A> c) {
if (!updating) {
try {
updating = true;
updateB.accept(listProperty);
} finally {
updating = false;
}
}
}
}
private static class BidirectionalMapBinding<A, V, B> implements MapChangeListener<A, V>, ChangeListener<B> {
private final ObservableMap<A, V> mapProperty;
private final ObservableValue<B> property;
private final Consumer<B> updateA;
private final Consumer<Map<A, V>> updateB;
private boolean updating = false;
public BidirectionalMapBinding(ObservableMap<A, V> mapProperty, ObservableValue<B> property, Consumer<B> updateA, Consumer<Map<A, V>> updateB) {
this.mapProperty = mapProperty;
this.property = property;
this.updateA = updateA;
this.updateB = updateB;
}
@Override
public void changed(ObservableValue<? extends B> observable, B oldValue, B newValue) {
if (!updating) {
try {
updating = true;
updateA.accept(newValue);
} finally {
updating = false;
}
}
}
@Override
public void onChanged(Change<? extends A, ? extends V> c) {
if (!updating) {
try {
updating = true;
updateB.accept(mapProperty);
} finally {
updating = false;
}
}
}
}
}
| 11,958
| 37.207668
| 176
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/ColorUtil.java
|
package org.jabref.gui.util;
import javafx.scene.paint.Color;
public class ColorUtil {
public static String toRGBCode(Color color) {
return String.format("#%02X%02X%02X",
(int) (color.getRed() * 255),
(int) (color.getGreen() * 255),
(int) (color.getBlue() * 255));
}
public static String toRGBACode(Color color) {
return String.format("rgba(%d,%d,%d,%f)",
(int) (color.getRed() * 255),
(int) (color.getGreen() * 255),
(int) (color.getBlue() * 255),
color.getOpacity());
}
public static String toHex(Color validFieldBackgroundColor) {
return String.format("#%02x%02x%02x", (int) validFieldBackgroundColor.getRed(), (int) validFieldBackgroundColor.getGreen(), (int) validFieldBackgroundColor.getBlue());
}
}
| 871
| 32.538462
| 175
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/ControlHelper.java
|
package org.jabref.gui.util;
import java.util.function.Consumer;
import java.util.function.UnaryOperator;
import javafx.css.PseudoClass;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Cell;
import javafx.scene.control.DialogPane;
import javafx.scene.control.TextFormatter;
import javafx.scene.input.DragEvent;
public class ControlHelper {
// Pseudo-classes for drag and drop
private static PseudoClass dragOverBottom = PseudoClass.getPseudoClass("dragOver-bottom");
private static PseudoClass dragOverCenter = PseudoClass.getPseudoClass("dragOver-center");
private static PseudoClass dragOverTop = PseudoClass.getPseudoClass("dragOver-top");
public enum EllipsisPosition { BEGINNING, CENTER, ENDING }
public static void setAction(ButtonType buttonType, DialogPane dialogPane, Consumer<Event> consumer) {
Button button = (Button) dialogPane.lookupButton(buttonType);
button.addEventFilter(ActionEvent.ACTION, (event -> {
consumer.accept(event);
event.consume();
}));
}
public static boolean childIsFocused(Parent node) {
return node.isFocused() || node.getChildrenUnmodifiable().stream().anyMatch(child -> {
if (child instanceof Parent) {
return childIsFocused((Parent) child);
} else {
return child.isFocused();
}
});
}
/**
* Returns a text formatter that restricts input to integers
*/
public static TextFormatter<String> getIntegerTextFormatter() {
UnaryOperator<TextFormatter.Change> filter = change -> {
String text = change.getText();
if (text.matches("[0-9]*")) {
return change;
}
return null;
};
return new TextFormatter<>(filter);
}
public static void removePseudoClasses(Cell<?> cell, PseudoClass... pseudoClasses) {
for (PseudoClass pseudoClass : pseudoClasses) {
cell.pseudoClassStateChanged(pseudoClass, false);
}
}
/**
* Determines where the mouse is in the given cell.
*/
public static DroppingMouseLocation getDroppingMouseLocation(Cell<?> cell, DragEvent event) {
if ((cell.getHeight() * 0.25) > event.getY()) {
return DroppingMouseLocation.TOP;
} else if ((cell.getHeight() * 0.75) < event.getY()) {
return DroppingMouseLocation.BOTTOM;
} else {
return DroppingMouseLocation.CENTER;
}
}
public static void setDroppingPseudoClasses(Cell<?> cell, DragEvent event) {
removeDroppingPseudoClasses(cell);
switch (getDroppingMouseLocation(cell, event)) {
case BOTTOM:
cell.pseudoClassStateChanged(dragOverBottom, true);
break;
case CENTER:
cell.pseudoClassStateChanged(dragOverCenter, true);
break;
case TOP:
cell.pseudoClassStateChanged(dragOverTop, true);
break;
}
}
public static void setDroppingPseudoClasses(Cell<?> cell) {
removeDroppingPseudoClasses(cell);
cell.pseudoClassStateChanged(dragOverCenter, true);
}
public static void removeDroppingPseudoClasses(Cell<?> cell) {
removePseudoClasses(cell, dragOverBottom, dragOverCenter, dragOverTop);
}
/**
* If needed, truncates a given string to <code>maxCharacters</code>, adding <code>ellipsisString</code> instead.
*
* @param text text which should be truncated, if needed
* @param maxCharacters maximum amount of characters which the resulting text should have, including the
* <code>ellipsisString</code>; if set to -1, then the default length of 75 characters will be
* used
* @param ellipsisString string which should be used for indicating the truncation
* @param ellipsisPosition location in the given text where the truncation should be performed
* @return the new, truncated string
*/
public static String truncateString(String text, int maxCharacters, String ellipsisString, EllipsisPosition ellipsisPosition) {
if (text == null || "".equals(text)) {
return text; // return original
}
if (ellipsisString == null) {
ellipsisString = "";
}
if (maxCharacters == -1) {
maxCharacters = 75; // default
}
maxCharacters = Math.max(ellipsisString.length(), maxCharacters);
if (text.length() > maxCharacters) {
// truncation necessary
switch (ellipsisPosition) {
case BEGINNING:
return ellipsisString + text.substring(text.length() - (maxCharacters - ellipsisString.length()));
case CENTER:
int partialLength = (int) Math.floor((maxCharacters - ellipsisString.length()) / 2f);
return text.substring(0, partialLength) + ellipsisString + text.substring(text.length() - partialLength);
case ENDING:
return text.substring(0, maxCharacters - ellipsisString.length()) + ellipsisString;
}
}
return text;
}
}
| 5,425
| 36.42069
| 131
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/CurrentThreadTaskExecutor.java
|
package org.jabref.gui.util;
import java.util.WeakHashMap;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import javafx.concurrent.Task;
import org.jabref.logic.util.DelayTaskThrottler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Implementation of {@link TaskExecutor} that runs every task on the current thread, i.e. in a sequential order. This
* class is not designed to be used in production but should make code involving asynchronous operations deterministic
* and testable.
*/
public class CurrentThreadTaskExecutor implements TaskExecutor {
private static final Logger LOGGER = LoggerFactory.getLogger(CurrentThreadTaskExecutor.class);
private final WeakHashMap<DelayTaskThrottler, Void> throttlers = new WeakHashMap<>();
/**
* Executes the task on the current thread. The code is essentially taken from {@link
* javafx.concurrent.Task.TaskCallable#call()}, but adapted to run sequentially.
*/
@Override
public <V> Future<V> execute(BackgroundTask<V> task) {
Runnable onRunning = task.getOnRunning();
if (onRunning != null) {
onRunning.run();
}
try {
final V result = task.call();
Consumer<V> onSuccess = task.getOnSuccess();
if (onSuccess != null) {
onSuccess.accept(result);
}
return CompletableFuture.completedFuture(result);
} catch (Exception exception) {
Consumer<Exception> onException = task.getOnException();
if (onException != null) {
onException.accept(exception);
} else {
LOGGER.error("Unhandled exception", exception);
}
return new FailedFuture<>(exception);
}
}
@Override
public <V> Future<V> execute(Task<V> task) {
return task;
}
@Override
public <V> Future<?> schedule(BackgroundTask<V> task, long delay, TimeUnit unit) {
return execute(task);
}
@Override
public void shutdown() {
throttlers.forEach((throttler, aVoid) -> throttler.shutdown());
}
@Override
public DelayTaskThrottler createThrottler(int delay) {
DelayTaskThrottler throttler = new DelayTaskThrottler(delay);
throttlers.put(throttler, null);
return throttler;
}
private static class FailedFuture<T> implements Future<T> {
private final Throwable exception;
FailedFuture(Throwable exception) {
this.exception = exception;
}
@Override
public T get() throws ExecutionException {
throw new ExecutionException(exception);
}
@Override
public T get(long timeout, TimeUnit unit) throws ExecutionException {
return get();
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public boolean isDone() {
return true;
}
}
}
| 3,284
| 28.863636
| 118
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/CustomLocalDragboard.java
|
package org.jabref.gui.util;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jabref.gui.DragAndDropDataFormats;
import org.jabref.gui.StateManager;
import org.jabref.logic.preview.PreviewLayout;
import org.jabref.model.entry.BibEntry;
/**
* Placeholder class for a custom generic type safe dragboard to be used in drag and drop, does not depend on serialization
* Don't use this class directly. Use the instance provided in {@link StateManager#getLocalDragboard()}
*/
public class CustomLocalDragboard {
@SuppressWarnings("unchecked") private static final Class<List<BibEntry>> BIB_ENTRIES = (Class<List<BibEntry>>) (Class<?>) List.class;
private final Map<Class<?>, Object> contents = new HashMap<>();
/**
* Puts the value of the concrete class in a map. All previous content stored in the map is removed
*
* @param type The Type of the class
* @param value The value to store
*/
public <T> void putValue(Class<T> type, T value) {
clearAll();
contents.put(type, type.cast(value));
}
public <T> T getValue(Class<T> type) {
return type.cast(contents.get(type));
}
public boolean hasType(Class<?> type) {
return contents.containsKey(type);
}
public void clear(Class<?> type) {
contents.remove(type);
}
public void clearAll() {
contents.clear();
}
/**
* Puts A List of {@link BibEntry} in the map All previous content is cleared
*
* @param entries The list to put
*/
public void putBibEntries(List<BibEntry> entries) {
putValue(BIB_ENTRIES, entries);
}
/**
* Get a List of {@link BibEntry} from the dragboard
*
* @return List of BibEntry or empty list if no entries are avaiable
*/
public List<BibEntry> getBibEntries() {
if (hasBibEntries()) {
return getValue(BIB_ENTRIES);
}
return Collections.emptyList();
}
public boolean hasBibEntries() {
return hasType(BIB_ENTRIES);
}
/**
* Puts A List of {@link PreviewLayout} in the map All previous content is cleared
*
* @param previewLayouts The list to put
*/
public void putPreviewLayouts(List<PreviewLayout> previewLayouts) {
putValue(DragAndDropDataFormats.PREVIEWLAYOUT_LIST_CLASS, previewLayouts);
}
/**
* Get a List of {@link PreviewLayout} from the dragboard
*
* @return List of PreviewLayout or empty list if no entries are avaiable
*/
public List<PreviewLayout> getPreviewLayouts() {
if (hasType(DragAndDropDataFormats.PREVIEWLAYOUT_LIST_CLASS)) {
return getValue(DragAndDropDataFormats.PREVIEWLAYOUT_LIST_CLASS);
}
return Collections.emptyList();
}
}
| 2,844
| 28.635417
| 138
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/CustomRatingSkin.java
|
package org.jabref.gui.util;
import javafx.scene.Node;
import org.jabref.gui.icon.IconTheme;
import impl.org.controlsfx.skin.RatingSkin;
import org.controlsfx.control.Rating;
public class CustomRatingSkin extends RatingSkin {
public CustomRatingSkin(Rating control) {
super(control);
consumeMouseEvents(false);
}
@Override
protected Node createButtonNode() {
return IconTheme.JabRefIcons.RANKING.getGraphicNode();
}
}
| 468
| 20.318182
| 62
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/CustomTitledPaneSkin.java
|
package org.jabref.gui.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.DoubleBinding;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.Property;
import javafx.css.CssMetaData;
import javafx.css.SimpleStyleableObjectProperty;
import javafx.css.StyleableObjectProperty;
import javafx.css.StyleableProperty;
import javafx.scene.Node;
import javafx.scene.control.Skin;
import javafx.scene.control.TitledPane;
import javafx.scene.control.skin.TitledPaneSkin;
import javafx.scene.layout.Region;
import javafx.scene.text.Text;
import javafx.scene.transform.Rotate;
import static javafx.css.StyleConverter.getEnumConverter;
/**
*
* CustomTitledPaneSkin with option to move arrow to the right
* https://stackoverflow.com/a/55085777/3450689s
*/
public class CustomTitledPaneSkin extends TitledPaneSkin {
public enum ArrowSide {
LEFT, RIGHT
}
/* ********************************************************
* *
* Properties *
* *
**********************************************************/
private final StyleableObjectProperty<ArrowSide> arrowSide = new SimpleStyleableObjectProperty<>(StyleableProperties.ARROW_SIDE, this, "arrowSide", ArrowSide.LEFT) {
@Override
protected void invalidated() {
adjustTitleLayout();
}
};
public final void setArrowSide(ArrowSide arrowSide) {
this.arrowSide.set(arrowSide);
}
public final ArrowSide getArrowSide() {
return arrowSide.get();
}
public final ObjectProperty<ArrowSide> arrowSideProperty() {
return arrowSide;
}
/* ********************************************************
* *
* Instance Fields *
* *
**********************************************************/
private final Region title;
private final Region arrowButton;
private final Region arrow;
private final Text text;
private DoubleBinding arrowTranslateBinding;
private DoubleBinding textGraphicTranslateBinding;
private Node graphic;
/* ********************************************************
* *
* Constructors *
* *
**********************************************************/
public CustomTitledPaneSkin(TitledPane control) {
super(control);
title = (Region) Objects.requireNonNull(control.lookup(".title"));
arrowButton = (Region) Objects.requireNonNull(title.lookup(".arrow-button"));
arrow = (Region) Objects.requireNonNull(arrowButton.lookup(".arrow"));
text = (Text) Objects.requireNonNull(title.lookup(".text"));
// based on https://stackoverflow.com/a/55156460/3450689
Rotate rotate = new Rotate();
rotate.pivotXProperty().bind(arrow.widthProperty().divide(2.0));
rotate.pivotYProperty().bind(arrow.heightProperty().divide(2.0));
rotate.angleProperty().bind(
Bindings.when(control.expandedProperty())
.then(-180.0)
.otherwise(90.0));
arrow.getTransforms().add(rotate);
registerChangeListener(control.graphicProperty(), ov -> adjustTitleLayout());
}
/* ********************************************************
* *
* Skin Stuff *
* *
**********************************************************/
private void adjustTitleLayout() {
clearBindings();
if (getArrowSide() != ArrowSide.RIGHT) {
// if arrow is on the left we don't need to translate anything
return;
}
arrowTranslateBinding = Bindings.createDoubleBinding(() -> {
double rightInset = title.getPadding().getRight();
return title.getWidth() - arrowButton.getLayoutX() - arrowButton.getWidth() - rightInset;
}, title.paddingProperty(), title.widthProperty(), arrowButton.widthProperty(), arrowButton.layoutXProperty());
arrowButton.translateXProperty().bind(arrowTranslateBinding);
textGraphicTranslateBinding = Bindings.createDoubleBinding(
() -> switch (getSkinnable().getAlignment()) {
case TOP_CENTER, CENTER, BOTTOM_CENTER, BASELINE_CENTER -> 0.0;
default -> -(arrowButton.getWidth());
}, getSkinnable().alignmentProperty(), arrowButton.widthProperty());
text.translateXProperty().bind(textGraphicTranslateBinding);
graphic = getSkinnable().getGraphic();
if (graphic != null) {
graphic.translateXProperty().bind(textGraphicTranslateBinding);
}
}
private void clearBindings() {
if (arrowTranslateBinding != null) {
arrowButton.translateXProperty().unbind();
arrowButton.setTranslateX(0);
arrowTranslateBinding.dispose();
arrowTranslateBinding = null;
}
if (textGraphicTranslateBinding != null) {
text.translateXProperty().unbind();
text.setTranslateX(0);
if (graphic != null) {
graphic.translateXProperty().unbind();
graphic.setTranslateX(0);
graphic = null;
}
textGraphicTranslateBinding.dispose();
textGraphicTranslateBinding = null;
}
}
@Override
public void dispose() {
clearBindings();
unregisterChangeListeners(getSkinnable().graphicProperty());
super.dispose();
}
/* ********************************************************
* *
* Stylesheet Handling *
* *
**********************************************************/
public static List<CssMetaData<?, ?>> getClassCssMetaData() {
return StyleableProperties.CSS_META_DATA;
}
@Override
public List<CssMetaData<?, ?>> getCssMetaData() {
return getClassCssMetaData();
}
private static class StyleableProperties {
private static final CssMetaData<TitledPane, ArrowSide> ARROW_SIDE = new CssMetaData<>("-fx-arrow-side", getEnumConverter(ArrowSide.class), ArrowSide.LEFT) {
@Override
public boolean isSettable(TitledPane styleable) {
Property<?> prop = (Property<?>) getStyleableProperty(styleable);
return (prop != null) && !prop.isBound();
}
@Override
public StyleableProperty<ArrowSide> getStyleableProperty(TitledPane styleable) {
Skin<?> skin = styleable.getSkin();
if (skin instanceof CustomTitledPaneSkin paneSkin) {
return paneSkin.arrowSide;
}
return null;
}
};
private static final List<CssMetaData<?, ?>> CSS_META_DATA;
static {
List<CssMetaData<?, ?>> list = new ArrayList<>(TitledPane.getClassCssMetaData().size() + 1);
list.addAll(TitledPaneSkin.getClassCssMetaData());
list.add(ARROW_SIDE);
CSS_META_DATA = Collections.unmodifiableList(list);
}
}
}
| 7,934
| 36.606635
| 169
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/DefaultFileUpdateMonitor.java
|
package org.jabref.gui.util;
import java.io.IOException;
import java.nio.file.ClosedWatchServiceException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.jabref.logic.JabRefException;
import org.jabref.logic.WatchServiceUnavailableException;
import org.jabref.model.util.FileUpdateListener;
import org.jabref.model.util.FileUpdateMonitor;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class monitors a set of files for changes. Upon detecting a change it notifies the registered {@link
* FileUpdateListener}s.
* <p>
* Implementation based on <a href="https://stackoverflow.com/questions/16251273/can-i-watch-for-single-file-change-with-watchservice-not-the-whole-directory">https://stackoverflow.com/questions/16251273/can-i-watch-for-single-file-change-with-watchservice-not-the-whole-directory</a>.
*/
public class DefaultFileUpdateMonitor implements Runnable, FileUpdateMonitor {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultFileUpdateMonitor.class);
private final Multimap<Path, FileUpdateListener> listeners = ArrayListMultimap.create(20, 4);
private volatile WatchService watcher;
private final AtomicBoolean notShutdown = new AtomicBoolean(true);
private final AtomicReference<Optional<JabRefException>> filesystemMonitorFailure = new AtomicReference<>(Optional.empty());
@Override
public void run() {
try (WatchService watcher = FileSystems.getDefault().newWatchService()) {
this.watcher = watcher;
filesystemMonitorFailure.set(Optional.empty());
while (notShutdown.get()) {
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException | ClosedWatchServiceException e) {
return;
}
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
if (kind == StandardWatchEventKinds.OVERFLOW) {
Thread.yield();
continue;
} else if (kind == StandardWatchEventKinds.ENTRY_CREATE || kind == StandardWatchEventKinds.ENTRY_MODIFY) {
// We only handle "ENTRY_CREATE" and "ENTRY_MODIFY" here, so the context is always a Path
@SuppressWarnings("unchecked")
WatchEvent<Path> ev = (WatchEvent<Path>) event;
Path path = ((Path) key.watchable()).resolve(ev.context());
notifyAboutChange(path);
}
key.reset();
}
Thread.yield();
}
} catch (IOException e) {
JabRefException exception = new WatchServiceUnavailableException(
e.getMessage(), e.getLocalizedMessage(), e.getCause());
filesystemMonitorFailure.set(Optional.of(exception));
LOGGER.warn(exception.getLocalizedMessage(), e);
}
}
@Override
public boolean isActive() {
return filesystemMonitorFailure.get().isEmpty();
}
private void notifyAboutChange(Path path) {
listeners.get(path).forEach(FileUpdateListener::fileUpdated);
}
@Override
public void addListenerForFile(Path file, FileUpdateListener listener) throws IOException {
if (isActive()) {
// We can't watch files directly, so monitor their parent directory for updates
Path directory = file.toAbsolutePath().getParent();
directory.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY);
listeners.put(file, listener);
} else {
LOGGER.warn("Not adding listener {} to file {} because the file update monitor isn't active", listener, file);
}
}
@Override
public void removeListener(Path path, FileUpdateListener listener) {
listeners.remove(path, listener);
}
@Override
public void shutdown() {
try {
notShutdown.set(false);
WatchService watcher = this.watcher;
if (watcher != null) {
watcher.close();
}
} catch (IOException e) {
LOGGER.error("error closing watcher", e);
}
}
}
| 4,757
| 39.322034
| 285
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/DefaultTaskExecutor.java
|
package org.jabref.gui.util;
import java.util.Objects;
import java.util.WeakHashMap;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import javafx.application.Platform;
import javafx.concurrent.Task;
import org.jabref.gui.StateManager;
import org.jabref.logic.util.DelayTaskThrottler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A very simple implementation of the {@link TaskExecutor} interface.
* Every submitted task is invoked in a separate thread.
*/
public class DefaultTaskExecutor implements TaskExecutor {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultTaskExecutor.class);
private final ExecutorService executor = Executors.newFixedThreadPool(5);
private final ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(2);
private final WeakHashMap<DelayTaskThrottler, Void> throttlers = new WeakHashMap<>();
private final StateManager stateManager;
public DefaultTaskExecutor(StateManager stateManager) {
super();
this.stateManager = stateManager;
}
/**
*
*/
public static <V> V runInJavaFXThread(Callable<V> callable) {
if (Platform.isFxApplicationThread()) {
try {
return callable.call();
} catch (Exception e) {
LOGGER.error("Problem executing call", e);
return null;
}
}
FutureTask<V> task = new FutureTask<>(callable);
Platform.runLater(task);
try {
return task.get();
} catch (InterruptedException | ExecutionException e) {
LOGGER.error("Problem running in fx thread", e);
return null;
}
}
/**
* Runs the specified {@link Runnable} on the JavaFX application thread and waits for completion.
*
* @param action the {@link Runnable} to run
* @throws NullPointerException if {@code action} is {@code null}
*/
public static void runAndWaitInJavaFXThread(Runnable action) {
Objects.requireNonNull(action);
// Run synchronously on JavaFX thread
if (Platform.isFxApplicationThread()) {
action.run();
return;
}
// Queue on JavaFX thread and wait for completion
final CountDownLatch doneLatch = new CountDownLatch(1);
Platform.runLater(() -> {
try {
action.run();
} finally {
doneLatch.countDown();
}
});
try {
doneLatch.await();
} catch (InterruptedException e) {
LOGGER.error("Problem running action on JavaFX thread", e);
}
}
public static void runInJavaFXThread(Runnable runnable) {
Platform.runLater(runnable);
}
@Override
public <V> Future<V> execute(BackgroundTask<V> task) {
Task<V> javafxTask = getJavaFXTask(task);
if (task.showToUser()) {
stateManager.addBackgroundTask(task, javafxTask);
}
return execute(javafxTask);
}
@Override
public <V> Future<V> execute(Task<V> task) {
executor.submit(task);
return task;
}
@Override
public <V> Future<?> schedule(BackgroundTask<V> task, long delay, TimeUnit unit) {
return scheduledExecutor.schedule(getJavaFXTask(task), delay, unit);
}
/**
* Shuts everything down. After termination, this method returns.
*/
@Override
public void shutdown() {
stateManager.getBackgroundTasks().stream().filter(task -> !task.isDone()).forEach(Task::cancel);
executor.shutdownNow();
scheduledExecutor.shutdownNow();
throttlers.forEach((throttler, aVoid) -> throttler.shutdown());
}
@Override
public DelayTaskThrottler createThrottler(int delay) {
DelayTaskThrottler throttler = new DelayTaskThrottler(delay);
throttlers.put(throttler, null);
return throttler;
}
private <V> Task<V> getJavaFXTask(BackgroundTask<V> task) {
Task<V> javaTask = new Task<V>() {
{
this.updateMessage(task.messageProperty().get());
this.updateTitle(task.titleProperty().get());
BindingsHelper.subscribeFuture(task.progressProperty(), progress -> updateProgress(progress.getWorkDone(), progress.getMax()));
BindingsHelper.subscribeFuture(task.messageProperty(), this::updateMessage);
BindingsHelper.subscribeFuture(task.titleProperty(), this::updateTitle);
BindingsHelper.subscribeFuture(task.isCanceledProperty(), cancelled -> {
if (cancelled) {
cancel();
}
});
setOnCancelled(event -> task.cancel());
}
@Override
public V call() throws Exception {
return task.call();
}
};
Runnable onRunning = task.getOnRunning();
if (onRunning != null) {
javaTask.setOnRunning(event -> onRunning.run());
}
Consumer<V> onSuccess = task.getOnSuccess();
if (onSuccess != null) {
javaTask.setOnSucceeded(event -> onSuccess.accept(javaTask.getValue()));
}
Consumer<Exception> onException = task.getOnException();
if (onException != null) {
javaTask.setOnFailed(event -> onException.accept(convertToException(javaTask.getException())));
}
return javaTask;
}
private Exception convertToException(Throwable throwable) {
if (throwable instanceof Exception exception) {
return exception;
} else {
return new Exception(throwable);
}
}
}
| 6,150
| 31.893048
| 143
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/DialogWindowState.java
|
package org.jabref.gui.util;
/**
* This class is used to store the size and position of dialog windows so that
* these properties stay consistent when they are closed and re-opened
*/
public class DialogWindowState {
private final double x;
private final double y;
private final double height;
private final double width;
public DialogWindowState(double x, double y, double height, double width) {
this.x = x;
this.y = y;
this.height = height;
this.width = width;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public double getHeight() {
return height;
}
public double getWidth() {
return width;
}
}
| 755
| 20
| 79
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/DirectoryDialogConfiguration.java
|
package org.jabref.gui.util;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
public class DirectoryDialogConfiguration {
private final Path initialDirectory;
private DirectoryDialogConfiguration(Path initialDirectory) {
this.initialDirectory = initialDirectory;
}
public Optional<Path> getInitialDirectory() {
return Optional.ofNullable(initialDirectory);
}
public static class Builder {
private Path initialDirectory;
public DirectoryDialogConfiguration build() {
return new DirectoryDialogConfiguration(initialDirectory);
}
public Builder withInitialDirectory(Path directory) {
directory = directory.toAbsolutePath();
// Dir must be a folder, not a file
if (!Files.isDirectory(directory)) {
directory = directory.getParent();
}
// The lines above work also if the dir does not exist at all!
// NULL is accepted by the filechooser as no initial path
if (!Files.exists(directory)) {
directory = null;
}
initialDirectory = directory;
return this;
}
public Builder withInitialDirectory(String directory) {
withInitialDirectory(Path.of(directory));
return this;
}
}
}
| 1,400
| 26.470588
| 74
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/DroppingMouseLocation.java
|
package org.jabref.gui.util;
/**
* The mouse location within the cell when the dropping gesture occurs.
*/
public enum DroppingMouseLocation {
BOTTOM,
CENTER,
TOP
}
| 180
| 15.454545
| 71
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/FieldsUtil.java
|
package org.jabref.gui.util;
import javafx.util.StringConverter;
import org.jabref.gui.Globals;
import org.jabref.gui.specialfields.SpecialFieldViewModel;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.FieldFactory;
import org.jabref.model.entry.field.IEEEField;
import org.jabref.model.entry.field.InternalField;
import org.jabref.model.entry.field.SpecialField;
import org.jabref.model.entry.field.UnknownField;
public class FieldsUtil {
public static final StringConverter<Field> FIELD_STRING_CONVERTER = new StringConverter<>() {
@Override
public String toString(Field object) {
if (object != null) {
return object.getDisplayName();
} else {
return "";
}
}
@Override
public Field fromString(String string) {
return FieldFactory.parseField(string);
}
};
public static String getNameWithType(Field field) {
if (field instanceof SpecialField specialField) {
return new SpecialFieldViewModel(specialField, Globals.prefs, Globals.undoManager).getLocalization()
+ " (" + Localization.lang("Special") + ")";
} else if (field instanceof IEEEField) {
return field.getDisplayName() + " (" + Localization.lang("IEEE") + ")";
} else if (field instanceof InternalField) {
return field.getDisplayName() + " (" + Localization.lang("Internal") + ")";
} else if (field instanceof UnknownField) {
return field.getDisplayName() + " (" + Localization.lang("Custom") + ")";
} else {
return field.getDisplayName();
}
}
}
| 1,756
| 35.604167
| 112
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/FileDialogConfiguration.java
|
package org.jabref.gui.util;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Stream;
import javafx.stage.FileChooser;
import org.jabref.logic.util.FileType;
public class FileDialogConfiguration {
private final List<FileChooser.ExtensionFilter> extensionFilters;
private final Path initialDirectory;
private final FileChooser.ExtensionFilter defaultExtension;
private final String initialFileName;
private FileChooser.ExtensionFilter selectedExtensionFilter;
private FileDialogConfiguration(Path initialDirectory, List<FileChooser.ExtensionFilter> extensionFilters,
FileChooser.ExtensionFilter defaultExtension, String initialFileName) {
this.initialDirectory = initialDirectory;
this.extensionFilters = Objects.requireNonNull(extensionFilters);
this.defaultExtension = defaultExtension;
this.initialFileName = initialFileName;
}
public Optional<Path> getInitialDirectory() {
return Optional.ofNullable(initialDirectory);
}
public FileChooser.ExtensionFilter getDefaultExtension() {
return defaultExtension;
}
public String getInitialFileName() {
return initialFileName;
}
public List<FileChooser.ExtensionFilter> getExtensionFilters() {
return extensionFilters;
}
public FileChooser.ExtensionFilter getSelectedExtensionFilter() {
return selectedExtensionFilter;
}
public void setSelectedExtensionFilter(FileChooser.ExtensionFilter selectedExtensionFilter) {
this.selectedExtensionFilter = selectedExtensionFilter;
}
public static class Builder {
private final List<FileChooser.ExtensionFilter> extensionFilters = new ArrayList<>();
private Path initialDirectory;
private FileChooser.ExtensionFilter defaultExtension;
private String initialFileName;
public FileDialogConfiguration build() {
return new FileDialogConfiguration(initialDirectory, extensionFilters, defaultExtension, initialFileName);
}
public Builder withInitialDirectory(Path directory) {
if (directory == null) { // It could be that somehow the path is null, for example if it got deleted in the meantime
initialDirectory = null;
} else { // Dir must be a folder, not a file
if (!Files.isDirectory(directory)) {
directory = directory.getParent();
}
// The lines above work also if the dir does not exist at all!
// NULL is accepted by the filechooser as no inital path
// Explicit null check, if somehow the parent is null, as Files.exists throws an NPE otherwise
if ((directory != null) && !Files.exists(directory)) {
directory = null;
}
initialDirectory = directory;
}
return this;
}
public Builder withInitialDirectory(String directory) {
if (directory != null) {
withInitialDirectory(Path.of(directory));
} else {
initialDirectory = null;
}
return this;
}
public Builder withInitialFileName(String initialFileName) {
this.initialFileName = initialFileName;
return this;
}
public Builder withDefaultExtension(FileChooser.ExtensionFilter extensionFilter) {
defaultExtension = extensionFilter;
return this;
}
public Builder withDefaultExtension(FileType fileType) {
defaultExtension = FileFilterConverter.toExtensionFilter(fileType);
return this;
}
public Builder withDefaultExtension(String description, FileType fileType) {
defaultExtension = FileFilterConverter.toExtensionFilter(description, fileType);
return this;
}
public Builder withDefaultExtension(String fileTypeDescription) {
extensionFilters.stream()
.filter(type -> type.getDescription().equalsIgnoreCase(fileTypeDescription))
.findFirst()
.ifPresent(extensionFilter -> defaultExtension = extensionFilter);
return this;
}
public Builder addExtensionFilter(FileChooser.ExtensionFilter filter) {
extensionFilters.add(filter);
return this;
}
public Builder addExtensionFilter(List<FileChooser.ExtensionFilter> filters) {
extensionFilters.addAll(filters);
return this;
}
public Builder addExtensionFilter(FileType... fileTypes) {
Stream.of(fileTypes)
.map(FileFilterConverter::toExtensionFilter)
.forEachOrdered(this::addExtensionFilter);
return this;
}
public Builder addExtensionFilter(String description, FileType fileType) {
extensionFilters.add(FileFilterConverter.toExtensionFilter(description, fileType));
return this;
}
}
}
| 5,304
| 35.586207
| 128
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/FileFilterConverter.java
|
package org.jabref.gui.util;
import java.io.FileFilter;
import java.io.IOException;
import java.nio.file.DirectoryStream.Filter;
import java.nio.file.Path;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.SortedSet;
import java.util.stream.Collectors;
import javafx.stage.FileChooser;
import org.jabref.logic.exporter.Exporter;
import org.jabref.logic.importer.Importer;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.FileType;
import org.jabref.logic.util.io.FileUtil;
import org.jabref.model.strings.StringUtil;
public class FileFilterConverter {
public static FileChooser.ExtensionFilter ANY_FILE = new FileChooser.ExtensionFilter(Localization.lang("Any file"), "*.*");
private FileFilterConverter() {
}
public static FileChooser.ExtensionFilter toExtensionFilter(FileType fileType) {
String fileList = String.join(", ", fileType.getExtensionsWithAsteriskAndDot());
String description = Localization.lang("%0 file (%1)", fileType.getName(), fileList);
return new FileChooser.ExtensionFilter(description, fileType.getExtensionsWithAsteriskAndDot());
}
public static FileChooser.ExtensionFilter toExtensionFilter(String description, FileType fileType) {
return new FileChooser.ExtensionFilter(description, fileType.getExtensionsWithAsteriskAndDot());
}
public static Optional<Importer> getImporter(FileChooser.ExtensionFilter extensionFilter, Collection<Importer> importers) {
return importers.stream().filter(importer -> importer.getName().equals(extensionFilter.getDescription())).findFirst();
}
public static Optional<Exporter> getExporter(FileChooser.ExtensionFilter extensionFilter, Collection<Exporter> exporters) {
return exporters.stream().filter(exporter -> exporter.getName().equals(extensionFilter.getDescription())).findFirst();
}
public static FileChooser.ExtensionFilter forAllImporters(SortedSet<Importer> importers) {
List<FileType> fileTypes = importers.stream().map(Importer::getFileType).collect(Collectors.toList());
List<String> flatExtensions = fileTypes.stream()
.flatMap(type -> type.getExtensionsWithAsteriskAndDot().stream())
.collect(Collectors.toList());
return new FileChooser.ExtensionFilter(Localization.lang("Available import formats"), flatExtensions);
}
public static List<FileChooser.ExtensionFilter> importerToExtensionFilter(Collection<Importer> importers) {
return importers.stream()
.map(importer -> toExtensionFilter(importer.getName(), importer.getFileType()))
.collect(Collectors.toList());
}
public static List<FileChooser.ExtensionFilter> exporterToExtensionFilter(Collection<Exporter> exporters) {
return exporters.stream()
.map(exporter -> toExtensionFilter(exporter.getName(), exporter.getFileType()))
.collect(Collectors.toList());
}
public static FileFilter toFileFilter(FileChooser.ExtensionFilter extensionFilter) {
return toFileFilter(extensionFilter.getExtensions());
}
public static FileFilter toFileFilter(List<String> extensions) {
var filter = toDirFilter(extensions);
return file -> {
try {
return filter.accept(file.toPath());
} catch (IOException e) {
return false;
}
};
}
public static Filter<Path> toDirFilter(List<String> extensions) {
List<String> extensionsCleaned = extensions.stream()
.map(extension -> extension.replace(".", "").replace("*", ""))
.filter(StringUtil::isNotBlank)
.collect(Collectors.toList());
if (extensionsCleaned.isEmpty()) {
// Except every file
return path -> true;
} else {
return path -> FileUtil.getFileExtension(path)
.map(extensionsCleaned::contains)
.orElse(false);
}
}
}
| 4,326
| 43.153061
| 127
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/FileNodeViewModel.java
|
package org.jabref.gui.util;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import javafx.beans.property.ReadOnlyListWrapper;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.jabref.logic.l10n.Localization;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FileNodeViewModel {
private static final Logger LOGGER = LoggerFactory.getLogger(FileNodeViewModel.class);
private final Path path;
private final ObservableList<FileNodeViewModel> children;
private int fileCount;
public FileNodeViewModel(Path path) {
this.path = path;
this.children = FXCollections.observableArrayList();
this.fileCount = 0;
}
public Path getPath() {
return path;
}
public ObservableList<FileNodeViewModel> getChildren() {
return new ReadOnlyListWrapper<>(children);
}
public int getFileCount() {
return fileCount;
}
public void setFileCount(int fileCount) {
this.fileCount = fileCount;
}
/**
* Return a string of a FileTime in a yyyy-MM-dd HH:mm format.
*/
public static String formatDateTime(FileTime fileTime) {
LocalDateTime localDateTime = fileTime
.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDateTime();
return localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
}
/**
* Return a string for displaying a node name (and its number of children if it is a directory).
*/
public String getDisplayText() {
if (path.toFile().isDirectory()) {
return String.format("%s (%s %s)", path.getFileName(), fileCount,
fileCount == 1 ? Localization.lang("file") : Localization.lang("files"));
}
return path.getFileName().toString();
}
/**
* Return a string for displaying a node name (and its number of children if it is a directory).
* along with the last edited time
*/
public String getDisplayTextWithEditDate() {
if (path.toFile().isDirectory()) {
return String.format("%s (%s %s)", path.getFileName(), fileCount,
fileCount == 1 ? Localization.lang("file") : Localization.lang("files"));
}
FileTime lastEditedTime = null;
try {
lastEditedTime = Files.getLastModifiedTime(path);
} catch (IOException e) {
LOGGER.error("Exception Caught", e);
}
return String.format("%s (%s: %s)", path.getFileName().toString(), Localization.lang("last edited"), formatDateTime(lastEditedTime));
}
@Override
public String toString() {
return String.format("FileNodeViewModel{path=%s, children=%s, fileCount=%s}",
this.path,
this.children,
this.fileCount);
}
@Override
public int hashCode() {
return Objects.hash(children, fileCount, path);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof FileNodeViewModel)) {
return false;
}
FileNodeViewModel other = (FileNodeViewModel) obj;
return Objects.equals(children, other.children) && (fileCount == other.fileCount) && Objects.equals(path, other.path);
}
}
| 3,604
| 30.077586
| 141
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/IconValidationDecorator.java
|
package org.jabref.gui.util;
import java.util.Collection;
import java.util.Collections;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import org.jabref.gui.icon.IconTheme;
import org.controlsfx.control.decoration.Decoration;
import org.controlsfx.control.decoration.GraphicDecoration;
import org.controlsfx.validation.Severity;
import org.controlsfx.validation.ValidationMessage;
import org.controlsfx.validation.decoration.GraphicValidationDecoration;
/**
* This class is similar to {@link GraphicValidationDecoration} but with a different style and font-based icon.
*/
public class IconValidationDecorator extends GraphicValidationDecoration {
private final Pos position;
public IconValidationDecorator() {
this(Pos.BOTTOM_LEFT);
}
public IconValidationDecorator(Pos position) {
this.position = position;
}
@Override
protected Node createErrorNode() {
return IconTheme.JabRefIcons.ERROR.getGraphicNode();
}
@Override
protected Node createWarningNode() {
return IconTheme.JabRefIcons.WARNING.getGraphicNode();
}
@Override
public Node createDecorationNode(ValidationMessage message) {
Node graphic = Severity.ERROR == message.getSeverity() ? createErrorNode() : createWarningNode();
graphic.getStyleClass().add(Severity.ERROR == message.getSeverity() ? "error-icon" : "warning-icon");
Label label = new Label();
label.setGraphic(graphic);
label.setTooltip(createTooltip(message));
label.setAlignment(position);
return label;
}
@Override
protected Tooltip createTooltip(ValidationMessage message) {
Tooltip tooltip = new Tooltip(message.getText());
tooltip.getStyleClass().add(Severity.ERROR == message.getSeverity() ? "tooltip-error" : "tooltip-warning");
return tooltip;
}
@Override
protected Collection<Decoration> createValidationDecorations(ValidationMessage message) {
return Collections.singletonList(new GraphicDecoration(createDecorationNode(message), position));
}
}
| 2,171
| 31.41791
| 115
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/JabRefResourceLocator.java
|
package org.jabref.gui.util;
import java.util.ResourceBundle;
import org.jabref.logic.l10n.Localization;
import com.airhacks.afterburner.views.ResourceLocator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JabRefResourceLocator implements ResourceLocator {
private static final Logger LOGGER = LoggerFactory.getLogger(JabRefResourceLocator.class);
@Override
public ResourceBundle getResourceBundle(String s) {
LOGGER.debug("Requested bundle for '{}'.", s);
return Localization.getMessages();
}
}
| 559
| 24.454545
| 94
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/NoSelectionModel.java
|
package org.jabref.gui.util;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.MultipleSelectionModel;
/**
* Disables selection
*/
public class NoSelectionModel<T> extends MultipleSelectionModel<T> {
@Override
public ObservableList<Integer> getSelectedIndices() {
return FXCollections.emptyObservableList();
}
@Override
public ObservableList<T> getSelectedItems() {
return FXCollections.emptyObservableList();
}
@Override
public void selectIndices(int index, int... indices) {
}
@Override
public void selectAll() {
}
@Override
public void selectFirst() {
}
@Override
public void selectLast() {
}
@Override
public void clearAndSelect(int index) {
}
@Override
public void select(int index) {
}
@Override
public void select(T obj) {
}
@Override
public void clearSelection(int index) {
}
@Override
public void clearSelection() {
}
@Override
public boolean isSelected(int index) {
return false;
}
@Override
public boolean isEmpty() {
return true;
}
@Override
public void selectPrevious() {
}
@Override
public void selectNext() {
}
}
| 1,320
| 16.381579
| 68
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/OnlyIntegerFormatter.java
|
package org.jabref.gui.util;
import java.util.function.UnaryOperator;
import java.util.regex.Pattern;
import javafx.scene.control.TextFormatter;
import javafx.util.converter.IntegerStringConverter;
/**
* Formatter that only accepts integer.
* <p>
* More or less taken from http://stackoverflow.com/a/36749659/873661
*/
public class OnlyIntegerFormatter extends TextFormatter<Integer> {
public OnlyIntegerFormatter() {
this(0);
}
public OnlyIntegerFormatter(Integer defaultValue) {
super(new IntegerStringConverter(), defaultValue, new IntegerFilter());
}
private static class IntegerFilter implements UnaryOperator<Change> {
private final static Pattern DIGIT_PATTERN = Pattern.compile("\\d*");
@Override
public Change apply(TextFormatter.Change aT) {
return DIGIT_PATTERN.matcher(aT.getText()).matches() ? aT : null;
}
}
}
| 919
| 26.878788
| 79
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/OpenHyperlinksInExternalBrowser.java
|
package org.jabref.gui.util;
import java.io.IOException;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.concurrent.Worker.State;
import javafx.scene.web.WebView;
import org.jabref.gui.desktop.JabRefDesktop;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventListener;
import org.w3c.dom.events.EventTarget;
import org.w3c.dom.html.HTMLAnchorElement;
/**
* A Hyperlink Click Listener for javafx.WebView to open links on click in the browser
* Code adapted from: <a href="https://stackoverflow.com/a/33445383/">https://stackoverflow.com/a/33445383/</a>
*/
public class OpenHyperlinksInExternalBrowser implements ChangeListener<Worker.State>, EventListener {
private static final Logger LOGGER = LoggerFactory.getLogger(OpenHyperlinksInExternalBrowser.class);
private static final String CLICK_EVENT = "click";
private static final String ANCHOR_TAG = "a";
private final WebView webView;
public OpenHyperlinksInExternalBrowser(WebView webView) {
this.webView = webView;
}
@Override
public void changed(ObservableValue<? extends State> observable, State oldValue, State newValue) {
if (State.SUCCEEDED.equals(newValue)) {
Document document = webView.getEngine().getDocument();
NodeList anchors = document.getElementsByTagName(ANCHOR_TAG);
for (int i = 0; i < anchors.getLength(); i++) {
Node node = anchors.item(i);
EventTarget eventTarget = (EventTarget) node;
eventTarget.addEventListener(CLICK_EVENT, this, false);
}
}
}
@Override
public void handleEvent(Event event) {
HTMLAnchorElement anchorElement = (HTMLAnchorElement) event.getCurrentTarget();
String href = anchorElement.getHref();
try {
JabRefDesktop.openBrowser(href);
} catch (IOException e) {
LOGGER.error("Problem opening browser", e);
}
event.preventDefault();
}
}
| 2,220
| 33.169231
| 112
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/OptionalObjectProperty.java
|
package org.jabref.gui.util;
import java.util.Optional;
import javafx.beans.binding.BooleanExpression;
import javafx.beans.binding.ObjectBinding;
import javafx.beans.property.SimpleObjectProperty;
import com.tobiasdiez.easybind.PreboundBinding;
/**
* Similar to {@link com.tobiasdiez.easybind.monadic.MonadicObservableValue}
*/
public class OptionalObjectProperty<T> extends SimpleObjectProperty<Optional<T>> {
private OptionalObjectProperty(Optional<T> initialValue) {
super(initialValue);
}
public static <T> OptionalObjectProperty<T> empty() {
return new OptionalObjectProperty<>(Optional.empty());
}
/**
* Returns a new ObservableValue that holds the value held by this
* ObservableValue, or {@code other} when this ObservableValue is empty.
*/
public ObjectBinding<T> orElseOpt(T other) {
return new PreboundBinding<>(this) {
@Override
protected T computeValue() {
return OptionalObjectProperty.this.getValue().orElse(other);
}
};
}
public BooleanExpression isPresent() {
return BooleanExpression.booleanExpression(new PreboundBinding<Boolean>(this) {
@Override
protected Boolean computeValue() {
return OptionalObjectProperty.this.getValue().isPresent();
}
});
}
}
| 1,384
| 29.108696
| 87
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/OptionalValueTableCellFactory.java
|
package org.jabref.gui.util;
import java.util.Optional;
import java.util.function.BiFunction;
import javafx.scene.Node;
import javafx.scene.control.TableCell;
/**
* Constructs a {@link TableCell} based on an optional value of the cell and a bunch of specified converter methods.
*
* @param <S> view model of table row
* @param <T> cell value
*/
public class OptionalValueTableCellFactory<S, T> extends ValueTableCellFactory<S, Optional<T>> {
private BiFunction<S, T, Node> toGraphicIfPresent;
private Node defaultGraphic;
public OptionalValueTableCellFactory<S, T> withGraphicIfPresent(BiFunction<S, T, Node> toGraphicIfPresent) {
this.toGraphicIfPresent = toGraphicIfPresent;
setToGraphic();
return this;
}
public OptionalValueTableCellFactory<S, T> withDefaultGraphic(Node defaultGraphic) {
this.defaultGraphic = defaultGraphic;
setToGraphic();
return this;
}
private void setToGraphic() {
withGraphic((rowItem, item) -> {
if (item.isPresent() && toGraphicIfPresent != null) {
return toGraphicIfPresent.apply(rowItem, item.get());
} else {
return defaultGraphic;
}
});
}
}
| 1,251
| 28.809524
| 116
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/RecursiveTreeItem.java
|
package org.jabref.gui.util;
import java.util.function.Predicate;
import javafx.beans.binding.Bindings;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.scene.Node;
import javafx.scene.control.CheckBoxTreeItem;
import javafx.util.Callback;
import com.tobiasdiez.easybind.EasyBind;
/**
* Taken from https://gist.github.com/lestard/011e9ed4433f9eb791a8
* As CheckBoxTreeItem extends TreeItem, this class will work for both.
*/
public class RecursiveTreeItem<T> extends CheckBoxTreeItem<T> {
private final Callback<T, BooleanProperty> expandedProperty;
private final Callback<T, ObservableList<T>> childrenFactory;
private final ObjectProperty<Predicate<T>> filter = new SimpleObjectProperty<>();
private FilteredList<RecursiveTreeItem<T>> children;
public RecursiveTreeItem(final T value, Callback<T, ObservableList<T>> func) {
this(value, func, null, null);
}
public RecursiveTreeItem(final T value, Callback<T, ObservableList<T>> func, Callback<T, BooleanProperty> expandedProperty, ObservableValue<Predicate<T>> filter) {
this(value, null, func, expandedProperty, filter);
}
public RecursiveTreeItem(final T value, Callback<T, ObservableList<T>> func, ObservableValue<Predicate<T>> filter) {
this(value, null, func, null, filter);
}
private RecursiveTreeItem(final T value, Node graphic, Callback<T, ObservableList<T>> func, Callback<T, BooleanProperty> expandedProperty, ObservableValue<Predicate<T>> filter) {
super(value, graphic);
this.childrenFactory = func;
this.expandedProperty = expandedProperty;
if (filter != null) {
this.filter.bind(filter);
}
if (value != null) {
addChildrenListener(value);
bindExpandedProperty(value, expandedProperty);
}
valueProperty().addListener((obs, oldValue, newValue) -> {
if (newValue != null) {
addChildrenListener(newValue);
bindExpandedProperty(newValue, expandedProperty);
}
});
}
private void bindExpandedProperty(T value, Callback<T, BooleanProperty> expandedProperty) {
if (expandedProperty != null) {
expandedProperty().bindBidirectional(expandedProperty.call(value));
}
}
private void addChildrenListener(T value) {
children = EasyBind.mapBacked(childrenFactory.call(value), child -> new RecursiveTreeItem<>(child, getGraphic(), childrenFactory, expandedProperty, filter))
.filtered(Bindings.createObjectBinding(() -> this::showNode, filter));
Bindings.bindContent(getChildren(), children);
}
private boolean showNode(RecursiveTreeItem<T> node) {
if (filter.get() == null) {
return true;
}
if (filter.get().test(node.getValue())) {
// Node is directly matched -> so show it
return true;
}
// Are there children (or children of children...) that are matched? If yes we also need to show this node
return node.children.getSource().stream().anyMatch(this::showNode);
}
}
| 3,402
| 36.811111
| 182
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/StreamGobbler.java
|
package org.jabref.gui.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.function.Consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StreamGobbler implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(StreamGobbler.class);
private InputStream inputStream;
private Consumer<String> consumer;
public StreamGobbler(InputStream inputStream, Consumer<String> consumer) {
this.inputStream = inputStream;
this.consumer = consumer;
}
@Override
public void run() {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
reader.lines().forEach(consumer);
} catch (IOException e) {
LOGGER.error("Error when reading process stream from external application", e);
}
}
}
| 944
| 27.636364
| 94
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/TaskExecutor.java
|
package org.jabref.gui.util;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import javafx.concurrent.Task;
import org.jabref.logic.util.DelayTaskThrottler;
/**
* An object that executes submitted {@link Task}s. This
* interface provides a way of decoupling task submission from the
* mechanics of how each task will be run, including details of thread
* use, scheduling, thread pooling, etc.
*/
public interface TaskExecutor {
/**
* Runs the given task and returns a Future representing that task.
*
* @param <V> type of return value of the task
* @param task the task to run
*/
<V> Future<V> execute(BackgroundTask<V> task);
/**
* Runs the given task and returns a Future representing that task. Usually, you want to use the other method {@link
* #execute(BackgroundTask)}.
*
* @param <V> type of return value of the task
* @param task the task to run
*/
<V> Future<V> execute(Task<V> task);
/**
* Submits a one-shot task that becomes enabled after the given delay.
*
* @param task the task to execute
* @param delay the time from now to delay execution
* @param unit the time unit of the delay parameter
* @return a ScheduledFuture representing pending completion of
* the task and whose {@code get()} method will return
* {@code null} upon completion
*/
<V> Future<?> schedule(BackgroundTask<V> task, long delay, TimeUnit unit);
/**
* Shutdown the task executor. May happen in the background or may be finished when this method returns.
*/
void shutdown();
/**
* Creates a new task throttler, and registers it so that it gets properly shutdown.
*/
DelayTaskThrottler createThrottler(int delay);
}
| 1,821
| 30.964912
| 120
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/TextFlowLimited.java
|
package org.jabref.gui.util;
import javafx.animation.Animation;
import javafx.animation.Transition;
import javafx.geometry.HPos;
import javafx.geometry.VPos;
import javafx.scene.control.Hyperlink;
import javafx.scene.layout.Region;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import javafx.util.Duration;
import org.jabref.logic.l10n.Localization;
public class TextFlowLimited extends TextFlow {
private boolean isCollapsed = true;
private Hyperlink moreLink = new Hyperlink(Localization.lang("(more)"));
private Rectangle clip = new Rectangle();
public TextFlowLimited(Text... texts) {
super(texts);
this.setPrefWidth(Region.USE_PREF_SIZE);
moreLink.setOnAction(event -> expand());
moreLink.setStyle("-fx-background-color: white");
this.setOnMouseClicked(event -> expand());
}
private void expand() {
double newPrefHeight = super.computePrefHeight(getWidth());
final Animation expandPanel = new Transition() {
{
setCycleDuration(Duration.millis(200));
}
@Override
protected void interpolate(double fraction) {
setPrefHeight(newPrefHeight * fraction);
}
};
expandPanel.setOnFinished(event -> {
isCollapsed = false;
requestLayout();
});
expandPanel.play();
}
@Override
protected double computePrefHeight(double width) {
if (isCollapsed) {
return 38;
} else {
return super.computePrefHeight(width);
}
}
@Override
protected void layoutChildren() {
super.layoutChildren();
if (isCollapsed) {
// Display link to expand text
if (!this.getChildren().contains(moreLink)) {
this.getChildren().add(moreLink);
}
layoutInArea(moreLink, 0, 0, getWidth(), getHeight(), getBaselineOffset(), HPos.RIGHT, VPos.BOTTOM);
// Clip content if it expands above pref height (no idea why this is needed, but otherwise sometimes the text is still visible)
clip.setHeight(computePrefHeight(this.getWidth()));
clip.setWidth(this.getWidth());
this.setClip(clip);
} else {
this.getChildren().remove(moreLink);
this.setClip(null);
}
}
}
| 2,451
| 28.902439
| 139
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/TooltipTextUtil.java
|
package org.jabref.gui.util;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javafx.scene.text.Text;
/**
* Utility class with static methods for javafx {@link Text} objects
*/
public class TooltipTextUtil {
// (?s) tells Java that "." also matches the newline character
// (?<...>...) are named groups in Java regular expressions: https://stackoverflow.com/a/415635/873282
// .*? tells to match non-greedy (see https://stackoverflow.com/q/7124778/873282 for details)
private static final Pattern TT_TEXT = Pattern.compile("(?s)(?<before>.*?)<tt>(?<in>.*?)</tt>");
private static final Pattern B_TEXT = Pattern.compile("(?s)(?<before>.*?)<b>(?<in>.*?)</b>");
public enum TextType {
NORMAL, BOLD, ITALIC, MONOSPACED
}
public static Text createText(String textString, TextType textType) {
Text text = new Text(textString);
switch (textType) {
case BOLD:
text.getStyleClass().setAll("tooltip-text-bold");
break;
case ITALIC:
text.getStyleClass().setAll("tooltip-text-italic");
break;
case MONOSPACED:
text.getStyleClass().setAll("tooltip-text-monospaced");
break;
default:
break;
}
return text;
}
public static Text createText(String textString) {
return createText(textString, TextType.NORMAL);
}
/**
* Creates a list of Text elements respecting <code>tt</code> and <code>b</code> markers.
* Nesting of these markers is not possible.
*/
public static List<Text> createTextsFromHtml(String htmlString) {
List<Text> result = new ArrayList<>();
Matcher matcher = TT_TEXT.matcher(htmlString);
int lastMatchPos = 0;
while (matcher.find()) {
lastMatchPos = matcher.end();
String before = matcher.group("before");
if (!before.isBlank()) {
result.addAll(convertHtmlBold(before));
}
String in = matcher.group("in");
result.add(TooltipTextUtil.createText(in, TooltipTextUtil.TextType.MONOSPACED));
}
if (lastMatchPos < htmlString.length()) {
String remaining = htmlString.substring(lastMatchPos);
result.addAll(convertHtmlBold(remaining));
}
return result;
}
private static List<Text> convertHtmlBold(String htmlString) {
List<Text> result = new ArrayList<>();
Matcher matcher = B_TEXT.matcher(htmlString);
int lastMatchPos = 0;
while (matcher.find()) {
lastMatchPos = matcher.end();
String before = matcher.group("before");
if (!before.isBlank()) {
result.add(TooltipTextUtil.createText(before));
}
String in = matcher.group("in");
result.add(TooltipTextUtil.createText(in, TextType.BOLD));
}
if (lastMatchPos < htmlString.length()) {
String remaining = htmlString.substring(lastMatchPos);
result.add(TooltipTextUtil.createText(remaining));
}
return result;
}
/**
* Formats a String to multiple Texts by replacing some parts and adding font characteristics.
*/
public static List<Text> formatToTexts(String original, TextReplacement... replacements) {
List<Text> textList = new ArrayList<>();
textList.add(new Text(original));
for (TextReplacement replacement : replacements) {
splitReplace(textList, replacement);
}
return textList;
}
private static void splitReplace(List<Text> textList, TextReplacement replacement) {
Optional<Text> textContainingReplacement = textList.stream().filter(it -> it.getText().contains(replacement.toReplace)).findFirst();
if (textContainingReplacement.isPresent()) {
int index = textList.indexOf(textContainingReplacement.get());
String original = textContainingReplacement.get().getText();
textList.remove(index);
String[] textParts = original.split(replacement.toReplace);
if (textParts.length == 2) {
if ("".equals(textParts[0])) {
textList.add(index, TooltipTextUtil.createText(replacement.replacement, replacement.textType));
textList.add(index + 1, TooltipTextUtil.createText(textParts[1], TooltipTextUtil.TextType.NORMAL));
} else {
textList.add(index, TooltipTextUtil.createText(textParts[0], TooltipTextUtil.TextType.NORMAL));
textList.add(index + 1, TooltipTextUtil.createText(replacement.replacement, replacement.textType));
textList.add(index + 2, TooltipTextUtil.createText(textParts[1], TooltipTextUtil.TextType.NORMAL));
}
} else if (textParts.length == 1) {
textList.add(index, TooltipTextUtil.createText(textParts[0], TooltipTextUtil.TextType.NORMAL));
textList.add(index + 1, TooltipTextUtil.createText(replacement.replacement, replacement.textType));
} else {
throw new IllegalStateException("It is not allowed that the toReplace string: '" + replacement.toReplace
+ "' exists multiple times in the original string");
}
} else {
throw new IllegalStateException("It is not allowed that the toReplace string: '" + replacement.toReplace
+ "' does not exist in the original string");
}
}
public static class TextReplacement {
private final String toReplace;
private final String replacement;
private final TooltipTextUtil.TextType textType;
public TextReplacement(String toReplace, String replacement, TooltipTextUtil.TextType textType) {
this.toReplace = toReplace;
this.replacement = replacement;
this.textType = textType;
}
}
public static String textToHtmlString(Text text) {
String textString = text.getText();
textString = textString.replace("\n", "<br>");
if (text.getStyleClass().toString().contains("tooltip-text-monospaced")) {
textString = String.format("<tt>%s</tt>", textString);
}
if (text.getStyleClass().toString().contains("tooltip-text-bold")) {
textString = String.format("<b>%s</b>", textString);
}
if (text.getStyleClass().toString().contains("tooltip-text-italic")) {
textString = String.format("<i>%s</i>", textString);
}
return textString;
}
}
| 6,827
| 40.13253
| 140
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/UiThreadList.java
|
package org.jabref.gui.util;
import java.util.concurrent.CountDownLatch;
import javafx.application.Platform;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.collections.transformation.TransformationList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class UiThreadList<T> extends TransformationList<T, T> {
private static final Logger LOGGER = LoggerFactory.getLogger(UiThreadList.class);
public UiThreadList(ObservableList<? extends T> source) {
super(source);
}
@Override
protected void sourceChanged(ListChangeListener.Change<? extends T> change) {
if (Platform.isFxApplicationThread()) {
fireChange(change);
} else {
CountDownLatch latch = new CountDownLatch(1);
Platform.runLater(() -> {
fireChange(change);
latch.countDown();
});
try {
latch.await();
} catch (InterruptedException e) {
LOGGER.error("Error while running on JavaFX thread", e);
}
}
}
@Override
public int getSourceIndex(int index) {
return index;
}
@Override
public int getViewIndex(int index) {
return index;
}
@Override
public T get(int index) {
return getSource().get(index);
}
@Override
public int size() {
return getSource().size();
}
}
| 1,473
| 23.983051
| 85
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/ValueTableCellFactory.java
|
package org.jabref.gui.util;
import java.util.function.BiFunction;
import java.util.function.Function;
import javafx.beans.binding.BooleanExpression;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.Tooltip;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.stage.Screen;
import javafx.util.Callback;
import org.jabref.model.strings.StringUtil;
/**
* Constructs a {@link TableCell} based on the value of the cell and a bunch of specified converter methods.
*
* @param <S> view model of table row
* @param <T> cell value
*/
public class ValueTableCellFactory<S, T> implements Callback<TableColumn<S, T>, TableCell<S, T>> {
private Function<T, String> toText;
private BiFunction<S, T, Node> toGraphic;
private BiFunction<S, T, EventHandler<? super MouseEvent>> toOnMouseClickedEvent;
private Function<T, BooleanExpression> toDisableExpression;
private Function<T, BooleanExpression> toVisibleExpression;
private BiFunction<S, T, String> toTooltip;
private Function<T, ContextMenu> contextMenuFactory;
private BiFunction<S, T, ContextMenu> menuFactory;
public ValueTableCellFactory<S, T> withText(Function<T, String> toText) {
this.toText = toText;
return this;
}
public ValueTableCellFactory<S, T> withGraphic(Function<T, Node> toGraphic) {
this.toGraphic = (rowItem, value) -> toGraphic.apply(value);
return this;
}
public ValueTableCellFactory<S, T> withGraphic(BiFunction<S, T, Node> toGraphic) {
this.toGraphic = toGraphic;
return this;
}
public ValueTableCellFactory<S, T> withTooltip(BiFunction<S, T, String> toTooltip) {
this.toTooltip = toTooltip;
return this;
}
public ValueTableCellFactory<S, T> withTooltip(Function<T, String> toTooltip) {
this.toTooltip = (rowItem, value) -> toTooltip.apply(value);
return this;
}
public ValueTableCellFactory<S, T> withOnMouseClickedEvent(BiFunction<S, T, EventHandler<? super MouseEvent>> toOnMouseClickedEvent) {
this.toOnMouseClickedEvent = toOnMouseClickedEvent;
return this;
}
public ValueTableCellFactory<S, T> withOnMouseClickedEvent(Function<T, EventHandler<? super MouseEvent>> toOnMouseClickedEvent) {
this.toOnMouseClickedEvent = (rowItem, value) -> toOnMouseClickedEvent.apply(value);
return this;
}
public ValueTableCellFactory<S, T> withDisableExpression(Function<T, BooleanExpression> toDisableBinding) {
this.toDisableExpression = toDisableBinding;
return this;
}
public ValueTableCellFactory<S, T> withVisibleExpression(Function<T, BooleanExpression> toVisibleBinding) {
this.toVisibleExpression = toVisibleBinding;
return this;
}
public ValueTableCellFactory<S, T> withContextMenu(Function<T, ContextMenu> contextMenuFactory) {
this.contextMenuFactory = contextMenuFactory;
return this;
}
public ValueTableCellFactory<S, T> withMenu(BiFunction<S, T, ContextMenu> menuFactory) {
this.menuFactory = menuFactory;
return this;
}
@Override
public TableCell<S, T> call(TableColumn<S, T> param) {
return new TableCell<>() {
@Override
protected void updateItem(T item, boolean empty) {
super.updateItem(item, empty);
if (empty || (item == null) || (getTableRow() == null) || (getTableRow().getItem() == null)) {
setText(null);
setGraphic(null);
setOnMouseClicked(null);
setTooltip(null);
} else {
S rowItem = getTableRow().getItem();
if (toText != null) {
setText(toText.apply(item));
}
if (toGraphic != null) {
setGraphic(toGraphic.apply(rowItem, item));
}
if (toTooltip != null) {
String tooltipText = toTooltip.apply(rowItem, item);
if (StringUtil.isNotBlank(tooltipText)) {
Screen currentScreen = Screen.getPrimary();
double maxWidth = currentScreen.getBounds().getWidth();
Tooltip tooltip = new Tooltip(tooltipText);
tooltip.setMaxWidth(maxWidth * 2 / 3);
tooltip.setWrapText(true);
setTooltip(tooltip);
}
}
if (contextMenuFactory != null) {
// We only create the context menu when really necessary
setOnContextMenuRequested(event -> {
if (!isEmpty()) {
setContextMenu(contextMenuFactory.apply(item));
getContextMenu().show(this, event.getScreenX(), event.getScreenY());
}
event.consume();
});
}
setOnMouseClicked(event -> {
if (toOnMouseClickedEvent != null) {
toOnMouseClickedEvent.apply(rowItem, item).handle(event);
}
if ((menuFactory != null) && !event.isConsumed()) {
if (event.getButton() == MouseButton.PRIMARY) {
ContextMenu menu = menuFactory.apply(rowItem, item);
if (menu != null) {
menu.show(this, event.getScreenX(), event.getScreenY());
event.consume();
}
}
}
});
if (toDisableExpression != null) {
disableProperty().bind(toDisableExpression.apply(item));
}
if (toVisibleExpression != null) {
visibleProperty().bind(toVisibleExpression.apply(item));
}
}
}
};
}
public void install(TableColumn<S, T> column) {
column.setCellFactory(this);
}
}
| 6,572
| 38.125
| 138
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/ViewModelListCellFactory.java
|
package org.jabref.gui.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import javafx.beans.value.ObservableValue;
import javafx.css.PseudoClass;
import javafx.scene.Node;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.Tooltip;
import javafx.scene.input.DragEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.util.Callback;
import org.jabref.gui.icon.JabRefIcon;
import org.jabref.model.strings.StringUtil;
import com.tobiasdiez.easybind.Subscription;
import de.saxsys.mvvmfx.utils.validation.ValidationStatus;
/**
* Constructs a {@link ListCell} based on the view model of the row and a bunch of specified converter methods.
*
* @param <T> cell value
*/
public class ViewModelListCellFactory<T> implements Callback<ListView<T>, ListCell<T>> {
private static final PseudoClass INVALID_PSEUDO_CLASS = PseudoClass.getPseudoClass("invalid");
private Callback<T, String> toText;
private Callback<T, Node> toGraphic;
private Callback<T, Tooltip> toTooltip;
private BiConsumer<T, ? super MouseEvent> toOnMouseClickedEvent;
private Callback<T, String> toStyleClass;
private Callback<T, ContextMenu> toContextMenu;
private BiConsumer<T, ? super MouseEvent> toOnDragDetected;
private BiConsumer<T, ? super DragEvent> toOnDragDropped;
private BiConsumer<T, ? super DragEvent> toOnDragEntered;
private BiConsumer<T, ? super DragEvent> toOnDragExited;
private BiConsumer<T, ? super DragEvent> toOnDragOver;
private final Map<PseudoClass, Callback<T, ObservableValue<Boolean>>> pseudoClasses = new HashMap<>();
private Callback<T, ValidationStatus> validationStatusProperty;
public ViewModelListCellFactory<T> withText(Callback<T, String> toText) {
this.toText = toText;
return this;
}
public ViewModelListCellFactory<T> withGraphic(Callback<T, Node> toGraphic) {
this.toGraphic = toGraphic;
return this;
}
public ViewModelListCellFactory<T> withIcon(Callback<T, JabRefIcon> toIcon) {
this.toGraphic = viewModel -> {
JabRefIcon icon = toIcon.call(viewModel);
if (icon != null) {
return icon.getGraphicNode();
}
return null;
};
return this;
}
public ViewModelListCellFactory<T> withIcon(Callback<T, JabRefIcon> toIcon, Callback<T, Color> toColor) {
this.toGraphic = viewModel -> toIcon.call(viewModel).withColor(toColor.call(viewModel)).getGraphicNode();
return this;
}
public ViewModelListCellFactory<T> withStringTooltip(Callback<T, String> toStringTooltip) {
this.toTooltip = viewModel -> {
String tooltipText = toStringTooltip.call(viewModel);
if (StringUtil.isNotBlank(tooltipText)) {
return new Tooltip(tooltipText);
}
return null;
};
return this;
}
public ViewModelListCellFactory<T> withTooltip(Callback<T, Tooltip> toTooltip) {
this.toTooltip = toTooltip;
return this;
}
public ViewModelListCellFactory<T> withContextMenu(Callback<T, ContextMenu> toContextMenu) {
this.toContextMenu = toContextMenu;
return this;
}
public ViewModelListCellFactory<T> withStyleClass(Callback<T, String> toStyleClass) {
this.toStyleClass = toStyleClass;
return this;
}
public ViewModelListCellFactory<T> withOnMouseClickedEvent(BiConsumer<T, ? super MouseEvent> toOnMouseClickedEvent) {
this.toOnMouseClickedEvent = toOnMouseClickedEvent;
return this;
}
public ViewModelListCellFactory<T> setOnDragDetected(BiConsumer<T, ? super MouseEvent> toOnDragDetected) {
this.toOnDragDetected = toOnDragDetected;
return this;
}
public ViewModelListCellFactory<T> setOnDragDropped(BiConsumer<T, ? super DragEvent> toOnDragDropped) {
this.toOnDragDropped = toOnDragDropped;
return this;
}
public ViewModelListCellFactory<T> setOnDragEntered(BiConsumer<T, ? super DragEvent> toOnDragEntered) {
this.toOnDragEntered = toOnDragEntered;
return this;
}
public ViewModelListCellFactory<T> setOnDragExited(BiConsumer<T, ? super DragEvent> toOnDragExited) {
this.toOnDragExited = toOnDragExited;
return this;
}
public ViewModelListCellFactory<T> setOnDragOver(BiConsumer<T, ? super DragEvent> toOnDragOver) {
this.toOnDragOver = toOnDragOver;
return this;
}
public ViewModelListCellFactory<T> withPseudoClass(PseudoClass pseudoClass, Callback<T, ObservableValue<Boolean>> toCondition) {
this.pseudoClasses.putIfAbsent(pseudoClass, toCondition);
return this;
}
public ViewModelListCellFactory<T> withValidation(Callback<T, ValidationStatus> validationStatusProperty) {
this.validationStatusProperty = validationStatusProperty;
return this;
}
public void install(ComboBox<T> comboBox) {
comboBox.setButtonCell(this.call(null));
comboBox.setCellFactory(this);
}
public void install(ListView<T> listView) {
listView.setCellFactory(this);
}
@Override
public ListCell<T> call(ListView<T> param) {
return new ListCell<>() {
final List<Subscription> subscriptions = new ArrayList<>();
@Override
protected void updateItem(T item, boolean empty) {
super.updateItem(item, empty);
// Remove previous subscriptions
subscriptions.forEach(Subscription::unsubscribe);
subscriptions.clear();
T viewModel = getItem();
if (empty || (viewModel == null)) {
setText(null);
setGraphic(null);
setOnMouseClicked(null);
setTooltip(null);
pseudoClassStateChanged(INVALID_PSEUDO_CLASS, false);
} else {
if (toText != null) {
setText(toText.call(viewModel));
}
if (toGraphic != null) {
setGraphic(toGraphic.call(viewModel));
}
if (toOnMouseClickedEvent != null) {
setOnMouseClicked(event -> toOnMouseClickedEvent.accept(viewModel, event));
}
if (toStyleClass != null) {
getStyleClass().setAll(toStyleClass.call(viewModel));
}
if (toTooltip != null) {
setTooltip(toTooltip.call(viewModel));
}
if (toContextMenu != null) {
setContextMenu(toContextMenu.call(viewModel));
}
if (toOnDragDetected != null) {
setOnDragDetected(event -> toOnDragDetected.accept(viewModel, event));
}
if (toOnDragDropped != null) {
setOnDragDropped(event -> toOnDragDropped.accept(viewModel, event));
}
if (toOnDragEntered != null) {
setOnDragEntered(event -> toOnDragEntered.accept(viewModel, event));
}
if (toOnDragExited != null) {
setOnDragExited(event -> toOnDragExited.accept(viewModel, event));
}
if (toOnDragOver != null) {
setOnDragOver(event -> toOnDragOver.accept(viewModel, event));
}
for (Map.Entry<PseudoClass, Callback<T, ObservableValue<Boolean>>> pseudoClassWithCondition : pseudoClasses.entrySet()) {
ObservableValue<Boolean> condition = pseudoClassWithCondition.getValue().call(viewModel);
subscriptions.add(BindingsHelper.includePseudoClassWhen(
this,
pseudoClassWithCondition.getKey(),
condition));
}
if (validationStatusProperty != null) {
validationStatusProperty.call(viewModel)
.getHighestMessage()
.ifPresent(message -> setTooltip(new Tooltip(message.getMessage())));
subscriptions.add(BindingsHelper.includePseudoClassWhen(
this,
INVALID_PSEUDO_CLASS,
validationStatusProperty.call(viewModel).validProperty().not()));
}
}
}
};
}
}
| 9,060
| 38.741228
| 141
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/ViewModelTableRowFactory.java
|
package org.jabref.gui.util;
import java.util.function.BiConsumer;
import java.util.function.Function;
import javafx.geometry.Bounds;
import javafx.geometry.Point2D;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.Tooltip;
import javafx.scene.control.TreeTableCell;
import javafx.scene.input.DragEvent;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseDragEvent;
import javafx.scene.input.MouseEvent;
import javafx.util.Callback;
import org.jabref.model.strings.StringUtil;
import org.reactfx.util.TriConsumer;
/**
* Constructs a {@link TreeTableCell} based on the view model of the row and a bunch of specified converter methods.
*
* @param <S> view model
*/
public class ViewModelTableRowFactory<S> implements Callback<TableView<S>, TableRow<S>> {
private BiConsumer<S, ? super MouseEvent> onMouseClickedEvent;
private Function<S, ContextMenu> contextMenuFactory;
private TriConsumer<TableRow<S>, S, ? super MouseEvent> toOnDragDetected;
private TriConsumer<TableRow<S>, S, ? super DragEvent> toOnDragDropped;
private BiConsumer<S, ? super DragEvent> toOnDragEntered;
private TriConsumer<TableRow<S>, S, ? super DragEvent> toOnDragExited;
private TriConsumer<TableRow<S>, S, ? super DragEvent> toOnDragOver;
private TriConsumer<TableRow<S>, S, ? super MouseDragEvent> toOnMouseDragEntered;
private Callback<S, String> toTooltip;
public ViewModelTableRowFactory<S> withOnMouseClickedEvent(BiConsumer<S, ? super MouseEvent> onMouseClickedEvent) {
this.onMouseClickedEvent = onMouseClickedEvent;
return this;
}
public ViewModelTableRowFactory<S> withContextMenu(Function<S, ContextMenu> contextMenuFactory) {
this.contextMenuFactory = contextMenuFactory;
return this;
}
public ViewModelTableRowFactory<S> setOnDragDetected(TriConsumer<TableRow<S>, S, ? super MouseEvent> toOnDragDetected) {
this.toOnDragDetected = toOnDragDetected;
return this;
}
public ViewModelTableRowFactory<S> setOnDragDetected(BiConsumer<S, ? super MouseEvent> toOnDragDetected) {
this.toOnDragDetected = (row, viewModel, event) -> toOnDragDetected.accept(viewModel, event);
return this;
}
public ViewModelTableRowFactory<S> setOnDragDropped(TriConsumer<TableRow<S>, S, ? super DragEvent> toOnDragDropped) {
this.toOnDragDropped = toOnDragDropped;
return this;
}
public ViewModelTableRowFactory<S> setOnDragDropped(BiConsumer<S, ? super DragEvent> toOnDragDropped) {
return setOnDragDropped((row, viewModel, event) -> toOnDragDropped.accept(viewModel, event));
}
public ViewModelTableRowFactory<S> setOnDragEntered(BiConsumer<S, ? super DragEvent> toOnDragEntered) {
this.toOnDragEntered = toOnDragEntered;
return this;
}
public ViewModelTableRowFactory<S> setOnMouseDragEntered(TriConsumer<TableRow<S>, S, ? super MouseDragEvent> toOnDragEntered) {
this.toOnMouseDragEntered = toOnDragEntered;
return this;
}
public ViewModelTableRowFactory<S> setOnMouseDragEntered(BiConsumer<S, ? super MouseDragEvent> toOnDragEntered) {
return setOnMouseDragEntered((row, viewModel, event) -> toOnDragEntered.accept(viewModel, event));
}
public ViewModelTableRowFactory<S> setOnDragExited(TriConsumer<TableRow<S>, S, ? super DragEvent> toOnDragExited) {
this.toOnDragExited = toOnDragExited;
return this;
}
public ViewModelTableRowFactory<S> setOnDragExited(BiConsumer<S, ? super DragEvent> toOnDragExited) {
return setOnDragExited((row, viewModel, event) -> toOnDragExited.accept(viewModel, event));
}
public ViewModelTableRowFactory<S> setOnDragOver(TriConsumer<TableRow<S>, S, ? super DragEvent> toOnDragOver) {
this.toOnDragOver = toOnDragOver;
return this;
}
public ViewModelTableRowFactory<S> setOnDragOver(BiConsumer<S, ? super DragEvent> toOnDragOver) {
return setOnDragOver((row, viewModel, event) -> toOnDragOver.accept(viewModel, event));
}
public ViewModelTableRowFactory<S> withTooltip(Callback<S, String> toTooltip) {
this.toTooltip = toTooltip;
return this;
}
@Override
public TableRow<S> call(TableView<S> tableView) {
TableRow<S> row = new TableRow<>();
if (toTooltip != null) {
String tooltipText = toTooltip.call(row.getItem());
if (StringUtil.isNotBlank(tooltipText)) {
row.setTooltip(new Tooltip(tooltipText));
}
}
if (onMouseClickedEvent != null) {
row.setOnMouseClicked(event -> {
if (!row.isEmpty()) {
onMouseClickedEvent.accept(row.getItem(), event);
}
});
}
if (contextMenuFactory != null) {
// We only create the context menu when really necessary
row.setOnContextMenuRequested(event -> {
if (!row.isEmpty()) {
row.setContextMenu(contextMenuFactory.apply(row.getItem()));
row.getContextMenu().show(row, event.getScreenX(), event.getScreenY());
}
event.consume();
});
// Activate context menu if user presses the "context menu" key
tableView.addEventHandler(KeyEvent.KEY_RELEASED, event -> {
boolean rowFocused = !row.isEmpty() && tableView.getFocusModel().getFocusedIndex() == row.getIndex();
if (event.getCode() == KeyCode.CONTEXT_MENU && rowFocused) {
// Get center of focused cell
Bounds anchorBounds = row.getBoundsInParent();
double x = anchorBounds.getMinX() + anchorBounds.getWidth() / 2;
double y = anchorBounds.getMinY() + anchorBounds.getHeight() / 2;
Point2D screenPosition = row.getParent().localToScreen(x, y);
if (row.getContextMenu() == null) {
row.setContextMenu(contextMenuFactory.apply(row.getItem()));
}
row.getContextMenu().show(row, screenPosition.getX(), screenPosition.getY());
}
});
}
if (toOnDragDetected != null) {
row.setOnDragDetected(event -> {
if (!row.isEmpty()) {
toOnDragDetected.accept(row, row.getItem(), event);
}
});
}
if (toOnDragDropped != null) {
row.setOnDragDropped(event -> {
if (!row.isEmpty()) {
toOnDragDropped.accept(row, row.getItem(), event);
}
});
}
if (toOnDragEntered != null) {
row.setOnDragEntered(event -> {
if (!row.isEmpty()) {
toOnDragEntered.accept(row.getItem(), event);
}
});
}
if (toOnDragExited != null) {
row.setOnDragExited(event -> {
if (!row.isEmpty()) {
toOnDragExited.accept(row, row.getItem(), event);
}
});
}
if (toOnDragOver != null) {
row.setOnDragOver(event -> {
if (!row.isEmpty()) {
toOnDragOver.accept(row, row.getItem(), event);
}
});
}
if (toOnMouseDragEntered != null) {
row.setOnMouseDragEntered(event -> {
if (!row.isEmpty()) {
toOnMouseDragEntered.accept(row, row.getItem(), event);
}
});
}
return row;
}
public void install(TableView<S> table) {
table.setRowFactory(this);
}
}
| 7,936
| 37.906863
| 131
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/ViewModelTextFieldTableCellVisualizationFactory.java
|
package org.jabref.gui.util;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import javafx.application.Platform;
import javafx.css.PseudoClass;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.layout.HBox;
import javafx.util.Callback;
import javafx.util.StringConverter;
import com.tobiasdiez.easybind.Subscription;
import de.saxsys.mvvmfx.utils.validation.ValidationStatus;
public class ViewModelTextFieldTableCellVisualizationFactory<S, T> implements Callback<TableColumn<S, T>, TableCell<S, T>> {
private static final PseudoClass INVALID_PSEUDO_CLASS = PseudoClass.getPseudoClass("invalid");
private Function<S, ValidationStatus> validationStatusProperty;
private StringConverter<T> stringConverter;
public ViewModelTextFieldTableCellVisualizationFactory<S, T> withValidation(Function<S, ValidationStatus> validationStatusProperty) {
this.validationStatusProperty = validationStatusProperty;
return this;
}
public void install(TableColumn<S, T> column, StringConverter<T> stringConverter) {
column.setCellFactory(this);
this.stringConverter = stringConverter;
}
@Override
public TextFieldTableCell<S, T> call(TableColumn<S, T> param) {
return new TextFieldTableCell<>(stringConverter) {
final List<Subscription> subscriptions = new ArrayList<>();
@Override
public void startEdit() {
super.startEdit();
// The textfield is lazily created and not already present when a TableCell is created.
lookupTextField().ifPresent(textField -> Platform.runLater(() -> {
textField.requestFocus();
textField.selectAll();
}));
}
/**
* As 'textfield' is a private member of TextFieldTableCell we need need to get to it through the backdoor.
*
* @return The TextField containing the editable content of the TableCell
*/
private Optional<TextField> lookupTextField() {
if (getGraphic() instanceof TextField) {
return Optional.of((TextField) getGraphic());
} else {
// Could be an HBox with some graphic and a TextField if a graphic is specified for the TableCell
if (getGraphic() instanceof HBox) {
HBox hbox = (HBox) getGraphic();
if ((hbox.getChildren().size() > 1) && hbox.getChildren().get(1) instanceof TextField) {
return Optional.of((TextField) hbox.getChildren().get(1));
}
}
return Optional.empty();
}
}
@Override
public void updateItem(T item, boolean empty) {
super.updateItem(item, empty);
subscriptions.forEach(Subscription::unsubscribe);
subscriptions.clear();
if (empty || getTableRow() == null || getTableRow().getItem() == null) {
setText(null);
setGraphic(null);
setOnMouseClicked(null);
setTooltip(null);
pseudoClassStateChanged(INVALID_PSEUDO_CLASS, false);
} else {
S viewModel = getTableRow().getItem();
if (validationStatusProperty != null) {
validationStatusProperty.apply(viewModel)
.getHighestMessage()
.ifPresent(message -> setTooltip(new Tooltip(message.getMessage())));
subscriptions.add(BindingsHelper.includePseudoClassWhen(
this,
INVALID_PSEUDO_CLASS,
validationStatusProperty.apply(viewModel).validProperty().not()));
}
}
}
};
}
}
| 4,318
| 40.133333
| 137
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/ViewModelTreeCellFactory.java
|
package org.jabref.gui.util;
import javafx.beans.value.ObservableValue;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.CheckBoxTreeItem;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeTableCell;
import javafx.scene.control.TreeView;
import javafx.scene.control.cell.CheckBoxTreeCell;
import javafx.scene.input.MouseEvent;
import javafx.util.Callback;
import javafx.util.StringConverter;
import org.jabref.gui.icon.JabRefIcon;
/**
* Constructs a {@link TreeTableCell} based on the view model of the row and a bunch of specified converter methods.
*
* @param <T> cell value
*/
public class ViewModelTreeCellFactory<T> implements Callback<TreeView<T>, TreeCell<T>> {
private Callback<T, String> toText;
private Callback<T, Node> toGraphic;
private Callback<T, EventHandler<? super MouseEvent>> toOnMouseClickedEvent;
private Callback<T, String> toTooltip;
public ViewModelTreeCellFactory<T> withText(Callback<T, String> toText) {
this.toText = toText;
return this;
}
public ViewModelTreeCellFactory<T> withGraphic(Callback<T, Node> toGraphic) {
this.toGraphic = toGraphic;
return this;
}
public ViewModelTreeCellFactory<T> withIcon(Callback<T, JabRefIcon> toIcon) {
this.toGraphic = viewModel -> toIcon.call(viewModel).getGraphicNode();
return this;
}
public ViewModelTreeCellFactory<T> withTooltip(Callback<T, String> toTooltip) {
this.toTooltip = toTooltip;
return this;
}
public ViewModelTreeCellFactory<T> withOnMouseClickedEvent(Callback<T, EventHandler<? super MouseEvent>> toOnMouseClickedEvent) {
this.toOnMouseClickedEvent = toOnMouseClickedEvent;
return this;
}
public void install(TreeView<T> treeView) {
treeView.setCellFactory(this);
}
@Override
public TreeCell<T> call(TreeView<T> tree) {
Callback<TreeItem<T>, ObservableValue<Boolean>> getSelectedProperty =
item -> {
if (item instanceof CheckBoxTreeItem<?>) {
return ((CheckBoxTreeItem<?>) item).selectedProperty();
}
return null;
};
StringConverter<TreeItem<T>> converter = new StringConverter<TreeItem<T>>() {
@Override
public String toString(TreeItem<T> treeItem) {
return (treeItem == null || treeItem.getValue() == null || toText == null) ?
"" : toText.call(treeItem.getValue());
}
@Override
public TreeItem<T> fromString(String string) {
throw new UnsupportedOperationException("Not supported.");
}
};
return new CheckBoxTreeCell<>(getSelectedProperty, converter);
}
}
| 2,897
| 33.5
| 133
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/ViewModelTreeTableCellFactory.java
|
package org.jabref.gui.util;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.Tooltip;
import javafx.scene.control.TreeTableCell;
import javafx.scene.control.TreeTableColumn;
import javafx.scene.input.MouseEvent;
import javafx.util.Callback;
import org.jabref.gui.icon.JabRefIcon;
import org.jabref.model.strings.StringUtil;
/**
* Constructs a {@link TreeTableCell} based on the view model of the row and a bunch of specified converter methods.
*
* @param <S> view model
*/
public class ViewModelTreeTableCellFactory<S> implements Callback<TreeTableColumn<S, S>, TreeTableCell<S, S>> {
private Callback<S, String> toText;
private Callback<S, Node> toGraphic;
private Callback<S, EventHandler<? super MouseEvent>> toOnMouseClickedEvent;
private Callback<S, String> toTooltip;
public ViewModelTreeTableCellFactory<S> withText(Callback<S, String> toText) {
this.toText = toText;
return this;
}
public ViewModelTreeTableCellFactory<S> withGraphic(Callback<S, Node> toGraphic) {
this.toGraphic = toGraphic;
return this;
}
public ViewModelTreeTableCellFactory<S> withIcon(Callback<S, JabRefIcon> toIcon) {
this.toGraphic = viewModel -> toIcon.call(viewModel).getGraphicNode();
return this;
}
public ViewModelTreeTableCellFactory<S> withTooltip(Callback<S, String> toTooltip) {
this.toTooltip = toTooltip;
return this;
}
public ViewModelTreeTableCellFactory<S> withOnMouseClickedEvent(
Callback<S, EventHandler<? super MouseEvent>> toOnMouseClickedEvent) {
this.toOnMouseClickedEvent = toOnMouseClickedEvent;
return this;
}
@Override
public TreeTableCell<S, S> call(TreeTableColumn<S, S> param) {
return new TreeTableCell<S, S>() {
@Override
protected void updateItem(S viewModel, boolean empty) {
super.updateItem(viewModel, empty);
if (empty || viewModel == null) {
setText(null);
setGraphic(null);
setOnMouseClicked(null);
} else {
if (toText != null) {
setText(toText.call(viewModel));
}
if (toGraphic != null) {
setGraphic(toGraphic.call(viewModel));
}
if (toTooltip != null) {
String tooltip = toTooltip.call(viewModel);
if (StringUtil.isNotBlank(tooltip)) {
setTooltip(new Tooltip(tooltip));
}
}
if (toOnMouseClickedEvent != null) {
setOnMouseClicked(toOnMouseClickedEvent.call(viewModel));
}
}
}
};
}
public void install(TreeTableColumn<S, S> column) {
column.setCellValueFactory(cellData -> cellData.getValue().valueProperty());
column.setCellFactory(this);
}
}
| 3,111
| 33.966292
| 116
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/ViewModelTreeTableRowFactory.java
|
package org.jabref.gui.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import javafx.beans.value.ObservableValue;
import javafx.css.PseudoClass;
import javafx.geometry.Bounds;
import javafx.geometry.Point2D;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.TreeTableRow;
import javafx.scene.control.TreeTableView;
import javafx.scene.input.DragEvent;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseDragEvent;
import javafx.scene.input.MouseEvent;
import javafx.util.Callback;
import com.tobiasdiez.easybind.Subscription;
import org.reactfx.util.TriConsumer;
public class ViewModelTreeTableRowFactory<S> implements Callback<TreeTableView<S>, TreeTableRow<S>> {
private BiConsumer<S, ? super MouseEvent> onMouseClickedEvent;
private BiConsumer<S, ? super MouseEvent> onMousePressedEvent;
private Consumer<TreeTableRow<S>> toCustomInitializer;
private Function<S, ContextMenu> contextMenuFactory;
private TriConsumer<TreeTableRow<S>, S, ? super MouseEvent> toOnDragDetected;
private TriConsumer<TreeTableRow<S>, S, ? super DragEvent> toOnDragDropped;
private BiConsumer<S, ? super DragEvent> toOnDragEntered;
private TriConsumer<TreeTableRow<S>, S, ? super DragEvent> toOnDragExited;
private TriConsumer<TreeTableRow<S>, S, ? super DragEvent> toOnDragOver;
private TriConsumer<TreeTableRow<S>, S, ? super MouseDragEvent> toOnMouseDragEntered;
private final Map<PseudoClass, Callback<TreeTableRow<S>, ObservableValue<Boolean>>> pseudoClasses = new HashMap<>();
public ViewModelTreeTableRowFactory<S> withOnMouseClickedEvent(BiConsumer<S, ? super MouseEvent> event) {
this.onMouseClickedEvent = event;
return this;
}
public ViewModelTreeTableRowFactory<S> withOnMousePressedEvent(BiConsumer<S, ? super MouseEvent> event) {
this.onMousePressedEvent = event;
return this;
}
public ViewModelTreeTableRowFactory<S> withCustomInitializer(Consumer<TreeTableRow<S>> customInitializer) {
this.toCustomInitializer = customInitializer;
return this;
}
public ViewModelTreeTableRowFactory<S> withContextMenu(Function<S, ContextMenu> contextMenuFactory) {
this.contextMenuFactory = contextMenuFactory;
return this;
}
public ViewModelTreeTableRowFactory<S> setOnDragDetected(TriConsumer<TreeTableRow<S>, S, ? super MouseEvent> toOnDragDetected) {
this.toOnDragDetected = toOnDragDetected;
return this;
}
public ViewModelTreeTableRowFactory<S> setOnDragDetected(BiConsumer<S, ? super MouseEvent> toOnDragDetected) {
this.toOnDragDetected = (row, viewModel, event) -> toOnDragDetected.accept(viewModel, event);
return this;
}
public ViewModelTreeTableRowFactory<S> setOnDragDropped(TriConsumer<TreeTableRow<S>, S, ? super DragEvent> toOnDragDropped) {
this.toOnDragDropped = toOnDragDropped;
return this;
}
public ViewModelTreeTableRowFactory<S> setOnDragDropped(BiConsumer<S, ? super DragEvent> toOnDragDropped) {
return setOnDragDropped((row, viewModel, event) -> toOnDragDropped.accept(viewModel, event));
}
public ViewModelTreeTableRowFactory<S> setOnDragEntered(BiConsumer<S, ? super DragEvent> toOnDragEntered) {
this.toOnDragEntered = toOnDragEntered;
return this;
}
public ViewModelTreeTableRowFactory<S> setOnMouseDragEntered(TriConsumer<TreeTableRow<S>, S, ? super MouseDragEvent> toOnDragEntered) {
this.toOnMouseDragEntered = toOnDragEntered;
return this;
}
public ViewModelTreeTableRowFactory<S> setOnMouseDragEntered(BiConsumer<S, ? super MouseDragEvent> toOnDragEntered) {
return setOnMouseDragEntered((row, viewModel, event) -> toOnDragEntered.accept(viewModel, event));
}
public ViewModelTreeTableRowFactory<S> setOnDragExited(TriConsumer<TreeTableRow<S>, S, ? super DragEvent> toOnDragExited) {
this.toOnDragExited = toOnDragExited;
return this;
}
public ViewModelTreeTableRowFactory<S> setOnDragExited(BiConsumer<S, ? super DragEvent> toOnDragExited) {
return setOnDragExited((row, viewModel, event) -> toOnDragExited.accept(viewModel, event));
}
public ViewModelTreeTableRowFactory<S> setOnDragOver(TriConsumer<TreeTableRow<S>, S, ? super DragEvent> toOnDragOver) {
this.toOnDragOver = toOnDragOver;
return this;
}
public ViewModelTreeTableRowFactory<S> setOnDragOver(BiConsumer<S, ? super DragEvent> toOnDragOver) {
return setOnDragOver((row, viewModel, event) -> toOnDragOver.accept(viewModel, event));
}
public ViewModelTreeTableRowFactory<S> withPseudoClass(PseudoClass pseudoClass, Callback<TreeTableRow<S>, ObservableValue<Boolean>> toCondition) {
this.pseudoClasses.putIfAbsent(pseudoClass, toCondition);
return this;
}
public void install(TreeTableView<S> table) {
table.setRowFactory(this);
}
@Override
public TreeTableRow<S> call(TreeTableView<S> treeTableView) {
return new TreeTableRow<>() {
final List<Subscription> subscriptions = new ArrayList<>();
@Override
protected void updateItem(S row, boolean empty) {
super.updateItem(row, empty);
// Remove previous subscriptions
subscriptions.forEach(Subscription::unsubscribe);
subscriptions.clear();
if (contextMenuFactory != null) {
// We only create the context menu when really necessary
setOnContextMenuRequested(event -> {
if (!isEmpty()) {
setContextMenu(contextMenuFactory.apply(row));
getContextMenu().show(this, event.getScreenX(), event.getScreenY());
}
event.consume();
});
// Activate context menu if user presses the "context menu" key
treeTableView.addEventHandler(KeyEvent.KEY_RELEASED, event -> {
boolean rowFocused = isEmpty() && treeTableView.getFocusModel().getFocusedIndex() == getIndex();
if (event.getCode() == KeyCode.CONTEXT_MENU && rowFocused) {
// Get center of focused cell
Bounds anchorBounds = getBoundsInParent();
double x = anchorBounds.getMinX() + anchorBounds.getWidth() / 2;
double y = anchorBounds.getMinY() + anchorBounds.getHeight() / 2;
Point2D screenPosition = getParent().localToScreen(x, y);
if (getContextMenu() == null) {
setContextMenu(contextMenuFactory.apply(getItem()));
}
getContextMenu().show(this, screenPosition.getX(), screenPosition.getY());
}
});
}
if (!empty && (row != null)) {
if (onMouseClickedEvent != null) {
setOnMouseClicked(event -> onMouseClickedEvent.accept(getItem(), event));
}
if (onMousePressedEvent != null) {
setOnMousePressed(event -> onMousePressedEvent.accept(getItem(), event));
}
if (toCustomInitializer != null) {
toCustomInitializer.accept(this);
}
if (toOnDragDetected != null) {
setOnDragDetected(event -> toOnDragDetected.accept(this, getItem(), event));
}
if (toOnDragDropped != null) {
setOnDragDropped(event -> toOnDragDropped.accept(this, getItem(), event));
}
if (toOnDragEntered != null) {
setOnDragEntered(event -> toOnDragEntered.accept(getItem(), event));
}
if (toOnDragExited != null) {
setOnDragExited(event -> toOnDragExited.accept(this, getItem(), event));
}
if (toOnDragOver != null) {
setOnDragOver(event -> toOnDragOver.accept(this, getItem(), event));
}
if (toOnMouseDragEntered != null) {
setOnMouseDragEntered(event -> toOnMouseDragEntered.accept(this, getItem(), event));
}
for (Map.Entry<PseudoClass, Callback<TreeTableRow<S>, ObservableValue<Boolean>>> pseudoClassWithCondition : pseudoClasses.entrySet()) {
ObservableValue<Boolean> condition = pseudoClassWithCondition.getValue().call(this);
subscriptions.add(BindingsHelper.includePseudoClassWhen(
this,
pseudoClassWithCondition.getKey(),
condition));
}
}
}
};
}
}
| 9,406
| 44.444444
| 155
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/ZipFileChooser.java
|
package org.jabref.gui.util;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.stream.Collectors;
import javafx.beans.property.ReadOnlyLongWrapper;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.ButtonType;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import org.jabref.logic.l10n.Localization;
/**
* Dialog to allow users to choose a file contained in a ZIP file.
*/
public class ZipFileChooser extends BaseDialog<Path> {
/**
* New ZIP file chooser.
*
* @param zipFile ZIP-Fle to choose from, must be readable
*/
public ZipFileChooser(FileSystem zipFile) throws IOException {
setTitle(Localization.lang("Select file from ZIP-archive"));
TableView<Path> table = new TableView<>(getSelectableZipEntries(zipFile));
TableColumn<Path, String> nameColumn = new TableColumn<>(Localization.lang("Name"));
TableColumn<Path, String> modifiedColumn = new TableColumn<>(Localization.lang("Last modified"));
TableColumn<Path, Number> sizeColumn = new TableColumn<>(Localization.lang("Size"));
table.getColumns().add(nameColumn);
table.getColumns().add(modifiedColumn);
table.getColumns().add(sizeColumn);
nameColumn.setCellValueFactory(data -> new ReadOnlyStringWrapper(data.getValue().toString()));
modifiedColumn.setCellValueFactory(data -> {
try {
return new ReadOnlyStringWrapper(
ZonedDateTime.ofInstant(Files.getLastModifiedTime(data.getValue()).toInstant(),
ZoneId.systemDefault())
.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)));
} catch (IOException e) {
// Ignore
return new ReadOnlyStringWrapper("");
}
});
sizeColumn.setCellValueFactory(data -> {
try {
return new ReadOnlyLongWrapper(Files.size(data.getValue()));
} catch (IOException e) {
// Ignore
return new ReadOnlyLongWrapper(0);
}
});
table.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
getDialogPane().setContent(table);
getDialogPane().getButtonTypes().setAll(
ButtonType.OK,
ButtonType.CANCEL
);
setResultConverter(button -> {
if (button == ButtonType.OK) {
return table.getSelectionModel().getSelectedItem();
} else {
return null;
}
});
}
/**
* Entries that can be selected with this dialog.
*
* @param zipFile ZIP-File
* @return entries that can be selected
*/
private static ObservableList<Path> getSelectableZipEntries(FileSystem zipFile) throws IOException {
Path rootDir = zipFile.getRootDirectories().iterator().next();
return FXCollections.observableArrayList(
Files.walk(rootDir)
.filter(file -> file.endsWith(".class"))
.collect(Collectors.toList()));
}
}
| 3,542
| 35.525773
| 105
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/comparator/NumericFieldComparator.java
|
package org.jabref.gui.util.comparator;
import java.util.Comparator;
import org.jabref.model.strings.StringUtil;
/**
* Comparator for numeric cases. The purpose of this class is to add the numeric comparison, because values are sorted
* as if they were strings.
*/
public class NumericFieldComparator implements Comparator<String> {
@Override
public int compare(String val1, String val2) {
Integer valInt1 = parseInt(val1);
Integer valInt2 = parseInt(val2);
if (valInt1 == null && valInt2 == null) {
if (val1 != null && val2 != null) {
return val1.compareTo(val2);
} else {
return 0;
}
} else if (valInt1 == null) {
// We assume that "null" is "less than" any other value.
return -1;
} else if (valInt2 == null) {
return 1;
}
// If we arrive at this stage then both values are actually numeric !
return valInt1 - valInt2;
}
private static Integer parseInt(String number) {
if (!isNumber(number)) {
return null;
}
try {
return Integer.valueOf(number.trim());
} catch (NumberFormatException ignore) {
return null;
}
}
private static boolean isNumber(String number) {
if (StringUtil.isNullOrEmpty(number)) {
return false;
}
if (number.length() == 1 && (number.charAt(0) == '-' || number.charAt(0) == '+')) {
return false;
}
for (int i = 0; i < number.length(); i++) {
char c = number.charAt(i);
if (i == 0 && (c == '-' || c == '+')) {
continue;
} else if (!Character.isDigit(c)) {
return false;
}
}
return true;
}
}
| 1,858
| 27.166667
| 118
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/comparator/RankingFieldComparator.java
|
package org.jabref.gui.util.comparator;
import java.util.Comparator;
import java.util.Optional;
import org.jabref.gui.specialfields.SpecialFieldValueViewModel;
/**
* Comparator for rankings.
* <p>
* Inverse comparison of ranking as rank5 is higher than rank1
*/
public class RankingFieldComparator implements Comparator<Optional<SpecialFieldValueViewModel>> {
@Override
public int compare(Optional<SpecialFieldValueViewModel> val1, Optional<SpecialFieldValueViewModel> val2) {
if (val1.isPresent()) {
if (val2.isPresent()) {
int compareToRes = val1.get().getValue().compareTo(val2.get().getValue());
if (compareToRes == 0) {
return 0;
} else {
return compareToRes * -1;
}
} else {
return -1;
}
} else {
if (val2.isPresent()) {
return 1;
} else {
return 0;
}
}
}
}
| 1,032
| 26.918919
| 110
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/comparator/SpecialFieldComparator.java
|
package org.jabref.gui.util.comparator;
import java.util.Comparator;
import java.util.Optional;
import org.jabref.gui.specialfields.SpecialFieldValueViewModel;
public class SpecialFieldComparator implements Comparator<Optional<SpecialFieldValueViewModel>> {
@Override
public int compare(Optional<SpecialFieldValueViewModel> val1, Optional<SpecialFieldValueViewModel> val2) {
if (val1.isPresent()) {
if (val2.isPresent()) {
return val1.get().getValue().compareTo(val2.get().getValue());
} else {
return -1;
}
} else {
if (val2.isPresent()) {
return 1;
} else {
return 0;
}
}
}
}
| 754
| 26.962963
| 110
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/component/TemporalAccessorPicker.java
|
package org.jabref.gui.util.component;
import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Year;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalQueries;
import java.util.Objects;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.DatePicker;
import javafx.util.StringConverter;
import org.jabref.gui.Globals;
import org.jabref.gui.fieldeditors.TextInputControlBehavior;
import org.jabref.gui.fieldeditors.contextmenu.EditorContextAction;
import org.jabref.gui.util.BindingsHelper;
import org.jabref.model.entry.Date;
import org.jabref.model.strings.StringUtil;
/**
* A date picker with configurable datetime format where both date and time can be changed via the text field and the
* date can additionally be changed via the JavaFX default date picker. Also supports incomplete dates.
*
* First recall how the date picker normally works: - The user selects a date in the popup, which sets {@link
* #valueProperty()} to the selected date. - The converter ({@link #converterProperty()}) is used to transform the date
* to a string representation and display it in the text field.
*
* The idea is now to intercept the process and add an additional step: - The user selects a date in the popup, which
* sets {@link #valueProperty()} to the selected date. - The date is converted to a {@link TemporalAccessor} (i.e,
* enriched by a time component) using {@link #addCurrentTime(LocalDate)} - The string converter ({@link
* #stringConverterProperty()}) is used to transform the temporal accessor to a string representation and display it in
* the text field.
*
* Inspiration taken from https://github.com/edvin/tornadofx-controls/blob/master/src/main/java/tornadofx/control/DateTimePicker.java
*/
public class TemporalAccessorPicker extends DatePicker {
private final ObjectProperty<TemporalAccessor> temporalAccessorValue = new SimpleObjectProperty<>(null);
private final DateTimeFormatter defaultFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
private final ObjectProperty<StringConverter<TemporalAccessor>> converter = new SimpleObjectProperty<>(null);
public TemporalAccessorPicker() {
setConverter(new InternalConverter());
// Synchronize changes of the underlying date value with the temporalAccessorValue
BindingsHelper.bindBidirectional(valueProperty(), temporalAccessorValue,
TemporalAccessorPicker::addCurrentTime,
TemporalAccessorPicker::getDate);
getEditor().setOnContextMenuRequested(event -> {
ContextMenu contextMenu = new ContextMenu();
contextMenu.getItems().setAll(EditorContextAction.getDefaultContextMenuItems(getEditor(), Globals.getKeyPrefs()));
TextInputControlBehavior.showContextMenu(getEditor(), contextMenu, event);
});
}
private static TemporalAccessor addCurrentTime(LocalDate date) {
if (date == null) {
return null;
}
return LocalDateTime.of(date, LocalTime.now());
}
private static LocalDate getDate(TemporalAccessor temporalAccessor) {
if (temporalAccessor == null) {
return null;
}
return getLocalDate(temporalAccessor);
}
private static LocalDate getLocalDate(TemporalAccessor dateTime) {
// Return null when dateTime is null pointer
if (dateTime == null) {
return null;
}
// Try to get as much information from the temporal accessor
LocalDate date = dateTime.query(TemporalQueries.localDate());
if (date != null) {
return date;
}
try {
return YearMonth.from(dateTime).atDay(1);
} catch (DateTimeException exception) {
return Year.from(dateTime).atDay(1);
}
}
public final ObjectProperty<StringConverter<TemporalAccessor>> stringConverterProperty() {
return converter;
}
public final StringConverter<TemporalAccessor> getStringConverter() {
StringConverter<TemporalAccessor> newConverter = new StringConverter<>() {
@Override
public String toString(TemporalAccessor value) {
return defaultFormatter.format(value);
}
@Override
public TemporalAccessor fromString(String value) {
if (StringUtil.isNotBlank(value)) {
try {
return defaultFormatter.parse(value);
} catch (DateTimeParseException exception) {
return Date.parse(value).map(Date::toTemporalAccessor).orElse(null);
}
} else {
return null;
}
}
};
return Objects.requireNonNullElseGet(stringConverterProperty().get(), () -> newConverter);
}
public final void setStringConverter(StringConverter<TemporalAccessor> value) {
stringConverterProperty().set(value);
}
public TemporalAccessor getTemporalAccessorValue() {
return temporalAccessorValue.get();
}
public void setTemporalAccessorValue(TemporalAccessor temporalAccessorValue) {
this.temporalAccessorValue.set(temporalAccessorValue);
}
public ObjectProperty<TemporalAccessor> temporalAccessorValueProperty() {
return temporalAccessorValue;
}
private class InternalConverter extends StringConverter<LocalDate> {
@Override
public String toString(LocalDate object) {
TemporalAccessor value = getTemporalAccessorValue();
// Keeps the original text when it is an invalid date
return (value != null) ? getStringConverter().toString(value) : getEditor().getText();
}
@Override
public LocalDate fromString(String value) {
if ((value == null) || value.isEmpty()) {
temporalAccessorValue.set(null);
return null;
}
TemporalAccessor dateTime = getStringConverter().fromString(value);
temporalAccessorValue.set(dateTime);
return getLocalDate(dateTime);
}
}
}
| 6,499
| 38.393939
| 133
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/uithreadaware/UiThreadBinding.java
|
package org.jabref.gui.util.uithreadaware;
import javafx.beans.InvalidationListener;
import javafx.beans.binding.Binding;
import javafx.beans.value.ChangeListener;
import javafx.collections.ObservableList;
/**
* This class can be used to wrap a {@link Binding} inside it. When wrapped, any Listener listening for updates to the wrapped {@link Binding} (for example because of a binding to it) is ensured to be notified on the JavaFX Application Thread. It should be used to implement bindings where updates come in from a background thread but should be reflected in the UI where it is necessary that changes to the UI are performed on the JavaFX Application thread.
*/
public class UiThreadBinding<T> implements Binding<T> {
private final Binding<T> delegate;
public UiThreadBinding(Binding<T> delegate) {
this.delegate = delegate;
}
@Override
public void addListener(InvalidationListener listener) {
delegate.addListener(new UiThreadInvalidationListener(listener));
}
@Override
public void removeListener(InvalidationListener listener) {
delegate.removeListener(listener);
}
@Override
public void addListener(ChangeListener<? super T> listener) {
delegate.addListener(new UiThreadChangeListener<>(listener));
}
@Override
public void removeListener(ChangeListener<? super T> listener) {
delegate.removeListener(listener);
}
@Override
public T getValue() {
return delegate.getValue();
}
@Override
public boolean isValid() {
return delegate.isValid();
}
@Override
public void invalidate() {
delegate.invalidate();
}
@Override
public ObservableList<?> getDependencies() {
return delegate.getDependencies();
}
@Override
public void dispose() {
delegate.dispose();
}
}
| 1,880
| 28.390625
| 457
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/uithreadaware/UiThreadChangeListener.java
|
package org.jabref.gui.util.uithreadaware;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
class UiThreadChangeListener<T> implements ChangeListener<T> {
private ChangeListener<T> delegate;
public UiThreadChangeListener(ChangeListener<T> delegate) {
this.delegate = delegate;
}
@Override
public void changed(ObservableValue<? extends T> observable, T oldValue, T newValue) {
UiThreadHelper.ensureUiThreadExecution(() -> delegate.changed(observable, oldValue, newValue));
}
@Override
public boolean equals(Object o) {
return delegate.equals(o);
}
@Override
public int hashCode() {
return delegate.hashCode();
}
}
| 736
| 24.413793
| 103
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/uithreadaware/UiThreadHelper.java
|
package org.jabref.gui.util.uithreadaware;
import javafx.application.Platform;
class UiThreadHelper {
static void ensureUiThreadExecution(Runnable task) {
if (Platform.isFxApplicationThread()) {
task.run();
} else {
Platform.runLater(task);
}
}
}
| 306
| 19.466667
| 56
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/uithreadaware/UiThreadInvalidationListener.java
|
package org.jabref.gui.util.uithreadaware;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
class UiThreadInvalidationListener implements InvalidationListener {
private final InvalidationListener delegate;
public UiThreadInvalidationListener(InvalidationListener delegate) {
this.delegate = delegate;
}
@Override
public void invalidated(Observable observable) {
UiThreadHelper.ensureUiThreadExecution(() -> delegate.invalidated(observable));
}
@Override
public boolean equals(Object o) {
return delegate.equals(o);
}
@Override
public int hashCode() {
return delegate.hashCode();
}
}
| 695
| 23
| 87
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/uithreadaware/UiThreadListChangeListener.java
|
package org.jabref.gui.util.uithreadaware;
import javafx.collections.ListChangeListener;
class UiThreadListChangeListener<E> implements ListChangeListener<E> {
private final ListChangeListener<E> delegate;
public UiThreadListChangeListener(ListChangeListener<E> delegate) {
this.delegate = delegate;
}
@Override
public void onChanged(Change<? extends E> c) {
UiThreadHelper.ensureUiThreadExecution(() -> delegate.onChanged(c));
}
@Override
public boolean equals(Object o) {
return delegate.equals(o);
}
@Override
public int hashCode() {
return delegate.hashCode();
}
}
| 656
| 22.464286
| 76
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/uithreadaware/UiThreadObservableList.java
|
package org.jabref.gui.util.uithreadaware;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import javafx.beans.InvalidationListener;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
/**
* This class can be used to wrap an @see ObservableList inside it. When wrapped, any Listener listening for updates to the wrapped ObservableList (for example because of a binding to it) is ensured to be notified on the JavaFX Application Thread. It should be used to implement bindings where updates come in from a background thread but should be reflected in the UI where it is necessary that changes to the UI are performed on the JavaFX Application thread.
*
* @param <E> the type of the elements of the wrapped ObservableList.
*/
public class UiThreadObservableList<E> implements ObservableList<E> {
private final ObservableList<E> delegate;
public UiThreadObservableList(ObservableList<E> delegate) {
this.delegate = delegate;
}
@Override
public void addListener(ListChangeListener<? super E> listener) {
delegate.addListener(new UiThreadListChangeListener(listener));
}
@Override
public void removeListener(ListChangeListener<? super E> listener) {
delegate.removeListener(listener);
}
@Override
public boolean addAll(E... elements) {
return delegate.addAll(elements);
}
@Override
public boolean setAll(E... elements) {
return delegate.setAll(elements);
}
@Override
public boolean setAll(Collection<? extends E> col) {
return delegate.setAll(col);
}
@Override
public boolean removeAll(E... elements) {
return delegate.removeAll(elements);
}
@Override
public boolean retainAll(E... elements) {
return delegate.retainAll(elements);
}
@Override
public void remove(int from, int to) {
delegate.remove(from, to);
}
@Override
public int size() {
return delegate.size();
}
@Override
public boolean isEmpty() {
return delegate.isEmpty();
}
@Override
public boolean contains(Object o) {
return delegate.contains(o);
}
@Override
public Iterator<E> iterator() {
return delegate.iterator();
}
@Override
public Object[] toArray() {
return delegate.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return delegate.toArray(a);
}
@Override
public boolean add(E e) {
return delegate.add(e);
}
@Override
public boolean remove(Object o) {
return delegate.remove(o);
}
@Override
public boolean containsAll(Collection<?> c) {
return delegate.containsAll(c);
}
@Override
public boolean addAll(Collection<? extends E> c) {
return delegate.addAll(c);
}
@Override
public boolean addAll(int index, Collection<? extends E> c) {
return delegate.addAll(index, c);
}
@Override
public boolean removeAll(Collection<?> c) {
return delegate.removeAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
return delegate.retainAll(c);
}
@Override
public void clear() {
delegate.clear();
}
@Override
public E get(int index) {
return delegate.get(index);
}
@Override
public E set(int index, E element) {
return delegate.set(index, element);
}
@Override
public void add(int index, E element) {
delegate.add(index, element);
}
@Override
public E remove(int index) {
return delegate.remove(index);
}
@Override
public int indexOf(Object o) {
return delegate.indexOf(o);
}
@Override
public int lastIndexOf(Object o) {
return delegate.lastIndexOf(o);
}
@Override
public ListIterator<E> listIterator() {
return delegate.listIterator();
}
@Override
public ListIterator<E> listIterator(int index) {
return delegate.listIterator(index);
}
@Override
public List<E> subList(int fromIndex, int toIndex) {
return delegate.subList(fromIndex, toIndex);
}
@Override
public void addListener(InvalidationListener listener) {
delegate.addListener(new UiThreadInvalidationListener(listener));
}
@Override
public void removeListener(InvalidationListener listener) {
delegate.removeListener(listener);
}
}
| 4,575
| 23.084211
| 461
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/util/uithreadaware/UiThreadStringProperty.java
|
package org.jabref.gui.util.uithreadaware;
import javafx.beans.InvalidationListener;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
/**
* This class can be used to wrap a @see StringProperty inside it. When wrapped, any Listener listening for updates to the wrapped StringProperty (for example because of a binding to it) is ensured to be notified on the JavaFX Application Thread. It should be used to implement bindings where updates come in from a background thread but should be reflected in the UI where it is necessary that changes to the UI are performed on the JavaFX Application thread.
*/
public class UiThreadStringProperty extends StringProperty {
private final StringProperty delegate;
public UiThreadStringProperty(StringProperty delegate) {
this.delegate = delegate;
}
@Override
public void bind(ObservableValue<? extends String> observable) {
delegate.bind(observable);
}
@Override
public void unbind() {
delegate.unbind();
}
@Override
public boolean isBound() {
return delegate.isBound();
}
@Override
public Object getBean() {
return delegate.getBean();
}
@Override
public String getName() {
return delegate.getName();
}
@Override
public String get() {
return delegate.get();
}
@Override
public void set(String value) {
delegate.set(value);
}
@Override
public void addListener(ChangeListener<? super String> listener) {
delegate.addListener(new UiThreadChangeListener(listener));
}
@Override
public void removeListener(ChangeListener<? super String> listener) {
delegate.removeListener(listener);
}
@Override
public void addListener(InvalidationListener listener) {
delegate.addListener(new UiThreadInvalidationListener(listener));
}
@Override
public void removeListener(InvalidationListener listener) {
delegate.removeListener(listener);
}
}
| 2,100
| 27.391892
| 460
|
java
|
null |
jabref-main/src/main/java/org/jabref/logic/JabRefException.java
|
package org.jabref.logic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JabRefException extends Exception {
private static final Logger LOGGER = LoggerFactory.getLogger(JabRefException.class);
private String localizedMessage;
public JabRefException(String message) {
super(message);
}
public JabRefException(String message, Throwable cause) {
super(message, cause);
}
public JabRefException(String message, String localizedMessage) {
super(message);
this.localizedMessage = localizedMessage;
}
public JabRefException(String message, String localizedMessage, Throwable cause) {
super(message, cause);
this.localizedMessage = localizedMessage;
}
public JabRefException(Throwable cause) {
super(cause);
}
@Override
public String getLocalizedMessage() {
if (localizedMessage == null) {
LOGGER.debug("No localized exception message defined. Falling back to getMessage().");
return getMessage();
} else {
return localizedMessage;
}
}
}
| 1,139
| 25.511628
| 98
|
java
|
null |
jabref-main/src/main/java/org/jabref/logic/TypedBibEntry.java
|
package org.jabref.logic;
import java.util.Objects;
import java.util.Optional;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.database.BibDatabaseMode;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.BibEntryType;
import org.jabref.model.entry.BibEntryTypesManager;
/**
* Wrapper around a {@link BibEntry} offering methods for {@link BibDatabaseMode}-dependent results
*/
public class TypedBibEntry {
private final BibEntry entry;
private final Optional<BibDatabase> database;
private final BibDatabaseMode mode;
public TypedBibEntry(BibEntry entry, BibDatabaseMode mode) {
this.entry = Objects.requireNonNull(entry);
this.database = Optional.empty();
// mode may be null
this.mode = mode;
}
public TypedBibEntry(BibEntry entry, BibDatabaseContext databaseContext) {
this.entry = Objects.requireNonNull(entry);
this.database = Optional.of(databaseContext.getDatabase());
this.mode = Objects.requireNonNull(databaseContext).getMode();
}
/**
* Checks the fields of the entry whether all required fields are set.
* In other words: It is checked whether this entry contains all fields it needs to be complete.
*
* @return true if all required fields are set, false otherwise
*/
public boolean hasAllRequiredFields(BibEntryTypesManager entryTypesManager) {
Optional<BibEntryType> type = entryTypesManager.enrich(entry.getType(), this.mode);
if (type.isPresent()) {
return entry.allFieldsPresent(type.get().getRequiredFields(), database.orElse(null));
} else {
return true;
}
}
/**
* Gets the display name for the type of the entry.
*/
public String getTypeForDisplay() {
return entry.getType().getDisplayName();
}
}
| 1,926
| 32.807018
| 100
|
java
|
null |
jabref-main/src/main/java/org/jabref/logic/WatchServiceUnavailableException.java
|
package org.jabref.logic;
public class WatchServiceUnavailableException extends JabRefException {
public WatchServiceUnavailableException(final String message, final String localizedMessage, final Throwable cause) {
super(message, localizedMessage, cause);
}
}
| 278
| 33.875
| 121
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.