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/libraryproperties/general/GeneralPropertiesViewModel.java
package org.jabref.gui.libraryproperties.general; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ListProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleListProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.collections.FXCollections; import org.jabref.gui.DialogService; import org.jabref.gui.libraryproperties.PropertiesTabViewModel; import org.jabref.gui.util.DirectoryDialogConfiguration; import org.jabref.logic.l10n.Encodings; import org.jabref.logic.shared.DatabaseLocation; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.database.BibDatabaseMode; import org.jabref.model.metadata.MetaData; import org.jabref.preferences.PreferencesService; public class GeneralPropertiesViewModel implements PropertiesTabViewModel { private final BooleanProperty encodingDisableProperty = new SimpleBooleanProperty(); private final ListProperty<Charset> encodingsProperty = new SimpleListProperty<>(FXCollections.observableArrayList(Encodings.getCharsets())); private final ObjectProperty<Charset> selectedEncodingProperty = new SimpleObjectProperty<>(Encodings.getCharsets().get(0)); private final ListProperty<BibDatabaseMode> databaseModesProperty = new SimpleListProperty<>(FXCollections.observableArrayList(BibDatabaseMode.values())); private final SimpleObjectProperty<BibDatabaseMode> selectedDatabaseModeProperty = new SimpleObjectProperty<>(BibDatabaseMode.BIBLATEX); private final StringProperty generalFileDirectoryProperty = new SimpleStringProperty(""); private final StringProperty userSpecificFileDirectoryProperty = new SimpleStringProperty(""); private final StringProperty laTexFileDirectoryProperty = new SimpleStringProperty(""); private final DialogService dialogService; private final PreferencesService preferencesService; private final BibDatabaseContext databaseContext; private final MetaData metaData; private final DirectoryDialogConfiguration directoryDialogConfiguration; GeneralPropertiesViewModel(BibDatabaseContext databaseContext, DialogService dialogService, PreferencesService preferencesService) { this.dialogService = dialogService; this.preferencesService = preferencesService; this.databaseContext = databaseContext; this.metaData = databaseContext.getMetaData(); this.directoryDialogConfiguration = new DirectoryDialogConfiguration.Builder() .withInitialDirectory(preferencesService.getFilePreferences().getWorkingDirectory()).build(); } @Override public void setValues() { boolean isShared = databaseContext.getLocation() == DatabaseLocation.SHARED; encodingDisableProperty.setValue(isShared); // the encoding of shared database is always UTF-8 selectedEncodingProperty.setValue(metaData.getEncoding().orElse(StandardCharsets.UTF_8)); selectedDatabaseModeProperty.setValue(metaData.getMode().orElse(BibDatabaseMode.BIBLATEX)); generalFileDirectoryProperty.setValue(metaData.getDefaultFileDirectory().orElse("").trim()); userSpecificFileDirectoryProperty.setValue(metaData.getUserFileDirectory(preferencesService.getFilePreferences().getUserAndHost()).orElse("").trim()); laTexFileDirectoryProperty.setValue(metaData.getLatexFileDirectory(preferencesService.getFilePreferences().getUserAndHost()).map(Path::toString).orElse("")); } @Override public void storeSettings() { MetaData newMetaData = databaseContext.getMetaData(); newMetaData.setEncoding(selectedEncodingProperty.getValue()); newMetaData.setMode(selectedDatabaseModeProperty.getValue()); String generalFileDirectory = generalFileDirectoryProperty.getValue().trim(); if (generalFileDirectory.isEmpty()) { newMetaData.clearDefaultFileDirectory(); } else { newMetaData.setDefaultFileDirectory(generalFileDirectory); } String userSpecificFileDirectory = userSpecificFileDirectoryProperty.getValue(); if (userSpecificFileDirectory.isEmpty()) { newMetaData.clearUserFileDirectory(preferencesService.getFilePreferences().getUserAndHost()); } else { newMetaData.setUserFileDirectory(preferencesService.getFilePreferences().getUserAndHost(), userSpecificFileDirectory); } String latexFileDirectory = laTexFileDirectoryProperty.getValue(); if (latexFileDirectory.isEmpty()) { newMetaData.clearLatexFileDirectory(preferencesService.getFilePreferences().getUserAndHost()); } else { newMetaData.setLatexFileDirectory(preferencesService.getFilePreferences().getUserAndHost(), Path.of(latexFileDirectory)); } databaseContext.setMetaData(newMetaData); } public void browseGeneralDir() { dialogService.showDirectorySelectionDialog(directoryDialogConfiguration) .ifPresent(dir -> generalFileDirectoryProperty.setValue(dir.toAbsolutePath().toString())); } public void browseUserDir() { dialogService.showDirectorySelectionDialog(directoryDialogConfiguration) .ifPresent(dir -> userSpecificFileDirectoryProperty.setValue(dir.toAbsolutePath().toString())); } public void browseLatexDir() { dialogService.showDirectorySelectionDialog(directoryDialogConfiguration) .ifPresent(dir -> laTexFileDirectoryProperty.setValue(dir.toAbsolutePath().toString())); } public BooleanProperty encodingDisableProperty() { return encodingDisableProperty; } public ListProperty<Charset> encodingsProperty() { return this.encodingsProperty; } public ObjectProperty<Charset> selectedEncodingProperty() { return selectedEncodingProperty; } public ListProperty<BibDatabaseMode> databaseModesProperty() { return databaseModesProperty; } public SimpleObjectProperty<BibDatabaseMode> selectedDatabaseModeProperty() { return selectedDatabaseModeProperty; } public StringProperty generalFileDirectoryPropertyProperty() { return this.generalFileDirectoryProperty; } public StringProperty userSpecificFileDirectoryProperty() { return this.userSpecificFileDirectoryProperty; } public StringProperty laTexFileDirectoryProperty() { return this.laTexFileDirectoryProperty; } }
6,749
45.551724
165
java
null
jabref-main/src/main/java/org/jabref/gui/libraryproperties/keypattern/KeyPatternPropertiesView.java
package org.jabref.gui.libraryproperties.keypattern; import javafx.fxml.FXML; import javafx.scene.control.Button; import org.jabref.gui.Globals; import org.jabref.gui.actions.ActionFactory; import org.jabref.gui.actions.StandardActions; import org.jabref.gui.commonfxcontrols.CitationKeyPatternPanel; import org.jabref.gui.help.HelpAction; import org.jabref.gui.libraryproperties.AbstractPropertiesTabView; import org.jabref.gui.libraryproperties.PropertiesTab; import org.jabref.logic.help.HelpFile; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntryTypesManager; import org.jabref.preferences.PreferencesService; import com.airhacks.afterburner.views.ViewLoader; import jakarta.inject.Inject; public class KeyPatternPropertiesView extends AbstractPropertiesTabView<KeyPatternPropertiesViewModel> implements PropertiesTab { @FXML private Button keyPatternHelp; @FXML private CitationKeyPatternPanel bibtexKeyPatternTable; @Inject private PreferencesService preferencesService; @Inject private BibEntryTypesManager bibEntryTypesManager; public KeyPatternPropertiesView(BibDatabaseContext databaseContext) { this.databaseContext = databaseContext; ViewLoader.view(this) .root(this) .load(); } @Override public String getTabName() { return Localization.lang("Citation key patterns"); } public void initialize() { this.viewModel = new KeyPatternPropertiesViewModel(databaseContext, preferencesService); bibtexKeyPatternTable.patternListProperty().bindBidirectional(viewModel.patternListProperty()); bibtexKeyPatternTable.defaultKeyPatternProperty().bindBidirectional(viewModel.defaultKeyPatternProperty()); ActionFactory actionFactory = new ActionFactory(Globals.getKeyPrefs()); actionFactory.configureIconButton(StandardActions.HELP_KEY_PATTERNS, new HelpAction(HelpFile.CITATION_KEY_PATTERN, dialogService), keyPatternHelp); } @Override public void setValues() { viewModel.setValues(); bibtexKeyPatternTable.setValues( bibEntryTypesManager.getAllTypes(databaseContext.getMetaData().getMode() .orElse(preferencesService.getLibraryPreferences() .getDefaultBibDatabaseMode())), databaseContext.getMetaData().getCiteKeyPattern(preferencesService.getCitationKeyPatternPreferences().getKeyPattern())); } @FXML public void resetAllKeyPatterns() { bibtexKeyPatternTable.resetAll(); } }
2,753
39.5
155
java
null
jabref-main/src/main/java/org/jabref/gui/libraryproperties/keypattern/KeyPatternPropertiesViewModel.java
package org.jabref.gui.libraryproperties.keypattern; import javafx.beans.property.ListProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleListProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.FXCollections; import org.jabref.gui.commonfxcontrols.CitationKeyPatternPanelItemModel; import org.jabref.gui.commonfxcontrols.CitationKeyPatternPanelViewModel; import org.jabref.gui.libraryproperties.PropertiesTabViewModel; import org.jabref.logic.citationkeypattern.DatabaseCitationKeyPattern; import org.jabref.model.database.BibDatabaseContext; import org.jabref.preferences.PreferencesService; public class KeyPatternPropertiesViewModel implements PropertiesTabViewModel { // The list and the default properties are being overwritten by the bound properties of the tableView, but to // prevent an NPE on storing the preferences before lazy-loading of the setValues, they need to be initialized. private final ListProperty<CitationKeyPatternPanelItemModel> patternListProperty = new SimpleListProperty<>(FXCollections.observableArrayList()); private final ObjectProperty<CitationKeyPatternPanelItemModel> defaultKeyPatternProperty = new SimpleObjectProperty<>( new CitationKeyPatternPanelItemModel(new CitationKeyPatternPanelViewModel.DefaultEntryType(), "")); private final PreferencesService preferencesService; private final BibDatabaseContext databaseContext; public KeyPatternPropertiesViewModel(BibDatabaseContext databaseContext, PreferencesService preferencesService) { this.databaseContext = databaseContext; this.preferencesService = preferencesService; } @Override public void setValues() { // empty } @Override public void storeSettings() { DatabaseCitationKeyPattern newKeyPattern = new DatabaseCitationKeyPattern(preferencesService.getCitationKeyPatternPreferences().getKeyPattern()); patternListProperty.forEach(item -> { String patternString = item.getPattern(); if (!item.getEntryType().getName().equals("default")) { if (!patternString.trim().isEmpty()) { newKeyPattern.addCitationKeyPattern(item.getEntryType(), patternString); } } }); if (!defaultKeyPatternProperty.getValue().getPattern().trim().isEmpty()) { // we do not trim the value at the assignment to enable users to have spaces at the beginning and // at the end of the pattern newKeyPattern.setDefaultValue(defaultKeyPatternProperty.getValue().getPattern()); } databaseContext.getMetaData().setCiteKeyPattern(newKeyPattern); } public ListProperty<CitationKeyPatternPanelItemModel> patternListProperty() { return patternListProperty; } public ObjectProperty<CitationKeyPatternPanelItemModel> defaultKeyPatternProperty() { return defaultKeyPatternProperty; } }
3,020
43.426471
153
java
null
jabref-main/src/main/java/org/jabref/gui/libraryproperties/preamble/PreamblePropertiesView.java
package org.jabref.gui.libraryproperties.preamble; import javax.swing.undo.UndoManager; import javafx.fxml.FXML; import javafx.scene.control.TextArea; import org.jabref.gui.libraryproperties.AbstractPropertiesTabView; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import com.airhacks.afterburner.views.ViewLoader; import jakarta.inject.Inject; public class PreamblePropertiesView extends AbstractPropertiesTabView<PreamblePropertiesViewModel> { @FXML private TextArea preamble; @Inject private UndoManager undoManager; public PreamblePropertiesView(BibDatabaseContext databaseContext) { this.databaseContext = databaseContext; ViewLoader.view(this) .root(this) .load(); } @Override public String getTabName() { return Localization.lang("Preamble"); } public void initialize() { this.viewModel = new PreamblePropertiesViewModel(databaseContext, undoManager); preamble.textProperty().bindBidirectional(viewModel.preambleProperty()); } }
1,108
27.435897
100
java
null
jabref-main/src/main/java/org/jabref/gui/libraryproperties/preamble/PreamblePropertiesViewModel.java
package org.jabref.gui.libraryproperties.preamble; import javax.swing.undo.UndoManager; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import org.jabref.gui.libraryproperties.PropertiesTabViewModel; import org.jabref.gui.undo.UndoablePreambleChange; import org.jabref.model.database.BibDatabaseContext; public class PreamblePropertiesViewModel implements PropertiesTabViewModel { private final StringProperty preambleProperty = new SimpleStringProperty(""); private final BibDatabaseContext databaseContext; private final UndoManager undoManager; PreamblePropertiesViewModel(BibDatabaseContext databaseContext, UndoManager undoManager) { this.undoManager = undoManager; this.databaseContext = databaseContext; } @Override public void setValues() { preambleProperty.setValue(databaseContext.getDatabase().getPreamble().orElse("")); } @Override public void storeSettings() { String newPreamble = preambleProperty.getValue(); if (!databaseContext.getDatabase().getPreamble().orElse("").equals(newPreamble)) { undoManager.addEdit(new UndoablePreambleChange(databaseContext.getDatabase(), databaseContext.getDatabase().getPreamble().orElse(null), newPreamble)); databaseContext.getDatabase().setPreamble(newPreamble); } } public StringProperty preambleProperty() { return this.preambleProperty; } }
1,484
35.219512
162
java
null
jabref-main/src/main/java/org/jabref/gui/libraryproperties/saving/SavingPropertiesView.java
package org.jabref.gui.libraryproperties.saving; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import org.jabref.gui.commonfxcontrols.FieldFormatterCleanupsPanel; import org.jabref.gui.commonfxcontrols.SaveOrderConfigPanel; import org.jabref.gui.libraryproperties.AbstractPropertiesTabView; import org.jabref.gui.libraryproperties.PropertiesTab; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.preferences.PreferencesService; import com.airhacks.afterburner.views.ViewLoader; import jakarta.inject.Inject; public class SavingPropertiesView extends AbstractPropertiesTabView<SavingPropertiesViewModel> implements PropertiesTab { @FXML private CheckBox protect; @FXML private SaveOrderConfigPanel saveOrderConfigPanel; @FXML private FieldFormatterCleanupsPanel fieldFormatterCleanupsPanel; @Inject private PreferencesService preferencesService; public SavingPropertiesView(BibDatabaseContext databaseContext) { this.databaseContext = databaseContext; ViewLoader.view(this) .root(this) .load(); } @Override public String getTabName() { return Localization.lang("Saving"); } public void initialize() { this.viewModel = new SavingPropertiesViewModel(databaseContext, preferencesService); protect.disableProperty().bind(viewModel.protectDisableProperty()); protect.selectedProperty().bindBidirectional(viewModel.libraryProtectedProperty()); saveOrderConfigPanel.saveInOriginalProperty().bindBidirectional(viewModel.saveInOriginalProperty()); saveOrderConfigPanel.saveInTableOrderProperty().bindBidirectional(viewModel.saveInTableOrderProperty()); saveOrderConfigPanel.saveInSpecifiedOrderProperty().bindBidirectional(viewModel.saveInSpecifiedOrderProperty()); saveOrderConfigPanel.sortableFieldsProperty().bind(viewModel.sortableFieldsProperty()); saveOrderConfigPanel.sortCriteriaProperty().bindBidirectional(viewModel.sortCriteriaProperty()); fieldFormatterCleanupsPanel.cleanupsDisableProperty().bindBidirectional(viewModel.cleanupsDisableProperty()); fieldFormatterCleanupsPanel.cleanupsProperty().bindBidirectional(viewModel.cleanupsProperty()); } }
2,329
42.148148
121
java
null
jabref-main/src/main/java/org/jabref/gui/libraryproperties/saving/SavingPropertiesViewModel.java
package org.jabref.gui.libraryproperties.saving; import java.util.ArrayList; import java.util.Optional; import java.util.Set; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ListProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleListProperty; import javafx.collections.FXCollections; import org.jabref.gui.commonfxcontrols.SortCriterionViewModel; import org.jabref.gui.libraryproperties.PropertiesTabViewModel; import org.jabref.logic.cleanup.FieldFormatterCleanup; import org.jabref.logic.cleanup.FieldFormatterCleanups; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldFactory; import org.jabref.model.entry.field.InternalField; import org.jabref.model.metadata.MetaData; import org.jabref.model.metadata.SaveOrder; import org.jabref.preferences.CleanupPreferences; import org.jabref.preferences.PreferencesService; public class SavingPropertiesViewModel implements PropertiesTabViewModel { private final BooleanProperty protectDisableProperty = new SimpleBooleanProperty(); private final BooleanProperty libraryProtectedProperty = new SimpleBooleanProperty(); // SaveOrderConfigPanel private final BooleanProperty saveInOriginalProperty = new SimpleBooleanProperty(); private final BooleanProperty saveInTableOrderProperty = new SimpleBooleanProperty(); private final BooleanProperty saveInSpecifiedOrderProperty = new SimpleBooleanProperty(); private final ListProperty<Field> sortableFieldsProperty = new SimpleListProperty<>(FXCollections.observableArrayList()); private final ListProperty<SortCriterionViewModel> sortCriteriaProperty = new SimpleListProperty<>(FXCollections.observableArrayList(new ArrayList<>())); // FieldFormatterCleanupsPanel private final BooleanProperty cleanupsDisableProperty = new SimpleBooleanProperty(); private final ListProperty<FieldFormatterCleanup> cleanupsProperty = new SimpleListProperty<>(FXCollections.emptyObservableList()); private final BibDatabaseContext databaseContext; private final MetaData initialMetaData; private final SaveOrder exportSaveOrder; private final PreferencesService preferencesService; public SavingPropertiesViewModel(BibDatabaseContext databaseContext, PreferencesService preferencesService) { this.databaseContext = databaseContext; this.preferencesService = preferencesService; this.initialMetaData = databaseContext.getMetaData(); this.exportSaveOrder = initialMetaData.getSaveOrderConfig() .orElseGet(() -> preferencesService.getExportPreferences().getExportSaveOrder()); } @Override public void setValues() { libraryProtectedProperty.setValue(initialMetaData.isProtected()); // SaveOrderConfigPanel switch (exportSaveOrder.getOrderType()) { case SPECIFIED -> saveInSpecifiedOrderProperty.setValue(true); case ORIGINAL -> saveInOriginalProperty.setValue(true); case TABLE -> saveInTableOrderProperty.setValue(true); } sortableFieldsProperty.clear(); Set<Field> fields = FieldFactory.getAllFieldsWithOutInternal(); fields.add(InternalField.INTERNAL_ALL_FIELD); fields.add(InternalField.INTERNAL_ALL_TEXT_FIELDS_FIELD); fields.add(InternalField.KEY_FIELD); fields.add(InternalField.TYPE_HEADER); sortableFieldsProperty.addAll(FieldFactory.getStandardFieldsWithCitationKey()); sortCriteriaProperty.clear(); sortCriteriaProperty.addAll(exportSaveOrder.getSortCriteria().stream() .map(SortCriterionViewModel::new) .toList()); // FieldFormatterCleanupsPanel Optional<FieldFormatterCleanups> saveActions = initialMetaData.getSaveActions(); saveActions.ifPresentOrElse(value -> { cleanupsDisableProperty.setValue(!value.isEnabled()); cleanupsProperty.setValue(FXCollections.observableArrayList(value.getConfiguredActions())); }, () -> { CleanupPreferences defaultPreset = preferencesService.getDefaultCleanupPreset(); cleanupsDisableProperty.setValue(!defaultPreset.getFieldFormatterCleanups().isEnabled()); cleanupsProperty.setValue(FXCollections.observableArrayList(defaultPreset.getFieldFormatterCleanups().getConfiguredActions())); }); } @Override public void storeSettings() { MetaData newMetaData = databaseContext.getMetaData(); if (libraryProtectedProperty.getValue()) { newMetaData.markAsProtected(); } else { newMetaData.markAsNotProtected(); } FieldFormatterCleanups fieldFormatterCleanups = new FieldFormatterCleanups( !cleanupsDisableProperty().getValue(), cleanupsProperty()); if (FieldFormatterCleanups.DEFAULT_SAVE_ACTIONS.equals(fieldFormatterCleanups.getConfiguredActions())) { newMetaData.clearSaveActions(); } else { // if all actions have been removed, remove the save actions from the MetaData if (fieldFormatterCleanups.getConfiguredActions().isEmpty()) { newMetaData.clearSaveActions(); } else { newMetaData.setSaveActions(fieldFormatterCleanups); } } SaveOrder newSaveOrder = new SaveOrder( SaveOrder.OrderType.fromBooleans(saveInSpecifiedOrderProperty.getValue(), saveInOriginalProperty.getValue()), sortCriteriaProperty.stream().map(SortCriterionViewModel::getCriterion).toList()); if (!newSaveOrder.equals(exportSaveOrder)) { if (newSaveOrder.equals(SaveOrder.getDefaultSaveOrder())) { newMetaData.clearSaveOrderConfig(); } else { newMetaData.setSaveOrderConfig(newSaveOrder); } } databaseContext.setMetaData(newMetaData); } public BooleanProperty protectDisableProperty() { return protectDisableProperty; } public BooleanProperty libraryProtectedProperty() { return libraryProtectedProperty; } // SaveOrderConfigPanel public BooleanProperty saveInOriginalProperty() { return saveInOriginalProperty; } public BooleanProperty saveInTableOrderProperty() { return saveInTableOrderProperty; } public BooleanProperty saveInSpecifiedOrderProperty() { return saveInSpecifiedOrderProperty; } public ListProperty<Field> sortableFieldsProperty() { return sortableFieldsProperty; } public ListProperty<SortCriterionViewModel> sortCriteriaProperty() { return sortCriteriaProperty; } // FieldFormatterCleanupsPanel public BooleanProperty cleanupsDisableProperty() { return cleanupsDisableProperty; } public ListProperty<FieldFormatterCleanup> cleanupsProperty() { return cleanupsProperty; } }
7,179
40.264368
157
java
null
jabref-main/src/main/java/org/jabref/gui/linkedfile/AttachFileAction.java
package org.jabref.gui.linkedfile; import java.nio.file.Path; import java.util.Optional; import org.jabref.gui.DialogService; 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.fieldeditors.LinkedFilesEditorViewModel; import org.jabref.gui.undo.UndoableFieldChange; import org.jabref.gui.util.FileDialogConfiguration; import org.jabref.logic.l10n.Localization; import org.jabref.model.FieldChange; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.LinkedFile; import org.jabref.preferences.FilePreferences; public class AttachFileAction extends SimpleCommand { private final LibraryTab libraryTab; private final StateManager stateManager; private final DialogService dialogService; private final FilePreferences filePreferences; public AttachFileAction(LibraryTab libraryTab, DialogService dialogService, StateManager stateManager, FilePreferences filePreferences) { this.libraryTab = libraryTab; this.stateManager = stateManager; this.dialogService = dialogService; this.filePreferences = filePreferences; this.executable.bind(ActionHelper.needsEntriesSelected(1, stateManager)); } @Override public void execute() { if (stateManager.getActiveDatabase().isEmpty()) { dialogService.notify(Localization.lang("This operation requires an open library.")); return; } if (stateManager.getSelectedEntries().size() != 1) { dialogService.notify(Localization.lang("This operation requires exactly one item to be selected.")); return; } BibDatabaseContext databaseContext = stateManager.getActiveDatabase().get(); BibEntry entry = stateManager.getSelectedEntries().get(0); Path workingDirectory = databaseContext.getFirstExistingFileDir(filePreferences) .orElse(filePreferences.getWorkingDirectory()); FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() .withInitialDirectory(workingDirectory) .build(); dialogService.showFileOpenDialog(fileDialogConfiguration).ifPresent(newFile -> { LinkedFile linkedFile = LinkedFilesEditorViewModel.fromFile( newFile, databaseContext.getFileDirectories(filePreferences), filePreferences); LinkedFileEditDialogView dialog = new LinkedFileEditDialogView(linkedFile); dialogService.showCustomDialogAndWait(dialog) .ifPresent(editedLinkedFile -> { Optional<FieldChange> fieldChange = entry.addFile(editedLinkedFile); fieldChange.ifPresent(change -> { UndoableFieldChange ce = new UndoableFieldChange(change); libraryTab.getUndoManager().addEdit(ce); libraryTab.markBaseChanged(); }); }); }); } }
3,315
38.951807
112
java
null
jabref-main/src/main/java/org/jabref/gui/linkedfile/AttachFileFromURLAction.java
package org.jabref.gui.linkedfile; import java.net.MalformedURLException; import java.net.URL; import java.util.Optional; import org.jabref.gui.ClipBoardManager; 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.gui.fieldeditors.LinkedFileViewModel; import org.jabref.gui.util.TaskExecutor; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.LinkedFile; import org.jabref.model.entry.field.StandardField; import org.jabref.preferences.PreferencesService; public class AttachFileFromURLAction extends SimpleCommand { private final StateManager stateManager; private final DialogService dialogService; private final PreferencesService preferencesService; private final TaskExecutor taskExecutor; public AttachFileFromURLAction(DialogService dialogService, StateManager stateManager, TaskExecutor taskExecutor, PreferencesService preferencesService) { this.stateManager = stateManager; this.dialogService = dialogService; this.taskExecutor = taskExecutor; this.preferencesService = preferencesService; this.executable.bind(ActionHelper.needsEntriesSelected(1, stateManager)); } @Override public void execute() { if (stateManager.getActiveDatabase().isEmpty()) { dialogService.notify(Localization.lang("This operation requires an open library.")); return; } if (stateManager.getSelectedEntries().size() != 1) { dialogService.notify(Localization.lang("This operation requires exactly one item to be selected.")); return; } BibDatabaseContext databaseContext = stateManager.getActiveDatabase().get(); BibEntry entry = stateManager.getSelectedEntries().get(0); Optional<String> urlforDownload = getUrlForDownloadFromClipBoardOrEntry(dialogService, entry); if (urlforDownload.isEmpty()) { return; } try { URL url = new URL(urlforDownload.get()); LinkedFileViewModel onlineFile = new LinkedFileViewModel( new LinkedFile(url, ""), entry, databaseContext, taskExecutor, dialogService, preferencesService); onlineFile.download(); } catch (MalformedURLException exception) { dialogService.showErrorDialogAndWait(Localization.lang("Invalid URL"), exception); } } public static Optional<String> getUrlForDownloadFromClipBoardOrEntry(DialogService dialogService, BibEntry entry) { String clipText = ClipBoardManager.getContents(); Optional<String> urlText; String urlField = entry.getField(StandardField.URL).orElse(""); if (clipText.startsWith("http://") || clipText.startsWith("https://") || clipText.startsWith("ftp://")) { urlText = dialogService.showInputDialogWithDefaultAndWait( Localization.lang("Download file"), Localization.lang("Enter URL to download"), clipText); } else if (urlField.startsWith("http://") || urlField.startsWith("https://") || urlField.startsWith("ftp://")) { urlText = dialogService.showInputDialogWithDefaultAndWait( Localization.lang("Download file"), Localization.lang("Enter URL to download"), urlField); } else { urlText = dialogService.showInputDialogAndWait( Localization.lang("Download file"), Localization.lang("Enter URL to download")); } return urlText; } }
3,970
41.244681
120
java
null
jabref-main/src/main/java/org/jabref/gui/linkedfile/DeleteFileAction.java
package org.jabref.gui.linkedfile; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Optional; import javafx.scene.control.Alert; import javafx.scene.control.ButtonBar; import javafx.scene.control.ButtonType; import javafx.scene.control.ListView; import org.jabref.gui.DialogService; import org.jabref.gui.actions.SimpleCommand; import org.jabref.gui.fieldeditors.LinkedFileViewModel; import org.jabref.gui.fieldeditors.LinkedFilesEditorViewModel; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.LinkedFile; import org.jabref.preferences.PreferencesService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DeleteFileAction extends SimpleCommand { private static final Logger LOGGER = LoggerFactory.getLogger(DeleteFileAction.class); private final DialogService dialogService; private final PreferencesService preferences; private final BibDatabaseContext databaseContext; private final LinkedFilesEditorViewModel viewModel; private final ListView<LinkedFileViewModel> listView; public DeleteFileAction(DialogService dialogService, PreferencesService preferences, BibDatabaseContext databaseContext, LinkedFilesEditorViewModel viewModel, ListView<LinkedFileViewModel> listView) { this.dialogService = dialogService; this.preferences = preferences; this.databaseContext = databaseContext; this.viewModel = viewModel; this.listView = listView; } @Override public void execute() { List<LinkedFileViewModel> toBeDeleted = List.copyOf(listView.getSelectionModel().getSelectedItems()); if (toBeDeleted.isEmpty()) { dialogService.notify(Localization.lang("This operation requires selected linked files.")); return; } String dialogTitle; String dialogContent; if (toBeDeleted.size() != 1) { dialogTitle = Localization.lang("Delete %0 files", toBeDeleted.size()); dialogContent = Localization.lang("Delete %0 files permanently from disk, or just remove the files from the entry? " + "Pressing Delete will delete the files permanently from disk.", toBeDeleted.size()); } else { Optional<Path> file = toBeDeleted.get(0).getFile().findIn(databaseContext, preferences.getFilePreferences()); if (file.isPresent()) { dialogTitle = Localization.lang("Delete '%0'", file.get().getFileName().toString()); dialogContent = Localization.lang("Delete '%0' permanently from disk, or just remove the file from the entry? " + "Pressing Delete will delete the file permanently from disk.", file.get().toString()); } else { dialogService.notify(Localization.lang("Error accessing file '%0'.", toBeDeleted.get(0).getFile().getLink())); return; } } ButtonType removeFromEntry = new ButtonType(Localization.lang("Remove from entry"), ButtonBar.ButtonData.YES); ButtonType deleteFromEntry = new ButtonType(Localization.lang("Delete from disk")); Optional<ButtonType> buttonType = dialogService.showCustomButtonDialogAndWait(Alert.AlertType.INFORMATION, dialogTitle, dialogContent, removeFromEntry, deleteFromEntry, ButtonType.CANCEL); if (buttonType.isPresent()) { if (buttonType.get().equals(removeFromEntry)) { deleteFiles(toBeDeleted, false); } if (buttonType.get().equals(deleteFromEntry)) { deleteFiles(toBeDeleted, true); } } } /** * Deletes the files from the entry and optionally from disk. * * @param toBeDeleted the files to be deleted * @param deleteFromDisk if true, the files are deleted from disk, otherwise they are only removed from the entry */ private void deleteFiles(List<LinkedFileViewModel> toBeDeleted, boolean deleteFromDisk) { for (LinkedFileViewModel fileViewModel : toBeDeleted) { if (fileViewModel.getFile().isOnlineLink()) { viewModel.removeFileLink(fileViewModel); } else { if (deleteFromDisk) { deleteFileFromDisk(fileViewModel); } viewModel.getFiles().remove(fileViewModel); } } } /** * Deletes the file from disk without asking the user for confirmation. * * @param fileViewModel the file to be deleted */ public void deleteFileFromDisk(LinkedFileViewModel fileViewModel) { LinkedFile linkedFile = fileViewModel.getFile(); Optional<Path> file = linkedFile.findIn(databaseContext, preferences.getFilePreferences()); if (file.isEmpty()) { LOGGER.warn("Could not find file {}", linkedFile.getLink()); } if (file.isPresent()) { try { Files.delete(file.get()); } catch ( IOException ex) { dialogService.showErrorDialogAndWait(Localization.lang("Cannot delete file"), Localization.lang("File permission error")); LOGGER.warn("File permission error while deleting: {}", linkedFile, ex); } } else { dialogService.notify(Localization.lang("Error accessing file '%0'.", linkedFile.getLink())); } } }
5,674
39.827338
138
java
null
jabref-main/src/main/java/org/jabref/gui/linkedfile/LinkedFileEditDialogView.java
package org.jabref.gui.linkedfile; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.ButtonType; import javafx.scene.control.ComboBox; import javafx.scene.control.TextField; import org.jabref.gui.DialogService; import org.jabref.gui.StateManager; import org.jabref.gui.externalfiletype.ExternalFileType; import org.jabref.gui.util.BaseDialog; import org.jabref.gui.util.ViewModelListCellFactory; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.LinkedFile; import org.jabref.preferences.PreferencesService; import com.airhacks.afterburner.views.ViewLoader; import jakarta.inject.Inject; public class LinkedFileEditDialogView extends BaseDialog<LinkedFile> { @FXML private TextField link; @FXML private TextField description; @FXML private ComboBox<ExternalFileType> fileType; @Inject private DialogService dialogService; @Inject private StateManager stateManager; @Inject private PreferencesService preferences; private LinkedFilesEditDialogViewModel viewModel; private final LinkedFile linkedFile; public LinkedFileEditDialogView(LinkedFile linkedFile) { this.linkedFile = linkedFile; ViewLoader.view(this) .load() .setAsContent(this.getDialogPane()); this.getDialogPane().getButtonTypes().addAll(ButtonType.APPLY, ButtonType.CANCEL); this.setResizable(false); this.setTitle(Localization.lang("Edit file link")); this.setResultConverter(button -> { if (button == ButtonType.APPLY) { return viewModel.getNewLinkedFile(); } else { return null; } }); } @FXML private void initialize() { viewModel = new LinkedFilesEditDialogViewModel(linkedFile, stateManager.getActiveDatabase().get(), dialogService, preferences.getFilePreferences()); fileType.itemsProperty().bindBidirectional(viewModel.externalFileTypeProperty()); new ViewModelListCellFactory<ExternalFileType>() .withIcon(ExternalFileType::getIcon) .withText(ExternalFileType::getName) .install(fileType); description.textProperty().bindBidirectional(viewModel.descriptionProperty()); link.textProperty().bindBidirectional(viewModel.linkProperty()); fileType.valueProperty().bindBidirectional(viewModel.selectedExternalFileTypeProperty()); } @FXML private void openBrowseDialog(ActionEvent event) { viewModel.openBrowseDialog(); link.requestFocus(); } }
2,619
33.473684
156
java
null
jabref-main/src/main/java/org/jabref/gui/linkedfile/LinkedFilesEditDialogViewModel.java
package org.jabref.gui.linkedfile; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Path; import java.util.List; import java.util.Optional; import java.util.regex.Pattern; import javafx.beans.property.ListProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleListProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.collections.FXCollections; import org.jabref.gui.AbstractViewModel; import org.jabref.gui.DialogService; import org.jabref.gui.externalfiletype.ExternalFileType; import org.jabref.gui.externalfiletype.ExternalFileTypes; import org.jabref.gui.externalfiletype.UnknownExternalFileType; import org.jabref.gui.util.FileDialogConfiguration; import org.jabref.logic.util.io.FileUtil; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.LinkedFile; import org.jabref.preferences.FilePreferences; import com.tobiasdiez.easybind.EasyBind; import com.tobiasdiez.easybind.optional.ObservableOptionalValue; public class LinkedFilesEditDialogViewModel extends AbstractViewModel { private static final Pattern REMOTE_LINK_PATTERN = Pattern.compile("[a-z]+://.*"); private final StringProperty link = new SimpleStringProperty(""); private final StringProperty description = new SimpleStringProperty(""); private final ListProperty<ExternalFileType> allExternalFileTypes = new SimpleListProperty<>(FXCollections.emptyObservableList()); private final ObjectProperty<ExternalFileType> selectedExternalFileType = new SimpleObjectProperty<>(); private final ObservableOptionalValue<ExternalFileType> monadicSelectedExternalFileType; private final BibDatabaseContext database; private final DialogService dialogService; private final FilePreferences filePreferences; public LinkedFilesEditDialogViewModel(LinkedFile linkedFile, BibDatabaseContext database, DialogService dialogService, FilePreferences filePreferences) { this.database = database; this.dialogService = dialogService; this.filePreferences = filePreferences; allExternalFileTypes.set(FXCollections.observableArrayList(filePreferences.getExternalFileTypes())); monadicSelectedExternalFileType = EasyBind.wrapNullable(selectedExternalFileType); setValues(linkedFile); } private void setExternalFileTypeByExtension(String link) { if (!link.isEmpty()) { // Check if this looks like a remote link: if (REMOTE_LINK_PATTERN.matcher(link).matches()) { ExternalFileTypes.getExternalFileTypeByExt("html", filePreferences) .ifPresent(selectedExternalFileType::setValue); } // Try to guess the file type: String theLink = link.trim(); ExternalFileTypes.getExternalFileTypeForName(theLink, filePreferences) .ifPresent(selectedExternalFileType::setValue); } } public void openBrowseDialog() { String fileText = link.get(); Optional<Path> file = FileUtil.find(database, fileText, filePreferences); Path workingDir = file.orElse(filePreferences.getWorkingDirectory()); String fileName = Path.of(fileText).getFileName().toString(); FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() .withInitialDirectory(workingDir) .withInitialFileName(fileName) .build(); dialogService.showFileOpenDialog(fileDialogConfiguration).ifPresent(path -> { // Store the directory for next time: filePreferences.setWorkingDirectory(path); link.set(relativize(path)); setExternalFileTypeByExtension(link.getValueSafe()); }); } public void setValues(LinkedFile linkedFile) { description.set(linkedFile.getDescription()); if (linkedFile.isOnlineLink()) { link.setValue(linkedFile.getLink()); // Might be an URL } else { link.setValue(relativize(Path.of(linkedFile.getLink()))); } selectedExternalFileType.setValue(null); // See what is a reasonable selection for the type combobox: Optional<ExternalFileType> fileType = ExternalFileTypes.getExternalFileTypeByLinkedFile(linkedFile, false, filePreferences); if (fileType.isPresent() && !(fileType.get() instanceof UnknownExternalFileType)) { selectedExternalFileType.setValue(fileType.get()); } else if ((linkedFile.getLink() != null) && (!linkedFile.getLink().isEmpty())) { setExternalFileTypeByExtension(linkedFile.getLink()); } } public StringProperty linkProperty() { return link; } public StringProperty descriptionProperty() { return description; } public ListProperty<ExternalFileType> externalFileTypeProperty() { return allExternalFileTypes; } public ObjectProperty<ExternalFileType> selectedExternalFileTypeProperty() { return selectedExternalFileType; } public LinkedFile getNewLinkedFile() { String fileType = monadicSelectedExternalFileType.getValue().map(ExternalFileType::toString).orElse(""); if (LinkedFile.isOnlineLink(link.getValue())) { try { return new LinkedFile(description.getValue(), new URL(link.getValue()), fileType); } catch (MalformedURLException e) { return new LinkedFile(description.getValue(), link.getValue(), fileType); } } return new LinkedFile(description.getValue(), Path.of(link.getValue()), fileType); } private String relativize(Path filePath) { List<Path> fileDirectories = database.getFileDirectories(filePreferences); return FileUtil.relativize(filePath, fileDirectories).toString(); } }
6,164
40.655405
134
java
null
jabref-main/src/main/java/org/jabref/gui/logging/ApplicationInsightsLogEvent.java
package org.jabref.gui.logging; /* * ApplicationInsightsJava * Copyright (c) Microsoft Corporation * All rights reserved. * * MIT License * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the ""Software""), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit * persons to whom the Software is furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import com.microsoft.applicationinsights.internal.common.ApplicationInsightsEvent; import com.microsoft.applicationinsights.internal.logger.InternalLogger; import com.microsoft.applicationinsights.telemetry.SeverityLevel; import org.tinylog.core.LogEntry; // TODO: Remove this copy as soon as the one included in AI is compatible with log4j 3 public final class ApplicationInsightsLogEvent extends ApplicationInsightsEvent { private final LogEntry logEvent; public ApplicationInsightsLogEvent(LogEntry logEvent) { this.logEvent = logEvent; } @Override public String getMessage() { String message = this.logEvent.getMessage() != null ? this.logEvent.getMessage() : "Tinylog Trace"; return message; } @Override public boolean isException() { return this.logEvent.getException() != null; } @Override public Exception getException() { Exception exception = null; if (isException()) { Throwable throwable = this.logEvent.getException(); exception = throwable instanceof Exception e ? e : new Exception(throwable); } return exception; } @Override public Map<String, String> getCustomParameters() { Map<String, String> metaData = new HashMap<>(); metaData.put("SourceType", "slf4j"); addLogEventProperty("LoggingLevel", logEvent.getLevel() != null ? logEvent.getLevel().name() : null, metaData); addLogEventProperty("ThreadName", logEvent.getThread().getName(), metaData); addLogEventProperty("TimeStamp", getFormattedDate(logEvent.getTimestamp().toInstant().toEpochMilli()), metaData); if (isException()) { addLogEventProperty("Logger Message", getMessage(), metaData); for (StackTraceElement stackTraceElement : logEvent.getException().getStackTrace()) { addLogEventProperty("ClassName", stackTraceElement.getClassName(), metaData); addLogEventProperty("FileName", stackTraceElement.getFileName(), metaData); addLogEventProperty("MethodName", stackTraceElement.getMethodName(), metaData); addLogEventProperty("LineNumber", String.valueOf(stackTraceElement.getLineNumber()), metaData); } } for (Entry<String, String> entry : logEvent.getContext().entrySet()) { addLogEventProperty(entry.getKey(), entry.getValue(), metaData); } // TODO: Username, domain and identity should be included as in .NET version. // TODO: Should check, seems that it is not included in Log4j2. return metaData; } @Override public SeverityLevel getNormalizedSeverityLevel() { org.tinylog.Level logEventLevel = logEvent.getLevel(); switch (logEventLevel) { case ERROR: return SeverityLevel.Error; case WARN: return SeverityLevel.Warning; case INFO: return SeverityLevel.Information; case TRACE: case DEBUG: return SeverityLevel.Verbose; default: InternalLogger.INSTANCE.error("Unknown slf4joption, %d, using TRACE level as default", logEventLevel); return SeverityLevel.Verbose; } } }
4,620
38.495726
121
java
null
jabref-main/src/main/java/org/jabref/gui/logging/ApplicationInsightsWriter.java
package org.jabref.gui.logging; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.Map; import org.jabref.gui.Globals; import com.microsoft.applicationinsights.telemetry.ExceptionTelemetry; import com.microsoft.applicationinsights.telemetry.Telemetry; import com.microsoft.applicationinsights.telemetry.TraceTelemetry; import org.tinylog.core.LogEntry; import org.tinylog.core.LogEntryValue; import org.tinylog.writers.AbstractFormatPatternWriter; public class ApplicationInsightsWriter extends AbstractFormatPatternWriter { public ApplicationInsightsWriter(final Map<String, String> properties) { super(properties); } public ApplicationInsightsWriter() { this(Collections.emptyMap()); } @Override public Collection<LogEntryValue> getRequiredLogEntryValues() { return EnumSet.allOf(LogEntryValue.class); } @Override public void write(LogEntry logEntry) throws Exception { ApplicationInsightsLogEvent event = new ApplicationInsightsLogEvent(logEntry); Telemetry telemetry; if (event.isException()) { ExceptionTelemetry exceptionTelemetry = new ExceptionTelemetry(event.getException()); exceptionTelemetry.getProperties().put("Message", logEntry.getMessage()); exceptionTelemetry.setSeverityLevel(event.getNormalizedSeverityLevel()); telemetry = exceptionTelemetry; } else { TraceTelemetry traceTelemetry = new TraceTelemetry(event.getMessage()); traceTelemetry.setSeverityLevel(event.getNormalizedSeverityLevel()); telemetry = traceTelemetry; } telemetry.getContext().getProperties().putAll(event.getCustomParameters()); Globals.getTelemetryClient().ifPresent(client -> client.track(telemetry)); } @Override public void flush() throws Exception { } @Override public void close() throws Exception { } }
1,992
32.216667
97
java
null
jabref-main/src/main/java/org/jabref/gui/logging/GuiWriter.java
package org.jabref.gui.logging; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.Map; import org.jabref.logic.logging.LogMessages; import org.tinylog.core.LogEntry; import org.tinylog.core.LogEntryValue; import org.tinylog.writers.AbstractFormatPatternWriter; public class GuiWriter extends AbstractFormatPatternWriter { public GuiWriter(final Map<String, String> properties) { super(properties); } public GuiWriter() { this(Collections.emptyMap()); } @Override public Collection<LogEntryValue> getRequiredLogEntryValues() { return EnumSet.allOf(LogEntryValue.class); } @Override public void write(LogEntry logEntry) throws Exception { LogMessages.getInstance().add(logEntry); } @Override public void flush() throws Exception { } @Override public void close() throws Exception { } }
942
21.452381
66
java
null
jabref-main/src/main/java/org/jabref/gui/maintable/BibEntryTableViewModel.java
package org.jabref.gui.maintable; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Predicate; import java.util.stream.Collectors; import javafx.beans.Observable; import javafx.beans.binding.Binding; import javafx.beans.binding.Bindings; import javafx.beans.property.ReadOnlyStringWrapper; import javafx.beans.property.StringProperty; import javafx.beans.value.ObservableValue; import org.jabref.gui.specialfields.SpecialFieldValueViewModel; import org.jabref.gui.util.uithreadaware.UiThreadBinding; import org.jabref.logic.importer.util.FileFieldParser; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.LinkedFile; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.OrFields; import org.jabref.model.entry.field.SpecialField; import org.jabref.model.entry.field.StandardField; import org.jabref.model.groups.AbstractGroup; import org.jabref.model.groups.GroupTreeNode; import com.tobiasdiez.easybind.EasyBind; import com.tobiasdiez.easybind.EasyBinding; import com.tobiasdiez.easybind.optional.OptionalBinding; public class BibEntryTableViewModel { private final BibEntry entry; private final ObservableValue<MainTableFieldValueFormatter> fieldValueFormatter; private final Map<OrFields, ObservableValue<String>> fieldValues = new HashMap<>(); private final Map<SpecialField, OptionalBinding<SpecialFieldValueViewModel>> specialFieldValues = new HashMap<>(); private final EasyBinding<List<LinkedFile>> linkedFiles; private final EasyBinding<Map<Field, String>> linkedIdentifiers; private final Binding<List<AbstractGroup>> matchedGroups; private final BibDatabaseContext bibDatabaseContext; public BibEntryTableViewModel(BibEntry entry, BibDatabaseContext bibDatabaseContext, ObservableValue<MainTableFieldValueFormatter> fieldValueFormatter) { this.entry = entry; this.fieldValueFormatter = fieldValueFormatter; this.linkedFiles = getField(StandardField.FILE).mapOpt(FileFieldParser::parse).orElseOpt(Collections.emptyList()); this.linkedIdentifiers = createLinkedIdentifiersBinding(entry); this.matchedGroups = createMatchedGroupsBinding(bibDatabaseContext, entry); this.bibDatabaseContext = bibDatabaseContext; } private static EasyBinding<Map<Field, String>> createLinkedIdentifiersBinding(BibEntry entry) { return EasyBind.combine( entry.getFieldBinding(StandardField.URL), entry.getFieldBinding(StandardField.DOI), entry.getFieldBinding(StandardField.URI), entry.getFieldBinding(StandardField.EPRINT), entry.getFieldBinding(StandardField.ISBN), (url, doi, uri, eprint, isbn) -> { Map<Field, String> identifiers = new HashMap<>(); url.ifPresent(value -> identifiers.put(StandardField.URL, value)); doi.ifPresent(value -> identifiers.put(StandardField.DOI, value)); uri.ifPresent(value -> identifiers.put(StandardField.URI, value)); eprint.ifPresent(value -> identifiers.put(StandardField.EPRINT, value)); isbn.ifPresent(value -> identifiers.put(StandardField.ISBN, value)); return identifiers; }); } public BibEntry getEntry() { return entry; } private static Binding<List<AbstractGroup>> createMatchedGroupsBinding(BibDatabaseContext database, BibEntry entry) { return new UiThreadBinding<>(EasyBind.combine(entry.getFieldBinding(StandardField.GROUPS), database.getMetaData().groupsBinding(), (a, b) -> database.getMetaData().getGroups().map(groupTreeNode -> groupTreeNode.getMatchingGroups(entry).stream() .map(GroupTreeNode::getGroup) .filter(Predicate.not(Predicate.isEqual(groupTreeNode.getGroup()))) .collect(Collectors.toList())) .orElse(Collections.emptyList()))); } public OptionalBinding<String> getField(Field field) { return entry.getFieldBinding(field); } public ObservableValue<List<LinkedFile>> getLinkedFiles() { return linkedFiles; } public ObservableValue<Map<Field, String>> getLinkedIdentifiers() { return linkedIdentifiers; } public ObservableValue<List<AbstractGroup>> getMatchedGroups() { return matchedGroups; } public ObservableValue<Optional<SpecialFieldValueViewModel>> getSpecialField(SpecialField field) { OptionalBinding<SpecialFieldValueViewModel> value = specialFieldValues.get(field); // Fetch possibly updated value from BibEntry entry Optional<String> currentValue = this.entry.getField(field); if (value != null) { if (currentValue.isEmpty() && value.getValue().isEmpty()) { var zeroValue = getField(field).flatMapOpt(fieldValue -> field.parseValue("CLEAR_RANK").map(SpecialFieldValueViewModel::new)); specialFieldValues.put(field, zeroValue); return zeroValue; } else if (value.getValue().isEmpty() || !value.getValue().get().getValue().getFieldValue().equals(currentValue)) { // specialFieldValues value and BibEntry value differ => Set specialFieldValues value to BibEntry value value = getField(field).flatMapOpt(fieldValue -> field.parseValue(fieldValue).map(SpecialFieldValueViewModel::new)); specialFieldValues.put(field, value); return value; } } else { value = getField(field).flatMapOpt(fieldValue -> field.parseValue(fieldValue).map(SpecialFieldValueViewModel::new)); specialFieldValues.put(field, value); } return value; } public ObservableValue<String> getFields(OrFields fields) { ObservableValue<String> value = fieldValues.get(fields); if (value != null) { return value; } ArrayList<Observable> observables = new ArrayList<>(List.of(entry.getObservables())); observables.add(fieldValueFormatter); value = Bindings.createStringBinding(() -> fieldValueFormatter.getValue().formatFieldsValues(fields, entry), observables.toArray(Observable[]::new)); fieldValues.put(fields, value); return value; } public StringProperty bibDatabaseContextProperty() { return new ReadOnlyStringWrapper(bibDatabaseContext.getDatabasePath().map(Path::toString).orElse("")); } }
6,962
45.731544
157
java
null
jabref-main/src/main/java/org/jabref/gui/maintable/CellFactory.java
package org.jabref.gui.maintable; import java.util.HashMap; import java.util.Map; import javax.swing.undo.UndoManager; import javafx.scene.Node; import org.jabref.gui.externalfiletype.ExternalFileType; import org.jabref.gui.icon.IconTheme; import org.jabref.gui.icon.JabRefIcon; import org.jabref.gui.specialfields.SpecialFieldViewModel; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.SpecialField; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.field.UnknownField; import org.jabref.preferences.PreferencesService; public class CellFactory { private final Map<Field, JabRefIcon> TABLE_ICONS = new HashMap<>(); public CellFactory(PreferencesService preferencesService, UndoManager undoManager) { JabRefIcon icon; icon = IconTheme.JabRefIcons.PDF_FILE; // icon.setToo(Localization.lang("Open") + " PDF"); TABLE_ICONS.put(StandardField.PDF, icon); icon = IconTheme.JabRefIcons.WWW; // icon.setToolTipText(Localization.lang("Open") + " URL"); TABLE_ICONS.put(StandardField.URL, icon); icon = IconTheme.JabRefIcons.WWW; // icon.setToolTipText(Localization.lang("Open") + " CiteSeer URL"); TABLE_ICONS.put(new UnknownField("citeseerurl"), icon); icon = IconTheme.JabRefIcons.WWW; // icon.setToolTipText(Localization.lang("Open") + " ArXivFetcher URL"); TABLE_ICONS.put(StandardField.EPRINT, icon); icon = IconTheme.JabRefIcons.DOI; // icon.setToolTipText(Localization.lang("Open") + " DOI " + Localization.lang("web link")); TABLE_ICONS.put(StandardField.DOI, icon); icon = IconTheme.JabRefIcons.FILE; // icon.setToolTipText(Localization.lang("Open") + " PS"); TABLE_ICONS.put(StandardField.PS, icon); icon = IconTheme.JabRefIcons.FOLDER; // icon.setToolTipText(Localization.lang("Open folder")); TABLE_ICONS.put(StandardField.FOLDER, icon); icon = IconTheme.JabRefIcons.FILE; // icon.setToolTipText(Localization.lang("Open file")); TABLE_ICONS.put(StandardField.FILE, icon); for (ExternalFileType fileType : preferencesService.getFilePreferences().getExternalFileTypes()) { icon = fileType.getIcon(); // icon.setToolTipText(Localization.lang("Open %0 file", fileType.getName())); TABLE_ICONS.put(fileType.getField(), icon); } SpecialFieldViewModel relevanceViewModel = new SpecialFieldViewModel(SpecialField.RELEVANCE, preferencesService, undoManager); icon = relevanceViewModel.getIcon(); // icon.setToolTipText(relevanceViewModel.getLocalization()); TABLE_ICONS.put(SpecialField.RELEVANCE, icon); SpecialFieldViewModel qualityViewModel = new SpecialFieldViewModel(SpecialField.QUALITY, preferencesService, undoManager); icon = qualityViewModel.getIcon(); // icon.setToolTipText(qualityViewModel.getLocalization()); TABLE_ICONS.put(SpecialField.QUALITY, icon); // Ranking item in the menu uses one star SpecialFieldViewModel rankViewModel = new SpecialFieldViewModel(SpecialField.RANKING, preferencesService, undoManager); icon = rankViewModel.getIcon(); // icon.setToolTipText(rankViewModel.getLocalization()); TABLE_ICONS.put(SpecialField.RANKING, icon); // Priority icon used for the menu SpecialFieldViewModel priorityViewModel = new SpecialFieldViewModel(SpecialField.PRIORITY, preferencesService, undoManager); icon = priorityViewModel.getIcon(); // icon.setToolTipText(priorityViewModel.getLocalization()); TABLE_ICONS.put(SpecialField.PRIORITY, icon); // Read icon used for menu SpecialFieldViewModel readViewModel = new SpecialFieldViewModel(SpecialField.READ_STATUS, preferencesService, undoManager); icon = readViewModel.getIcon(); // icon.setToolTipText(readViewModel.getLocalization()); TABLE_ICONS.put(SpecialField.READ_STATUS, icon); // Print icon used for menu SpecialFieldViewModel printedViewModel = new SpecialFieldViewModel(SpecialField.PRINTED, preferencesService, undoManager); icon = printedViewModel.getIcon(); // icon.setToolTipText(printedViewModel.getLocalization()); TABLE_ICONS.put(SpecialField.PRINTED, icon); } public Node getTableIcon(Field field) { JabRefIcon icon = TABLE_ICONS.get(field); if (icon == null) { // LOGGER.info("Error: no table icon defined for type '" + field + "'."); return null; } else { // node should be generated for each call, as nodes can be added to the scene graph only once return icon.getGraphicNode(); } } }
4,831
42.927273
134
java
null
jabref-main/src/main/java/org/jabref/gui/maintable/ColumnPreferences.java
package org.jabref.gui.maintable; import java.util.List; import javafx.collections.FXCollections; import javafx.collections.ObservableList; public class ColumnPreferences { public static final double DEFAULT_COLUMN_WIDTH = 100; public static final double ICON_COLUMN_WIDTH = 16 + 12; // add some additional space to improve appearance private final ObservableList<MainTableColumnModel> columns; private final ObservableList<MainTableColumnModel> columnSortOrder; public ColumnPreferences(List<MainTableColumnModel> columns, List<MainTableColumnModel> columnSortOrder) { this.columns = FXCollections.observableArrayList(columns); this.columnSortOrder = FXCollections.observableArrayList(columnSortOrder); } public ObservableList<MainTableColumnModel> getColumns() { return columns; } public ObservableList<MainTableColumnModel> getColumnSortOrder() { return columnSortOrder; } public void setColumns(List<MainTableColumnModel> list) { columns.clear(); columns.addAll(list); } public void setColumnSortOrder(List<MainTableColumnModel> list) { columnSortOrder.clear(); columnSortOrder.addAll(list); } }
1,259
30.5
110
java
null
jabref-main/src/main/java/org/jabref/gui/maintable/MainTable.java
package org.jabref.gui.maintable; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import javax.swing.undo.UndoManager; import javafx.collections.ListChangeListener; import javafx.scene.control.SelectionMode; import javafx.scene.control.TableColumn; import javafx.scene.control.TableRow; import javafx.scene.control.TableView; import javafx.scene.input.ClipboardContent; import javafx.scene.input.DragEvent; import javafx.scene.input.Dragboard; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseDragEvent; import javafx.scene.input.MouseEvent; import javafx.scene.input.TransferMode; import org.jabref.gui.ClipBoardManager; import org.jabref.gui.DialogService; import org.jabref.gui.DragAndDropDataFormats; import org.jabref.gui.Globals; import org.jabref.gui.LibraryTab; import org.jabref.gui.StateManager; import org.jabref.gui.actions.StandardActions; import org.jabref.gui.edit.EditAction; import org.jabref.gui.externalfiles.ImportHandler; import org.jabref.gui.keyboard.KeyBinding; import org.jabref.gui.keyboard.KeyBindingRepository; import org.jabref.gui.maintable.columns.LibraryColumn; import org.jabref.gui.maintable.columns.MainTableColumn; import org.jabref.gui.util.ControlHelper; import org.jabref.gui.util.CustomLocalDragboard; import org.jabref.gui.util.DefaultTaskExecutor; import org.jabref.gui.util.TaskExecutor; import org.jabref.gui.util.ViewModelTableRowFactory; import org.jabref.logic.importer.FetcherClientException; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.FetcherServerException; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.database.event.EntriesAddedEvent; import org.jabref.model.entry.BibEntry; import org.jabref.model.util.FileUpdateMonitor; import org.jabref.preferences.PreferencesService; import com.google.common.eventbus.Subscribe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MainTable extends TableView<BibEntryTableViewModel> { private static final Logger LOGGER = LoggerFactory.getLogger(MainTable.class); private final LibraryTab libraryTab; private final DialogService dialogService; private final StateManager stateManager; private final BibDatabaseContext database; private final MainTableDataModel model; private final ImportHandler importHandler; private final CustomLocalDragboard localDragboard; private final ClipBoardManager clipBoardManager; private long lastKeyPressTime; private String columnSearchTerm; public MainTable(MainTableDataModel model, LibraryTab libraryTab, BibDatabaseContext database, PreferencesService preferencesService, DialogService dialogService, StateManager stateManager, KeyBindingRepository keyBindingRepository, ClipBoardManager clipBoardManager, TaskExecutor taskExecutor, FileUpdateMonitor fileUpdateMonitor) { super(); this.libraryTab = libraryTab; this.dialogService = dialogService; this.stateManager = stateManager; this.database = Objects.requireNonNull(database); this.model = model; this.clipBoardManager = clipBoardManager; UndoManager undoManager = libraryTab.getUndoManager(); MainTablePreferences mainTablePreferences = preferencesService.getMainTablePreferences(); importHandler = new ImportHandler( database, preferencesService, fileUpdateMonitor, undoManager, stateManager, dialogService, taskExecutor); localDragboard = stateManager.getLocalDragboard(); this.setOnDragOver(this::handleOnDragOverTableView); this.setOnDragDropped(this::handleOnDragDroppedTableView); this.getColumns().addAll( new MainTableColumnFactory( database, preferencesService, preferencesService.getMainTableColumnPreferences(), libraryTab.getUndoManager(), dialogService, stateManager).createColumns()); this.getColumns().removeIf(LibraryColumn.class::isInstance); new ViewModelTableRowFactory<BibEntryTableViewModel>() .withOnMouseClickedEvent((entry, event) -> { if (event.getClickCount() == 2) { libraryTab.showAndEdit(entry.getEntry()); } }) .withContextMenu(entry -> RightClickMenu.create(entry, keyBindingRepository, libraryTab, dialogService, stateManager, preferencesService, undoManager, clipBoardManager, Globals.TASK_EXECUTOR, Globals.journalAbbreviationRepository, Globals.entryTypesManager)) .setOnDragDetected(this::handleOnDragDetected) .setOnDragDropped(this::handleOnDragDropped) .setOnDragOver(this::handleOnDragOver) .setOnDragExited(this::handleOnDragExited) .setOnMouseDragEntered(this::handleOnDragEntered) .install(this); this.getSortOrder().clear(); /* KEEP for debugging purposes for (var colModel : mainTablePreferences.getColumnPreferences().getColumnSortOrder()) { for (var col : this.getColumns()) { var tablecColModel = ((MainTableColumn<?>) col).getModel(); if (tablecColModel.equals(colModel)) { LOGGER.debug("Adding sort order for col {} ", col); this.getSortOrder().add(col); break; } } } */ mainTablePreferences.getColumnPreferences().getColumnSortOrder().forEach(columnModel -> this.getColumns().stream() .map(column -> (MainTableColumn<?>) column) .filter(column -> column.getModel().equals(columnModel)) .findFirst() .ifPresent(column -> this.getSortOrder().add(column))); if (mainTablePreferences.getResizeColumnsToFit()) { this.setColumnResizePolicy(new SmartConstrainedResizePolicy()); } this.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); this.setItems(model.getEntriesFilteredAndSorted()); // Enable sorting model.getEntriesFilteredAndSorted().comparatorProperty().bind(this.comparatorProperty()); this.getStylesheets().add(MainTable.class.getResource("MainTable.css").toExternalForm()); // Store visual state new PersistenceVisualStateTable(this, mainTablePreferences.getColumnPreferences()); setupKeyBindings(keyBindingRepository); this.setOnKeyTyped(key -> { if (this.getSortOrder().isEmpty()) { return; } this.jumpToSearchKey(getSortOrder().get(0), key); }); database.getDatabase().registerListener(this); MainTableColumnFactory rightClickMenuFactory = new MainTableColumnFactory( database, preferencesService, preferencesService.getMainTableColumnPreferences(), libraryTab.getUndoManager(), dialogService, stateManager); // Enable the header right-click menu. new MainTableHeaderContextMenu(this, rightClickMenuFactory).show(true); } /** * This is called, if a user starts typing some characters into the keyboard with focus on main table. The {@link MainTable} will scroll to the cell with the same starting column value and typed string * * @param sortedColumn The sorted column in {@link MainTable} * @param keyEvent The pressed character */ private void jumpToSearchKey(TableColumn<BibEntryTableViewModel, ?> sortedColumn, KeyEvent keyEvent) { if ((keyEvent.getCharacter() == null) || (sortedColumn == null)) { return; } if ((System.currentTimeMillis() - lastKeyPressTime) < 700) { columnSearchTerm += keyEvent.getCharacter().toLowerCase(); } else { columnSearchTerm = keyEvent.getCharacter().toLowerCase(); } lastKeyPressTime = System.currentTimeMillis(); this.getItems().stream() .filter(item -> Optional.ofNullable(sortedColumn.getCellObservableValue(item).getValue()) .map(Object::toString) .orElse("") .toLowerCase() .startsWith(columnSearchTerm)) .findFirst() .ifPresent(item -> { this.scrollTo(item); this.clearAndSelect(item.getEntry()); }); } @Subscribe public void listen(EntriesAddedEvent event) { DefaultTaskExecutor.runInJavaFXThread(() -> clearAndSelect(event.getFirstEntry())); } public void clearAndSelect(BibEntry bibEntry) { getSelectionModel().clearSelection(); findEntry(bibEntry).ifPresent(entry -> { getSelectionModel().select(entry); scrollTo(entry); }); } public void copy() { List<BibEntry> selectedEntries = getSelectedEntries(); if (!selectedEntries.isEmpty()) { try { clipBoardManager.setContent(selectedEntries); dialogService.notify(libraryTab.formatOutputMessage(Localization.lang("Copied"), selectedEntries.size())); } catch (IOException e) { LOGGER.error("Error while copying selected entries to clipboard", e); } } } public void cut() { copy(); libraryTab.delete(true); } private void setupKeyBindings(KeyBindingRepository keyBindings) { EditAction pasteAction = new EditAction(StandardActions.PASTE, libraryTab.frame(), stateManager); EditAction copyAction = new EditAction(StandardActions.COPY, libraryTab.frame(), stateManager); EditAction cutAction = new EditAction(StandardActions.CUT, libraryTab.frame(), stateManager); EditAction deleteAction = new EditAction(StandardActions.DELETE_ENTRY, libraryTab.frame(), stateManager); this.addEventFilter(KeyEvent.KEY_PRESSED, event -> { if (event.getCode() == KeyCode.ENTER) { getSelectedEntries().stream() .findFirst() .ifPresent(libraryTab::showAndEdit); event.consume(); return; } Optional<KeyBinding> keyBinding = keyBindings.mapToKeyBinding(event); if (keyBinding.isPresent()) { switch (keyBinding.get()) { case SELECT_FIRST_ENTRY: clearAndSelectFirst(); event.consume(); break; case SELECT_LAST_ENTRY: clearAndSelectLast(); event.consume(); break; case PASTE: pasteAction.execute(); event.consume(); break; case COPY: copyAction.execute(); event.consume(); break; case CUT: cutAction.execute(); event.consume(); break; case DELETE_ENTRY: deleteAction.execute(); event.consume(); break; default: // Pass other keys to parent } } }); } public void clearAndSelectFirst() { getSelectionModel().clearSelection(); getSelectionModel().selectFirst(); scrollTo(0); } private void clearAndSelectLast() { getSelectionModel().clearSelection(); getSelectionModel().selectLast(); scrollTo(getItems().size() - 1); } public void paste() { List<BibEntry> entriesToAdd; String content = ClipBoardManager.getContents(); entriesToAdd = importHandler.handleBibTeXData(content); if (entriesToAdd.isEmpty()) { entriesToAdd = handleNonBibTeXStringData(content); } if (entriesToAdd.isEmpty()) { return; } for (BibEntry entry : entriesToAdd) { importHandler.importEntryWithDuplicateCheck(database, entry); } } private List<BibEntry> handleNonBibTeXStringData(String data) { try { return this.importHandler.handleStringData(data); } catch (FetcherException exception) { if (exception instanceof FetcherClientException) { dialogService.showInformationDialogAndWait(Localization.lang("Look up identifier"), Localization.lang("No data was found for the identifier")); } else if (exception instanceof FetcherServerException) { dialogService.showInformationDialogAndWait(Localization.lang("Look up identifier"), Localization.lang("Server not available")); } else { dialogService.showErrorDialogAndWait(exception); } return List.of(); } } public void dropEntry(List<BibEntry> entriesToAdd) { for (BibEntry entry : entriesToAdd) { importHandler.importEntryWithDuplicateCheck(database, (BibEntry) entry.clone()); } } private void handleOnDragOver(TableRow<BibEntryTableViewModel> row, BibEntryTableViewModel item, DragEvent event) { if (event.getDragboard().hasFiles()) { event.acceptTransferModes(TransferMode.ANY); ControlHelper.setDroppingPseudoClasses(row, event); } event.consume(); } private void handleOnDragOverTableView(DragEvent event) { if (event.getDragboard().hasFiles()) { event.acceptTransferModes(TransferMode.ANY); } event.consume(); } private void handleOnDragEntered(TableRow<BibEntryTableViewModel> row, BibEntryTableViewModel entry, MouseDragEvent event) { // Support the following gesture to select entries: click on one row -> hold mouse button -> move over other rows // We need to select all items between the starting row and the row where the user currently hovers the mouse over // It is not enough to just select the currently hovered row since then sometimes rows are not marked selected if the user moves to fast @SuppressWarnings("unchecked") TableRow<BibEntryTableViewModel> sourceRow = (TableRow<BibEntryTableViewModel>) event.getGestureSource(); getSelectionModel().selectRange(sourceRow.getIndex(), row.getIndex()); } private void handleOnDragExited(TableRow<BibEntryTableViewModel> row, BibEntryTableViewModel entry, DragEvent dragEvent) { ControlHelper.removeDroppingPseudoClasses(row); } private void handleOnDragDetected(TableRow<BibEntryTableViewModel> row, BibEntryTableViewModel entry, MouseEvent event) { // Start drag'n'drop row.startFullDrag(); List<BibEntry> entries = getSelectionModel().getSelectedItems().stream().map(BibEntryTableViewModel::getEntry).collect(Collectors.toList()); // The following is necessary to initiate the drag and drop in JavaFX, // although we don't need the contents, it does not work without // Drag'n'drop to other tabs use COPY TransferMode, drop to group sidepane use MOVE ClipboardContent content = new ClipboardContent(); Dragboard dragboard = startDragAndDrop(TransferMode.COPY_OR_MOVE); content.put(DragAndDropDataFormats.ENTRIES, ""); dragboard.setContent(content); if (!entries.isEmpty()) { localDragboard.putBibEntries(entries); } event.consume(); } private void handleOnDragDropped(TableRow<BibEntryTableViewModel> row, BibEntryTableViewModel target, DragEvent event) { boolean success = false; if (event.getDragboard().hasFiles()) { List<Path> files = event.getDragboard().getFiles().stream().map(File::toPath).collect(Collectors.toList()); // Different actions depending on where the user releases the drop in the target row // Bottom + top -> import entries // Center -> link files to entry // Depending on the pressed modifier, move/copy/link files to drop target switch (ControlHelper.getDroppingMouseLocation(row, event)) { case TOP, BOTTOM -> importHandler.importFilesInBackground(files).executeWith(Globals.TASK_EXECUTOR); case CENTER -> { BibEntry entry = target.getEntry(); switch (event.getTransferMode()) { case LINK -> { LOGGER.debug("Mode LINK"); // shift on win or no modifier importHandler.getLinker().addFilesToEntry(entry, files); } case MOVE -> { LOGGER.debug("Mode MOVE"); // alt on win importHandler.getLinker().moveFilesToFileDirAndAddToEntry(entry, files, libraryTab.getIndexingTaskManager()); } case COPY -> { LOGGER.debug("Mode Copy"); // ctrl on win importHandler.getLinker().copyFilesToFileDirAndAddToEntry(entry, files, libraryTab.getIndexingTaskManager()); } } } } success = true; } event.setDropCompleted(success); event.consume(); } private void handleOnDragDroppedTableView(DragEvent event) { boolean success = false; if (event.getDragboard().hasFiles()) { List<Path> files = event.getDragboard().getFiles().stream().map(File::toPath).collect(Collectors.toList()); importHandler.importFilesInBackground(files).executeWith(Globals.TASK_EXECUTOR); success = true; } event.setDropCompleted(success); event.consume(); } public void addSelectionListener(ListChangeListener<? super BibEntryTableViewModel> listener) { getSelectionModel().getSelectedItems().addListener(listener); } public MainTableDataModel getTableModel() { return model; } public BibEntry getEntryAt(int row) { return model.getEntriesFilteredAndSorted().get(row).getEntry(); } public List<BibEntry> getSelectedEntries() { return getSelectionModel() .getSelectedItems() .stream() .map(BibEntryTableViewModel::getEntry) .collect(Collectors.toList()); } private Optional<BibEntryTableViewModel> findEntry(BibEntry entry) { return model.getEntriesFilteredAndSorted() .stream() .filter(viewModel -> viewModel.getEntry().equals(entry)) .findFirst(); } }
20,032
39.552632
205
java
null
jabref-main/src/main/java/org/jabref/gui/maintable/MainTableColumnFactory.java
package org.jabref.gui.maintable; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import javax.swing.undo.UndoManager; import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.control.TableColumn; import javafx.scene.control.Tooltip; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.text.Text; import org.jabref.gui.DialogService; import org.jabref.gui.StateManager; import org.jabref.gui.icon.IconTheme; import org.jabref.gui.maintable.columns.FieldColumn; import org.jabref.gui.maintable.columns.FileColumn; import org.jabref.gui.maintable.columns.LibraryColumn; import org.jabref.gui.maintable.columns.LinkedIdentifierColumn; import org.jabref.gui.maintable.columns.MainTableColumn; import org.jabref.gui.maintable.columns.SpecialFieldColumn; import org.jabref.gui.specialfields.SpecialFieldValueViewModel; import org.jabref.gui.util.ValueTableCellFactory; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.LinkedFile; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldFactory; import org.jabref.model.entry.field.SpecialField; import org.jabref.model.groups.AbstractGroup; import org.jabref.model.util.OptionalUtil; import org.jabref.preferences.PreferencesService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MainTableColumnFactory { public static final String STYLE_ICON_COLUMN = "column-icon"; private static final Logger LOGGER = LoggerFactory.getLogger(MainTableColumnFactory.class); private final PreferencesService preferencesService; private final ColumnPreferences columnPreferences; private final BibDatabaseContext database; private final CellFactory cellFactory; private final UndoManager undoManager; private final DialogService dialogService; private final StateManager stateManager; public MainTableColumnFactory(BibDatabaseContext database, PreferencesService preferencesService, ColumnPreferences abstractColumnPrefs, UndoManager undoManager, DialogService dialogService, StateManager stateManager) { this.database = Objects.requireNonNull(database); this.preferencesService = Objects.requireNonNull(preferencesService); this.columnPreferences = abstractColumnPrefs; this.dialogService = dialogService; this.cellFactory = new CellFactory(preferencesService, undoManager); this.undoManager = undoManager; this.stateManager = stateManager; } public TableColumn<BibEntryTableViewModel, ?> createColumn(MainTableColumnModel column) { TableColumn<BibEntryTableViewModel, ?> returnColumn = null; switch (column.getType()) { case INDEX: returnColumn = createIndexColumn(column); break; case GROUPS: returnColumn = createGroupColumn(column); break; case FILES: returnColumn = createFilesColumn(column); break; case LINKED_IDENTIFIER: returnColumn = createIdentifierColumn(column); break; case LIBRARY_NAME: returnColumn = createLibraryColumn(column); break; case EXTRAFILE: if (!column.getQualifier().isBlank()) { returnColumn = createExtraFileColumn(column); } break; case SPECIALFIELD: if (!column.getQualifier().isBlank()) { Field field = FieldFactory.parseField(column.getQualifier()); if (field instanceof SpecialField) { returnColumn = createSpecialFieldColumn(column); } else { LOGGER.warn("Special field type '{}' is unknown. Using normal column type.", column.getQualifier()); returnColumn = createFieldColumn(column); } } break; default: case NORMALFIELD: if (!column.getQualifier().isBlank()) { returnColumn = createFieldColumn(column); } break; } return returnColumn; } public List<TableColumn<BibEntryTableViewModel, ?>> createColumns() { List<TableColumn<BibEntryTableViewModel, ?>> columns = new ArrayList<>(); columnPreferences.getColumns().forEach(column -> { columns.add(createColumn(column)); }); return columns; } public static void setExactWidth(TableColumn<?, ?> column, double width) { column.setMinWidth(width); column.setPrefWidth(width); column.setMaxWidth(width); } /** * Creates a column with a continous number */ private TableColumn<BibEntryTableViewModel, String> createIndexColumn(MainTableColumnModel columnModel) { TableColumn<BibEntryTableViewModel, String> column = new MainTableColumn<>(columnModel); Node header = new Text("#"); header.getStyleClass().add("mainTable-header"); Tooltip.install(header, new Tooltip(MainTableColumnModel.Type.INDEX.getDisplayName())); column.setGraphic(header); column.setStyle("-fx-alignment: CENTER-RIGHT;"); column.setCellValueFactory(cellData -> new ReadOnlyObjectWrapper<>( String.valueOf(cellData.getTableView().getItems().indexOf(cellData.getValue()) + 1))); new ValueTableCellFactory<BibEntryTableViewModel, String>() .withText(text -> text) .install(column); column.setSortable(false); return column; } /** * Creates a column for group color bars. */ private TableColumn<BibEntryTableViewModel, ?> createGroupColumn(MainTableColumnModel columnModel) { TableColumn<BibEntryTableViewModel, List<AbstractGroup>> column = new MainTableColumn<>(columnModel); Node headerGraphic = IconTheme.JabRefIcons.DEFAULT_GROUP_ICON.getGraphicNode(); Tooltip.install(headerGraphic, new Tooltip(Localization.lang("Group color"))); column.setGraphic(headerGraphic); column.getStyleClass().add(STYLE_ICON_COLUMN); setExactWidth(column, ColumnPreferences.ICON_COLUMN_WIDTH); column.setResizable(false); column.setCellValueFactory(cellData -> cellData.getValue().getMatchedGroups()); new ValueTableCellFactory<BibEntryTableViewModel, List<AbstractGroup>>() .withGraphic(this::createGroupColorRegion) .install(column); column.setStyle("-fx-padding: 0 0 0 0;"); column.setSortable(true); return column; } private Node createGroupColorRegion(BibEntryTableViewModel entry, List<AbstractGroup> matchedGroups) { List<Color> groupColors = matchedGroups.stream() .flatMap(group -> OptionalUtil.toStream(group.getColor())) .collect(Collectors.toList()); if (!groupColors.isEmpty()) { HBox container = new HBox(); container.setSpacing(2); container.setMinWidth(10); container.setAlignment(Pos.CENTER_LEFT); container.setPadding(new Insets(0, 2, 0, 2)); groupColors.stream().distinct().forEach(groupColor -> { Rectangle groupRectangle = new Rectangle(); groupRectangle.getStyleClass().add("groupColumnBackground"); groupRectangle.setWidth(3); groupRectangle.setHeight(18); groupRectangle.setFill(groupColor); groupRectangle.setStrokeWidth(1); container.getChildren().add(groupRectangle); }); String matchedGroupsString = matchedGroups.stream() .distinct() .map(AbstractGroup::getName) .collect(Collectors.joining(", ")); Tooltip tooltip = new Tooltip(Localization.lang("Entry is contained in the following groups:") + "\n" + matchedGroupsString); Tooltip.install(container, tooltip); return container; } return new Pane(); } /** * Creates a text column to display any standard field. */ private TableColumn<BibEntryTableViewModel, ?> createFieldColumn(MainTableColumnModel columnModel) { return new FieldColumn(columnModel); } /** * Creates a clickable icons column for DOIs, URLs, URIs and EPrints. */ private TableColumn<BibEntryTableViewModel, Map<Field, String>> createIdentifierColumn(MainTableColumnModel columnModel) { return new LinkedIdentifierColumn(columnModel, cellFactory, database, dialogService, preferencesService, stateManager); } /** * Creates a column that displays a {@link SpecialField} */ private TableColumn<BibEntryTableViewModel, Optional<SpecialFieldValueViewModel>> createSpecialFieldColumn(MainTableColumnModel columnModel) { return new SpecialFieldColumn(columnModel, preferencesService, undoManager); } /** * Creates a column for all the linked files. Instead of creating a column for a single file type, like {@link * #createExtraFileColumn(MainTableColumnModel)} createExtraFileColumn} does, this creates one single column collecting all file links. */ private TableColumn<BibEntryTableViewModel, List<LinkedFile>> createFilesColumn(MainTableColumnModel columnModel) { return new FileColumn(columnModel, database, dialogService, preferencesService); } /** * Creates a column for all the linked files of a single file type. */ private TableColumn<BibEntryTableViewModel, List<LinkedFile>> createExtraFileColumn(MainTableColumnModel columnModel) { return new FileColumn(columnModel, database, dialogService, preferencesService, columnModel.getQualifier()); } /** * Create library column containing the Filename of the library's bib file */ private TableColumn<BibEntryTableViewModel, String> createLibraryColumn(MainTableColumnModel columnModel) { return new LibraryColumn(columnModel); } }
10,997
41.46332
146
java
null
jabref-main/src/main/java/org/jabref/gui/maintable/MainTableColumnModel.java
package org.jabref.gui.maintable; import java.util.EnumSet; import java.util.Objects; import javafx.beans.property.DoubleProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.ReadOnlyStringWrapper; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.scene.control.TableColumn; import org.jabref.gui.util.FieldsUtil; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.field.FieldFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Represents the full internal name of a column in the main table. Consists of two parts: The type of the column and a qualifier, like the * field name to be displayed in the column. */ public class MainTableColumnModel { public static final Character COLUMNS_QUALIFIER_DELIMITER = ':'; private static final Logger LOGGER = LoggerFactory.getLogger(MainTableColumnModel.class); public enum Type { INDEX("index", Localization.lang("Index")), EXTRAFILE("extrafile", Localization.lang("File type")), FILES("files", Localization.lang("Linked files")), GROUPS("groups", Localization.lang("Groups")), LINKED_IDENTIFIER("linked_id", Localization.lang("Linked identifiers")), NORMALFIELD("field"), SPECIALFIELD("special", Localization.lang("Special")), LIBRARY_NAME("library", Localization.lang("Library")); public static final EnumSet<Type> ICON_COLUMNS = EnumSet.of(EXTRAFILE, FILES, GROUPS, LINKED_IDENTIFIER); private final String name; private final String displayName; Type(String name) { this.name = name; this.displayName = name; } Type(String name, String displayName) { this.name = name; this.displayName = displayName; } public String getName() { return name; } public String getDisplayName() { return displayName; } public static Type fromString(String text) { for (Type type : Type.values()) { if (type.getName().equals(text)) { return type; } } LOGGER.warn("Column type '{}' is unknown.", text); return NORMALFIELD; } } private final ObjectProperty<Type> typeProperty = new SimpleObjectProperty<>(); private final StringProperty qualifierProperty = new SimpleStringProperty(); private final DoubleProperty widthProperty = new SimpleDoubleProperty(); private final ObjectProperty<TableColumn.SortType> sortTypeProperty = new SimpleObjectProperty<>(); /** * This is used by the preferences dialog, to initialize available columns the user can add to the table. * * @param type the {@code MainTableColumnModel.Type} of the column, e.g. "NORMALFIELD" or "EXTRAFILE" * @param qualifier the stored qualifier of the column, e.g. "author/editor" */ public MainTableColumnModel(Type type, String qualifier) { Objects.requireNonNull(type); Objects.requireNonNull(qualifier); this.typeProperty.setValue(type); this.qualifierProperty.setValue(qualifier); this.sortTypeProperty.setValue(TableColumn.SortType.ASCENDING); if (Type.ICON_COLUMNS.contains(type)) { this.widthProperty.setValue(ColumnPreferences.ICON_COLUMN_WIDTH); } else { this.widthProperty.setValue(ColumnPreferences.DEFAULT_COLUMN_WIDTH); } } /** * This is used by the preferences dialog, to initialize available basic icon columns, the user can add to the table. * * @param type the {@code MainTableColumnModel.Type} of the column, e.g. "GROUPS" or "LINKED_IDENTIFIER" */ public MainTableColumnModel(Type type) { this(type, ""); } /** * This is used by the preference migrations. * * @param type the {@code MainTableColumnModel.Type} of the column, e.g. "NORMALFIELD" or "GROUPS" * @param qualifier the stored qualifier of the column, e.g. "author/editor" * @param width the stored width of the column */ public MainTableColumnModel(Type type, String qualifier, double width) { this(type, qualifier); this.widthProperty.setValue(width); } public Type getType() { return typeProperty.getValue(); } public String getQualifier() { return qualifierProperty.getValue(); } public String getName() { if (qualifierProperty.getValue().isBlank()) { return typeProperty.getValue().getName(); } else { return typeProperty.getValue().getName() + COLUMNS_QUALIFIER_DELIMITER + qualifierProperty.getValue(); } } public String getDisplayName() { if ((Type.ICON_COLUMNS.contains(typeProperty.getValue()) && qualifierProperty.getValue().isBlank()) || (typeProperty.getValue() == Type.INDEX)) { return typeProperty.getValue().getDisplayName(); } else { return FieldsUtil.getNameWithType(FieldFactory.parseField(qualifierProperty.getValue())); } } public StringProperty nameProperty() { return new ReadOnlyStringWrapper(getDisplayName()); } public double getWidth() { return widthProperty.getValue(); } public DoubleProperty widthProperty() { return widthProperty; } public TableColumn.SortType getSortType() { return sortTypeProperty.getValue(); } public ObjectProperty<TableColumn.SortType> sortTypeProperty() { return sortTypeProperty; } @Override public boolean equals(Object o) { if (this == o) { return true; } if ((o == null) || (getClass() != o.getClass())) { return false; } MainTableColumnModel that = (MainTableColumnModel) o; if (typeProperty.getValue() != that.typeProperty.getValue()) { return false; } return Objects.equals(qualifierProperty.getValue(), that.qualifierProperty.getValue()); } @Override public int hashCode() { return Objects.hash(typeProperty.getValue(), qualifierProperty.getValue()); } /** * This creates a new {@code MainTableColumnModel} out of a given string * * @param rawColumnName the name of the column, e.g. "field:author", or "author" * @return A new {@code MainTableColumnModel} */ public static MainTableColumnModel parse(String rawColumnName) { Objects.requireNonNull(rawColumnName); String[] splittedName = rawColumnName.split(COLUMNS_QUALIFIER_DELIMITER.toString()); Type type = Type.fromString(splittedName[0]); String qualifier = ""; if ((type == Type.NORMALFIELD) || (type == Type.SPECIALFIELD) || (type == Type.EXTRAFILE)) { if (splittedName.length == 1) { qualifier = splittedName[0]; // By default the rawColumnName is parsed as NORMALFIELD } else { qualifier = splittedName[1]; } } return new MainTableColumnModel(type, qualifier); } }
7,405
32.972477
139
java
null
jabref-main/src/main/java/org/jabref/gui/maintable/MainTableDataModel.java
package org.jabref.gui.maintable; import java.util.List; import java.util.Optional; import javafx.beans.binding.Bindings; import javafx.beans.property.IntegerProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.ObservableList; import javafx.collections.transformation.FilteredList; import javafx.collections.transformation.SortedList; import org.jabref.gui.StateManager; import org.jabref.gui.groups.GroupViewMode; import org.jabref.gui.groups.GroupsPreferences; import org.jabref.gui.util.BindingsHelper; import org.jabref.logic.search.SearchQuery; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.groups.GroupTreeNode; import org.jabref.model.search.matchers.MatcherSet; import org.jabref.model.search.matchers.MatcherSets; import org.jabref.preferences.PreferencesService; import com.tobiasdiez.easybind.EasyBind; public class MainTableDataModel { private final FilteredList<BibEntryTableViewModel> entriesFiltered; private final SortedList<BibEntryTableViewModel> entriesSorted; private final ObjectProperty<MainTableFieldValueFormatter> fieldValueFormatter; private final GroupsPreferences groupsPreferences; private final NameDisplayPreferences nameDisplayPreferences; private final BibDatabaseContext bibDatabaseContext; public MainTableDataModel(BibDatabaseContext context, PreferencesService preferencesService, StateManager stateManager) { this.groupsPreferences = preferencesService.getGroupsPreferences(); this.nameDisplayPreferences = preferencesService.getNameDisplayPreferences(); this.bibDatabaseContext = context; this.fieldValueFormatter = new SimpleObjectProperty<>( new MainTableFieldValueFormatter(nameDisplayPreferences, bibDatabaseContext)); ObservableList<BibEntry> allEntries = BindingsHelper.forUI(context.getDatabase().getEntries()); ObservableList<BibEntryTableViewModel> entriesViewModel = EasyBind.mapBacked(allEntries, entry -> new BibEntryTableViewModel(entry, bibDatabaseContext, fieldValueFormatter)); entriesFiltered = new FilteredList<>(entriesViewModel); entriesFiltered.predicateProperty().bind( EasyBind.combine(stateManager.activeGroupProperty(), stateManager.activeSearchQueryProperty(), groupsPreferences.groupViewModeProperty(), (groups, query, groupViewMode) -> entry -> isMatched(groups, query, entry)) ); IntegerProperty resultSize = new SimpleIntegerProperty(); resultSize.bind(Bindings.size(entriesFiltered)); stateManager.setActiveSearchResultSize(context, resultSize); // We need to wrap the list since otherwise sorting in the table does not work entriesSorted = new SortedList<>(entriesFiltered); } private boolean isMatched(ObservableList<GroupTreeNode> groups, Optional<SearchQuery> query, BibEntryTableViewModel entry) { return isMatchedByGroup(groups, entry) && isMatchedBySearch(query, entry); } private boolean isMatchedBySearch(Optional<SearchQuery> query, BibEntryTableViewModel entry) { return query.map(matcher -> matcher.isMatch(entry.getEntry())) .orElse(true); } private boolean isMatchedByGroup(ObservableList<GroupTreeNode> groups, BibEntryTableViewModel entry) { return createGroupMatcher(groups) .map(matcher -> matcher.isMatch(entry.getEntry())) .orElse(true); } private Optional<MatcherSet> createGroupMatcher(List<GroupTreeNode> selectedGroups) { if ((selectedGroups == null) || selectedGroups.isEmpty()) { // No selected group, show all entries return Optional.empty(); } final MatcherSet searchRules = MatcherSets.build( groupsPreferences.getGroupViewMode() == GroupViewMode.INTERSECTION ? MatcherSets.MatcherType.AND : MatcherSets.MatcherType.OR); for (GroupTreeNode node : selectedGroups) { searchRules.addRule(node.getSearchMatcher()); } return Optional.of(searchRules); } public SortedList<BibEntryTableViewModel> getEntriesFilteredAndSorted() { return entriesSorted; } public void refresh() { this.fieldValueFormatter.setValue(new MainTableFieldValueFormatter(nameDisplayPreferences, bibDatabaseContext)); } }
4,657
44.223301
128
java
null
jabref-main/src/main/java/org/jabref/gui/maintable/MainTableFieldValueFormatter.java
package org.jabref.gui.maintable; import java.util.Optional; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.AuthorList; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldProperty; import org.jabref.model.entry.field.OrFields; import static org.jabref.gui.maintable.NameDisplayPreferences.AbbreviationStyle; import static org.jabref.gui.maintable.NameDisplayPreferences.DisplayStyle; public class MainTableFieldValueFormatter { private final DisplayStyle displayStyle; private final AbbreviationStyle abbreviationStyle; private final BibDatabase bibDatabase; public MainTableFieldValueFormatter(NameDisplayPreferences nameDisplayPreferences, BibDatabaseContext bibDatabaseContext) { this.displayStyle = nameDisplayPreferences.getDisplayStyle(); this.abbreviationStyle = nameDisplayPreferences.getAbbreviationStyle(); this.bibDatabase = bibDatabaseContext.getDatabase(); } /** * Format fields for {@link BibEntryTableViewModel}, according to user preferences and with latex translated to * unicode if possible. * * @param fields the fields argument of {@link BibEntryTableViewModel#getFields(OrFields)}. * @param entry the BibEntry of {@link BibEntryTableViewModel}. * @return The formatted name field. */ public String formatFieldsValues(final OrFields fields, final BibEntry entry) { for (Field field : fields) { if (field.getProperties().contains(FieldProperty.PERSON_NAMES) && (displayStyle != DisplayStyle.AS_IS)) { Optional<String> name = entry.getResolvedFieldOrAlias(field, bibDatabase); if (name.isPresent()) { return formatFieldWithAuthorValue(name.get()); } } else { Optional<String> content = entry.getResolvedFieldOrAliasLatexFree(field, bibDatabase); if (content.isPresent()) { return content.get(); } } } return ""; } /** * Format a name field for the table, according to user preferences and with latex expressions translated if * possible. * * @param nameToFormat The contents of the name field. * @return The formatted name field. */ private String formatFieldWithAuthorValue(final String nameToFormat) { if (nameToFormat == null) { return null; } AuthorList authors = AuthorList.parse(nameToFormat); if (((displayStyle == DisplayStyle.FIRSTNAME_LASTNAME) || (displayStyle == DisplayStyle.LASTNAME_FIRSTNAME)) && (abbreviationStyle == AbbreviationStyle.LASTNAME_ONLY)) { return authors.latexFree().getAsLastNames(false); } return switch (displayStyle) { default -> nameToFormat; case FIRSTNAME_LASTNAME -> authors.latexFree().getAsFirstLastNames( abbreviationStyle == AbbreviationStyle.FULL, false); case LASTNAME_FIRSTNAME -> authors.latexFree().getAsLastFirstNames( abbreviationStyle == AbbreviationStyle.FULL, false); case NATBIB -> authors.latexFree().getAsNatbib(); }; } }
3,431
38.906977
127
java
null
jabref-main/src/main/java/org/jabref/gui/maintable/MainTableHeaderContextMenu.java
package org.jabref.gui.maintable; import java.util.ArrayList; import java.util.List; import javafx.collections.ObservableList; import javafx.scene.control.ContextMenu; import javafx.scene.control.RadioMenuItem; import javafx.scene.control.SeparatorMenuItem; import javafx.scene.control.TableColumn; import javafx.scene.layout.StackPane; import org.jabref.gui.maintable.columns.MainTableColumn; public class MainTableHeaderContextMenu extends ContextMenu { private static final int OUT_OF_BOUNDS = -1; MainTable mainTable; MainTableColumnFactory factory; /** * Constructor for the right click menu * */ public MainTableHeaderContextMenu(MainTable mainTable, MainTableColumnFactory factory) { super(); this.mainTable = mainTable; this.factory = factory; constructItems(mainTable); } /** * Handles showing the menu in the cursors position when right-clicked. */ public void show(boolean show) { // TODO: 20/10/2022 unknown bug where issue does not show unless parameter is passed through this method. mainTable.setOnContextMenuRequested(event -> { // Display the menu if header is clicked, otherwise, remove from display. if (!(event.getTarget() instanceof StackPane) && show) { this.show(mainTable, event.getScreenX(), event.getScreenY()); } else if (this.isShowing()) { this.hide(); } event.consume(); }); } /** * Constructs the items for the list and places them in the menu. */ private void constructItems(MainTable mainTable) { // Reset the right-click menu this.getItems().clear(); List<TableColumn<BibEntryTableViewModel, ?>> commonColumns = commonColumns(); // Populate the menu with currently used fields for (TableColumn<BibEntryTableViewModel, ?> column : mainTable.getColumns()) { // Append only if the column has not already been added (a common column) RightClickMenuItem itemToAdd = createMenuItem(column, true); this.getItems().add(itemToAdd); // Remove from remaining common columns pool MainTableColumn searchCol = (MainTableColumn<?>) column; if (isACommonColumn(searchCol)) { commonColumns.removeIf(tableCol -> ((MainTableColumn) tableCol).getModel().equals(searchCol.getModel())); } } SeparatorMenuItem separator = new SeparatorMenuItem(); this.getItems().add(separator); // Append to the menu the current remaining columns in the common columns. for (TableColumn<BibEntryTableViewModel, ?> tableColumn : commonColumns) { RightClickMenuItem itemToAdd = createMenuItem(tableColumn, false); this.getItems().add(itemToAdd); } } /** * Creates an item for the menu constructed with the name/visibility of the table column. * */ @SuppressWarnings("rawtypes") private RightClickMenuItem createMenuItem(TableColumn<BibEntryTableViewModel, ?> column, boolean isDisplaying) { // Gets display name and constructs Radio Menu Item. MainTableColumn tableColumn = (MainTableColumn) column; String displayName = tableColumn.getDisplayName(); return new RightClickMenuItem(displayName, tableColumn, isDisplaying); } /** * Returns the current position of the inputted column in the table (index). * */ private int obtainIndexOfColumn(MainTableColumn searchColumn) { ObservableList<TableColumn<BibEntryTableViewModel, ?>> columns = mainTable.getColumns(); for (int i = 0; i < columns.size(); i++) { TableColumn<BibEntryTableViewModel, ?> column = columns.get(i); MainTableColumnModel model = ((MainTableColumn) column).getModel(); if (model.equals(searchColumn.getModel())) { return i; } } return OUT_OF_BOUNDS; } /** * Adds the column into the MainTable for display. */ @SuppressWarnings("rawtypes") private void addColumn(MainTableColumn tableColumn, int index) { if (index <= OUT_OF_BOUNDS || index >= mainTable.getColumns().size()) { mainTable.getColumns().add(tableColumn); } else { mainTable.getColumns().add(index, tableColumn); } } /** * Removes the column from the MainTable to remove visibility. */ @SuppressWarnings("rawtypes") private void removeColumn(MainTableColumn tableColumn) { mainTable.getColumns().removeIf(tableCol -> ((MainTableColumn) tableCol).getModel().equals(tableColumn.getModel())); } /** * Checks if a column is one of the commonly used columns. */ private boolean isACommonColumn(MainTableColumn tableColumn) { return isColumnInList(tableColumn, commonColumns()); } /** * Determines if a list of TableColumns contains the searched column. */ private boolean isColumnInList(MainTableColumn searchColumn, List<TableColumn<BibEntryTableViewModel, ?>> tableColumns) { for (TableColumn<BibEntryTableViewModel, ?> column: tableColumns) { MainTableColumnModel model = ((MainTableColumn) column).getModel(); if (model.equals(searchColumn.getModel())) { return true; } } return false; } /** * Creates the list of the "commonly used" columns (currently based on the default preferences). */ private List<TableColumn<BibEntryTableViewModel, ?>> commonColumns() { // Qualifier strings String entryTypeQualifier = "entrytype"; String authorEditQualifier = "author/editor"; String titleQualifier = "title"; String yearQualifier = "year"; String journalBookQualifier = "journal/booktitle"; String rankQualifier = "ranking"; String readStatusQualifier = "readstatus"; String priorityQualifier = "priority"; // Create the MainTableColumn Models from qualifiers + types. List<MainTableColumnModel> commonColumns = new ArrayList<>(); commonColumns.add(new MainTableColumnModel(MainTableColumnModel.Type.GROUPS)); commonColumns.add(new MainTableColumnModel(MainTableColumnModel.Type.FILES)); commonColumns.add(new MainTableColumnModel(MainTableColumnModel.Type.LINKED_IDENTIFIER)); commonColumns.add(new MainTableColumnModel(MainTableColumnModel.Type.NORMALFIELD, entryTypeQualifier)); commonColumns.add(new MainTableColumnModel(MainTableColumnModel.Type.NORMALFIELD, authorEditQualifier)); commonColumns.add(new MainTableColumnModel(MainTableColumnModel.Type.NORMALFIELD, titleQualifier)); commonColumns.add(new MainTableColumnModel(MainTableColumnModel.Type.NORMALFIELD, yearQualifier)); commonColumns.add(new MainTableColumnModel(MainTableColumnModel.Type.NORMALFIELD, journalBookQualifier)); commonColumns.add(new MainTableColumnModel(MainTableColumnModel.Type.SPECIALFIELD, rankQualifier)); commonColumns.add(new MainTableColumnModel(MainTableColumnModel.Type.SPECIALFIELD, readStatusQualifier)); commonColumns.add(new MainTableColumnModel(MainTableColumnModel.Type.SPECIALFIELD, priorityQualifier)); // Create the Table Columns from the models using factory methods. List<TableColumn<BibEntryTableViewModel, ?>> commonTableColumns = new ArrayList<>(); for (MainTableColumnModel columnModel: commonColumns) { TableColumn<BibEntryTableViewModel, ?> tableColumn = factory.createColumn(columnModel); commonTableColumns.add(tableColumn); } return commonTableColumns; } /** * RightClickMenuItem: RadioMenuItem holding position in MainTable and its visibility. * */ private class RightClickMenuItem extends RadioMenuItem { private int index; private boolean visibleInTable; RightClickMenuItem(String displayName, MainTableColumn column, boolean isVisible) { super(displayName); setVisibleInTable(isVisible); // Flag item as selected if the item is already in the main table. this.setSelected(isVisible); setIndex(OUT_OF_BOUNDS); // Set action to toggle visibility from main table when item is clicked this.setOnAction(event -> { if (isVisibleInTable()) { setIndex(obtainIndexOfColumn(column)); removeColumn(column); } else { addColumn(column, this.index); setIndex(obtainIndexOfColumn(column)); } setVisibleInTable(!this.visibleInTable); }); } public void setIndex(int index) { this.index = index; } public void setVisibleInTable(boolean visibleInTable) { this.visibleInTable = visibleInTable; } public boolean isVisibleInTable() { return visibleInTable; } } }
9,218
39.434211
125
java
null
jabref-main/src/main/java/org/jabref/gui/maintable/MainTablePreferences.java
package org.jabref.gui.maintable; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; public class MainTablePreferences { private final ColumnPreferences columnPreferences; private final BooleanProperty resizeColumnsToFit = new SimpleBooleanProperty(); private final BooleanProperty extraFileColumnsEnabled = new SimpleBooleanProperty(); public MainTablePreferences(ColumnPreferences columnPreferences, boolean resizeColumnsToFit, boolean extraFileColumnsEnabled) { this.columnPreferences = columnPreferences; this.resizeColumnsToFit.set(resizeColumnsToFit); this.extraFileColumnsEnabled.set(extraFileColumnsEnabled); } public ColumnPreferences getColumnPreferences() { return columnPreferences; } public boolean getResizeColumnsToFit() { return resizeColumnsToFit.get(); } public BooleanProperty resizeColumnsToFitProperty() { return resizeColumnsToFit; } public void setResizeColumnsToFit(boolean resizeColumnsToFit) { this.resizeColumnsToFit.set(resizeColumnsToFit); } public boolean getExtraFileColumnsEnabled() { return extraFileColumnsEnabled.get(); } public BooleanProperty extraFileColumnsEnabledProperty() { return extraFileColumnsEnabled; } public void setExtraFileColumnsEnabled(boolean extraFileColumnsEnabled) { this.extraFileColumnsEnabled.set(extraFileColumnsEnabled); } }
1,564
32.297872
88
java
null
jabref-main/src/main/java/org/jabref/gui/maintable/NameDisplayPreferences.java
package org.jabref.gui.maintable; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; public class NameDisplayPreferences { public enum DisplayStyle { NATBIB, AS_IS, FIRSTNAME_LASTNAME, LASTNAME_FIRSTNAME } public enum AbbreviationStyle { NONE, LASTNAME_ONLY, FULL } private final ObjectProperty<DisplayStyle> displayStyle = new SimpleObjectProperty<>(); private final ObjectProperty<AbbreviationStyle> abbreviationStyle = new SimpleObjectProperty<>(); public NameDisplayPreferences(DisplayStyle displayStyle, AbbreviationStyle abbreviationStyle) { this.displayStyle.set(displayStyle); this.abbreviationStyle.set(abbreviationStyle); } public DisplayStyle getDisplayStyle() { return displayStyle.get(); } public ObjectProperty<DisplayStyle> displayStyleProperty() { return displayStyle; } public void setDisplayStyle(DisplayStyle displayStyle) { this.displayStyle.set(displayStyle); } public AbbreviationStyle getAbbreviationStyle() { return abbreviationStyle.get(); } public ObjectProperty<AbbreviationStyle> abbreviationStyleProperty() { return abbreviationStyle; } public void setAbbreviationStyle(AbbreviationStyle abbreviationStyle) { this.abbreviationStyle.set(abbreviationStyle); } }
1,440
28.408163
101
java
null
jabref-main/src/main/java/org/jabref/gui/maintable/OpenExternalFileAction.java
package org.jabref.gui.maintable; import java.util.LinkedList; import java.util.List; import org.jabref.gui.DialogService; import org.jabref.gui.Globals; import org.jabref.gui.StateManager; import org.jabref.gui.actions.ActionHelper; import org.jabref.gui.actions.SimpleCommand; import org.jabref.gui.fieldeditors.LinkedFileViewModel; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.LinkedFile; import org.jabref.preferences.PreferencesService; public class OpenExternalFileAction extends SimpleCommand { private final int FILES_LIMIT = 10; private final DialogService dialogService; private final StateManager stateManager; private final PreferencesService preferencesService; private final BibEntry entry; private final LinkedFile linkedFile; public OpenExternalFileAction(DialogService dialogService, StateManager stateManager, PreferencesService preferencesService) { this(dialogService, stateManager, preferencesService, null, null); } public OpenExternalFileAction(DialogService dialogService, StateManager stateManager, PreferencesService preferencesService, BibEntry entry, LinkedFile linkedFile) { this.dialogService = dialogService; this.stateManager = stateManager; this.preferencesService = preferencesService; this.entry = entry; this.linkedFile = linkedFile; if (this.linkedFile == null) { this.executable.bind(ActionHelper.hasLinkedFileForSelectedEntries(stateManager) .and(ActionHelper.needsEntriesSelected(stateManager)) ); } else { this.setExecutable(true); } } /** * Open all linked files of the selected entries. If opening too many files, pop out a dialog to ask the user if to continue. * <br> * If some selected entries have linked file and others do not, ignore the latter. */ @Override public void execute() { stateManager.getActiveDatabase().ifPresent(databaseContext -> { if (entry == null) { final List<BibEntry> selectedEntries = stateManager.getSelectedEntries(); List<LinkedFileViewModel> linkedFileViewModelList = new LinkedList<>(); LinkedFileViewModel linkedFileViewModel; for (BibEntry entry : selectedEntries) { for (LinkedFile linkedFile : entry.getFiles()) { linkedFileViewModel = new LinkedFileViewModel( linkedFile, entry, databaseContext, Globals.TASK_EXECUTOR, dialogService, preferencesService); linkedFileViewModelList.add(linkedFileViewModel); } } // ask the user when detecting # of files > FILES_LIMIT if (linkedFileViewModelList.size() > FILES_LIMIT) { boolean continueOpening = dialogService.showConfirmationDialogAndWait(Localization.lang("Opening large number of files"), Localization.lang("You are about to open %0 files. Continue?", linkedFileViewModelList.size()), Localization.lang("Continue"), Localization.lang("Cancel")); if (!continueOpening) { return; } } linkedFileViewModelList.forEach(LinkedFileViewModel::open); } else { LinkedFileViewModel linkedFileViewModel = new LinkedFileViewModel( linkedFile, entry, databaseContext, Globals.TASK_EXECUTOR, dialogService, preferencesService); linkedFileViewModel.open(); } }); } }
4,086
39.87
169
java
null
jabref-main/src/main/java/org/jabref/gui/maintable/OpenFolderAction.java
package org.jabref.gui.maintable; import org.jabref.gui.DialogService; import org.jabref.gui.Globals; import org.jabref.gui.StateManager; import org.jabref.gui.actions.ActionHelper; import org.jabref.gui.actions.SimpleCommand; import org.jabref.gui.fieldeditors.LinkedFileViewModel; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.LinkedFile; import org.jabref.preferences.PreferencesService; public class OpenFolderAction extends SimpleCommand { private final DialogService dialogService; private final StateManager stateManager; private final PreferencesService preferencesService; private final BibEntry entry; private final LinkedFile linkedFile; public OpenFolderAction(DialogService dialogService, StateManager stateManager, PreferencesService preferencesService) { this(dialogService, stateManager, preferencesService, null, null); } public OpenFolderAction(DialogService dialogService, StateManager stateManager, PreferencesService preferencesService, BibEntry entry, LinkedFile linkedFile) { this.dialogService = dialogService; this.stateManager = stateManager; this.preferencesService = preferencesService; this.entry = entry; this.linkedFile = linkedFile; if (this.linkedFile == null) { this.executable.bind(ActionHelper.isFilePresentForSelectedEntry(stateManager, preferencesService)); } else { this.setExecutable(true); } } @Override public void execute() { stateManager.getActiveDatabase().ifPresent(databaseContext -> { if (entry == null) { stateManager.getSelectedEntries().stream().filter(entry -> !entry.getFiles().isEmpty()).forEach(entry -> { LinkedFileViewModel linkedFileViewModel = new LinkedFileViewModel( entry.getFiles().get(0), entry, databaseContext, Globals.TASK_EXECUTOR, dialogService, preferencesService); linkedFileViewModel.openFolder(); }); } else { LinkedFileViewModel linkedFileViewModel = new LinkedFileViewModel( linkedFile, entry, databaseContext, Globals.TASK_EXECUTOR, dialogService, preferencesService); linkedFileViewModel.openFolder(); } }); } }
2,725
39.686567
163
java
null
jabref-main/src/main/java/org/jabref/gui/maintable/OpenUrlAction.java
package org.jabref.gui.maintable; import java.io.IOException; import java.util.List; import java.util.Optional; import javafx.beans.binding.BooleanExpression; 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.gui.desktop.JabRefDesktop; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.StandardField; import org.jabref.preferences.PreferencesService; public class OpenUrlAction extends SimpleCommand { private final DialogService dialogService; private final StateManager stateManager; private final PreferencesService preferences; public OpenUrlAction(DialogService dialogService, StateManager stateManager, PreferencesService preferences) { this.dialogService = dialogService; this.stateManager = stateManager; this.preferences = preferences; BooleanExpression fieldIsSet = ActionHelper.isAnyFieldSetForSelectedEntry( List.of(StandardField.URL, StandardField.DOI, StandardField.URI, StandardField.EPRINT), stateManager); this.executable.bind(ActionHelper.needsEntriesSelected(1, stateManager).and(fieldIsSet)); } @Override public void execute() { stateManager.getActiveDatabase().ifPresent(databaseContext -> { final List<BibEntry> entries = stateManager.getSelectedEntries(); if (entries.size() != 1) { dialogService.notify(Localization.lang("This operation requires exactly one item to be selected.")); return; } BibEntry entry = entries.get(0); // ToDo: Create dialog or menu to chose which one to open // URL - DOI - DOI - EPRINT Optional<String> link = entry.getField(StandardField.EPRINT); Field field = StandardField.EPRINT; if (entry.hasField(StandardField.URI)) { link = entry.getField(StandardField.URI); field = StandardField.URI; } if (entry.hasField(StandardField.ISBN)) { link = entry.getField(StandardField.ISBN); field = StandardField.ISBN; } if (entry.hasField(StandardField.DOI)) { link = entry.getField(StandardField.DOI); field = StandardField.DOI; } if (entry.hasField(StandardField.URL)) { link = entry.getField(StandardField.URL); field = StandardField.URL; } if (link.isPresent()) { try { if (field.equals(StandardField.DOI) && preferences.getDOIPreferences().isUseCustom()) { JabRefDesktop.openCustomDoi(link.get(), preferences, dialogService); } else { JabRefDesktop.openExternalViewer(databaseContext, preferences, link.get(), field, dialogService, entry); } } catch (IOException e) { dialogService.showErrorDialogAndWait(Localization.lang("Unable to open link."), e); } } }); } }
3,336
38.72619
128
java
null
jabref-main/src/main/java/org/jabref/gui/maintable/PersistenceVisualStateTable.java
package org.jabref.gui.maintable; import java.util.stream.Collectors; import javafx.beans.InvalidationListener; import javafx.scene.control.TableView; import org.jabref.gui.maintable.columns.MainTableColumn; /** * Keep track of changes made to the columns (reordering, resorting, resizing). */ public class PersistenceVisualStateTable { protected final TableView<BibEntryTableViewModel> table; protected final ColumnPreferences preferences; public PersistenceVisualStateTable(final TableView<BibEntryTableViewModel> table, ColumnPreferences preferences) { this.table = table; this.preferences = preferences; table.getColumns().addListener((InvalidationListener) obs -> updateColumns()); table.getSortOrder().addListener((InvalidationListener) obs -> updateSortOrder()); // As we store the ColumnModels of the MainTable, we need to add the listener to the ColumnModel properties, // since the value is bound to the model after the listener to the column itself is called. table.getColumns().forEach(col -> ((MainTableColumn<?>) col).getModel().widthProperty().addListener(obs -> updateColumns())); table.getColumns().forEach(col -> ((MainTableColumn<?>) col).getModel().sortTypeProperty().addListener(obs -> updateColumns())); } /** * Stores shown columns, their width and their sortType in preferences. */ private void updateColumns() { preferences.setColumns( table.getColumns().stream() .filter(col -> col instanceof MainTableColumn<?>) .map(column -> ((MainTableColumn<?>) column).getModel()) .collect(Collectors.toList())); } /** * Stores the SortOrder of the Table in the preferences. Cannot be combined with updateColumns, because JavaFX * would provide just an empty list for the sort order on other changes. */ private void updateSortOrder() { preferences.setColumnSortOrder( table.getSortOrder().stream() .filter(col -> col instanceof MainTableColumn<?>) .map(column -> ((MainTableColumn<?>) column).getModel()) .collect(Collectors.toList())); } }
2,304
40.160714
118
java
null
jabref-main/src/main/java/org/jabref/gui/maintable/RightClickMenu.java
package org.jabref.gui.maintable; import javax.swing.undo.UndoManager; import javafx.scene.control.ContextMenu; import javafx.scene.control.Menu; import javafx.scene.control.SeparatorMenuItem; import org.jabref.gui.ClipBoardManager; import org.jabref.gui.DialogService; import org.jabref.gui.LibraryTab; import org.jabref.gui.SendAsKindleEmailAction; import org.jabref.gui.SendAsStandardEmailAction; import org.jabref.gui.StateManager; import org.jabref.gui.actions.ActionFactory; import org.jabref.gui.actions.StandardActions; import org.jabref.gui.edit.CopyMoreAction; import org.jabref.gui.edit.EditAction; import org.jabref.gui.exporter.ExportToClipboardAction; import org.jabref.gui.keyboard.KeyBindingRepository; import org.jabref.gui.linkedfile.AttachFileAction; import org.jabref.gui.linkedfile.AttachFileFromURLAction; import org.jabref.gui.menus.ChangeEntryTypeMenu; import org.jabref.gui.mergeentries.MergeEntriesAction; import org.jabref.gui.mergeentries.MergeWithFetchedEntryAction; import org.jabref.gui.preview.CopyCitationAction; import org.jabref.gui.specialfields.SpecialFieldMenuItemFactory; import org.jabref.gui.util.TaskExecutor; import org.jabref.logic.citationstyle.CitationStyleOutputFormat; import org.jabref.logic.citationstyle.CitationStylePreviewLayout; import org.jabref.logic.journals.JournalAbbreviationRepository; import org.jabref.model.entry.BibEntryTypesManager; import org.jabref.model.entry.field.SpecialField; import org.jabref.preferences.PreferencesService; import org.jabref.preferences.PreviewPreferences; public class RightClickMenu { public static ContextMenu create(BibEntryTableViewModel entry, KeyBindingRepository keyBindingRepository, LibraryTab libraryTab, DialogService dialogService, StateManager stateManager, PreferencesService preferencesService, UndoManager undoManager, ClipBoardManager clipBoardManager, TaskExecutor taskExecutor, JournalAbbreviationRepository abbreviationRepository, BibEntryTypesManager entryTypesManager) { ActionFactory factory = new ActionFactory(keyBindingRepository); ContextMenu contextMenu = new ContextMenu(); contextMenu.getItems().addAll( factory.createMenuItem(StandardActions.COPY, new EditAction(StandardActions.COPY, libraryTab.frame(), stateManager)), createCopySubMenu(factory, dialogService, stateManager, preferencesService, clipBoardManager, abbreviationRepository, taskExecutor), factory.createMenuItem(StandardActions.PASTE, new EditAction(StandardActions.PASTE, libraryTab.frame(), stateManager)), factory.createMenuItem(StandardActions.CUT, new EditAction(StandardActions.CUT, libraryTab.frame(), stateManager)), factory.createMenuItem(StandardActions.MERGE_ENTRIES, new MergeEntriesAction(dialogService, stateManager, preferencesService.getBibEntryPreferences())), factory.createMenuItem(StandardActions.DELETE_ENTRY, new EditAction(StandardActions.DELETE_ENTRY, libraryTab.frame(), stateManager)), new SeparatorMenuItem(), createSendSubMenu(factory, dialogService, stateManager, preferencesService), SpecialFieldMenuItemFactory.createSpecialFieldMenu(SpecialField.RANKING, factory, libraryTab.frame(), dialogService, preferencesService, undoManager, stateManager), SpecialFieldMenuItemFactory.getSpecialFieldSingleItem(SpecialField.RELEVANCE, factory, libraryTab.frame(), dialogService, preferencesService, undoManager, stateManager), SpecialFieldMenuItemFactory.getSpecialFieldSingleItem(SpecialField.QUALITY, factory, libraryTab.frame(), dialogService, preferencesService, undoManager, stateManager), SpecialFieldMenuItemFactory.getSpecialFieldSingleItem(SpecialField.PRINTED, factory, libraryTab.frame(), dialogService, preferencesService, undoManager, stateManager), SpecialFieldMenuItemFactory.createSpecialFieldMenu(SpecialField.PRIORITY, factory, libraryTab.frame(), dialogService, preferencesService, undoManager, stateManager), SpecialFieldMenuItemFactory.createSpecialFieldMenu(SpecialField.READ_STATUS, factory, libraryTab.frame(), dialogService, preferencesService, undoManager, stateManager), new SeparatorMenuItem(), factory.createMenuItem(StandardActions.ATTACH_FILE, new AttachFileAction(libraryTab, dialogService, stateManager, preferencesService.getFilePreferences())), factory.createMenuItem(StandardActions.ATTACH_FILE_FROM_URL, new AttachFileFromURLAction(dialogService, stateManager, taskExecutor, preferencesService)), factory.createMenuItem(StandardActions.OPEN_FOLDER, new OpenFolderAction(dialogService, stateManager, preferencesService)), factory.createMenuItem(StandardActions.OPEN_EXTERNAL_FILE, new OpenExternalFileAction(dialogService, stateManager, preferencesService)), factory.createMenuItem(StandardActions.OPEN_URL, new OpenUrlAction(dialogService, stateManager, preferencesService)), factory.createMenuItem(StandardActions.SEARCH_SHORTSCIENCE, new SearchShortScienceAction(dialogService, stateManager, preferencesService)), new SeparatorMenuItem(), new ChangeEntryTypeMenu(libraryTab.getSelectedEntries(), libraryTab.getBibDatabaseContext(), libraryTab.getUndoManager(), keyBindingRepository, entryTypesManager).asSubMenu(), factory.createMenuItem(StandardActions.MERGE_WITH_FETCHED_ENTRY, new MergeWithFetchedEntryAction(libraryTab, dialogService, stateManager, taskExecutor, preferencesService)) ); return contextMenu; } private static Menu createCopySubMenu(ActionFactory factory, DialogService dialogService, StateManager stateManager, PreferencesService preferencesService, ClipBoardManager clipBoardManager, JournalAbbreviationRepository abbreviationRepository, TaskExecutor taskExecutor) { Menu copySpecialMenu = factory.createMenu(StandardActions.COPY_MORE); copySpecialMenu.getItems().addAll( factory.createMenuItem(StandardActions.COPY_TITLE, new CopyMoreAction(StandardActions.COPY_TITLE, dialogService, stateManager, clipBoardManager, preferencesService, abbreviationRepository)), factory.createMenuItem(StandardActions.COPY_KEY, new CopyMoreAction(StandardActions.COPY_KEY, dialogService, stateManager, clipBoardManager, preferencesService, abbreviationRepository)), factory.createMenuItem(StandardActions.COPY_CITE_KEY, new CopyMoreAction(StandardActions.COPY_CITE_KEY, dialogService, stateManager, clipBoardManager, preferencesService, abbreviationRepository)), factory.createMenuItem(StandardActions.COPY_KEY_AND_TITLE, new CopyMoreAction(StandardActions.COPY_KEY_AND_TITLE, dialogService, stateManager, clipBoardManager, preferencesService, abbreviationRepository)), factory.createMenuItem(StandardActions.COPY_KEY_AND_LINK, new CopyMoreAction(StandardActions.COPY_KEY_AND_LINK, dialogService, stateManager, clipBoardManager, preferencesService, abbreviationRepository)), factory.createMenuItem(StandardActions.COPY_DOI, new CopyMoreAction(StandardActions.COPY_DOI, dialogService, stateManager, clipBoardManager, preferencesService, abbreviationRepository)), factory.createMenuItem(StandardActions.COPY_DOI_URL, new CopyMoreAction(StandardActions.COPY_DOI_URL, dialogService, stateManager, clipBoardManager, preferencesService, abbreviationRepository)), new SeparatorMenuItem() ); // the submenu will behave dependent on what style is currently selected (citation/preview) PreviewPreferences previewPreferences = preferencesService.getPreviewPreferences(); if (previewPreferences.getSelectedPreviewLayout() instanceof CitationStylePreviewLayout) { copySpecialMenu.getItems().addAll( factory.createMenuItem(StandardActions.COPY_CITATION_HTML, new CopyCitationAction(CitationStyleOutputFormat.HTML, dialogService, stateManager, clipBoardManager, taskExecutor, preferencesService, abbreviationRepository)), factory.createMenuItem(StandardActions.COPY_CITATION_TEXT, new CopyCitationAction(CitationStyleOutputFormat.TEXT, dialogService, stateManager, clipBoardManager, taskExecutor, preferencesService, abbreviationRepository))); } else { copySpecialMenu.getItems().add(factory.createMenuItem(StandardActions.COPY_CITATION_PREVIEW, new CopyCitationAction(CitationStyleOutputFormat.HTML, dialogService, stateManager, clipBoardManager, taskExecutor, preferencesService, abbreviationRepository))); } copySpecialMenu.getItems().addAll( new SeparatorMenuItem(), factory.createMenuItem(StandardActions.EXPORT_TO_CLIPBOARD, new ExportToClipboardAction(dialogService, stateManager, clipBoardManager, taskExecutor, preferencesService))); return copySpecialMenu; } private static Menu createSendSubMenu(ActionFactory factory, DialogService dialogService, StateManager stateManager, PreferencesService preferencesService) { Menu sendMenu = factory.createMenu(StandardActions.SEND); sendMenu.getItems().addAll( factory.createMenuItem(StandardActions.SEND_AS_EMAIL, new SendAsStandardEmailAction(dialogService, preferencesService, stateManager)), factory.createMenuItem(StandardActions.SEND_TO_KINDLE, new SendAsKindleEmailAction(dialogService, preferencesService, stateManager)), new SeparatorMenuItem() ); return sendMenu; } }
10,471
72.746479
267
java
null
jabref-main/src/main/java/org/jabref/gui/maintable/SearchShortScienceAction.java
package org.jabref.gui.maintable; import java.io.IOException; import java.util.List; import javafx.beans.binding.BooleanExpression; import org.jabref.gui.DialogService; import org.jabref.gui.StateManager; import org.jabref.gui.actions.SimpleCommand; import org.jabref.gui.desktop.JabRefDesktop; import org.jabref.logic.l10n.Localization; import org.jabref.logic.util.ExternalLinkCreator; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.preferences.PreferencesService; import static org.jabref.gui.actions.ActionHelper.isFieldSetForSelectedEntry; import static org.jabref.gui.actions.ActionHelper.needsEntriesSelected; public class SearchShortScienceAction extends SimpleCommand { private final DialogService dialogService; private final StateManager stateManager; private final PreferencesService preferencesService; public SearchShortScienceAction(DialogService dialogService, StateManager stateManager, PreferencesService preferencesService) { this.dialogService = dialogService; this.stateManager = stateManager; this.preferencesService = preferencesService; BooleanExpression fieldIsSet = isFieldSetForSelectedEntry(StandardField.TITLE, stateManager); this.executable.bind(needsEntriesSelected(1, stateManager).and(fieldIsSet)); } @Override public void execute() { stateManager.getActiveDatabase().ifPresent(databaseContext -> { final List<BibEntry> bibEntries = stateManager.getSelectedEntries(); if (bibEntries.size() != 1) { dialogService.notify(Localization.lang("This operation requires exactly one item to be selected.")); return; } ExternalLinkCreator.getShortScienceSearchURL(bibEntries.get(0)).ifPresent(url -> { try { JabRefDesktop.openExternalViewer(databaseContext, preferencesService, url, StandardField.URL, dialogService, bibEntries.get(0)); } catch (IOException ex) { dialogService.showErrorDialogAndWait(Localization.lang("Unable to open ShortScience."), ex); } }); }); } }
2,233
40.37037
148
java
null
jabref-main/src/main/java/org/jabref/gui/maintable/SmartConstrainedResizePolicy.java
package org.jabref.gui.maintable; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import javafx.scene.control.ResizeFeaturesBase; import javafx.scene.control.TableColumnBase; import javafx.scene.control.TableView; import javafx.util.Callback; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This resize policy is almost the same as {@link TableView#CONSTRAINED_RESIZE_POLICY} * We make sure that the width of all columns sums up to the total width of the table. * However, in contrast to {@link TableView#CONSTRAINED_RESIZE_POLICY} we size the columns initially by their preferred width. */ public class SmartConstrainedResizePolicy implements Callback<TableView.ResizeFeatures, Boolean> { private static final Logger LOGGER = LoggerFactory.getLogger(SmartConstrainedResizePolicy.class); @Override public Boolean call(TableView.ResizeFeatures prop) { if (prop.getColumn() == null) { return initColumnSize(prop.getTable()); } else { return constrainedResize(prop); } } private Boolean initColumnSize(TableView<?> table) { double tableWidth = getContentWidth(table); List<? extends TableColumnBase<?, ?>> visibleLeafColumns = table.getVisibleLeafColumns(); double totalWidth = visibleLeafColumns.stream().mapToDouble(TableColumnBase::getWidth).sum(); if (Math.abs(totalWidth - tableWidth) > 1) { double totalPrefWidth = visibleLeafColumns.stream().mapToDouble(TableColumnBase::getPrefWidth).sum(); double currPrefWidth = 0; if (totalPrefWidth > 0) { for (TableColumnBase col : visibleLeafColumns) { double share = col.getPrefWidth() / totalPrefWidth; double newSize = tableWidth * share; // Just to make sure that we are staying under the total table width (due to rounding errors) currPrefWidth += newSize; if (currPrefWidth > tableWidth) { newSize -= currPrefWidth - tableWidth; currPrefWidth -= tableWidth; } resize(col, newSize - col.getWidth()); } } } return false; } private void resize(TableColumnBase column, double delta) { // We have to use reflection since TableUtil is not visible to us try { // TODO: reflective access, should be removed Class<?> clazz = Class.forName("javafx.scene.control.TableUtil"); Method constrainedResize = clazz.getDeclaredMethod("resize", TableColumnBase.class, double.class); constrainedResize.setAccessible(true); constrainedResize.invoke(null, column, delta); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | ClassNotFoundException e) { LOGGER.error("Could not invoke resize in TableUtil", e); } } private Boolean constrainedResize(TableView.ResizeFeatures<?> prop) { TableView<?> table = prop.getTable(); List<? extends TableColumnBase<?, ?>> visibleLeafColumns = table.getVisibleLeafColumns(); return constrainedResize(prop, false, getContentWidth(table) - 2, visibleLeafColumns); } private Boolean constrainedResize(TableView.ResizeFeatures prop, Boolean isFirstRun, Double contentWidth, List<? extends TableColumnBase<?, ?>> visibleLeafColumns) { // We have to use reflection since TableUtil is not visible to us try { // TODO: reflective access, should be removed Class<?> clazz = Class.forName("javafx.scene.control.TableUtil"); Method constrainedResize = clazz.getDeclaredMethod("constrainedResize", ResizeFeaturesBase.class, Boolean.TYPE, Double.TYPE, List.class); constrainedResize.setAccessible(true); Object returnValue = constrainedResize.invoke(null, prop, isFirstRun, contentWidth, visibleLeafColumns); return (Boolean) returnValue; } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | ClassNotFoundException e) { LOGGER.error("Could not invoke constrainedResize in TableUtil", e); return false; } } private Double getContentWidth(TableView<?> table) { try { // TODO: reflective access, should be removed Field privateStringField = TableView.class.getDeclaredField("contentWidth"); privateStringField.setAccessible(true); return (Double) privateStringField.get(table); } catch (IllegalAccessException | NoSuchFieldException e) { return 0d; } } }
4,904
43.590909
169
java
null
jabref-main/src/main/java/org/jabref/gui/maintable/columns/FieldColumn.java
package org.jabref.gui.maintable.columns; import javafx.beans.value.ObservableValue; import org.jabref.gui.maintable.BibEntryTableViewModel; import org.jabref.gui.maintable.MainTableColumnModel; import org.jabref.gui.util.ValueTableCellFactory; import org.jabref.gui.util.comparator.NumericFieldComparator; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldFactory; import org.jabref.model.entry.field.OrFields; import org.jabref.model.entry.field.UnknownField; import com.google.common.collect.MoreCollectors; /** * A column that displays the text-value of the field */ public class FieldColumn extends MainTableColumn<String> { private final OrFields fields; public FieldColumn(MainTableColumnModel model) { super(model); this.fields = FieldFactory.parseOrFields(model.getQualifier()); setText(getDisplayName()); setCellValueFactory(param -> getFieldValue(param.getValue())); new ValueTableCellFactory<BibEntryTableViewModel, String>() .withText(text -> text) .install(this); if (fields.size() == 1) { // comparator can't parse more than one value Field field = fields.stream().collect(MoreCollectors.onlyElement()); if ((field instanceof UnknownField) || field.isNumeric()) { this.setComparator(new NumericFieldComparator()); } } this.setSortable(true); } /** * Get the table column name to be displayed in the UI * * @return name to be displayed. null if field is empty. */ @Override public String getDisplayName() { return fields.getDisplayName(); } private ObservableValue<String> getFieldValue(BibEntryTableViewModel entry) { if (fields.isEmpty()) { return null; } else { return entry.getFields(fields); } } }
1,938
29.296875
81
java
null
jabref-main/src/main/java/org/jabref/gui/maintable/columns/FileColumn.java
package org.jabref.gui.maintable.columns; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import javafx.scene.Node; import javafx.scene.control.ContextMenu; import javafx.scene.control.MenuItem; import javafx.scene.control.Tooltip; import javafx.scene.input.MouseButton; import org.jabref.gui.DialogService; import org.jabref.gui.Globals; import org.jabref.gui.externalfiletype.ExternalFileType; import org.jabref.gui.externalfiletype.ExternalFileTypes; import org.jabref.gui.fieldeditors.LinkedFileViewModel; import org.jabref.gui.icon.IconTheme; import org.jabref.gui.maintable.BibEntryTableViewModel; import org.jabref.gui.maintable.ColumnPreferences; import org.jabref.gui.maintable.MainTableColumnFactory; import org.jabref.gui.maintable.MainTableColumnModel; import org.jabref.gui.util.ValueTableCellFactory; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.LinkedFile; import org.jabref.preferences.PreferencesService; /** * A column that draws a clickable symbol for either all the files of a defined file type * or a joined column with all the files of any type */ public class FileColumn extends MainTableColumn<List<LinkedFile>> { private final DialogService dialogService; private final BibDatabaseContext database; private final PreferencesService preferencesService; /** * Creates a joined column for all the linked files. */ public FileColumn(MainTableColumnModel model, BibDatabaseContext database, DialogService dialogService, PreferencesService preferencesService) { super(model); this.database = Objects.requireNonNull(database); this.dialogService = dialogService; this.preferencesService = preferencesService; setCommonSettings(); Node headerGraphic = IconTheme.JabRefIcons.FILE.getGraphicNode(); Tooltip.install(headerGraphic, new Tooltip(Localization.lang("Linked files"))); this.setGraphic(headerGraphic); new ValueTableCellFactory<BibEntryTableViewModel, List<LinkedFile>>() .withGraphic(this::createFileIcon) .withTooltip(this::createFileTooltip) .withMenu(this::createFileMenu) .withOnMouseClickedEvent((entry, linkedFiles) -> event -> { if ((event.getButton() == MouseButton.PRIMARY) && (linkedFiles.size() == 1)) { // Only one linked file -> open directly LinkedFileViewModel linkedFileViewModel = new LinkedFileViewModel(linkedFiles.get(0), entry.getEntry(), database, Globals.TASK_EXECUTOR, dialogService, preferencesService); linkedFileViewModel.open(); } }) .install(this); } /** * Creates a column for all the linked files of a single file type. */ public FileColumn(MainTableColumnModel model, BibDatabaseContext database, DialogService dialogService, PreferencesService preferencesService, String fileType) { super(model); this.database = Objects.requireNonNull(database); this.dialogService = dialogService; this.preferencesService = preferencesService; setCommonSettings(); this.setGraphic(ExternalFileTypes.getExternalFileTypeByName(fileType, preferencesService.getFilePreferences()) .map(ExternalFileType::getIcon).orElse(IconTheme.JabRefIcons.FILE) .getGraphicNode()); new ValueTableCellFactory<BibEntryTableViewModel, List<LinkedFile>>() .withGraphic(linkedFiles -> createFileIcon(linkedFiles.stream().filter(linkedFile -> linkedFile.getFileType().equalsIgnoreCase(fileType)).collect(Collectors.toList()))) .install(this); } private void setCommonSettings() { this.setResizable(false); MainTableColumnFactory.setExactWidth(this, ColumnPreferences.ICON_COLUMN_WIDTH); this.getStyleClass().add(MainTableColumnFactory.STYLE_ICON_COLUMN); this.setCellValueFactory(cellData -> cellData.getValue().getLinkedFiles()); } private String createFileTooltip(List<LinkedFile> linkedFiles) { if (linkedFiles.size() > 0) { return Localization.lang("Open file %0", linkedFiles.get(0).getLink()); } return null; } private ContextMenu createFileMenu(BibEntryTableViewModel entry, List<LinkedFile> linkedFiles) { if (linkedFiles.size() <= 1) { return null; } ContextMenu contextMenu = new ContextMenu(); for (LinkedFile linkedFile : linkedFiles) { LinkedFileViewModel linkedFileViewModel = new LinkedFileViewModel(linkedFile, entry.getEntry(), database, Globals.TASK_EXECUTOR, dialogService, preferencesService); MenuItem menuItem = new MenuItem(linkedFileViewModel.getTruncatedDescriptionAndLink(), linkedFileViewModel.getTypeIcon().getGraphicNode()); menuItem.setOnAction(event -> linkedFileViewModel.open()); contextMenu.getItems().add(menuItem); } return contextMenu; } private Node createFileIcon(List<LinkedFile> linkedFiles) { if (linkedFiles.size() > 1) { return IconTheme.JabRefIcons.FILE_MULTIPLE.getGraphicNode(); } else if (linkedFiles.size() == 1) { return ExternalFileTypes.getExternalFileTypeByLinkedFile(linkedFiles.get(0), true, preferencesService.getFilePreferences()) .map(ExternalFileType::getIcon) .orElse(IconTheme.JabRefIcons.FILE) .getGraphicNode(); } else { return null; } } }
6,287
40.642384
135
java
null
jabref-main/src/main/java/org/jabref/gui/maintable/columns/LibraryColumn.java
package org.jabref.gui.maintable.columns; import org.jabref.gui.maintable.BibEntryTableViewModel; import org.jabref.gui.maintable.MainTableColumnModel; import org.jabref.gui.maintable.MainTableColumnModel.Type; import org.jabref.gui.util.ValueTableCellFactory; import org.jabref.logic.l10n.Localization; import org.jabref.logic.util.io.FileUtil; public class LibraryColumn extends MainTableColumn<String> { public LibraryColumn(MainTableColumnModel model) { super(model); setText(Localization.lang("Library")); new ValueTableCellFactory<BibEntryTableViewModel, String>().withText(FileUtil::getBaseName) .install(this); setCellValueFactory(param -> param.getValue().bibDatabaseContextProperty()); } public LibraryColumn() { this(new MainTableColumnModel(Type.LIBRARY_NAME)); } }
906
35.28
99
java
null
jabref-main/src/main/java/org/jabref/gui/maintable/columns/LinkedIdentifierColumn.java
package org.jabref.gui.maintable.columns; import java.io.IOException; import java.util.Map; import javafx.scene.Node; import javafx.scene.control.ContextMenu; import javafx.scene.control.MenuItem; import javafx.scene.control.Tooltip; import javafx.scene.input.MouseButton; import org.jabref.gui.DialogService; import org.jabref.gui.StateManager; import org.jabref.gui.desktop.JabRefDesktop; import org.jabref.gui.icon.IconTheme; import org.jabref.gui.maintable.BibEntryTableViewModel; import org.jabref.gui.maintable.CellFactory; import org.jabref.gui.maintable.ColumnPreferences; import org.jabref.gui.maintable.MainTableColumnFactory; import org.jabref.gui.maintable.MainTableColumnModel; import org.jabref.gui.maintable.OpenUrlAction; import org.jabref.gui.util.ControlHelper; import org.jabref.gui.util.ValueTableCellFactory; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.field.Field; import org.jabref.preferences.PreferencesService; /** * A clickable icons column for DOIs, URLs, URIs and EPrints. */ public class LinkedIdentifierColumn extends MainTableColumn<Map<Field, String>> { private final BibDatabaseContext database; private final CellFactory cellFactory; private final DialogService dialogService; private final PreferencesService preferences; public LinkedIdentifierColumn(MainTableColumnModel model, CellFactory cellFactory, BibDatabaseContext database, DialogService dialogService, PreferencesService preferences, StateManager stateManager) { super(model); this.database = database; this.cellFactory = cellFactory; this.dialogService = dialogService; this.preferences = preferences; Node headerGraphic = IconTheme.JabRefIcons.WWW.getGraphicNode(); Tooltip.install(headerGraphic, new Tooltip(Localization.lang("Linked identifiers"))); this.setGraphic(headerGraphic); this.getStyleClass().add(MainTableColumnFactory.STYLE_ICON_COLUMN); MainTableColumnFactory.setExactWidth(this, ColumnPreferences.ICON_COLUMN_WIDTH); this.setResizable(false); this.setCellValueFactory(cellData -> cellData.getValue().getLinkedIdentifiers()); new ValueTableCellFactory<BibEntryTableViewModel, Map<Field, String>>() .withGraphic(this::createIdentifierGraphic) .withTooltip(this::createIdentifierTooltip) .withMenu(this::createIdentifierMenu) .withOnMouseClickedEvent((entry, linkedFiles) -> event -> { // If we only have one identifer, open directly if ((linkedFiles.size() == 1) && (event.getButton() == MouseButton.PRIMARY)) { new OpenUrlAction(dialogService, stateManager, preferences).execute(); } }) .install(this); } private Node createIdentifierGraphic(Map<Field, String> values) { if (values.size() > 1) { return IconTheme.JabRefIcons.LINK_VARIANT.getGraphicNode(); } else if (values.size() == 1) { return IconTheme.JabRefIcons.LINK.getGraphicNode(); } else { return null; } } private String createIdentifierTooltip(Map<Field, String> values) { StringBuilder identifiers = new StringBuilder(); values.keySet().forEach(field -> identifiers.append(field.getDisplayName()).append(": ").append(values.get(field)).append("\n")); return identifiers.toString(); } private ContextMenu createIdentifierMenu(BibEntryTableViewModel entry, Map<Field, String> values) { ContextMenu contextMenu = new ContextMenu(); if (values.size() <= 1) { return null; } values.keySet().forEach(field -> { MenuItem menuItem = new MenuItem(field.getDisplayName() + ": " + ControlHelper.truncateString(values.get(field), -1, "...", ControlHelper.EllipsisPosition.CENTER), cellFactory.getTableIcon(field)); menuItem.setOnAction(event -> { try { JabRefDesktop.openExternalViewer(database, preferences, values.get(field), field, dialogService, entry.getEntry()); } catch (IOException e) { dialogService.showErrorDialogAndWait(Localization.lang("Unable to open link."), e); } event.consume(); }); contextMenu.getItems().add(menuItem); }); return contextMenu; } }
4,775
41.642857
137
java
null
jabref-main/src/main/java/org/jabref/gui/maintable/columns/MainTableColumn.java
package org.jabref.gui.maintable.columns; import javafx.beans.value.ObservableValue; import javafx.scene.control.TableColumn; import org.jabref.gui.maintable.BibEntryTableViewModel; import org.jabref.gui.maintable.MainTableColumnModel; import org.jabref.gui.util.BindingsHelper; public class MainTableColumn<T> extends TableColumn<BibEntryTableViewModel, T> { private MainTableColumnModel model; public MainTableColumn(MainTableColumnModel model) { this.model = model; BindingsHelper.bindBidirectional( this.widthProperty(), model.widthProperty(), value -> this.setPrefWidth(model.widthProperty().getValue()), value -> model.widthProperty().setValue(this.getWidth())); BindingsHelper.bindBidirectional( this.sortTypeProperty(), (ObservableValue<SortType>) model.sortTypeProperty(), value -> this.setSortType(model.sortTypeProperty().getValue()), value -> model.sortTypeProperty().setValue(this.getSortType())); } public MainTableColumnModel getModel() { return model; } public String getDisplayName() { return model.getDisplayName(); } }
1,243
31.736842
80
java
null
jabref-main/src/main/java/org/jabref/gui/maintable/columns/SpecialFieldColumn.java
package org.jabref.gui.maintable.columns; import java.util.Optional; import javax.swing.undo.UndoManager; import javafx.scene.Node; import javafx.scene.control.ContextMenu; import javafx.scene.control.MenuItem; import javafx.scene.control.Tooltip; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import org.jabref.gui.icon.JabRefIcon; import org.jabref.gui.maintable.BibEntryTableViewModel; import org.jabref.gui.maintable.ColumnPreferences; import org.jabref.gui.maintable.MainTableColumnFactory; import org.jabref.gui.maintable.MainTableColumnModel; import org.jabref.gui.specialfields.SpecialFieldValueViewModel; import org.jabref.gui.specialfields.SpecialFieldViewModel; import org.jabref.gui.specialfields.SpecialFieldsPreferences; import org.jabref.gui.util.OptionalValueTableCellFactory; import org.jabref.gui.util.comparator.RankingFieldComparator; import org.jabref.gui.util.comparator.SpecialFieldComparator; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.FieldFactory; import org.jabref.model.entry.field.SpecialField; import org.jabref.model.entry.field.SpecialFieldValue; import org.jabref.preferences.PreferencesService; import com.tobiasdiez.easybind.EasyBind; import org.controlsfx.control.Rating; /** * A column that displays a SpecialField */ public class SpecialFieldColumn extends MainTableColumn<Optional<SpecialFieldValueViewModel>> { private final PreferencesService preferencesService; private final UndoManager undoManager; public SpecialFieldColumn(MainTableColumnModel model, PreferencesService preferencesService, UndoManager undoManager) { super(model); this.preferencesService = preferencesService; this.undoManager = undoManager; SpecialField specialField = (SpecialField) FieldFactory.parseField(model.getQualifier()); SpecialFieldViewModel specialFieldViewModel = new SpecialFieldViewModel(specialField, preferencesService, undoManager); Node headerGraphic = specialFieldViewModel.getIcon().getGraphicNode(); Tooltip.install(headerGraphic, new Tooltip(specialFieldViewModel.getLocalization())); this.setGraphic(headerGraphic); this.getStyleClass().add(MainTableColumnFactory.STYLE_ICON_COLUMN); if (specialField == SpecialField.RANKING) { MainTableColumnFactory.setExactWidth(this, SpecialFieldsPreferences.COLUMN_RANKING_WIDTH); this.setResizable(false); new OptionalValueTableCellFactory<BibEntryTableViewModel, SpecialFieldValueViewModel>() .withGraphic(this::createSpecialRating) .install(this); } else { MainTableColumnFactory.setExactWidth(this, ColumnPreferences.ICON_COLUMN_WIDTH); this.setResizable(false); if (specialField.isSingleValueField()) { new OptionalValueTableCellFactory<BibEntryTableViewModel, SpecialFieldValueViewModel>() .withGraphic((entry, value) -> createSpecialFieldIcon(value, specialFieldViewModel)) .withOnMouseClickedEvent((entry, value) -> event -> { if (event.getButton() == MouseButton.PRIMARY) { specialFieldViewModel.toggle(entry.getEntry()); } }) .install(this); } else { new OptionalValueTableCellFactory<BibEntryTableViewModel, SpecialFieldValueViewModel>() .withGraphic((entry, value) -> createSpecialFieldIcon(value, specialFieldViewModel)) .withMenu((entry, value) -> createSpecialFieldMenu(entry.getEntry(), specialFieldViewModel)) .install(this); } } this.setCellValueFactory(cellData -> cellData.getValue().getSpecialField(specialField)); if (specialField == SpecialField.RANKING) { this.setComparator(new RankingFieldComparator()); } else { this.setComparator(new SpecialFieldComparator()); } this.setSortable(true); } private Rating createSpecialRating(BibEntryTableViewModel entry, Optional<SpecialFieldValueViewModel> value) { Rating ranking = new Rating(); if (value.isPresent()) { ranking.setRating(value.get().getValue().toRating()); } else { ranking.setRating(0); } ranking.addEventFilter(MouseEvent.MOUSE_CLICKED, event -> { if (event.getButton().equals(MouseButton.PRIMARY) && event.getClickCount() == 2) { ranking.setRating(0); event.consume(); } else if (event.getButton().equals(MouseButton.SECONDARY)) { event.consume(); } }); EasyBind.subscribe(ranking.ratingProperty(), rating -> new SpecialFieldViewModel(SpecialField.RANKING, preferencesService, undoManager) .setSpecialFieldValue(entry.getEntry(), SpecialFieldValue.getRating(rating.intValue()))); return ranking; } private ContextMenu createSpecialFieldMenu(BibEntry entry, SpecialFieldViewModel specialField) { ContextMenu contextMenu = new ContextMenu(); for (SpecialFieldValueViewModel value : specialField.getValues()) { MenuItem menuItem = new MenuItem(value.getMenuString(), value.getIcon().map(JabRefIcon::getGraphicNode).orElse(null)); menuItem.setOnAction(event -> specialField.setSpecialFieldValue(entry, value.getValue())); contextMenu.getItems().add(menuItem); } return contextMenu; } private Node createSpecialFieldIcon(Optional<SpecialFieldValueViewModel> fieldValue, SpecialFieldViewModel specialField) { return fieldValue.flatMap(SpecialFieldValueViewModel::getIcon) .map(JabRefIcon::getGraphicNode) .orElseGet(() -> { Node node = specialField.getEmptyIcon().getGraphicNode(); node.getStyleClass().add("empty-special-field"); return node; }); } }
6,270
43.792857
130
java
null
jabref-main/src/main/java/org/jabref/gui/menus/ChangeEntryTypeAction.java
package org.jabref.gui.menus; import java.util.List; import javax.swing.undo.UndoManager; import javafx.beans.property.ReadOnlyStringProperty; import javafx.beans.property.ReadOnlyStringWrapper; import org.jabref.gui.EntryTypeView; import org.jabref.gui.actions.SimpleCommand; import org.jabref.gui.undo.NamedCompound; import org.jabref.gui.undo.UndoableChangeType; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.types.EntryType; public class ChangeEntryTypeAction extends SimpleCommand { private final EntryType type; private final List<BibEntry> entries; private final UndoManager undoManager; private final ReadOnlyStringWrapper statusMessageProperty; public ChangeEntryTypeAction(EntryType type, List<BibEntry> entries, UndoManager undoManager) { this.type = type; this.entries = entries; this.undoManager = undoManager; this.statusMessageProperty = new ReadOnlyStringWrapper(EntryTypeView.getDescription(type)); } @Override public void execute() { NamedCompound compound = new NamedCompound(Localization.lang("Change entry type")); entries.forEach(e -> e.setType(type) .ifPresent(change -> compound.addEdit(new UndoableChangeType(change)))); undoManager.addEdit(compound); } @Override public String getStatusMessage() { return statusMessage.get(); } @Override public ReadOnlyStringProperty statusMessageProperty() { return statusMessageProperty.getReadOnlyProperty(); } }
1,615
31.32
102
java
null
jabref-main/src/main/java/org/jabref/gui/menus/ChangeEntryTypeMenu.java
package org.jabref.gui.menus; import java.util.Collection; import java.util.List; import java.util.Optional; import javax.swing.undo.UndoManager; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.control.ContextMenu; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.control.SeparatorMenuItem; import org.jabref.gui.actions.ActionFactory; import org.jabref.gui.keyboard.KeyBindingRepository; import org.jabref.logic.l10n.Localization; 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; import org.jabref.model.entry.types.BibtexEntryTypeDefinitions; import org.jabref.model.entry.types.IEEETranEntryTypeDefinitions; public class ChangeEntryTypeMenu { private final List<BibEntry> entries; private final BibDatabaseContext bibDatabaseContext; private final UndoManager undoManager; private final ActionFactory factory; private final BibEntryTypesManager entryTypesManager; public ChangeEntryTypeMenu(List<BibEntry> entries, BibDatabaseContext bibDatabaseContext, UndoManager undoManager, KeyBindingRepository keyBindingRepository, BibEntryTypesManager entryTypesManager) { this.entries = entries; this.bibDatabaseContext = bibDatabaseContext; this.undoManager = undoManager; this.entryTypesManager = entryTypesManager; this.factory = new ActionFactory(keyBindingRepository); } public ContextMenu asContextMenu() { ContextMenu menu = new ContextMenu(); menu.getItems().setAll(getMenuItems(entries, bibDatabaseContext, undoManager)); return menu; } public Menu asSubMenu() { Menu menu = new Menu(Localization.lang("Change entry type")); menu.getItems().setAll(getMenuItems(entries, bibDatabaseContext, undoManager)); return menu; } private ObservableList<MenuItem> getMenuItems(List<BibEntry> entries, BibDatabaseContext bibDatabaseContext, UndoManager undoManager) { ObservableList<MenuItem> items = FXCollections.observableArrayList(); if (bibDatabaseContext.isBiblatexMode()) { // Default BibLaTeX items.addAll(fromEntryTypes(entryTypesManager.getAllTypes(BibDatabaseMode.BIBLATEX), entries, undoManager)); // Custom types createSubMenu(Localization.lang("Custom"), entryTypesManager.getAllCustomTypes(BibDatabaseMode.BIBLATEX), entries, undoManager) .ifPresent(subMenu -> items.addAll(new SeparatorMenuItem(), subMenu )); } else { // Default BibTeX createSubMenu(BibDatabaseMode.BIBTEX.getFormattedName(), BibtexEntryTypeDefinitions.ALL, entries, undoManager) .ifPresent(items::add); // IEEETran createSubMenu("IEEETran", IEEETranEntryTypeDefinitions.ALL, entries, undoManager) .ifPresent(subMenu -> items.addAll( new SeparatorMenuItem(), subMenu )); // Custom types createSubMenu(Localization.lang("Custom"), entryTypesManager.getAllCustomTypes(BibDatabaseMode.BIBTEX), entries, undoManager) .ifPresent(subMenu -> items.addAll( new SeparatorMenuItem(), subMenu )); } return items; } private Optional<Menu> createSubMenu(String text, List<BibEntryType> entryTypes, List<BibEntry> entries, UndoManager undoManager) { Menu subMenu = null; if (!entryTypes.isEmpty()) { subMenu = factory.createMenu(() -> text); subMenu.getItems().addAll(fromEntryTypes(entryTypes, entries, undoManager)); } return Optional.ofNullable(subMenu); } private List<MenuItem> fromEntryTypes(Collection<BibEntryType> types, List<BibEntry> entries, UndoManager undoManager) { return types.stream() .map(BibEntryType::getType) .map(type -> factory.createMenuItem(type::getDisplayName, new ChangeEntryTypeAction(type, entries, undoManager))) .toList(); } }
4,601
39.725664
139
java
null
jabref-main/src/main/java/org/jabref/gui/menus/FileHistoryMenu.java
package org.jabref.gui.menus; import java.nio.file.Files; import java.nio.file.Path; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.control.SeparatorMenuItem; import javafx.scene.input.KeyEvent; import org.jabref.gui.DialogService; import org.jabref.gui.importer.actions.OpenDatabaseAction; import org.jabref.logic.l10n.Localization; import org.jabref.logic.util.io.FileHistory; public class FileHistoryMenu extends Menu { protected final MenuItem clearRecentLibraries; private final FileHistory history; private final DialogService dialogService; private final OpenDatabaseAction openDatabaseAction; public FileHistoryMenu(FileHistory fileHistory, DialogService dialogService, OpenDatabaseAction openDatabaseAction) { setText(Localization.lang("Recent libraries")); this.clearRecentLibraries = new MenuItem(); clearRecentLibraries.setText(Localization.lang("Clear recent libraries")); clearRecentLibraries.setOnAction(event -> clearLibrariesHistory()); this.history = fileHistory; this.dialogService = dialogService; this.openDatabaseAction = openDatabaseAction; if (history.isEmpty()) { setDisable(true); } else { setItems(); } } /** * This method is to use typed letters to access recent libraries in menu. * * @param keyEvent a KeyEvent. * @return false if typed char is invalid or not a number. */ public boolean openFileByKey(KeyEvent keyEvent) { if (keyEvent.getCharacter() == null) { return false; } char key = keyEvent.getCharacter().charAt(0); int num = Character.getNumericValue(key); if (num <= 0 || num > history.size()) { return false; } this.openFile(history.get(Integer.parseInt(keyEvent.getCharacter()) - 1)); return true; } /** * Adds the filename to the top of the menu. If it already is in * the menu, it is merely moved to the top. */ public void newFile(Path file) { history.newFile(file); setItems(); setDisable(false); } private void setItems() { getItems().clear(); for (int index = 0; index < history.size(); index++) { addItem(history.get(index), index + 1); } getItems().addAll( new SeparatorMenuItem(), clearRecentLibraries ); } private void addItem(Path file, int num) { String number = Integer.toString(num); MenuItem item = new MenuItem(number + ". " + file); // By default mnemonic parsing is set to true for anything that is Labeled, if an underscore character // is present, it would create a key combination ALT+the succeeding character (at least for Windows OS) // and the underscore character will be parsed (deleted). // i.e if the file name was called "bib_test.bib", a key combination "ALT+t" will be created // so to avoid this, mnemonic parsing should be set to false to print normally the underscore character. item.setMnemonicParsing(false); item.setOnAction(event -> openFile(file)); getItems().add(item); } public void openFile(Path file) { if (!Files.exists(file)) { this.dialogService.showErrorDialogAndWait( Localization.lang("File not found"), Localization.lang("File not found") + ": " + file); history.removeItem(file); setItems(); return; } openDatabaseAction.openFile(file); } public void clearLibrariesHistory() { history.clear(); setDisable(true); } }
3,796
33.518182
121
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/DiffHighlighting.java
package org.jabref.gui.mergeentries; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import javafx.scene.text.Text; import com.github.difflib.DiffUtils; import com.github.difflib.patch.AbstractDelta; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DiffHighlighting { private static final Logger LOGGER = LoggerFactory.getLogger(DiffHighlighting.class); private DiffHighlighting() { } public static List<Text> generateDiffHighlighting(String baseString, String modifiedString, String separator) { List<String> stringList = Arrays.asList(baseString.split(separator)); List<Text> result = stringList.stream().map(text -> forUnchanged(text + separator)).collect(Collectors.toList()); List<AbstractDelta<String>> deltaList = DiffUtils.diff(stringList, Arrays.asList(modifiedString.split(separator))).getDeltas(); Collections.reverse(deltaList); for (AbstractDelta<String> delta : deltaList) { int startPos = delta.getSource().getPosition(); List<String> lines = delta.getSource().getLines(); int offset = 0; switch (delta.getType()) { case CHANGE: for (String line : lines) { result.set(startPos + offset, forRemoved(line + separator)); offset++; } result.set(startPos + offset - 1, forRemoved(stringList.get((startPos + offset) - 1) + separator)); result.add(startPos + offset, forAdded(String.join(separator, delta.getTarget().getLines()))); break; case DELETE: for (String line : lines) { result.set(startPos + offset, forRemoved(line + separator)); offset++; } break; case INSERT: result.add(delta.getSource().getPosition(), forAdded(String.join(separator, delta.getTarget().getLines()))); break; default: break; } } return result; } public static Text forChanged(String text) { Text node = new Text(text); node.getStyleClass().add("text-changed"); return node; } public static Text forUnchanged(String text) { Text node = new Text(text); node.getStyleClass().add("text-unchanged"); return node; } public static Text forAdded(String text) { Text node = new Text(text); node.getStyleClass().add("text-added"); return node; } public static Text forRemoved(String text) { Text node = new Text(text); node.getStyleClass().add("text-removed"); return node; } public static List<Text> generateSymmetricHighlighting(String baseString, String modifiedString, String separator) { List<String> stringList = Arrays.asList(baseString.split(separator)); List<Text> result = stringList.stream().map(text -> DiffHighlighting.forUnchanged(text + separator)).collect(Collectors.toList()); List<AbstractDelta<String>> deltaList = DiffUtils.diff(stringList, Arrays.asList(modifiedString.split(separator))).getDeltas(); Collections.reverse(deltaList); for (AbstractDelta<String> delta : deltaList) { int startPos = delta.getSource().getPosition(); List<String> lines = delta.getSource().getLines(); int offset = 0; switch (delta.getType()) { case CHANGE: for (String line : lines) { result.set(startPos + offset, forChanged(line + separator)); offset++; } break; case DELETE: for (String line : lines) { result.set(startPos + offset, forAdded(line + separator)); offset++; } break; case INSERT: break; default: break; } } return result; } }
4,309
37.482143
138
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/DiffHighlightingEllipsingTextFlow.java
package org.jabref.gui.mergeentries; import java.util.List; import javafx.beans.DefaultProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.StringProperty; import javafx.beans.value.ChangeListener; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.scene.Node; import javafx.scene.text.Text; import javafx.scene.text.TextFlow; import com.tobiasdiez.easybind.EasyObservableValue; @DefaultProperty("children") public class DiffHighlightingEllipsingTextFlow extends TextFlow { private final static String DEFAULT_ELLIPSIS_STRING = "..."; private StringProperty ellipsisString; private final ObservableList<Node> allChildren = FXCollections.observableArrayList(); private final ChangeListener<Number> sizeChangeListener = (observableValue, number, t1) -> adjustText(); private final ListChangeListener<Node> listChangeListener = this::adjustChildren; private final String fullText; private final EasyObservableValue<String> comparisonString; private final ObjectProperty<DiffMode> diffMode; public DiffHighlightingEllipsingTextFlow(String fullText, EasyObservableValue<String> comparisonString, ObjectProperty<DiffMode> diffMode) { this.fullText = fullText; allChildren.addListener(listChangeListener); widthProperty().addListener(sizeChangeListener); heightProperty().addListener(sizeChangeListener); this.comparisonString = comparisonString; this.diffMode = diffMode; comparisonString.addListener((obs, oldValue, newValue) -> highlightDiff()); diffMode.addListener((obs, oldValue, newValue) -> highlightDiff()); highlightDiff(); } @Override public ObservableList<Node> getChildren() { return allChildren; } private void adjustChildren(ListChangeListener.Change<? extends Node> change) { super.getChildren().clear(); super.getChildren().addAll(allChildren); super.autosize(); adjustText(); } private void adjustText() { if (allChildren.size() == 0) { return; } // remove listeners widthProperty().removeListener(sizeChangeListener); heightProperty().removeListener(sizeChangeListener); if (removeUntilTextFits() && fillUntilOverflowing()) { ellipseUntilTextFits(); } widthProperty().addListener(sizeChangeListener); heightProperty().addListener(sizeChangeListener); } private boolean removeUntilTextFits() { while (getHeight() > getMaxHeight() || getWidth() > getMaxWidth()) { if (super.getChildren().isEmpty()) { // nothing fits return false; } super.getChildren().remove(super.getChildren().size() - 1); super.autosize(); } return true; } private boolean fillUntilOverflowing() { while (getHeight() <= getMaxHeight() && getWidth() <= getMaxWidth()) { if (super.getChildren().size() == allChildren.size()) { if (allChildren.size() > 0) { // all Texts are displayed, let's make sure all chars are as well Node lastChildAsShown = super.getChildren().get(super.getChildren().size() - 1); Node lastChild = allChildren.get(allChildren.size() - 1); if (lastChildAsShown instanceof Text && ((Text) lastChildAsShown).getText().length() < ((Text) lastChild).getText().length()) { ((Text) lastChildAsShown).setText(((Text) lastChild).getText()); } else { // nothing to fill the space with return false; } } } else { super.getChildren().add(allChildren.get(super.getChildren().size())); } super.autosize(); } return true; } private boolean ellipseUntilTextFits() { while (getHeight() > getMaxHeight() || getWidth() > getMaxWidth()) { Text lastChildAsShown = (Text) super.getChildren().remove(super.getChildren().size() - 1); while (getEllipsisString().equals(lastChildAsShown.getText()) || "".equals(lastChildAsShown.getText())) { if (super.getChildren().isEmpty()) { return false; } lastChildAsShown = (Text) super.getChildren().remove(super.getChildren().size() - 1); } Text shortenedChild = new Text(ellipseString(lastChildAsShown.getText())); shortenedChild.getStyleClass().addAll(lastChildAsShown.getStyleClass()); super.getChildren().add(shortenedChild); super.autosize(); } return true; } public void highlightDiff() { allChildren.clear(); if (comparisonString.get() != null && !comparisonString.get().equals(fullText)) { final List<Text> highlightedText = switch (diffMode.getValue()) { case PLAIN -> { Text text = new Text(fullText); text.getStyleClass().add("text-unchanged"); yield List.of(text); } case WORD -> DiffHighlighting.generateDiffHighlighting(comparisonString.get(), fullText, " "); case CHARACTER -> DiffHighlighting.generateDiffHighlighting(comparisonString.get(), fullText, ""); default -> throw new UnsupportedOperationException("Not implemented " + diffMode.getValue()); }; allChildren.addAll(highlightedText); } else { Text text = new Text(fullText); text.getStyleClass().add("text-unchanged"); allChildren.add(text); } super.autosize(); adjustText(); } private String ellipseString(String s) { int spacePos = s.lastIndexOf(' '); if (spacePos <= 0) { return ""; } return s.substring(0, spacePos) + getEllipsisString(); } public final void setEllipsisString(String value) { ellipsisString.set((value == null) ? "" : value); } public String getEllipsisString() { return ellipsisString == null ? DEFAULT_ELLIPSIS_STRING : ellipsisString.get(); } public final StringProperty ellipsisStringProperty() { return ellipsisString; } public String getFullText() { return fullText; } }
6,611
37.666667
147
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/DiffMode.java
package org.jabref.gui.mergeentries; import org.jabref.logic.l10n.Localization; public enum DiffMode { PLAIN(Localization.lang("None")), WORD(Localization.lang("Word by word")), CHARACTER(Localization.lang("Character by character")), WORD_SYMMETRIC(Localization.lang("Symmetric word by word")), CHARACTER_SYMMETRIC(Localization.lang("Symmetric character by character")); private final String text; DiffMode(String text) { this.text = text; } public static DiffMode parse(String name) { try { return DiffMode.valueOf(name); } catch (IllegalArgumentException e) { return WORD; // default } } public String getDisplayText() { return text; } }
759
23.516129
79
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/EntriesMergeResult.java
package org.jabref.gui.mergeentries; import org.jabref.model.entry.BibEntry; public record EntriesMergeResult( BibEntry originalLeftEntry, BibEntry originalRightEntry, BibEntry newLeftEntry, BibEntry newRightEntry, BibEntry mergedEntry ) { }
252
27.111111
132
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/FetchAndMergeEntry.java
package org.jabref.gui.mergeentries; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.TreeSet; import org.jabref.gui.DialogService; import org.jabref.gui.LibraryTab; import org.jabref.gui.undo.NamedCompound; import org.jabref.gui.undo.UndoableChangeType; import org.jabref.gui.undo.UndoableFieldChange; import org.jabref.gui.util.BackgroundTask; import org.jabref.gui.util.TaskExecutor; import org.jabref.logic.importer.EntryBasedFetcher; import org.jabref.logic.importer.FetcherClientException; import org.jabref.logic.importer.FetcherServerException; import org.jabref.logic.importer.IdBasedFetcher; import org.jabref.logic.importer.ImportCleanup; import org.jabref.logic.importer.WebFetcher; import org.jabref.logic.importer.WebFetchers; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldFactory; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.EntryType; import org.jabref.preferences.BibEntryPreferences; import org.jabref.preferences.PreferencesService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Class for fetching and merging bibliographic information */ public class FetchAndMergeEntry { // A list of all field which are supported public static List<Field> SUPPORTED_FIELDS = Arrays.asList(StandardField.DOI, StandardField.EPRINT, StandardField.ISBN); private static final Logger LOGGER = LoggerFactory.getLogger(FetchAndMergeEntry.class); private final DialogService dialogService; private final TaskExecutor taskExecutor; private final BibDatabaseContext bibDatabaseContext; private final PreferencesService preferencesService; private final LibraryTab libraryTab; public FetchAndMergeEntry(LibraryTab libraryTab, TaskExecutor taskExecutor, PreferencesService preferencesService, DialogService dialogService) { this.libraryTab = libraryTab; this.bibDatabaseContext = libraryTab.getBibDatabaseContext(); this.taskExecutor = taskExecutor; this.preferencesService = preferencesService; this.dialogService = dialogService; } public void fetchAndMerge(BibEntry entry) { fetchAndMerge(entry, SUPPORTED_FIELDS); } public void fetchAndMerge(BibEntry entry, Field field) { fetchAndMerge(entry, Collections.singletonList(field)); } public void fetchAndMerge(BibEntry entry, List<Field> fields) { for (Field field : fields) { Optional<String> fieldContent = entry.getField(field); if (fieldContent.isPresent()) { Optional<IdBasedFetcher> fetcher = WebFetchers.getIdBasedFetcherForField(field, preferencesService.getImportFormatPreferences()); if (fetcher.isPresent()) { BackgroundTask.wrap(() -> fetcher.get().performSearchById(fieldContent.get())) .onSuccess(fetchedEntry -> { ImportCleanup cleanup = new ImportCleanup(bibDatabaseContext.getMode()); String type = field.getDisplayName(); if (fetchedEntry.isPresent()) { cleanup.doPostCleanup(fetchedEntry.get()); showMergeDialog(entry, fetchedEntry.get(), fetcher.get(), preferencesService.getBibEntryPreferences()); } else { dialogService.notify(Localization.lang("Cannot get info based on given %0: %1", type, fieldContent.get())); } }) .onFailure(exception -> { LOGGER.error("Error while fetching bibliographic information", exception); if (exception instanceof FetcherClientException) { dialogService.showInformationDialogAndWait(Localization.lang("Fetching information using %0", fetcher.get().getName()), Localization.lang("No data was found for the identifier")); } else if (exception instanceof FetcherServerException) { dialogService.showInformationDialogAndWait(Localization.lang("Fetching information using %0", fetcher.get().getName()), Localization.lang("Server not available")); } else { dialogService.showInformationDialogAndWait(Localization.lang("Fetching information using %0", fetcher.get().getName()), Localization.lang("Error occurred %0", exception.getMessage())); } }) .executeWith(taskExecutor); } } else { dialogService.notify(Localization.lang("No %0 found", field.getDisplayName())); } } } private void showMergeDialog(BibEntry originalEntry, BibEntry fetchedEntry, WebFetcher fetcher, BibEntryPreferences bibEntryPreferences) { MergeEntriesDialog dialog = new MergeEntriesDialog(originalEntry, fetchedEntry, bibEntryPreferences); dialog.setTitle(Localization.lang("Merge entry with %0 information", fetcher.getName())); dialog.setLeftHeaderText(Localization.lang("Original entry")); dialog.setRightHeaderText(Localization.lang("Entry from %0", fetcher.getName())); Optional<BibEntry> mergedEntry = dialogService.showCustomDialogAndWait(dialog).map(EntriesMergeResult::mergedEntry); if (mergedEntry.isPresent()) { NamedCompound ce = new NamedCompound(Localization.lang("Merge entry with %0 information", fetcher.getName())); // Updated the original entry with the new fields Set<Field> jointFields = new TreeSet<>(Comparator.comparing(Field::getName)); jointFields.addAll(mergedEntry.get().getFields()); Set<Field> originalFields = new TreeSet<>(Comparator.comparing(Field::getName)); originalFields.addAll(originalEntry.getFields()); boolean edited = false; // entry type EntryType oldType = originalEntry.getType(); EntryType newType = mergedEntry.get().getType(); if (!oldType.equals(newType)) { originalEntry.setType(newType); ce.addEdit(new UndoableChangeType(originalEntry, oldType, newType)); edited = true; } // fields for (Field field : jointFields) { Optional<String> originalString = originalEntry.getField(field); Optional<String> mergedString = mergedEntry.get().getField(field); if (originalString.isEmpty() || !originalString.equals(mergedString)) { originalEntry.setField(field, mergedString.get()); // mergedString always present ce.addEdit(new UndoableFieldChange(originalEntry, field, originalString.orElse(null), mergedString.get())); edited = true; } } // Remove fields which are not in the merged entry, unless they are internal fields for (Field field : originalFields) { if (!jointFields.contains(field) && !FieldFactory.isInternalField(field)) { Optional<String> originalString = originalEntry.getField(field); originalEntry.clearField(field); ce.addEdit(new UndoableFieldChange(originalEntry, field, originalString.get(), null)); // originalString always present edited = true; } } if (edited) { ce.end(); libraryTab.getUndoManager().addEdit(ce); dialogService.notify(Localization.lang("Updated entry with info from %0", fetcher.getName())); } else { dialogService.notify(Localization.lang("No information added")); } } else { dialogService.notify(Localization.lang("Canceled merging entries")); } } public void fetchAndMerge(BibEntry entry, EntryBasedFetcher fetcher) { BackgroundTask.wrap(() -> fetcher.performSearch(entry).stream().findFirst()) .onSuccess(fetchedEntry -> { if (fetchedEntry.isPresent()) { ImportCleanup cleanup = new ImportCleanup(libraryTab.getBibDatabaseContext().getMode()); cleanup.doPostCleanup(fetchedEntry.get()); showMergeDialog(entry, fetchedEntry.get(), fetcher, preferencesService.getBibEntryPreferences()); } else { dialogService.notify(Localization.lang("Could not find any bibliographic information.")); } }) .onFailure(exception -> { LOGGER.error("Error while fetching entry with {} ", fetcher.getName(), exception); dialogService.showErrorDialogAndWait(Localization.lang("Error while fetching from %0", fetcher.getName()), exception); }) .executeWith(taskExecutor); } }
9,741
52.527473
226
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/MergeEntriesAction.java
package org.jabref.gui.mergeentries; import java.util.List; import java.util.Optional; 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.bibtex.comparator.EntryComparator; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.InternalField; import org.jabref.preferences.BibEntryPreferences; public class MergeEntriesAction extends SimpleCommand { private static final int NUMBER_OF_ENTRIES_NEEDED = 2; private final DialogService dialogService; private final StateManager stateManager; private final BibEntryPreferences bibEntryPreferences; public MergeEntriesAction(DialogService dialogService, StateManager stateManager, BibEntryPreferences bibEntryPreferences) { this.dialogService = dialogService; this.stateManager = stateManager; this.bibEntryPreferences = bibEntryPreferences; this.executable.bind(ActionHelper.needsEntriesSelected(NUMBER_OF_ENTRIES_NEEDED, stateManager)); } @Override public void execute() { if (stateManager.getActiveDatabase().isEmpty()) { return; } // Check if there are two entries selected List<BibEntry> selectedEntries = stateManager.getSelectedEntries(); if (selectedEntries.size() != 2) { // Inform the user to select entries first. dialogService.showInformationDialogAndWait( Localization.lang("Merge entries"), Localization.lang("You have to choose exactly two entries to merge.")); return; } // Store the two entries BibEntry one = selectedEntries.get(0); BibEntry two = selectedEntries.get(1); // compare two entries BibEntry first; BibEntry second; EntryComparator entryComparator = new EntryComparator(false, false, InternalField.KEY_FIELD); if (entryComparator.compare(one, two) <= 0) { first = one; second = two; } else { first = two; second = one; } MergeEntriesDialog dialog = new MergeEntriesDialog(first, second, bibEntryPreferences); dialog.setTitle(Localization.lang("Merge entries")); Optional<EntriesMergeResult> mergeResultOpt = dialogService.showCustomDialogAndWait(dialog); mergeResultOpt.ifPresentOrElse(entriesMergeResult -> { new MergeTwoEntriesAction(entriesMergeResult, stateManager).execute(); dialogService.notify(Localization.lang("Merged entries")); }, () -> dialogService.notify(Localization.lang("Canceled merging entries"))); } }
2,805
37.438356
128
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/MergeEntriesDialog.java
package org.jabref.gui.mergeentries; import javafx.scene.control.ButtonBar; import javafx.scene.control.ButtonType; import org.jabref.gui.mergeentries.newmergedialog.ShowDiffConfig; import org.jabref.gui.mergeentries.newmergedialog.ThreeWayMergeView; import org.jabref.gui.util.BaseDialog; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.BibEntry; import org.jabref.preferences.BibEntryPreferences; public class MergeEntriesDialog extends BaseDialog<EntriesMergeResult> { private final ThreeWayMergeView threeWayMergeView; private final BibEntry one; private final BibEntry two; public MergeEntriesDialog(BibEntry one, BibEntry two, BibEntryPreferences bibEntryPreferences) { threeWayMergeView = new ThreeWayMergeView(one, two, bibEntryPreferences); this.one = one; this.two = two; init(); } /** * Sets up the dialog */ private void init() { this.setX(20); this.setY(20); this.getDialogPane().setContent(threeWayMergeView); // Create buttons ButtonType replaceEntries = new ButtonType(Localization.lang("Merge entries"), ButtonBar.ButtonData.OK_DONE); this.getDialogPane().getButtonTypes().setAll(ButtonType.CANCEL, replaceEntries); this.setResultConverter(buttonType -> { threeWayMergeView.saveConfiguration(); if (buttonType.equals(replaceEntries)) { return new EntriesMergeResult(one, two, threeWayMergeView.getLeftEntry(), threeWayMergeView.getRightEntry(), threeWayMergeView.getMergedEntry()); } else { return null; } }); } public void setLeftHeaderText(String leftHeaderText) { threeWayMergeView.setLeftHeader(leftHeaderText); } public void setRightHeaderText(String rightHeaderText) { threeWayMergeView.setRightHeader(rightHeaderText); } public void configureDiff(ShowDiffConfig diffConfig) { threeWayMergeView.showDiff(diffConfig); } }
2,046
33.116667
161
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/MergeResult.java
package org.jabref.gui.mergeentries; import org.jabref.model.entry.BibEntry; public record MergeResult( BibEntry leftEntry, BibEntry rightEntry, BibEntry mergedEntry ) { }
182
19.333333
69
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/MergeTwoEntriesAction.java
package org.jabref.gui.mergeentries; import java.util.Arrays; import java.util.List; import org.jabref.gui.Globals; import org.jabref.gui.StateManager; import org.jabref.gui.actions.SimpleCommand; import org.jabref.gui.undo.NamedCompound; import org.jabref.gui.undo.UndoableInsertEntries; import org.jabref.gui.undo.UndoableRemoveEntries; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; public class MergeTwoEntriesAction extends SimpleCommand { private final EntriesMergeResult entriesMergeResult; private final StateManager stateManager; public MergeTwoEntriesAction(EntriesMergeResult entriesMergeResult, StateManager stateManager) { this.entriesMergeResult = entriesMergeResult; this.stateManager = stateManager; } @Override public void execute() { if (stateManager.getActiveDatabase().isEmpty()) { return; } BibDatabase database = stateManager.getActiveDatabase().get().getDatabase(); List<BibEntry> entriesToRemove = Arrays.asList(entriesMergeResult.originalLeftEntry(), entriesMergeResult.originalRightEntry()); database.insertEntry(entriesMergeResult.mergedEntry()); database.removeEntries(entriesToRemove); NamedCompound ce = new NamedCompound(Localization.lang("Merge entries")); ce.addEdit(new UndoableInsertEntries(stateManager.getActiveDatabase().get().getDatabase(), entriesMergeResult.mergedEntry())); ce.addEdit(new UndoableRemoveEntries(database, entriesToRemove)); ce.end(); Globals.undoManager.addEdit(ce); } }
1,664
36
136
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/MergeWithFetchedEntryAction.java
package org.jabref.gui.mergeentries; import org.jabref.gui.DialogService; 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.util.TaskExecutor; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.OrFields; import org.jabref.model.entry.field.StandardField; import org.jabref.preferences.PreferencesService; public class MergeWithFetchedEntryAction extends SimpleCommand { private final LibraryTab libraryTab; private final DialogService dialogService; private final StateManager stateManager; private final PreferencesService preferencesService; private final TaskExecutor taskExecutor; public MergeWithFetchedEntryAction(LibraryTab libraryTab, DialogService dialogService, StateManager stateManager, TaskExecutor taskExecutor, PreferencesService preferencesService) { this.libraryTab = libraryTab; this.dialogService = dialogService; this.stateManager = stateManager; this.taskExecutor = taskExecutor; this.preferencesService = preferencesService; this.executable.bind(ActionHelper.needsEntriesSelected(1, stateManager) .and(ActionHelper.isAnyFieldSetForSelectedEntry(FetchAndMergeEntry.SUPPORTED_FIELDS, stateManager))); } @Override public void execute() { if (stateManager.getSelectedEntries().size() != 1) { dialogService.showInformationDialogAndWait( Localization.lang("Merge entry with %0 information", new OrFields(StandardField.DOI, StandardField.ISBN, StandardField.EPRINT).getDisplayName()), Localization.lang("This operation requires exactly one item to be selected.")); } BibEntry originalEntry = stateManager.getSelectedEntries().get(0); new FetchAndMergeEntry(libraryTab, taskExecutor, preferencesService, dialogService).fetchAndMerge(originalEntry); } }
2,086
44.369565
185
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/MultiMergeEntriesView.java
package org.jabref.gui.mergeentries; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.function.Supplier; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.MapChangeListener; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.ButtonBar; import javafx.scene.control.ButtonType; import javafx.scene.control.ComboBox; import javafx.scene.control.ContentDisplay; import javafx.scene.control.Control; import javafx.scene.control.Label; import javafx.scene.control.ProgressIndicator; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.control.TextInputControl; import javafx.scene.control.ToggleButton; import javafx.scene.control.ToggleGroup; import javafx.scene.control.Tooltip; import javafx.scene.input.KeyEvent; import javafx.scene.layout.ColumnConstraints; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import javafx.scene.layout.Region; import javafx.scene.layout.RowConstraints; import javafx.scene.layout.VBox; import javafx.scene.text.TextAlignment; import org.jabref.gui.icon.IconTheme; import org.jabref.gui.util.BaseDialog; import org.jabref.gui.util.BindingsHelper; import org.jabref.gui.util.DefaultTaskExecutor; import org.jabref.gui.util.TaskExecutor; import org.jabref.gui.util.ViewModelListCellFactory; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.fetcher.DoiFetcher; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldFactory; import org.jabref.model.entry.field.StandardField; import org.jabref.preferences.PreferencesService; import com.airhacks.afterburner.views.ViewLoader; import com.tobiasdiez.easybind.EasyBind; import com.tobiasdiez.easybind.EasyObservableValue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MultiMergeEntriesView extends BaseDialog<BibEntry> { private static final Logger LOGGER = LoggerFactory.getLogger(MultiMergeEntriesView.class); // LEFT @FXML private ScrollPane leftScrollPane; @FXML private VBox fieldHeader; // CENTER @FXML private ScrollPane topScrollPane; @FXML private HBox supplierHeader; @FXML private ScrollPane centerScrollPane; @FXML private GridPane optionsGrid; // RIGHT @FXML private ScrollPane rightScrollPane; @FXML private VBox fieldEditor; @FXML private Label failedSuppliers; @FXML private ComboBox<DiffMode> diffMode; private final ToggleGroup headerToggleGroup = new ToggleGroup(); private final HashMap<Field, FieldRow> fieldRows = new HashMap<>(); private final MultiMergeEntriesViewModel viewModel; private final TaskExecutor taskExecutor; private final PreferencesService preferences; public MultiMergeEntriesView(PreferencesService preferences, TaskExecutor taskExecutor) { this.preferences = preferences; this.taskExecutor = taskExecutor; viewModel = new MultiMergeEntriesViewModel(); ViewLoader.view(this) .load() .setAsDialogPane(this); ButtonType mergeEntries = new ButtonType(Localization.lang("Merge entries"), ButtonBar.ButtonData.OK_DONE); this.getDialogPane().getButtonTypes().setAll(ButtonType.CANCEL, mergeEntries); this.setResultConverter(viewModel::resultConverter); viewModel.entriesProperty().addListener((ListChangeListener<MultiMergeEntriesViewModel.EntrySource>) c -> { while (c.next()) { if (c.wasAdded()) { for (MultiMergeEntriesViewModel.EntrySource entrySourceColumn : c.getAddedSubList()) { addColumn(entrySourceColumn); } } } }); viewModel.mergedEntryProperty().get().getFieldsObservable().addListener((MapChangeListener<Field, String>) change -> { if (change.wasAdded() && !fieldRows.containsKey(change.getKey())) { FieldRow fieldRow = new FieldRow( change.getKey(), viewModel.mergedEntryProperty().get().getFields().size() - 1); fieldRows.put(change.getKey(), fieldRow); } }); } @FXML public void initialize() { topScrollPane.hvalueProperty().bindBidirectional(centerScrollPane.hvalueProperty()); leftScrollPane.vvalueProperty().bindBidirectional(centerScrollPane.vvalueProperty()); rightScrollPane.vvalueProperty().bindBidirectional(centerScrollPane.vvalueProperty()); viewModel.failedSuppliersProperty().addListener((obs, oldValue, newValue) -> failedSuppliers.setText(viewModel.failedSuppliersProperty().get().isEmpty() ? "" : Localization.lang( "Could not extract Metadata from: %0", String.join(", ", viewModel.failedSuppliersProperty()) )) ); fillDiffModes(); } private void fillDiffModes() { diffMode.setItems(FXCollections.observableList(List.of( DiffMode.PLAIN, DiffMode.WORD, DiffMode.CHARACTER))); new ViewModelListCellFactory<DiffMode>() .withText(DiffMode::getDisplayText) .install(diffMode); diffMode.setValue(preferences.getGuiPreferences().getMergeDiffMode()); EasyBind.subscribe(this.diffMode.valueProperty(), mode -> preferences.getGuiPreferences().setMergeDiffMode(mode)); } private void addColumn(MultiMergeEntriesViewModel.EntrySource entrySourceColumn) { // add header int columnIndex = supplierHeader.getChildren().size(); ToggleButton header = generateEntryHeader(entrySourceColumn, columnIndex); header.getStyleClass().add("toggle-button"); HBox.setHgrow(header, Priority.ALWAYS); supplierHeader.getChildren().add(header); header.setMinWidth(250); // setup column constraints ColumnConstraints constraint = new ColumnConstraints(); constraint.setMinWidth(Control.USE_PREF_SIZE); constraint.setMaxWidth(Control.USE_PREF_SIZE); constraint.prefWidthProperty().bind(header.widthProperty()); optionsGrid.getColumnConstraints().add(constraint); if (!entrySourceColumn.isLoadingProperty().getValue()) { writeBibEntryToColumn(entrySourceColumn, columnIndex); } else { header.setDisable(true); entrySourceColumn.isLoadingProperty().addListener((observable, oldValue, newValue) -> { if (!newValue && entrySourceColumn.entryProperty().get() != null) { writeBibEntryToColumn(entrySourceColumn, columnIndex); header.setDisable(false); } }); } } private ToggleButton generateEntryHeader(MultiMergeEntriesViewModel.EntrySource column, int columnIndex) { ToggleButton header = new ToggleButton(); header.setToggleGroup(headerToggleGroup); header.textProperty().bind(column.titleProperty()); setupSourceButtonAction(header, columnIndex); if (column.isLoadingProperty().getValue()) { ProgressIndicator progressIndicator = new ProgressIndicator(-1); progressIndicator.setPrefHeight(20); progressIndicator.setMinHeight(Control.USE_PREF_SIZE); progressIndicator.setMaxHeight(Control.USE_PREF_SIZE); header.setGraphic(progressIndicator); progressIndicator.visibleProperty().bind(column.isLoadingProperty()); } column.isLoadingProperty().addListener((obs, oldValue, newValue) -> { if (!newValue) { header.setGraphic(null); if (column.entryProperty().get() == null) { header.setMinWidth(0); header.setMaxWidth(0); header.setVisible(false); } } }); return header; } /** * Adds ToggleButtons for all fields that are set for this BibEntry * * @param entrySourceColumn the entry to write * @param columnIndex the index of the column to write this entry to */ private void writeBibEntryToColumn(MultiMergeEntriesViewModel.EntrySource entrySourceColumn, int columnIndex) { for (Map.Entry<Field, String> entry : entrySourceColumn.entryProperty().get().getFieldsObservable().entrySet()) { Field key = entry.getKey(); String value = entry.getValue(); Cell cell = new Cell(value, key, columnIndex); optionsGrid.add(cell, columnIndex, fieldRows.get(key).rowIndex); } } /** * Set up the button that displays the name of the source so that if it is clicked, all toggles in that column are * selected. * * @param sourceButton the header button to setup * @param column the column this button is heading */ private void setupSourceButtonAction(ToggleButton sourceButton, int column) { sourceButton.selectedProperty().addListener((observable, oldValue, newValue) -> { if (newValue) { optionsGrid.getChildrenUnmodifiable().stream() .filter(node -> GridPane.getColumnIndex(node) == column) .filter(HBox.class::isInstance) .forEach(hbox -> ((HBox) hbox).getChildrenUnmodifiable().stream() .filter(ToggleButton.class::isInstance) .forEach(toggleButton -> ((ToggleButton) toggleButton).setSelected(true))); sourceButton.setSelected(true); } }); } /** * Checks if the Field can be multiline * * @param field the field to be checked * @return true if the field may be multiline, false otherwise */ private boolean isMultilineField(Field field) { if (field.equals(StandardField.DOI)) { return false; } return FieldFactory.isMultiLineField(field, preferences.getFieldPreferences().getNonWrappableFields()); } private class Cell extends HBox { private final String content; public Cell(String content, Field field, int columnIndex) { this.content = content; /* If this is not explicitly done on the JavaFX thread, the bindings to the text fields don't work properly. The text only shows up after one text in that same row is selected by the user. */ DefaultTaskExecutor.runInJavaFXThread(() -> { FieldRow row = fieldRows.get(field); prefWidthProperty().bind(((Region) supplierHeader.getChildren().get(columnIndex)).widthProperty()); setMinWidth(Control.USE_PREF_SIZE); setMaxWidth(Control.USE_PREF_SIZE); prefHeightProperty().bind(((Region) fieldEditor.getChildren().get(row.rowIndex)).heightProperty()); setMinHeight(Control.USE_PREF_SIZE); setMaxHeight(Control.USE_PREF_SIZE); // Button ToggleButton cellButton = new ToggleButton(); cellButton.prefHeightProperty().bind(heightProperty()); cellButton.setMinHeight(Control.USE_PREF_SIZE); cellButton.setMaxHeight(Control.USE_PREF_SIZE); cellButton.setGraphicTextGap(0); getChildren().add(cellButton); cellButton.maxWidthProperty().bind(widthProperty()); HBox.setHgrow(cellButton, Priority.ALWAYS); // Text DiffHighlightingEllipsingTextFlow buttonText = new DiffHighlightingEllipsingTextFlow(content, viewModel.mergedEntryProperty().get().getFieldBinding(field).asOrdinary(), diffMode.valueProperty()); buttonText.maxWidthProperty().bind(widthProperty().add(-10)); buttonText.maxHeightProperty().bind(heightProperty()); cellButton.setGraphic(buttonText); cellButton.setContentDisplay(ContentDisplay.GRAPHIC_ONLY); cellButton.setContentDisplay(ContentDisplay.CENTER); // Tooltip Tooltip buttonTooltip = new Tooltip(content); buttonTooltip.setWrapText(true); buttonTooltip.prefWidthProperty().bind(widthProperty()); buttonTooltip.setTextAlignment(TextAlignment.LEFT); cellButton.setTooltip(buttonTooltip); cellButton.setToggleGroup(row.toggleGroup); if (row.toggleGroup.getSelectedToggle() == null) { cellButton.setSelected(true); } if (field.equals(StandardField.DOI)) { Button doiButton = IconTheme.JabRefIcons.LOOKUP_IDENTIFIER.asButton(); HBox.setHgrow(doiButton, Priority.NEVER); doiButton.prefHeightProperty().bind(cellButton.heightProperty()); doiButton.setMinHeight(Control.USE_PREF_SIZE); doiButton.setMaxHeight(Control.USE_PREF_SIZE); getChildren().add(doiButton); doiButton.setOnAction(event -> { DoiFetcher doiFetcher = new DoiFetcher(preferences.getImportFormatPreferences()); doiButton.setDisable(true); addSource(Localization.lang("From DOI"), () -> { try { return doiFetcher.performSearchById(content).get(); } catch (FetcherException | NoSuchElementException e) { LOGGER.warn("Failed to fetch BibEntry for DOI {}", content, e); return null; } }); }); } }); } public String getContent() { return content; } } public void addSource(String title, BibEntry entry) { viewModel.addSource(new MultiMergeEntriesViewModel.EntrySource(title, entry)); } public void addSource(String title, Supplier<BibEntry> supplier) { viewModel.addSource(new MultiMergeEntriesViewModel.EntrySource(title, supplier, taskExecutor)); } private class FieldRow { public final ToggleGroup toggleGroup = new ToggleGroup(); private final TextInputControl fieldEditorCell; private final int rowIndex; // Reference needs to be kept, since java garbage collection would otherwise destroy the subscription @SuppressWarnings("FieldCanBeLocal") private EasyObservableValue<String> fieldBinding; public FieldRow(Field field, int rowIndex) { this.rowIndex = rowIndex; // setup field editor column entry boolean isMultiLine = isMultilineField(field); if (isMultiLine) { fieldEditorCell = new TextArea(); ((TextArea) fieldEditorCell).setWrapText(true); } else { fieldEditorCell = new TextField(); } addRow(field); fieldEditorCell.addEventFilter(KeyEvent.KEY_PRESSED, event -> toggleGroup.selectToggle(null)); toggleGroup.selectedToggleProperty().addListener((obs, oldValue, newValue) -> { if (newValue == null) { viewModel.mergedEntryProperty().get().setField(field, ""); } else { viewModel.mergedEntryProperty().get().setField(field, ((DiffHighlightingEllipsingTextFlow) ((ToggleButton) newValue).getGraphic()).getFullText()); headerToggleGroup.selectToggle(null); } }); } /** * Adds a row that represents this field * * @param field the field to add to the view as a new row in the table */ private void addRow(Field field) { VBox.setVgrow(fieldEditorCell, Priority.ALWAYS); fieldBinding = viewModel.mergedEntryProperty().get().getFieldBinding(field).asOrdinary(); BindingsHelper.bindBidirectional( fieldEditorCell.textProperty(), fieldBinding, text -> { if (text != null) { fieldEditorCell.setText(text); } }, binding -> { if (binding != null) { viewModel.mergedEntryProperty().get().setField(field, binding); } }); fieldEditorCell.setMaxHeight(Double.MAX_VALUE); VBox.setVgrow(fieldEditorCell, Priority.ALWAYS); fieldEditor.getChildren().add(fieldEditorCell); // setup header label Label fieldHeaderLabel = new Label(field.getDisplayName()); fieldHeaderLabel.prefHeightProperty().bind(fieldEditorCell.heightProperty()); fieldHeaderLabel.setMaxWidth(Control.USE_PREF_SIZE); fieldHeaderLabel.setMinWidth(Control.USE_PREF_SIZE); fieldHeader.getChildren().add(fieldHeaderLabel); // setup RowConstraints RowConstraints constraint = new RowConstraints(); constraint.setMinHeight(Control.USE_PREF_SIZE); constraint.setMaxHeight(Control.USE_PREF_SIZE); constraint.prefHeightProperty().bind(fieldEditorCell.heightProperty()); optionsGrid.getRowConstraints().add(constraint); } } }
18,164
41.441589
211
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/MultiMergeEntriesViewModel.java
package org.jabref.gui.mergeentries; import java.util.Map; import java.util.function.Supplier; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ListProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleListProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.collections.FXCollections; import javafx.scene.control.ButtonType; import org.jabref.gui.AbstractViewModel; import org.jabref.gui.util.BackgroundTask; import org.jabref.gui.util.TaskExecutor; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; public class MultiMergeEntriesViewModel extends AbstractViewModel { private final ListProperty<EntrySource> entries = new SimpleListProperty<>(FXCollections.observableArrayList()); private final ObjectProperty<BibEntry> mergedEntry = new SimpleObjectProperty<>(new BibEntry()); private final ListProperty<String> failedSuppliers = new SimpleListProperty<>(FXCollections.observableArrayList()); public void addSource(EntrySource entrySource) { if (!entrySource.isLoading.getValue()) { updateFields(entrySource.entry.get()); } else { entrySource.isLoading.addListener((observable, oldValue, newValue) -> { if (!newValue) { updateFields(entrySource.entry.get()); if (entrySource.entryProperty().get() == null) { failedSuppliers.add(entrySource.titleProperty().get()); } } }); } entries.add(entrySource); } public void updateFields(BibEntry entry) { if (entry == null) { return; } for (Map.Entry<Field, String> fieldEntry : entry.getFieldMap().entrySet()) { // make sure there is a row for the field if (!mergedEntry.get().getFieldsObservable().containsKey(fieldEntry.getKey())) { mergedEntry.get().setField(fieldEntry.getKey(), fieldEntry.getValue()); } } } public BibEntry resultConverter(ButtonType button) { if (button == ButtonType.CANCEL) { return null; } return mergedEntry.get(); } public ListProperty<EntrySource> entriesProperty() { return entries; } public ObjectProperty<BibEntry> mergedEntryProperty() { return mergedEntry; } public ListProperty<String> failedSuppliersProperty() { return failedSuppliers; } public static class EntrySource { private final StringProperty title = new SimpleStringProperty(""); private final ObjectProperty<BibEntry> entry = new SimpleObjectProperty<>(); private final BooleanProperty isLoading = new SimpleBooleanProperty(false); public EntrySource(String title, Supplier<BibEntry> entrySupplier, TaskExecutor taskExecutor) { this.title.set(title); isLoading.set(true); BackgroundTask.wrap(entrySupplier::get) .onSuccess(value -> { entry.set(value); isLoading.set(false); }) .executeWith(taskExecutor); } public EntrySource(String title, BibEntry entry) { this.title.set(title); this.entry.set(entry); } public StringProperty titleProperty() { return title; } public ObjectProperty<BibEntry> entryProperty() { return entry; } public BooleanProperty isLoadingProperty() { return isLoading; } } }
3,868
33.238938
119
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/newmergedialog/DiffMethod.java
package org.jabref.gui.mergeentries.newmergedialog; public interface DiffMethod { public String separator(); }
116
18.5
51
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/newmergedialog/FieldRowView.java
package org.jabref.gui.mergeentries.newmergedialog; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ReadOnlyStringProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.scene.control.ToggleGroup; import javafx.scene.layout.GridPane; import org.jabref.gui.mergeentries.newmergedialog.FieldRowViewModel.Selection; import org.jabref.gui.mergeentries.newmergedialog.cell.FieldNameCell; import org.jabref.gui.mergeentries.newmergedialog.cell.FieldValueCell; import org.jabref.gui.mergeentries.newmergedialog.cell.MergedFieldCell; import org.jabref.gui.mergeentries.newmergedialog.cell.sidebuttons.ToggleMergeUnmergeButton; import org.jabref.gui.mergeentries.newmergedialog.diffhighlighter.SplitDiffHighlighter; import org.jabref.gui.mergeentries.newmergedialog.diffhighlighter.UnifiedDiffHighlighter; import org.jabref.gui.mergeentries.newmergedialog.fieldsmerger.FieldMergerFactory; import org.jabref.gui.mergeentries.newmergedialog.toolbar.ThreeWayMergeToolbar; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.strings.StringUtil; import com.tobiasdiez.easybind.EasyBind; import org.fxmisc.richtext.StyleClassedTextArea; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A controller class to control left, right and merged field values */ public class FieldRowView { private static final Logger LOGGER = LoggerFactory.getLogger(FieldRowView.class); protected final FieldRowViewModel viewModel; protected final BooleanProperty shouldShowDiffs = new SimpleBooleanProperty(true); private final FieldNameCell fieldNameCell; private final FieldValueCell leftValueCell; private final FieldValueCell rightValueCell; private final MergedFieldCell mergedValueCell; private final ToggleGroup toggleGroup = new ToggleGroup(); private GridPane parent; public FieldRowView(Field field, BibEntry leftEntry, BibEntry rightEntry, BibEntry mergedEntry, FieldMergerFactory fieldMergerFactory, int rowIndex) { viewModel = new FieldRowViewModel(field, leftEntry, rightEntry, mergedEntry, fieldMergerFactory); fieldNameCell = new FieldNameCell(field.getDisplayName(), rowIndex); leftValueCell = new FieldValueCell(viewModel.getLeftFieldValue(), rowIndex); rightValueCell = new FieldValueCell(viewModel.getRightFieldValue(), rowIndex); mergedValueCell = new MergedFieldCell(viewModel.getMergedFieldValue(), rowIndex); // As a workaround we need to have a reference to the parent grid pane to be able to show/hide the row. // This won't be necessary when https://bugs.openjdk.org/browse/JDK-8136901 is fixed. leftValueCell.parentProperty().addListener(e -> { if (leftValueCell.getParent() instanceof GridPane grid) { parent = grid; } }); if (FieldMergerFactory.canMerge(field)) { ToggleMergeUnmergeButton toggleMergeUnmergeButton = new ToggleMergeUnmergeButton(field); toggleMergeUnmergeButton.setCanMerge(!viewModel.hasEqualLeftAndRightValues()); fieldNameCell.addSideButton(toggleMergeUnmergeButton); EasyBind.listen(toggleMergeUnmergeButton.fieldStateProperty(), ((observableValue, old, fieldState) -> { LOGGER.debug("Field merge state is {} for field {}", fieldState, field); if (fieldState == ToggleMergeUnmergeButton.FieldState.MERGED) { viewModel.mergeFields(); } else { viewModel.unmergeFields(); } })); } toggleGroup.getToggles().addAll(leftValueCell, rightValueCell); mergedValueCell.textProperty().bindBidirectional(viewModel.mergedFieldValueProperty()); leftValueCell.textProperty().bindBidirectional(viewModel.leftFieldValueProperty()); rightValueCell.textProperty().bindBidirectional(viewModel.rightFieldValueProperty()); EasyBind.subscribe(viewModel.selectionProperty(), selection -> { if (selection == Selection.LEFT) { toggleGroup.selectToggle(leftValueCell); } else if (selection == Selection.RIGHT) { toggleGroup.selectToggle(rightValueCell); } else if (selection == Selection.NONE) { toggleGroup.selectToggle(null); } }); EasyBind.subscribe(toggleGroup.selectedToggleProperty(), selectedToggle -> { if (selectedToggle == leftValueCell) { selectLeftValue(); } else if (selectedToggle == rightValueCell) { selectRightValue(); } else { selectNone(); } }); // Hide rightValueCell and extend leftValueCell to 2 columns when fields are merged EasyBind.subscribe(viewModel.isFieldsMergedProperty(), isFieldsMerged -> { if (isFieldsMerged) { rightValueCell.setVisible(false); GridPane.setColumnSpan(leftValueCell, 2); } else { rightValueCell.setVisible(true); GridPane.setColumnSpan(leftValueCell, 1); } }); EasyBind.listen(viewModel.hasEqualLeftAndRightBinding(), (obs, old, isEqual) -> { if (isEqual) { LOGGER.debug("Left and right values are equal, LEFT==RIGHT=={}", viewModel.getLeftFieldValue()); hideDiff(); } }); } public void selectLeftValue() { viewModel.selectLeftValue(); } public void selectRightValue() { viewModel.selectRightValue(); } public void selectNone() { viewModel.selectNone(); } public String getMergedValue() { return mergedValueProperty().getValue(); } public ReadOnlyStringProperty mergedValueProperty() { return viewModel.mergedFieldValueProperty(); } public FieldNameCell getFieldNameCell() { return fieldNameCell; } public FieldValueCell getLeftValueCell() { return leftValueCell; } public FieldValueCell getRightValueCell() { return rightValueCell; } public MergedFieldCell getMergedValueCell() { return mergedValueCell; } public void showDiff(ShowDiffConfig diffConfig) { if (!rightValueCell.isVisible() || StringUtil.isNullOrEmpty(viewModel.getLeftFieldValue()) || StringUtil.isNullOrEmpty(viewModel.getRightFieldValue())) { return; } LOGGER.debug("Showing diffs..."); StyleClassedTextArea leftLabel = leftValueCell.getStyleClassedLabel(); StyleClassedTextArea rightLabel = rightValueCell.getStyleClassedLabel(); // Clearing old diff styles based on previous diffConfig hideDiff(); if (shouldShowDiffs.get()) { if (diffConfig.diffView() == ThreeWayMergeToolbar.DiffView.UNIFIED) { new UnifiedDiffHighlighter(leftLabel, rightLabel, diffConfig.diffHighlightingMethod()).highlight(); } else { new SplitDiffHighlighter(leftLabel, rightLabel, diffConfig.diffHighlightingMethod()).highlight(); } } } public void hide() { if (parent != null) { parent.getChildren().removeAll(leftValueCell, rightValueCell, mergedValueCell, fieldNameCell); } } public void show() { if (parent != null) { if (!parent.getChildren().contains(leftValueCell)) { parent.getChildren().addAll(leftValueCell, rightValueCell, mergedValueCell, fieldNameCell); } } } public void hideDiff() { if (!rightValueCell.isVisible()) { return; } LOGGER.debug("Hiding diffs..."); int leftValueLength = getLeftValueCell().getStyleClassedLabel().getLength(); getLeftValueCell().getStyleClassedLabel().clearStyle(0, leftValueLength); getLeftValueCell().getStyleClassedLabel().replaceText(viewModel.getLeftFieldValue()); int rightValueLength = getRightValueCell().getStyleClassedLabel().getLength(); getRightValueCell().getStyleClassedLabel().clearStyle(0, rightValueLength); getRightValueCell().getStyleClassedLabel().replaceText(viewModel.getRightFieldValue()); } public boolean hasEqualLeftAndRightValues() { return viewModel.hasEqualLeftAndRightValues(); } @Override public String toString() { return "FieldRowView [shouldShowDiffs=" + shouldShowDiffs.get() + ", fieldNameCell=" + fieldNameCell + ", leftValueCell=" + leftValueCell + ", rightValueCell=" + rightValueCell + ", mergedValueCell=" + mergedValueCell + "]"; } }
8,775
39.818605
232
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/newmergedialog/FieldRowViewModel.java
package org.jabref.gui.mergeentries.newmergedialog; import javax.swing.undo.AbstractUndoableEdit; import javax.swing.undo.CannotRedoException; import javax.swing.undo.CannotUndoException; import javax.swing.undo.CompoundEdit; import javafx.beans.binding.Bindings; import javafx.beans.binding.BooleanBinding; 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 org.jabref.gui.mergeentries.newmergedialog.fieldsmerger.FieldMerger; import org.jabref.gui.mergeentries.newmergedialog.fieldsmerger.FieldMergerFactory; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.InternalField; import org.jabref.model.entry.types.EntryTypeFactory; import org.jabref.model.strings.StringUtil; import com.tobiasdiez.easybind.EasyBind; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FieldRowViewModel { public enum Selection { LEFT, RIGHT, /** * When the user types something into the merged field value and neither the left nor * right values match it, NONE is selected * */ NONE } private final Logger LOGGER = LoggerFactory.getLogger(FieldRowViewModel.class); private final BooleanProperty isFieldsMerged = new SimpleBooleanProperty(Boolean.FALSE); private final ObjectProperty<Selection> selection = new SimpleObjectProperty<>(); private final StringProperty leftFieldValue = new SimpleStringProperty(""); private final StringProperty rightFieldValue = new SimpleStringProperty(""); private final StringProperty mergedFieldValue = new SimpleStringProperty(""); private final Field field; private final BibEntry leftEntry; private final BibEntry rightEntry; private final BibEntry mergedEntry; private final BooleanBinding hasEqualLeftAndRight; private final FieldMergerFactory fieldMergerFactory; private final CompoundEdit fieldsMergedEdit = new CompoundEdit(); public FieldRowViewModel(Field field, BibEntry leftEntry, BibEntry rightEntry, BibEntry mergedEntry, FieldMergerFactory fieldMergerFactory) { this.field = field; this.leftEntry = leftEntry; this.rightEntry = rightEntry; this.mergedEntry = mergedEntry; this.fieldMergerFactory = fieldMergerFactory; if (field.equals(InternalField.TYPE_HEADER)) { setLeftFieldValue(leftEntry.getType().getDisplayName()); setRightFieldValue(rightEntry.getType().getDisplayName()); } else { setLeftFieldValue(leftEntry.getField(field).orElse("")); setRightFieldValue(rightEntry.getField(field).orElse("")); } EasyBind.listen(leftFieldValueProperty(), (obs, old, leftValue) -> leftEntry.setField(field, leftValue)); EasyBind.listen(rightFieldValueProperty(), (obs, old, rightValue) -> rightEntry.setField(field, rightValue)); EasyBind.listen(mergedFieldValueProperty(), (obs, old, mergedFieldValue) -> { if (field.equals(InternalField.TYPE_HEADER)) { getMergedEntry().setType(EntryTypeFactory.parse(mergedFieldValue)); } else { getMergedEntry().setField(field, mergedFieldValue); } }); hasEqualLeftAndRight = Bindings.createBooleanBinding(this::hasEqualLeftAndRightValues, leftFieldValueProperty(), rightFieldValueProperty()); selectNonEmptyValue(); EasyBind.listen(isFieldsMergedProperty(), (obs, old, areFieldsMerged) -> { LOGGER.debug("Field are merged: {}", areFieldsMerged); if (areFieldsMerged) { selectLeftValue(); } else { selectNonEmptyValue(); } }); EasyBind.subscribe(selectionProperty(), selection -> { LOGGER.debug("Selecting {}' value for field {}", selection, field.getDisplayName()); switch (selection) { case LEFT -> EasyBind.subscribe(leftFieldValueProperty(), this::setMergedFieldValue); case RIGHT -> EasyBind.subscribe(rightFieldValueProperty(), this::setMergedFieldValue); } }); EasyBind.subscribe(mergedFieldValueProperty(), mergedValue -> { LOGGER.debug("Merged value is {} for field {}", mergedValue, field.getDisplayName()); if (mergedValue.equals(getLeftFieldValue())) { selectLeftValue(); } else if (getMergedFieldValue().equals(getRightFieldValue())) { selectRightValue(); } else { selectNone(); } }); EasyBind.subscribe(hasEqualLeftAndRightBinding(), this::setIsFieldsMerged); } public void selectNonEmptyValue() { if (StringUtil.isNullOrEmpty(leftFieldValue.get())) { selectRightValue(); } else { selectLeftValue(); } } public boolean hasEqualLeftAndRightValues() { return leftFieldValue.get().equals(rightFieldValue.get()); } public void selectLeftValue() { setSelection(Selection.LEFT); } public void selectRightValue() { if (isFieldsMerged()) { selectLeftValue(); } else { setSelection(Selection.RIGHT); } } public void selectNone() { setSelection(Selection.NONE); } public void setMergedFieldValue(String mergedFieldValue) { mergedFieldValueProperty().set(mergedFieldValue); } public StringProperty mergedFieldValueProperty() { return mergedFieldValue; } public String getMergedFieldValue() { return mergedFieldValue.get(); } public void mergeFields() { assert !hasEqualLeftAndRightValues(); if (!FieldMergerFactory.canMerge(field)) { throw new UnsupportedOperationException(); } String oldLeftFieldValue = getLeftFieldValue(); String oldRightFieldValue = getRightFieldValue(); FieldMerger fieldMerger = fieldMergerFactory.create(field); String mergedFields = fieldMerger.merge(getLeftFieldValue(), getRightFieldValue()); setLeftFieldValue(mergedFields); setRightFieldValue(mergedFields); if (fieldsMergedEdit.canRedo()) { fieldsMergedEdit.redo(); } else { fieldsMergedEdit.addEdit(new MergeFieldsUndo(oldLeftFieldValue, oldRightFieldValue, mergedFields)); fieldsMergedEdit.end(); } } public void unmergeFields() { if (fieldsMergedEdit.canUndo()) { fieldsMergedEdit.undo(); } } public BooleanBinding hasEqualLeftAndRightBinding() { return hasEqualLeftAndRight; } public ObjectProperty<Selection> selectionProperty() { return selection; } public void setSelection(Selection select) { selectionProperty().set(select); } public Selection getSelection() { return selectionProperty().get(); } public boolean isFieldsMerged() { return isFieldsMerged.get(); } public BooleanProperty isFieldsMergedProperty() { return isFieldsMerged; } public void setIsFieldsMerged(boolean isFieldsMerged) { this.isFieldsMerged.set(isFieldsMerged); } public String getLeftFieldValue() { return leftFieldValue.get(); } public StringProperty leftFieldValueProperty() { return leftFieldValue; } public void setLeftFieldValue(String leftFieldValue) { this.leftFieldValue.set(leftFieldValue); } public String getRightFieldValue() { return rightFieldValue.get(); } public StringProperty rightFieldValueProperty() { return rightFieldValue; } public void setRightFieldValue(String rightFieldValue) { this.rightFieldValue.set(rightFieldValue); } public Field getField() { return field; } public BibEntry getLeftEntry() { return leftEntry; } public BibEntry getRightEntry() { return rightEntry; } public BibEntry getMergedEntry() { return mergedEntry; } class MergeFieldsUndo extends AbstractUndoableEdit { private final String oldLeft; private final String oldRight; private final String mergedFields; MergeFieldsUndo(String oldLeft, String oldRight, String mergedFields) { this.oldLeft = oldLeft; this.oldRight = oldRight; this.mergedFields = mergedFields; } @Override public void undo() throws CannotUndoException { super.undo(); setLeftFieldValue(oldLeft); setRightFieldValue(oldRight); } @Override public void redo() throws CannotRedoException { super.redo(); setLeftFieldValue(mergedFields); setRightFieldValue(mergedFields); } } }
9,199
31.167832
148
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/newmergedialog/GroupDiffMode.java
package org.jabref.gui.mergeentries.newmergedialog; public class GroupDiffMode implements DiffMethod { private final String separator; public GroupDiffMode(String separator) { this.separator = separator; } @Override public String separator() { return this.separator; } }
314
18.6875
51
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/newmergedialog/PersonsNameFieldRowView.java
package org.jabref.gui.mergeentries.newmergedialog; import org.jabref.gui.mergeentries.newmergedialog.cell.sidebuttons.InfoButton; import org.jabref.gui.mergeentries.newmergedialog.fieldsmerger.FieldMergerFactory; import org.jabref.logic.importer.AuthorListParser; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.AuthorList; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldProperty; public class PersonsNameFieldRowView extends FieldRowView { private final AuthorList leftEntryNames; private final AuthorList rightEntryNames; public PersonsNameFieldRowView(Field field, BibEntry leftEntry, BibEntry rightEntry, BibEntry mergedEntry, FieldMergerFactory fieldMergerFactory, int rowIndex) { super(field, leftEntry, rightEntry, mergedEntry, fieldMergerFactory, rowIndex); assert field.getProperties().contains(FieldProperty.PERSON_NAMES); var authorsParser = new AuthorListParser(); leftEntryNames = authorsParser.parse(viewModel.getLeftFieldValue()); rightEntryNames = authorsParser.parse(viewModel.getRightFieldValue()); if (!viewModel.hasEqualLeftAndRightValues() && leftEntryNames.equals(rightEntryNames)) { showPersonsNamesAreTheSameInfo(); shouldShowDiffs.set(false); } } private void showPersonsNamesAreTheSameInfo() { InfoButton infoButton = new InfoButton(Localization.lang("The %0s are the same. However, the order of field content differs", viewModel.getField().getName())); getFieldNameCell().addSideButton(infoButton); } }
1,659
46.428571
167
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/newmergedialog/ShowDiffConfig.java
package org.jabref.gui.mergeentries.newmergedialog; import org.jabref.gui.mergeentries.newmergedialog.toolbar.ThreeWayMergeToolbar.DiffView; public record ShowDiffConfig( DiffView diffView, DiffMethod diffHighlightingMethod) { }
247
26.555556
88
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/newmergedialog/ThreeWayMergeHeaderView.java
package org.jabref.gui.mergeentries.newmergedialog; import javafx.geometry.Insets; import javafx.scene.control.Control; import javafx.scene.layout.GridPane; import org.jabref.gui.mergeentries.newmergedialog.cell.HeaderCell; import org.jabref.logic.l10n.Localization; /** * GridPane was used instead of a Hbox because Hbox allocates more space for cells * with longer text, but I wanted all cells to have the same width */ public class ThreeWayMergeHeaderView extends GridPane { public static final String DEFAULT_STYLE_CLASS = "merge-header"; private final HeaderCell leftHeaderCell; private final HeaderCell rightHeaderCell; private final HeaderCell mergedHeaderCell; public ThreeWayMergeHeaderView(String leftHeader, String rightHeader) { getStyleClass().add(DEFAULT_STYLE_CLASS); this.leftHeaderCell = new HeaderCell(leftHeader); this.rightHeaderCell = new HeaderCell(rightHeader); this.mergedHeaderCell = new HeaderCell(Localization.lang("Merged Entry")); addRow(0, new HeaderCell(""), leftHeaderCell, rightHeaderCell, mergedHeaderCell ); setPrefHeight(Control.USE_COMPUTED_SIZE); setMaxHeight(Control.USE_PREF_SIZE); setMinHeight(Control.USE_PREF_SIZE); // The fields grid pane is contained within a scroll pane, thus it doesn't allocate the full available width. In // fact, it uses the available width minus the size of the scrollbar which is 8. This leads to header columns being // always wider than fields columns. This hack should fix it. setPadding(new Insets(0, 8, 0, 0)); } public void setLeftHeader(String leftHeader) { leftHeaderCell.setText(leftHeader); } public void setRightHeader(String rightHeader) { rightHeaderCell.setText(rightHeader); } }
1,898
34.830189
123
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/newmergedialog/ThreeWayMergeView.java
package org.jabref.gui.mergeentries.newmergedialog; import java.util.ArrayList; import java.util.List; import javafx.scene.control.ScrollPane; import javafx.scene.layout.ColumnConstraints; import javafx.scene.layout.GridPane; import javafx.scene.layout.Priority; import javafx.scene.layout.RowConstraints; import javafx.scene.layout.VBox; import javafx.stage.Screen; import org.jabref.gui.mergeentries.newmergedialog.fieldsmerger.FieldMergerFactory; import org.jabref.gui.mergeentries.newmergedialog.toolbar.ThreeWayMergeToolbar; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldProperty; import org.jabref.preferences.BibEntryPreferences; public class ThreeWayMergeView extends VBox { public static final int GRID_COLUMN_MIN_WIDTH = 250; public static final String LEFT_DEFAULT_HEADER = Localization.lang("Left Entry"); public static final String RIGHT_DEFAULT_HEADER = Localization.lang("Right Entry"); private final ColumnConstraints fieldNameColumnConstraints = new ColumnConstraints(150); private final ColumnConstraints leftEntryColumnConstraints = new ColumnConstraints(GRID_COLUMN_MIN_WIDTH, 256, Double.MAX_VALUE); private final ColumnConstraints rightEntryColumnConstraints = new ColumnConstraints(GRID_COLUMN_MIN_WIDTH, 256, Double.MAX_VALUE); private final ColumnConstraints mergedEntryColumnConstraints = new ColumnConstraints(GRID_COLUMN_MIN_WIDTH, 256, Double.MAX_VALUE); private final ThreeWayMergeToolbar toolbar; private final ThreeWayMergeHeaderView headerView; private final ScrollPane scrollPane; private final GridPane mergeGridPane; private final ThreeWayMergeViewModel viewModel; private final List<FieldRowView> fieldRows = new ArrayList<>(); private final FieldMergerFactory fieldMergerFactory; private final String keywordSeparator; public ThreeWayMergeView(BibEntry leftEntry, BibEntry rightEntry, String leftHeader, String rightHeader, BibEntryPreferences bibEntryPreferences) { getStylesheets().add(ThreeWayMergeView.class.getResource("ThreeWayMergeView.css").toExternalForm()); viewModel = new ThreeWayMergeViewModel((BibEntry) leftEntry.clone(), (BibEntry) rightEntry.clone(), leftHeader, rightHeader); this.fieldMergerFactory = new FieldMergerFactory(bibEntryPreferences); this.keywordSeparator = bibEntryPreferences.getKeywordSeparator().toString(); mergeGridPane = new GridPane(); scrollPane = new ScrollPane(); headerView = new ThreeWayMergeHeaderView(leftHeader, rightHeader); toolbar = new ThreeWayMergeToolbar(); initializeColumnConstraints(); initializeMergeGridPane(); initializeScrollPane(); initializeHeaderView(); initializeToolbar(); this.setPrefHeight(Screen.getPrimary().getBounds().getHeight() * 0.76); this.setPrefWidth(Screen.getPrimary().getBounds().getWidth() * 0.97); getChildren().addAll(toolbar, headerView, scrollPane); } public ThreeWayMergeView(BibEntry leftEntry, BibEntry rightEntry, BibEntryPreferences bibEntryPreferences) { this(leftEntry, rightEntry, LEFT_DEFAULT_HEADER, RIGHT_DEFAULT_HEADER, bibEntryPreferences); } private void initializeToolbar() { toolbar.setOnSelectLeftEntryValuesButtonClicked(this::selectLeftEntryValues); toolbar.setOnSelectRightEntryValuesButtonClicked(this::selectRightEntryValues); toolbar.showDiffProperty().addListener(e -> updateDiff()); toolbar.diffViewProperty().addListener(e -> updateDiff()); toolbar.diffHighlightingMethodProperty().addListener(e -> updateDiff()); toolbar.hideEqualFieldsProperty().addListener(e -> showOrHideEqualFields()); updateDiff(); showOrHideEqualFields(); } private void showOrHideEqualFields() { for (FieldRowView row : fieldRows) { if (toolbar.shouldHideEqualFields()) { if (row.hasEqualLeftAndRightValues()) { row.hide(); } } else { row.show(); } } } private void updateDiff() { if (toolbar.shouldShowDiffs()) { for (FieldRowView row : fieldRows) { if ("Groups".equals(row.getFieldNameCell().getText()) && (row.getLeftValueCell().getText().contains(keywordSeparator) || row.getRightValueCell().getText().contains(keywordSeparator))) { row.showDiff(new ShowDiffConfig(toolbar.getDiffView(), new GroupDiffMode(keywordSeparator))); } else { row.showDiff(new ShowDiffConfig(toolbar.getDiffView(), toolbar.getDiffHighlightingMethod())); } } } else { fieldRows.forEach(FieldRowView::hideDiff); } } private void initializeHeaderView() { headerView.getColumnConstraints().addAll(fieldNameColumnConstraints, leftEntryColumnConstraints, rightEntryColumnConstraints, mergedEntryColumnConstraints); } private void initializeScrollPane() { scrollPane.setFitToWidth(true); scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER); scrollPane.setContent(mergeGridPane); } private void initializeColumnConstraints() { fieldNameColumnConstraints.setHgrow(Priority.NEVER); leftEntryColumnConstraints.setHgrow(Priority.ALWAYS); rightEntryColumnConstraints.setHgrow(Priority.ALWAYS); mergedEntryColumnConstraints.setHgrow(Priority.ALWAYS); } private void initializeMergeGridPane() { mergeGridPane.getColumnConstraints().addAll(fieldNameColumnConstraints, leftEntryColumnConstraints, rightEntryColumnConstraints, mergedEntryColumnConstraints); for (int fieldIndex = 0; fieldIndex < viewModel.numberOfVisibleFields(); fieldIndex++) { addRow(fieldIndex); mergeGridPane.getRowConstraints().add(new RowConstraints()); } } private Field getFieldAtIndex(int index) { return viewModel.getVisibleFields().get(index); } private void addRow(int fieldIndex) { Field field = getFieldAtIndex(fieldIndex); FieldRowView fieldRow; if (field.getProperties().contains(FieldProperty.PERSON_NAMES)) { fieldRow = new PersonsNameFieldRowView(field, getLeftEntry(), getRightEntry(), getMergedEntry(), fieldMergerFactory, fieldIndex); } else { fieldRow = new FieldRowView(field, getLeftEntry(), getRightEntry(), getMergedEntry(), fieldMergerFactory, fieldIndex); } fieldRows.add(fieldIndex, fieldRow); mergeGridPane.add(fieldRow.getFieldNameCell(), 0, fieldIndex); mergeGridPane.add(fieldRow.getLeftValueCell(), 1, fieldIndex); mergeGridPane.add(fieldRow.getRightValueCell(), 2, fieldIndex); mergeGridPane.add(fieldRow.getMergedValueCell(), 3, fieldIndex); } public BibEntry getMergedEntry() { return viewModel.getMergedEntry(); } public void setLeftHeader(String leftHeader) { headerView.setLeftHeader(leftHeader); } public void setRightHeader(String rightHeader) { headerView.setRightHeader(rightHeader); } public void selectLeftEntryValues() { fieldRows.forEach(FieldRowView::selectLeftValue); } public void selectRightEntryValues() { fieldRows.forEach(FieldRowView::selectRightValue); } public void showDiff(ShowDiffConfig diffConfig) { toolbar.setDiffView(diffConfig.diffView()); toolbar.setDiffHighlightingMethod(diffConfig.diffHighlightingMethod()); toolbar.setShowDiff(true); } public BibEntry getLeftEntry() { return viewModel.getLeftEntry(); } public BibEntry getRightEntry() { return viewModel.getRightEntry(); } public void saveConfiguration() { toolbar.saveToolbarConfiguration(); } }
8,188
40.150754
201
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/newmergedialog/ThreeWayMergeViewModel.java
package org.jabref.gui.mergeentries.newmergedialog; import java.util.Comparator; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import org.jabref.gui.AbstractViewModel; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldFactory; import org.jabref.model.entry.field.InternalField; public class ThreeWayMergeViewModel extends AbstractViewModel { private final ObjectProperty<BibEntry> leftEntry = new SimpleObjectProperty<>(); private final ObjectProperty<BibEntry> rightEntry = new SimpleObjectProperty<>(); private final ObjectProperty<BibEntry> mergedEntry = new SimpleObjectProperty<>(); private final StringProperty leftHeader = new SimpleStringProperty(); private final StringProperty rightHeader = new SimpleStringProperty(); private final ObservableList<Field> visibleFields = FXCollections.observableArrayList(); public ThreeWayMergeViewModel(BibEntry leftEntry, BibEntry rightEntry, String leftHeader, String rightHeader) { Objects.requireNonNull(leftEntry, "Left entry is required"); Objects.requireNonNull(rightEntry, "Right entry is required"); Objects.requireNonNull(leftHeader, "Left header entry is required"); Objects.requireNonNull(rightHeader, "Right header is required"); setLeftEntry(leftEntry); setRightEntry(rightEntry); setLeftHeader(leftHeader); setRightHeader(rightHeader); mergedEntry.set(new BibEntry()); setVisibleFields(Stream.concat( leftEntry.getFields().stream(), rightEntry.getFields().stream()).collect(Collectors.toSet())); } public StringProperty leftHeaderProperty() { return leftHeader; } public String getLeftHeader() { return leftHeader.get(); } public void setLeftHeader(String leftHeader) { leftHeaderProperty().set(leftHeader); } public StringProperty rightHeaderProperty() { return rightHeader; } public String getRightHeader() { return rightHeaderProperty().get(); } public void setRightHeader(String rightHeader) { rightHeaderProperty().set(rightHeader); } public BibEntry getLeftEntry() { return leftEntry.get(); } private void setLeftEntry(BibEntry bibEntry) { leftEntry.set(bibEntry); } public BibEntry getRightEntry() { return rightEntry.get(); } private void setRightEntry(BibEntry bibEntry) { rightEntry.set(bibEntry); } public BibEntry getMergedEntry() { return mergedEntry.get(); } public ObservableList<Field> getVisibleFields() { return visibleFields; } /** * Convince method to determine the total number of fields in the union of the left and right fields. */ public int numberOfVisibleFields() { return visibleFields.size(); } private void setVisibleFields(Set<Field> fields) { visibleFields.clear(); visibleFields.addAll(fields); // Don't show internal fields. See org.jabref.model.entry.field.InternalField visibleFields.removeIf(FieldFactory::isInternalField); visibleFields.sort(Comparator.comparing(Field::getName)); // Add the entry type field as the first field to display visibleFields.add(0, InternalField.TYPE_HEADER); } }
3,764
31.179487
115
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/CopyFieldValueCommand.java
package org.jabref.gui.mergeentries.newmergedialog.cell; import java.util.Objects; import org.jabref.gui.ClipBoardManager; import org.jabref.gui.actions.SimpleCommand; import org.jabref.preferences.PreferencesService; public class CopyFieldValueCommand extends SimpleCommand { private final String fieldValue; private final ClipBoardManager clipBoardManager; public CopyFieldValueCommand(PreferencesService preferencesService, final String fieldValue) { Objects.requireNonNull(fieldValue, "Field value cannot be null"); this.fieldValue = fieldValue; this.clipBoardManager = new ClipBoardManager(preferencesService); } @Override public void execute() { clipBoardManager.setContent(fieldValue); } }
762
30.791667
98
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/FieldNameCell.java
package org.jabref.gui.mergeentries.newmergedialog.cell; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; /** * A readonly cell used to display the name of some field. */ public class FieldNameCell extends ThreeWayMergeCell { public static final String DEFAULT_STYLE_CLASS = "field-name"; protected final HBox actionLayout = new HBox(); private final Label label = new Label(); private final HBox labelBox = new HBox(label); public FieldNameCell(String text, int rowIndex) { super(text, rowIndex); initialize(); } private void initialize() { getStyleClass().add(DEFAULT_STYLE_CLASS); initializeLabel(); getChildren().addAll(labelBox, actionLayout); } private void initializeLabel() { label.textProperty().bind(textProperty()); HBox.setHgrow(labelBox, Priority.ALWAYS); } public void addSideButton(Button sideButton) { // TODO: Allow adding more than one side button actionLayout.getChildren().clear(); actionLayout.getChildren().setAll(sideButton); } }
1,182
28.575
66
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/FieldValueCell.java
package org.jabref.gui.mergeentries.newmergedialog.cell; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ObjectProperty; import javafx.css.PseudoClass; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Cursor; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.ContentDisplay; import javafx.scene.control.ScrollPane; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import javafx.scene.input.MouseEvent; import javafx.scene.input.ScrollEvent; import javafx.scene.layout.Background; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import javafx.scene.paint.Color; import org.jabref.gui.Globals; import org.jabref.gui.actions.ActionFactory; import org.jabref.gui.fieldeditors.URLUtil; import org.jabref.gui.icon.IconTheme; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.identifier.DOI; import org.jabref.model.strings.StringUtil; import com.tobiasdiez.easybind.EasyBind; import org.fxmisc.flowless.VirtualizedScrollPane; import org.fxmisc.richtext.StyleClassedTextArea; import org.kordamp.ikonli.javafx.FontIcon; import org.kordamp.ikonli.materialdesign2.MaterialDesignC; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A readonly, selectable field cell that contains the value of some field */ public class FieldValueCell extends ThreeWayMergeCell implements Toggle { public static final Logger LOGGER = LoggerFactory.getLogger(FieldValueCell.class); public static final String DEFAULT_STYLE_CLASS = "merge-field-value"; public static final String SELECTION_BOX_STYLE_CLASS = "selection-box"; private static final PseudoClass SELECTED_PSEUDO_CLASS = PseudoClass.getPseudoClass("selected"); private final StyleClassedTextArea label = new StyleClassedTextArea(); private final ActionFactory factory = new ActionFactory(Globals.getKeyPrefs()); private final VirtualizedScrollPane<StyleClassedTextArea> scrollPane = new VirtualizedScrollPane<>(label); HBox labelBox = new HBox(scrollPane); private final HBox selectionBox = new HBox(); private final HBox actionsContainer = new HBox(); private final FieldValueCellViewModel viewModel; public FieldValueCell(String text, int rowIndex) { super(text, rowIndex); viewModel = new FieldValueCellViewModel(text); EasyBind.listen(viewModel.selectedProperty(), (observable, old, isSelected) -> { pseudoClassStateChanged(SELECTED_PSEUDO_CLASS, isSelected); getToggleGroup().selectToggle(FieldValueCell.this); }); viewModel.fieldValueProperty().bind(textProperty()); initialize(); } private void initialize() { getStyleClass().add(DEFAULT_STYLE_CLASS); initializeScrollPane(); initializeLabel(); initializeSelectionBox(); initializeActions(); setOnMouseClicked(e -> { if (!isDisabled()) { setSelected(true); } }); selectionBox.getChildren().addAll(labelBox, actionsContainer); getChildren().setAll(selectionBox); } private void initializeLabel() { label.setEditable(false); label.setBackground(Background.fill(Color.TRANSPARENT)); EasyBind.subscribe(textProperty(), label::replaceText); label.setAutoHeight(true); label.setWrapText(true); label.setStyle("-fx-cursor: hand"); // Workarounds preventTextSelectionViaMouseEvents(); label.prefHeightProperty().bind(label.totalHeightEstimateProperty().orElseConst(-1d)); // Fix text area consuming scroll events before they reach the outer scrollable label.addEventFilter(ScrollEvent.SCROLL, e -> { e.consume(); FieldValueCell.this.fireEvent(e.copyFor(e.getSource(), FieldValueCell.this)); }); } private void initializeActions() { actionsContainer.getChildren().setAll(createOpenLinkButton(), createCopyButton()); actionsContainer.setAlignment(Pos.TOP_CENTER); actionsContainer.setPrefWidth(28); } private void initializeSelectionBox() { selectionBox.getStyleClass().add(SELECTION_BOX_STYLE_CLASS); HBox.setHgrow(selectionBox, Priority.ALWAYS); HBox.setHgrow(labelBox, Priority.ALWAYS); labelBox.setPadding(new Insets(8)); labelBox.setCursor(Cursor.HAND); } private Button createCopyButton() { FontIcon copyIcon = FontIcon.of(MaterialDesignC.CONTENT_COPY); copyIcon.getStyleClass().add("action-icon"); Button copyButton = factory.createIconButton(() -> Localization.lang("Copy"), new CopyFieldValueCommand(Globals.prefs, getText())); copyButton.setGraphic(copyIcon); copyButton.setContentDisplay(ContentDisplay.GRAPHIC_ONLY); copyButton.setMaxHeight(Double.MAX_VALUE); copyButton.visibleProperty().bind(textProperty().isEmpty().not()); return copyButton; } public Button createOpenLinkButton() { Node openLinkIcon = IconTheme.JabRefIcons.OPEN_LINK.getGraphicNode(); openLinkIcon.getStyleClass().add("action-icon"); Button openLinkButton = factory.createIconButton(() -> Localization.lang("Open Link"), new OpenExternalLinkAction(getText())); openLinkButton.setGraphic(openLinkIcon); openLinkButton.setContentDisplay(ContentDisplay.GRAPHIC_ONLY); openLinkButton.setMaxHeight(Double.MAX_VALUE); openLinkButton.visibleProperty().bind(EasyBind.map(textProperty(), input -> StringUtil.isNotBlank(input) && (URLUtil.isURL(input) || DOI.isValid(input)))); return openLinkButton; } private void initializeScrollPane() { HBox.setHgrow(scrollPane, Priority.ALWAYS); scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER); } private void preventTextSelectionViaMouseEvents() { label.addEventFilter(MouseEvent.ANY, e -> { if ((e.getEventType() == MouseEvent.MOUSE_DRAGGED) || (e.getEventType() == MouseEvent.DRAG_DETECTED) || (e.getEventType() == MouseEvent.MOUSE_ENTERED)) { e.consume(); } else if (e.getEventType() == MouseEvent.MOUSE_PRESSED) { if (e.getClickCount() > 1) { e.consume(); } } }); } @Override public ToggleGroup getToggleGroup() { return viewModel.getToggleGroup(); } @Override public void setToggleGroup(ToggleGroup toggleGroup) { viewModel.setToggleGroup(toggleGroup); } @Override public ObjectProperty<ToggleGroup> toggleGroupProperty() { return viewModel.toggleGroupProperty(); } @Override public boolean isSelected() { return viewModel.isSelected(); } @Override public void setSelected(boolean selected) { viewModel.setSelected(selected); } @Override public BooleanProperty selectedProperty() { return viewModel.selectedProperty(); } public StyleClassedTextArea getStyleClassedLabel() { return label; } }
7,245
34.871287
163
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/FieldValueCellViewModel.java
package org.jabref.gui.mergeentries.newmergedialog.cell; 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.ToggleGroup; public class FieldValueCellViewModel { private final StringProperty fieldValue = new SimpleStringProperty(); private final BooleanProperty selected = new SimpleBooleanProperty(FieldValueCell.class, "selected"); private final ObjectProperty<ToggleGroup> toggleGroup = new SimpleObjectProperty<>(); public FieldValueCellViewModel(String text) { setFieldValue(text); } public String getFieldValue() { return fieldValue.get(); } public StringProperty fieldValueProperty() { return fieldValue; } public void setFieldValue(String fieldValue) { this.fieldValue.set(fieldValue); } public boolean isSelected() { return selected.get(); } public BooleanProperty selectedProperty() { return selected; } public void setSelected(boolean selected) { this.selected.set(selected); } public ToggleGroup getToggleGroup() { return toggleGroup.get(); } public ObjectProperty<ToggleGroup> toggleGroupProperty() { return toggleGroup; } public void setToggleGroup(ToggleGroup toggleGroup) { this.toggleGroup.set(toggleGroup); } }
1,578
27.196429
105
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/HeaderCell.java
package org.jabref.gui.mergeentries.newmergedialog.cell; import javafx.geometry.Insets; import javafx.scene.control.Label; /** * A readonly cell used to display the header of the ThreeWayMerge UI at the top of the layout. * */ public class HeaderCell extends ThreeWayMergeCell { public static final String DEFAULT_STYLE_CLASS = "merge-header-cell"; private final Label label = new Label(); public HeaderCell(String text) { super(text, ThreeWayMergeCell.HEADER_ROW); initialize(); } private void initialize() { getStyleClass().add(DEFAULT_STYLE_CLASS); initializeLabel(); getChildren().add(label); } private void initializeLabel() { label.textProperty().bind(textProperty()); label.setPadding(new Insets(getPadding().getTop(), getPadding().getRight(), getPadding().getBottom(), 16)); } }
882
29.448276
115
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/MergedFieldCell.java
package org.jabref.gui.mergeentries.newmergedialog.cell; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.input.ScrollEvent; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import org.jabref.gui.util.BindingsHelper; import org.fxmisc.richtext.StyleClassedTextArea; public class MergedFieldCell extends ThreeWayMergeCell { private static final String DEFAULT_STYLE_CLASS = "merged-field"; private final StyleClassedTextArea textArea = new StyleClassedTextArea(); public MergedFieldCell(String text, int rowIndex) { super(text, rowIndex); initialize(); } private void initialize() { getStyleClass().add(DEFAULT_STYLE_CLASS); initializeTextArea(); getChildren().add(textArea); } private void initializeTextArea() { BindingsHelper.bindBidirectional(textArea.textProperty(), textProperty(), textArea::replaceText, textProperty()::setValue); setAlignment(Pos.CENTER); textArea.setWrapText(true); textArea.setAutoHeight(true); textArea.setPadding(new Insets(8)); HBox.setHgrow(textArea, Priority.ALWAYS); textArea.addEventFilter(ScrollEvent.SCROLL, e -> { e.consume(); MergedFieldCell.this.fireEvent(e.copyFor(e.getSource(), MergedFieldCell.this)); }); } }
1,495
30.829787
91
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/OpenExternalLinkAction.java
package org.jabref.gui.mergeentries.newmergedialog.cell; import java.io.IOException; import java.net.URI; import org.jabref.gui.actions.SimpleCommand; import org.jabref.gui.desktop.JabRefDesktop; import org.jabref.model.entry.identifier.DOI; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A command for opening DOIs and URLs. This was created primarily for simplifying {@link FieldValueCell}. */ public class OpenExternalLinkAction extends SimpleCommand { private final String urlOrDoi; private final Logger LOGGER = LoggerFactory.getLogger(OpenExternalLinkAction.class); public OpenExternalLinkAction(String urlOrDoi) { this.urlOrDoi = urlOrDoi; } @Override public void execute() { try { if (DOI.isValid(urlOrDoi)) { JabRefDesktop.openBrowser( DOI.parse(urlOrDoi) .flatMap(DOI::getExternalURI) .map(URI::toString) .orElse("") ); } else { JabRefDesktop.openBrowser( urlOrDoi ); } } catch (IOException e) { LOGGER.warn("Cannot open the given external link '{}'", urlOrDoi, e); } } }
1,307
28.727273
106
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/ThreeWayMergeCell.java
package org.jabref.gui.mergeentries.newmergedialog.cell; import javafx.beans.property.StringProperty; import javafx.css.PseudoClass; import javafx.scene.layout.HBox; import com.tobiasdiez.easybind.EasyBind; public abstract class ThreeWayMergeCell extends HBox { public static final String ODD_PSEUDO_CLASS = "odd"; public static final String EVEN_PSEUDO_CLASS = "even"; public static final int HEADER_ROW = -1; private static final String DEFAULT_STYLE_CLASS = "field-cell"; private final ThreeWayMergeCellViewModel viewModel; public ThreeWayMergeCell(String text, int rowIndex) { getStyleClass().add(DEFAULT_STYLE_CLASS); viewModel = new ThreeWayMergeCellViewModel(text, rowIndex); EasyBind.subscribe(viewModel.oddProperty(), isOdd -> { pseudoClassStateChanged(PseudoClass.getPseudoClass(ODD_PSEUDO_CLASS), isOdd); }); EasyBind.subscribe(viewModel.evenProperty(), isEven -> { pseudoClassStateChanged(PseudoClass.getPseudoClass(EVEN_PSEUDO_CLASS), isEven); }); } public String getText() { return viewModel.getText(); } public StringProperty textProperty() { return viewModel.textProperty(); } public void setText(String text) { viewModel.setText(text); } @Override public String toString() { return "ThreeWayMergeCell [getText()=" + getText() + "]"; } }
1,432
30.152174
91
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/ThreeWayMergeCellViewModel.java
package org.jabref.gui.mergeentries.newmergedialog.cell; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import com.tobiasdiez.easybind.EasyBind; import static org.jabref.gui.mergeentries.newmergedialog.cell.ThreeWayMergeCell.HEADER_ROW; public class ThreeWayMergeCellViewModel { private final StringProperty text = new SimpleStringProperty(); private final BooleanProperty odd = new SimpleBooleanProperty(ThreeWayMergeCell.class, "odd"); private final BooleanProperty even = new SimpleBooleanProperty(ThreeWayMergeCell.class, "even"); public ThreeWayMergeCellViewModel(String text, int rowIndex) { setText(text); if (rowIndex != HEADER_ROW) { if (rowIndex % 2 == 1) { odd.setValue(true); } else { even.setValue(true); } } EasyBind.subscribe(odd, isOdd -> { setEven(!isOdd); }); EasyBind.subscribe(even, isEven -> { setOdd(!isEven); }); } public String getText() { return text.get(); } public StringProperty textProperty() { return text; } public void setText(String text) { this.text.set(text); } public boolean isOdd() { return odd.get(); } public BooleanProperty oddProperty() { return odd; } public void setOdd(boolean odd) { this.odd.set(odd); } public boolean isEven() { return even.get(); } public BooleanProperty evenProperty() { return even; } public void setEven(boolean even) { this.even.set(even); } }
1,788
23.847222
100
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/sidebuttons/InfoButton.java
package org.jabref.gui.mergeentries.newmergedialog.cell.sidebuttons; import java.util.Optional; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.scene.control.Button; import org.jabref.gui.Globals; import org.jabref.gui.actions.Action; import org.jabref.gui.actions.ActionFactory; import org.jabref.gui.actions.SimpleCommand; import org.jabref.gui.icon.IconTheme; import org.jabref.gui.icon.JabRefIcon; import com.tobiasdiez.easybind.EasyBind; public class InfoButton extends Button { private final StringProperty infoMessage = new SimpleStringProperty(); private final ActionFactory actionFactory = new ActionFactory(Globals.getKeyPrefs()); private final Action mergeAction = new Action() { @Override public Optional<JabRefIcon> getIcon() { return Optional.of(IconTheme.JabRefIcons.INTEGRITY_INFO); } @Override public String getText() { return infoMessage.get(); } }; public InfoButton(String infoMessage) { this.infoMessage.setValue(infoMessage); configureButton(); EasyBind.subscribe(this.infoMessage, newWarningMessage -> configureButton()); } private void configureButton() { setMaxHeight(Double.MAX_VALUE); setFocusTraversable(false); actionFactory.configureIconButton(mergeAction, new SimpleCommand() { @Override public void execute() { // The info button is not meant to be clickable that's why this is empty } }, this); } }
1,616
30.096154
89
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/sidebuttons/ToggleMergeUnmergeButton.java
package org.jabref.gui.mergeentries.newmergedialog.cell.sidebuttons; import java.util.Optional; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.scene.control.Button; import org.jabref.gui.Globals; import org.jabref.gui.actions.Action; import org.jabref.gui.actions.ActionFactory; import org.jabref.gui.actions.SimpleCommand; import org.jabref.gui.icon.IconTheme; import org.jabref.gui.icon.JabRefIcon; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.field.Field; public class ToggleMergeUnmergeButton extends Button { private final ObjectProperty<FieldState> fieldState = new SimpleObjectProperty<>(FieldState.UNMERGED); private final BooleanProperty canMerge = new SimpleBooleanProperty(Boolean.TRUE); private final ActionFactory actionFactory = new ActionFactory(Globals.getKeyPrefs()); private final Field field; public ToggleMergeUnmergeButton(Field field) { this.field = field; setMaxHeight(Double.MAX_VALUE); setFocusTraversable(false); configureMergeButton(); this.disableProperty().bind(canMergeProperty().not()); } private void configureMergeButton() { ToggleMergeCommand mergeCommand = new ToggleMergeCommand(); actionFactory.configureIconButton(mergeCommand.mergeAction, mergeCommand, this); } private void configureUnmergeButton() { ToggleMergeCommand unmergeCommand = new ToggleMergeCommand(); actionFactory.configureIconButton(unmergeCommand.unmergeAction, unmergeCommand, this); } public ObjectProperty<FieldState> fieldStateProperty() { return fieldState; } private void setFieldState(FieldState fieldState) { fieldStateProperty().set(fieldState); } public FieldState getFieldState() { return fieldState.get(); } public BooleanProperty canMergeProperty() { return canMerge; } public boolean canMerge() { return canMerge.get(); } /** * Setting {@code canMerge} to {@code false} will disable the merge/unmerge button * */ public void setCanMerge(boolean value) { canMergeProperty().set(value); } private class ToggleMergeCommand extends SimpleCommand { private final Action mergeAction = new Action() { @Override public Optional<JabRefIcon> getIcon() { return Optional.of(IconTheme.JabRefIcons.MERGE_GROUPS); } @Override public String getText() { return Localization.lang("Merge %0", field.getDisplayName()); } }; private final Action unmergeAction = new Action() { @Override public Optional<JabRefIcon> getIcon() { return Optional.of(IconTheme.JabRefIcons.UNDO); } @Override public String getText() { return Localization.lang("Unmerge %0", field.getDisplayName()); } }; @Override public void execute() { if (fieldStateProperty().get() == FieldState.MERGED) { setFieldState(FieldState.UNMERGED); configureMergeButton(); } else { setFieldState(FieldState.MERGED); configureUnmergeButton(); } } } public enum FieldState { MERGED, UNMERGED } }
3,572
30.069565
106
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/newmergedialog/diffhighlighter/DiffHighlighter.java
package org.jabref.gui.mergeentries.newmergedialog.diffhighlighter; import java.util.Arrays; import java.util.List; import java.util.Objects; import org.jabref.gui.mergeentries.newmergedialog.DiffMethod; import org.fxmisc.richtext.StyleClassedTextArea; public abstract sealed class DiffHighlighter permits SplitDiffHighlighter, UnifiedDiffHighlighter { protected final StyleClassedTextArea sourceTextview; protected final StyleClassedTextArea targetTextview; protected DiffMethod diffMethod; public DiffHighlighter(StyleClassedTextArea sourceTextview, StyleClassedTextArea targetTextview, DiffMethod diffMethod) { Objects.requireNonNull(sourceTextview, "source text view MUST NOT be null."); Objects.requireNonNull(targetTextview, "target text view MUST NOT be null."); this.sourceTextview = sourceTextview; this.targetTextview = targetTextview; this.diffMethod = diffMethod; } abstract void highlight(); protected List<String> splitString(String str) { return Arrays.asList(str.split(diffMethod.separator())); } private void setDiffMethod(DiffMethod diffMethod) { this.diffMethod = diffMethod; } public DiffMethod getDiffMethod() { return diffMethod; } public String getSeparator() { return diffMethod.separator(); } public enum BasicDiffMethod implements DiffMethod { WORDS(" "), CHARS(""), COMMA(","); private final String separator; BasicDiffMethod(String separator) { this.separator = separator; } @Override public String separator() { return separator; } } protected String join(List<String> stringList) { return String.join(getSeparator(), stringList); } enum ChangeType { ADDITION, DELETION, CHANGE_DELETION } record Change( int position, int spanSize, ChangeType type) { } }
1,995
26.342466
125
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/newmergedialog/diffhighlighter/SplitDiffHighlighter.java
package org.jabref.gui.mergeentries.newmergedialog.diffhighlighter; import java.util.List; import org.jabref.gui.mergeentries.newmergedialog.DiffMethod; import com.github.difflib.DiffUtils; import com.github.difflib.patch.AbstractDelta; import org.fxmisc.richtext.StyleClassedTextArea; /** * A diff highlighter in which changes are split between source and target text view. * They are represented by an addition in the target text view and deletion in the source text view. */ public final class SplitDiffHighlighter extends DiffHighlighter { public SplitDiffHighlighter(StyleClassedTextArea sourceTextview, StyleClassedTextArea targetTextview, DiffMethod diffMethod) { super(sourceTextview, targetTextview, diffMethod); } @Override public void highlight() { String sourceContent = sourceTextview.getText(); String targetContent = targetTextview.getText(); if (sourceContent.equals(targetContent)) { return; } List<String> sourceTokens = splitString(sourceContent); List<String> targetTokens = splitString(targetContent); List<AbstractDelta<String>> deltaList = DiffUtils.diff(sourceTokens, targetTokens).getDeltas(); for (AbstractDelta<String> delta : deltaList) { int affectedSourceTokensPosition = delta.getSource().getPosition(); int affectedTargetTokensPosition = delta.getTarget().getPosition(); List<String> affectedTokensInSource = delta.getSource().getLines(); List<String> affectedTokensInTarget = delta.getTarget().getLines(); int joinedSourceTokensLength = affectedTokensInSource.stream() .map(String::length) .reduce(Integer::sum) .map(value -> value + (getSeparator().length() * (affectedTokensInSource.size() - 1))) .orElse(0); int joinedTargetTokensLength = affectedTokensInTarget.stream() .map(String::length) .reduce(Integer::sum) .map(value -> value + (getSeparator().length() * (affectedTokensInTarget.size() - 1))) .orElse(0); int affectedSourceTokensPositionInText = getPositionInText(affectedSourceTokensPosition, sourceTokens); int affectedTargetTokensPositionInText = getPositionInText(affectedTargetTokensPosition, targetTokens); switch (delta.getType()) { case CHANGE -> { sourceTextview.setStyleClass(affectedSourceTokensPositionInText, affectedSourceTokensPositionInText + joinedSourceTokensLength, "deletion"); targetTextview.setStyleClass(affectedTargetTokensPositionInText, affectedTargetTokensPositionInText + joinedTargetTokensLength, "updated"); } case DELETE -> sourceTextview.setStyleClass(affectedSourceTokensPositionInText, affectedSourceTokensPositionInText + joinedSourceTokensLength, "deletion"); case INSERT -> targetTextview.setStyleClass(affectedTargetTokensPositionInText, affectedTargetTokensPositionInText + joinedTargetTokensLength, "addition"); } } } public int getPositionInText(int positionInTokenList, List<String> tokenList) { if (positionInTokenList == 0) { return 0; } else { return tokenList.stream().limit(positionInTokenList).map(String::length) .reduce(Integer::sum) .map(value -> value + (getSeparator().length() * positionInTokenList)) .orElse(0); } } }
3,692
46.961039
164
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/newmergedialog/diffhighlighter/UnifiedDiffHighlighter.java
package org.jabref.gui.mergeentries.newmergedialog.diffhighlighter; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.jabref.gui.mergeentries.newmergedialog.DiffMethod; import com.github.difflib.DiffUtils; import com.github.difflib.patch.AbstractDelta; import com.github.difflib.patch.DeltaType; import org.fxmisc.richtext.StyleClassedTextArea; /** * A diff highlighter in which differences of type {@link DeltaType#CHANGE} are unified and represented by an insertion * and deletion in the target text view. Normal addition and deletion are kept as they are. */ public final class UnifiedDiffHighlighter extends DiffHighlighter { public UnifiedDiffHighlighter(StyleClassedTextArea sourceTextview, StyleClassedTextArea targetTextview, DiffMethod diffMethod) { super(sourceTextview, targetTextview, diffMethod); } @Override public void highlight() { String sourceContent = sourceTextview.getText(); String targetContent = targetTextview.getText(); if (sourceContent.equals(targetContent)) { return; } List<String> sourceWords = splitString(sourceContent); List<String> targetWords = splitString(targetContent); List<String> unifiedWords = new ArrayList<>(targetWords); List<AbstractDelta<String>> deltaList = DiffUtils.diff(sourceWords, targetWords).getDeltas(); List<Change> changeList = new ArrayList<>(); int deletionCount = 0; for (AbstractDelta<String> delta : deltaList) { switch (delta.getType()) { case CHANGE -> { int changePosition = delta.getTarget().getPosition(); int deletionPoint = changePosition + deletionCount; int insertionPoint = deletionPoint + 1; List<String> deltaSourceWords = delta.getSource().getLines(); List<String> deltaTargetWords = delta.getTarget().getLines(); unifiedWords.add(deletionPoint, join(deltaSourceWords)); changeList.add(new Change(deletionPoint, 1, ChangeType.CHANGE_DELETION)); changeList.add(new Change(insertionPoint, deltaTargetWords.size(), ChangeType.ADDITION)); deletionCount++; } case DELETE -> { int deletionPoint = delta.getTarget().getPosition() + deletionCount; unifiedWords.add(deletionPoint, join(delta.getSource().getLines())); changeList.add(new Change(deletionPoint, 1, ChangeType.DELETION)); deletionCount++; } case INSERT -> { int insertionPoint = delta.getTarget().getPosition() + deletionCount; changeList.add(new Change(insertionPoint, delta.getTarget().getLines().size(), ChangeType.ADDITION)); } } } targetTextview.clear(); boolean changeInProgress = false; for (int position = 0; position < unifiedWords.size(); position++) { String word = unifiedWords.get(position); Optional<Change> changeAtPosition = findChange(position, changeList); if (changeAtPosition.isEmpty()) { appendToTextArea(targetTextview, getSeparator() + word, "unchanged"); } else { Change change = changeAtPosition.get(); List<String> changeWords = unifiedWords.subList(change.position(), change.position() + change.spanSize()); if (change.type() == ChangeType.DELETION) { appendToTextArea(targetTextview, getSeparator() + join(changeWords), "deletion"); } else if (change.type() == ChangeType.ADDITION) { if (changeInProgress) { appendToTextArea(targetTextview, join(changeWords), "addition"); changeInProgress = false; } else { appendToTextArea(targetTextview, getSeparator() + join(changeWords), "addition"); } } else if (change.type() == ChangeType.CHANGE_DELETION) { appendToTextArea(targetTextview, getSeparator() + join(changeWords), "deletion"); changeInProgress = true; } position = (position + changeWords.size()) - 1; } } if (targetTextview.getLength() >= getSeparator().length()) { // There always going to be an extra separator at the start targetTextview.deleteText(0, getSeparator().length()); } } private void appendToTextArea(StyleClassedTextArea textArea, String text, String styleClass) { if (text.isEmpty()) { return; } // Append separator without styling it if (text.startsWith(getSeparator())) { textArea.append(getSeparator(), "unchanged"); textArea.append(text.substring(getSeparator().length()), styleClass); } else { textArea.append(text, styleClass); } } private Optional<Change> findChange(int position, List<Change> changeList) { return changeList.stream().filter(change -> change.position() == position).findAny(); } }
5,373
43.783333
132
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/newmergedialog/fieldsmerger/CommentMerger.java
package org.jabref.gui.mergeentries.newmergedialog.fieldsmerger; import org.jabref.logic.util.OS; import org.jabref.model.entry.field.StandardField; /** * A merger for the {@link StandardField#COMMENT} field * */ public class CommentMerger implements FieldMerger { @Override public String merge(String fieldValueA, String fieldValueB) { return fieldValueA + OS.NEWLINE + fieldValueB; } }
412
26.533333
65
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/newmergedialog/fieldsmerger/FieldMerger.java
package org.jabref.gui.mergeentries.newmergedialog.fieldsmerger; /** * This class is responsible for taking two values for some field and merging them to into one value * */ @FunctionalInterface public interface FieldMerger { String merge(String fieldValueA, String fieldValueB); }
289
28
100
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/newmergedialog/fieldsmerger/FieldMergerFactory.java
package org.jabref.gui.mergeentries.newmergedialog.fieldsmerger; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.StandardField; import org.jabref.preferences.BibEntryPreferences; public class FieldMergerFactory { private final BibEntryPreferences bibEntryPreferences; public FieldMergerFactory(BibEntryPreferences bibEntryPreferences) { this.bibEntryPreferences = bibEntryPreferences; } public FieldMerger create(Field field) { if (field == StandardField.GROUPS) { return new GroupMerger(); } else if (field == StandardField.KEYWORDS) { return new KeywordMerger(bibEntryPreferences); } else if (field == StandardField.COMMENT) { return new CommentMerger(); } else if (field == StandardField.FILE) { return new FileMerger(); } else { throw new IllegalArgumentException("No implementation found for merging the given field: " + field.getDisplayName()); } } public static boolean canMerge(Field field) { return field == StandardField.GROUPS || field == StandardField.KEYWORDS || field == StandardField.COMMENT || field == StandardField.FILE; } }
1,231
37.5
145
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/newmergedialog/fieldsmerger/FileMerger.java
package org.jabref.gui.mergeentries.newmergedialog.fieldsmerger; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jabref.logic.bibtex.FileFieldWriter; import org.jabref.logic.importer.util.FileFieldParser; import org.jabref.model.entry.LinkedFile; import org.jabref.model.entry.field.StandardField; import org.jabref.model.strings.StringUtil; /** * A merger for the {@link StandardField#FILE} field * */ public class FileMerger implements FieldMerger { @Override public String merge(String filesA, String filesB) { if (StringUtil.isBlank(filesA + filesB)) { return ""; } else if (StringUtil.isBlank(filesA)) { return filesB; } else if (StringUtil.isBlank(filesB)) { return filesA; } else { List<LinkedFile> linkedFilesA = FileFieldParser.parse(filesA); List<LinkedFile> linkedFilesB = FileFieldParser.parse(filesB); // TODO: If one of the linked files list is empty then the its string value is malformed. return Stream.concat(linkedFilesA.stream(), linkedFilesB.stream()) .map(FileFieldWriter::getStringRepresentation) .collect(Collectors.joining()); } } }
1,302
36.228571
101
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/newmergedialog/fieldsmerger/GroupMerger.java
package org.jabref.gui.mergeentries.newmergedialog.fieldsmerger; import java.util.Arrays; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.jabref.model.entry.field.StandardField; import org.jabref.model.strings.StringUtil; /** * A merger for the {@link StandardField#GROUPS} field * */ public class GroupMerger implements FieldMerger { public static final String GROUPS_SEPARATOR = ", "; public static final Pattern GROUPS_SEPARATOR_REGEX = Pattern.compile("\s*,\s*"); @Override public String merge(String groupsA, String groupsB) { if (StringUtil.isBlank(groupsA) && StringUtil.isBlank(groupsB)) { return ""; } else if (StringUtil.isBlank(groupsA)) { return groupsB; } else if (StringUtil.isBlank(groupsB)) { return groupsA; } else { return Arrays.stream(GROUPS_SEPARATOR_REGEX.split(groupsA + GROUPS_SEPARATOR + groupsB)) .distinct() .collect(Collectors.joining(GROUPS_SEPARATOR)); } } }
1,084
32.90625
100
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/newmergedialog/fieldsmerger/KeywordMerger.java
package org.jabref.gui.mergeentries.newmergedialog.fieldsmerger; import java.util.Objects; import org.jabref.model.entry.KeywordList; import org.jabref.model.entry.field.StandardField; import org.jabref.preferences.BibEntryPreferences; /** * A merger for the {@link StandardField#KEYWORDS} field * */ public class KeywordMerger implements FieldMerger { private final BibEntryPreferences bibEntryPreferences; public KeywordMerger(BibEntryPreferences bibEntryPreferences) { Objects.requireNonNull(bibEntryPreferences); this.bibEntryPreferences = bibEntryPreferences; } @Override public String merge(String keywordsA, String keywordsB) { Character delimiter = bibEntryPreferences.getKeywordSeparator(); return KeywordList.merge(keywordsA, keywordsB, delimiter).getAsString(delimiter); } }
849
31.692308
89
java
null
jabref-main/src/main/java/org/jabref/gui/mergeentries/newmergedialog/toolbar/ThreeWayMergeToolbar.java
package org.jabref.gui.mergeentries.newmergedialog.toolbar; import javafx.beans.binding.BooleanExpression; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.RadioButton; import javafx.scene.control.ToggleGroup; import javafx.scene.layout.AnchorPane; import javafx.util.StringConverter; import org.jabref.gui.mergeentries.newmergedialog.DiffMethod; import org.jabref.gui.mergeentries.newmergedialog.diffhighlighter.DiffHighlighter.BasicDiffMethod; import org.jabref.logic.l10n.Localization; import org.jabref.preferences.GuiPreferences; import org.jabref.preferences.PreferencesService; import com.airhacks.afterburner.views.ViewLoader; import com.google.common.base.Enums; import com.tobiasdiez.easybind.EasyBind; import com.tobiasdiez.easybind.EasyBinding; import jakarta.inject.Inject; public class ThreeWayMergeToolbar extends AnchorPane { @FXML private RadioButton highlightCharactersRadioButtons; @FXML private RadioButton highlightWordsRadioButton; @FXML private ToggleGroup diffHighlightingMethodToggleGroup; @FXML private ComboBox<DiffView> diffViewComboBox; @FXML private ComboBox<PlainTextOrDiff> plainTextOrDiffComboBox; @FXML private Button selectLeftEntryValuesButton; @FXML private Button selectRightEntryValuesButton; @FXML private CheckBox onlyShowChangedFieldsCheck; @Inject private PreferencesService preferencesService; private final ObjectProperty<DiffMethod> diffHighlightingMethod = new SimpleObjectProperty<>(); private final BooleanProperty onlyShowChangedFields = new SimpleBooleanProperty(); private EasyBinding<Boolean> showDiff; public ThreeWayMergeToolbar() { ViewLoader.view(this) .root(this) .load(); } @FXML public void initialize() { showDiff = EasyBind.map(plainTextOrDiffComboBox.valueProperty(), plainTextOrDiff -> plainTextOrDiff == PlainTextOrDiff.Diff); plainTextOrDiffComboBox.getItems().addAll(PlainTextOrDiff.values()); plainTextOrDiffComboBox.setConverter(new StringConverter<>() { @Override public String toString(PlainTextOrDiff plainTextOrDiff) { return plainTextOrDiff.getValue(); } @Override public PlainTextOrDiff fromString(String string) { return PlainTextOrDiff.fromString(string); } }); diffViewComboBox.disableProperty().bind(notShowDiffProperty()); diffViewComboBox.getItems().addAll(DiffView.values()); diffViewComboBox.setConverter(new StringConverter<>() { @Override public String toString(DiffView diffView) { return diffView.getValue(); } @Override public DiffView fromString(String string) { return DiffView.fromString(string); } }); highlightWordsRadioButton.disableProperty().bind(notShowDiffProperty()); highlightCharactersRadioButtons.disableProperty().bind(notShowDiffProperty()); diffHighlightingMethodToggleGroup.selectedToggleProperty().addListener((observable -> { if (diffHighlightingMethodToggleGroup.getSelectedToggle().equals(highlightCharactersRadioButtons)) { diffHighlightingMethod.set(BasicDiffMethod.CHARS); } else { diffHighlightingMethod.set(BasicDiffMethod.WORDS); } })); onlyShowChangedFieldsCheck.selectedProperty().bindBidirectional(preferencesService.getGuiPreferences().mergeShowChangedFieldOnlyProperty()); onlyShowChangedFields.bind(onlyShowChangedFieldsCheck.selectedProperty()); loadSavedConfiguration(); } private void loadSavedConfiguration() { GuiPreferences guiPreferences = preferencesService.getGuiPreferences(); PlainTextOrDiff plainTextOrDiffPreference = guiPreferences.getMergeShouldShowDiff() ? PlainTextOrDiff.Diff : PlainTextOrDiff.PLAIN_TEXT; plainTextOrDiffComboBox.getSelectionModel().select(plainTextOrDiffPreference); DiffView diffViewPreference = guiPreferences.getMergeShouldShowUnifiedDiff() ? DiffView.UNIFIED : DiffView.SPLIT; diffViewComboBox.getSelectionModel().select(diffViewPreference); diffHighlightingMethodToggleGroup.selectToggle(guiPreferences.getMergeHighlightWords() ? highlightWordsRadioButton : highlightCharactersRadioButtons); } public void saveToolbarConfiguration() { preferencesService.getGuiPreferences().setMergeShouldShowDiff(plainTextOrDiffComboBox.getValue() == PlainTextOrDiff.Diff); preferencesService.getGuiPreferences().setMergeShouldShowUnifiedDiff(diffViewComboBox.getValue() == DiffView.UNIFIED); boolean highlightWordsRadioButtonValue = diffHighlightingMethodToggleGroup.getSelectedToggle().equals(highlightWordsRadioButton); preferencesService.getGuiPreferences().setMergeHighlightWords(highlightWordsRadioButtonValue); } public ObjectProperty<DiffView> diffViewProperty() { return diffViewComboBox.valueProperty(); } public DiffView getDiffView() { return diffViewProperty().get(); } public void setDiffView(DiffView diffView) { diffViewProperty().set(diffView); } public EasyBinding<Boolean> showDiffProperty() { return showDiff; } public void setShowDiff(boolean showDiff) { plainTextOrDiffComboBox.valueProperty().set(showDiff ? PlainTextOrDiff.Diff : PlainTextOrDiff.PLAIN_TEXT); } public BooleanProperty hideEqualFieldsProperty() { return onlyShowChangedFields; } public boolean shouldHideEqualFields() { return onlyShowChangedFields.get(); } /** * Convenience method used to disable diff related views when diff is not selected. * * <p> * This method is required because {@link EasyBinding} class doesn't have a method to invert a boolean property, * like {@link BooleanExpression#not()} * </p> */ public EasyBinding<Boolean> notShowDiffProperty() { return showDiffProperty().map(showDiff -> !showDiff); } public Boolean shouldShowDiffs() { return showDiffProperty().get(); } public ObjectProperty<DiffMethod> diffHighlightingMethodProperty() { return diffHighlightingMethod; } public DiffMethod getDiffHighlightingMethod() { return diffHighlightingMethodProperty().get(); } public void setDiffHighlightingMethod(DiffMethod diffHighlightingMethod) { diffHighlightingMethodProperty().set(diffHighlightingMethod); } public void setOnSelectLeftEntryValuesButtonClicked(Runnable onClick) { selectLeftEntryValuesButton.setOnMouseClicked(e -> onClick.run()); } public void setOnSelectRightEntryValuesButtonClicked(Runnable onClick) { selectRightEntryValuesButton.setOnMouseClicked(e -> onClick.run()); } public enum PlainTextOrDiff { PLAIN_TEXT(Localization.lang("Plain Text")), Diff(Localization.lang("Show Diff")); private final String value; PlainTextOrDiff(String value) { this.value = value; } public static PlainTextOrDiff parse(String name) { return Enums.getIfPresent(PlainTextOrDiff.class, name).or(Diff); } public String getValue() { return value; } public static PlainTextOrDiff fromString(String str) { return Enum.valueOf(PlainTextOrDiff.class, str); } } public enum DiffView { UNIFIED(Localization.lang("Unified View")), SPLIT(Localization.lang("Split View")); private final String value; DiffView(String value) { this.value = value; } public static DiffView parse(String name) { return Enums.getIfPresent(DiffView.class, name).or(UNIFIED); } public String getValue() { return value; } public static DiffView fromString(String str) { return Enum.valueOf(DiffView.class, str); } } }
8,486
33.782787
158
java
null
jabref-main/src/main/java/org/jabref/gui/openoffice/AdvancedCiteDialogView.java
package org.jabref.gui.openoffice; import javafx.fxml.FXML; import javafx.scene.control.ButtonType; import javafx.scene.control.RadioButton; import javafx.scene.control.TextField; import javafx.scene.control.ToggleGroup; import org.jabref.gui.util.BaseDialog; import org.jabref.logic.l10n.Localization; import com.airhacks.afterburner.views.ViewLoader; public class AdvancedCiteDialogView extends BaseDialog<AdvancedCiteDialogViewModel> { @FXML private TextField pageInfo; @FXML private RadioButton inPar; @FXML private RadioButton inText; @FXML private ToggleGroup citeToggleGroup; private AdvancedCiteDialogViewModel viewModel; public AdvancedCiteDialogView() { ViewLoader.view(this) .load() .setAsDialogPane(this); setResultConverter(btn -> { if (btn == ButtonType.OK) { return viewModel; } return null; }); setTitle(Localization.lang("Cite special")); } @FXML private void initialize() { viewModel = new AdvancedCiteDialogViewModel(); inPar.selectedProperty().bindBidirectional(viewModel.citeInParProperty()); inText.selectedProperty().bindBidirectional(viewModel.citeInTextProperty()); pageInfo.textProperty().bindBidirectional(viewModel.pageInfoProperty()); } }
1,370
28.804348
85
java
null
jabref-main/src/main/java/org/jabref/gui/openoffice/AdvancedCiteDialogViewModel.java
package org.jabref.gui.openoffice; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; public class AdvancedCiteDialogViewModel { private final StringProperty pageInfo = new SimpleStringProperty(""); private final BooleanProperty citeInPar = new SimpleBooleanProperty(); private final BooleanProperty citeInText = new SimpleBooleanProperty(); public StringProperty pageInfoProperty() { return pageInfo; } public BooleanProperty citeInParProperty() { return citeInPar; } public BooleanProperty citeInTextProperty() { return citeInText; } }
747
27.769231
75
java
null
jabref-main/src/main/java/org/jabref/gui/openoffice/Bootstrap.java
// -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ package org.jabref.gui.openoffice; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; import java.util.Random; import com.sun.star.bridge.UnoUrlResolver; import com.sun.star.bridge.XUnoUrlResolver; import com.sun.star.comp.helper.BootstrapException; import com.sun.star.comp.helper.ComponentContext; import com.sun.star.comp.helper.ComponentContextEntry; import com.sun.star.comp.loader.JavaLoader; import com.sun.star.comp.servicemanager.ServiceManager; import com.sun.star.container.XSet; import com.sun.star.lang.XInitialization; import com.sun.star.lang.XMultiComponentFactory; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.lib.util.NativeLibraryLoader; import com.sun.star.loader.XImplementationLoader; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XComponentContext; /** Bootstrap offers functionality to obtain a context or simply * a service manager. * The service manager can create a few basic services, whose implementations are: * <ul> * <li>com.sun.star.comp.loader.JavaLoader</li> * <li>com.sun.star.comp.urlresolver.UrlResolver</li> * <li>com.sun.star.comp.bridgefactory.BridgeFactory</li> * <li>com.sun.star.comp.connections.Connector</li> * <li>com.sun.star.comp.connections.Acceptor</li> * <li>com.sun.star.comp.servicemanager.ServiceManager</li> * </ul> * * Other services can be inserted into the service manager by * using its XSet interface: * <pre> * XSet xSet = UnoRuntime.queryInterface( XSet.class, aMultiComponentFactory ); * // insert the service manager * xSet.insert( aSingleComponentFactory ); * </pre> */ public class Bootstrap { private static final Random RANDOM_PIPE_NAME = new Random(); private static boolean M_LOADED_JUH = false; private static void insertBasicFactories(XSet xSet, XImplementationLoader xImpLoader) throws Exception { // insert the factory of the loader xSet.insert(xImpLoader.activate("com.sun.star.comp.loader.JavaLoader", null, null, null)); // insert the factory of the URLResolver xSet.insert(xImpLoader.activate("com.sun.star.comp.urlresolver.UrlResolver", null, null, null)); // insert the bridgefactory xSet.insert(xImpLoader.activate("com.sun.star.comp.bridgefactory.BridgeFactory", null, null, null)); // insert the connector xSet.insert(xImpLoader.activate("com.sun.star.comp.connections.Connector", null, null, null)); // insert the acceptor xSet.insert(xImpLoader.activate("com.sun.star.comp.connections.Acceptor", null, null, null)); } /** * Returns an array of default commandline options to start bootstrapped * instance of soffice with. You may use it in connection with bootstrap * method for example like this: * <pre> * List list = Arrays.asList( Bootstrap.getDefaultOptions() ); * list.remove("--nologo"); * list.remove("--nodefault"); * list.add("--invisible"); * * Bootstrap.bootstrap( list.toArray( new String[list.size()] ); * </pre> * * @return an array of default commandline options * @see #bootstrap(String[]) * @since LibreOffice 5.1 */ public static final String[] getDefaultOptions() { return new String[] {"--nologo", "--nodefault", "--norestore", "--nolockcheck"}; } /** * backwards compatibility stub. * * @param context_entries the hash table contains mappings of entry names (type string) to context entries (type class ComponentContextEntry). * @return a new context. * @throws Exception if things go awry. */ public static XComponentContext createInitialComponentContext(Hashtable<String, Object> context_entries) throws Exception { return createInitialComponentContext((Map<String, Object>) context_entries); } /** * Bootstraps an initial component context with service manager and basic jurt components inserted. * * @param context_entries the hash table contains mappings of entry names (type string) to context entries (type class ComponentContextEntry). * @return a new context. * @throws Exception if things go awry. */ public static XComponentContext createInitialComponentContext(Map<String, Object> context_entries) throws Exception { ServiceManager xSMgr = new ServiceManager(); XImplementationLoader xImpLoader = UnoRuntime.queryInterface(XImplementationLoader.class, new JavaLoader()); XInitialization xInit = UnoRuntime.queryInterface(XInitialization.class, xImpLoader); Object[] args = new Object[] {xSMgr}; xInit.initialize(args); // initial component context if (context_entries == null) { context_entries = new HashMap<>(1); } // add smgr context_entries.put("/singletons/com.sun.star.lang.theServiceManager", new ComponentContextEntry(null, xSMgr)); // ... xxx todo: add standard entries XComponentContext xContext = new ComponentContext(context_entries, null); xSMgr.setDefaultContext(xContext); XSet xSet = UnoRuntime.queryInterface(XSet.class, xSMgr); // insert basic jurt factories insertBasicFactories(xSet, xImpLoader); return xContext; } /** * Bootstraps a servicemanager with the jurt base components registered. * <p> * See also UNOIDL <code>com.sun.star.lang.ServiceManager</code>. * * @return a freshly bootstrapped service manager * @throws Exception if things go awry. */ public static XMultiServiceFactory createSimpleServiceManager() throws Exception { return UnoRuntime.queryInterface(XMultiServiceFactory.class, createInitialComponentContext((Map<String, Object>) null).getServiceManager()); } /** * Bootstraps the initial component context from a native UNO installation. * * @return a freshly bootstrapped component context. * <p> * See also * <code>cppuhelper/defaultBootstrap_InitialComponentContext()</code>. * @throws Exception if things go awry. */ public static final XComponentContext defaultBootstrap_InitialComponentContext() throws Exception { return defaultBootstrap_InitialComponentContext((String) null, (Map<String, String>) null); } /** * Backwards compatibility stub. * * @param ini_file ini_file (may be null: uno.rc besides cppuhelper lib) * @param bootstrap_parameters bootstrap parameters (maybe null) * @return a freshly bootstrapped component context. * @throws Exception if things go awry. */ public static final XComponentContext defaultBootstrap_InitialComponentContext(String ini_file, Hashtable<String, String> bootstrap_parameters) throws Exception { return defaultBootstrap_InitialComponentContext(ini_file, (Map<String, String>) bootstrap_parameters); } /** * Bootstraps the initial component context from a native UNO installation. * <p> * See also * <code>cppuhelper/defaultBootstrap_InitialComponentContext()</code>. * * @param ini_file ini_file (may be null: uno.rc besides cppuhelper lib) * @param bootstrap_parameters bootstrap parameters (maybe null) * @return a freshly bootstrapped component context. * @throws Exception if things go awry. */ public static final XComponentContext defaultBootstrap_InitialComponentContext(String ini_file, Map<String, String> bootstrap_parameters) throws Exception { // jni convenience: easier to iterate over array than calling Hashtable String pairs[] = null; if (null != bootstrap_parameters) { pairs = new String[2 * bootstrap_parameters.size()]; int n = 0; for (Map.Entry<String, String> bootstrap_parameter : bootstrap_parameters.entrySet()) { pairs[n++] = bootstrap_parameter.getKey(); pairs[n++] = bootstrap_parameter.getValue(); } } if (!M_LOADED_JUH) { if ("The Android Project".equals(System.getProperty("java.vendor"))) { // Find out if we are configured with DISABLE_DYNLOADING or // not. Try to load the lo-bootstrap shared library which // won't exist in the DISABLE_DYNLOADING case. (And which will // be already loaded otherwise, so nothing unexpected happens // that case.) Yeah, this would be simpler if I just could be // bothered to keep a separate branch for DISABLE_DYNLOADING // on Android, merging in master periodically, until I know // for sure whether it is what I want, or not. boolean disable_dynloading = false; try { System.loadLibrary("lo-bootstrap"); } catch (UnsatisfiedLinkError e) { disable_dynloading = true; } if (!disable_dynloading) { NativeLibraryLoader.loadLibrary(Bootstrap.class.getClassLoader(), "juh"); } } else { NativeLibraryLoader.loadLibrary(Bootstrap.class.getClassLoader(), "juh"); } M_LOADED_JUH = true; } return UnoRuntime.queryInterface(XComponentContext.class, cppuhelper_bootstrap(ini_file, pairs, Bootstrap.class.getClassLoader())); } private static native Object cppuhelper_bootstrap(String ini_file, String bootstrap_parameters[], ClassLoader loader) throws Exception; /** * Bootstraps the component context from a UNO installation. * * @return a bootstrapped component context. * @throws BootstrapException if things go awry. * @since UDK 3.1.0 */ public static final XComponentContext bootstrap(Path ooPath) throws BootstrapException { String[] defaultArgArray = getDefaultOptions(); return bootstrap(defaultArgArray, ooPath); } /** * Bootstraps the component context from a UNO installation. * * @param argArray an array of strings - commandline options to start instance of soffice with * @return a bootstrapped component context. * @throws BootstrapException if things go awry. * @see #getDefaultOptions() * @since LibreOffice 5.1 */ public static final XComponentContext bootstrap(String[] argArray, Path path) throws BootstrapException { XComponentContext xContext = null; try { // create default local component context XComponentContext xLocalContext = createInitialComponentContext((Map<String, Object>) null); if (xLocalContext == null) { throw new BootstrapException("no local component context!"); } // create call with arguments // We need a socket, pipe does not work. https://api.libreoffice.org/examples/examples.html String[] cmdArray = new String[argArray.length + 2]; cmdArray[0] = path.toAbsolutePath().toString(); cmdArray[1] = "--accept=socket,host=localhost,port=2083" + ";urp;"; System.arraycopy(argArray, 0, cmdArray, 2, argArray.length); // start office process Process p = Runtime.getRuntime().exec(cmdArray); pipe(p.getInputStream(), System.out, "CO> "); pipe(p.getErrorStream(), System.err, "CE> "); // initial service manager XMultiComponentFactory xLocalServiceManager = xLocalContext.getServiceManager(); if (xLocalServiceManager == null) { throw new BootstrapException("no initial service manager!"); } // create a URL resolver XUnoUrlResolver xUrlResolver = UnoUrlResolver.create(xLocalContext); // connection string String sConnect = "uno:socket,host=localhost,port=2083" + ";urp;StarOffice.ComponentContext"; // wait until office is started for (int i = 0; ; ++i) { try { // try to connect to office Object context = xUrlResolver.resolve(sConnect); xContext = UnoRuntime.queryInterface(XComponentContext.class, context); if (xContext == null) { throw new BootstrapException("no component context!"); } break; } catch (com.sun.star.connection.NoConnectException ex) { // Wait 500 ms, then try to connect again, but do not wait // longer than 5 min (= 600 * 500 ms) total: if (i == 600) { throw new BootstrapException(ex); } Thread.sleep(500); } } } catch (BootstrapException e) { throw e; } catch (java.lang.RuntimeException e) { throw e; } catch (java.lang.Exception e) { throw new BootstrapException(e); } return xContext; } private static void pipe(final InputStream in, final PrintStream out, final String prefix) { new Thread("Pipe: " + prefix) { @Override public void run() { try { BufferedReader r = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8)); for (; ; ) { String s = r.readLine(); if (s == null) { break; } out.println(prefix + s); } } catch (UnsupportedEncodingException e) { e.printStackTrace(System.err); } catch (java.io.IOException e) { e.printStackTrace(System.err); } } }.start(); } } // vim:set shiftwidth=4 softtabstop=4 expandtab:
15,255
41.260388
166
java
null
jabref-main/src/main/java/org/jabref/gui/openoffice/CitationEntryViewModel.java
package org.jabref.gui.openoffice; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import org.jabref.model.openoffice.CitationEntry; public class CitationEntryViewModel { private final StringProperty citation = new SimpleStringProperty(""); private final StringProperty extraInformation = new SimpleStringProperty(""); private final String refMarkName; public CitationEntryViewModel(String refMarkName, String citation, String extraInfo) { this.refMarkName = refMarkName; this.citation.setValue(citation); this.extraInformation.setValue(extraInfo); } public CitationEntryViewModel(CitationEntry citationEntry) { this(citationEntry.getRefMarkName(), citationEntry.getContext(), citationEntry.getPageInfo().orElse("")); } public CitationEntry toCitationEntry() { return new CitationEntry(refMarkName, citation.getValue(), extraInformation.getValue()); } public StringProperty citationProperty() { return citation; } public StringProperty extraInformationProperty() { return extraInformation; } public void setExtraInfo(String extraInfo) { extraInformation.setValue(extraInfo); } }
1,261
30.55
113
java
null
jabref-main/src/main/java/org/jabref/gui/openoffice/DetectOpenOfficeInstallation.java
package org.jabref.gui.openoffice; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Optional; import org.jabref.gui.DialogService; import org.jabref.gui.desktop.os.NativeDesktop; import org.jabref.gui.util.DirectoryDialogConfiguration; import org.jabref.logic.l10n.Localization; import org.jabref.logic.openoffice.OpenOfficePreferences; import org.jabref.logic.util.OS; import org.jabref.logic.util.io.FileUtil; import org.jabref.model.strings.StringUtil; /** * Tools for automatically detecting OpenOffice or LibreOffice installations. */ public class DetectOpenOfficeInstallation { private final OpenOfficePreferences openOfficePreferences; private final DialogService dialogService; public DetectOpenOfficeInstallation(OpenOfficePreferences openOfficePreferences, DialogService dialogService) { this.dialogService = dialogService; this.openOfficePreferences = openOfficePreferences; } public boolean isExecutablePathDefined() { return checkAutoDetectedPaths(openOfficePreferences); } public Optional<Path> selectInstallationPath() { final NativeDesktop nativeDesktop = OS.getNativeDesktop(); dialogService.showInformationDialogAndWait(Localization.lang("Could not find OpenOffice/LibreOffice installation"), Localization.lang("Unable to autodetect OpenOffice/LibreOffice installation. Please choose the installation directory manually.")); DirectoryDialogConfiguration dirDialogConfiguration = new DirectoryDialogConfiguration.Builder() .withInitialDirectory(nativeDesktop.getApplicationDirectory()) .build(); return dialogService.showDirectorySelectionDialog(dirDialogConfiguration); } /** * Checks whether the executablePath exists */ private boolean checkAutoDetectedPaths(OpenOfficePreferences openOfficePreferences) { String executablePath = openOfficePreferences.getExecutablePath(); if (OS.LINUX && (System.getenv("FLATPAK_SANDBOX_DIR") != null)) { executablePath = OpenOfficePreferences.DEFAULT_LINUX_FLATPAK_EXEC_PATH; } return !StringUtil.isNullOrEmpty(executablePath) && Files.exists(Path.of(executablePath)); } public boolean setOpenOfficePreferences(Path installDir) { Optional<Path> execPath = Optional.empty(); if (OS.WINDOWS) { execPath = FileUtil.find(OpenOfficePreferences.WINDOWS_EXECUTABLE, installDir); } else if (OS.OS_X) { execPath = FileUtil.find(OpenOfficePreferences.OSX_EXECUTABLE, installDir); } else if (OS.LINUX) { execPath = FileUtil.find(OpenOfficePreferences.LINUX_EXECUTABLE, installDir); } if (execPath.isPresent()) { openOfficePreferences.setExecutablePath(execPath.get().toString()); return true; } return false; } public Optional<Path> chooseAmongInstallations(List<Path> installDirs) { if (installDirs.isEmpty()) { return Optional.empty(); } if (installDirs.size() == 1) { return Optional.of(installDirs.get(0).toAbsolutePath()); } return dialogService.showChoiceDialogAndWait( Localization.lang("Choose OpenOffice/LibreOffice executable"), Localization.lang("Found more than one OpenOffice/LibreOffice executable.") + "\n" + Localization.lang("Please choose which one to connect to:"), Localization.lang("Use selected instance"), installDirs); } }
3,650
38.258065
147
java
null
jabref-main/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java
package org.jabref.gui.openoffice; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.ButtonType; import javafx.scene.control.TableColumn; import javafx.scene.control.TableColumn.CellEditEvent; import javafx.scene.control.TableView; import javafx.scene.control.cell.TextFieldTableCell; import javafx.scene.layout.FlowPane; import javafx.scene.text.Text; import org.jabref.gui.DialogService; import org.jabref.gui.util.BaseDialog; import org.jabref.gui.util.ValueTableCellFactory; import org.jabref.logic.l10n.Localization; import org.jabref.model.strings.StringUtil; import com.airhacks.afterburner.views.ViewLoader; import jakarta.inject.Inject; public class ManageCitationsDialogView extends BaseDialog<Void> { private static final String HTML_BOLD_END_TAG = "</b>"; private static final String HTML_BOLD_START_TAG = "<b>"; private final OOBibBase ooBase; @FXML private TableView<CitationEntryViewModel> citationsTableView; @FXML private TableColumn<CitationEntryViewModel, String> citation; @FXML private TableColumn<CitationEntryViewModel, String> extraInfo; @Inject private DialogService dialogService; private ManageCitationsDialogViewModel viewModel; public ManageCitationsDialogView(OOBibBase ooBase) { this.ooBase = ooBase; ViewLoader.view(this) .load() .setAsDialogPane(this); setResultConverter(btn -> { if (btn == ButtonType.OK) { viewModel.storeSettings(); } return null; }); setTitle(Localization.lang("Manage citations")); } @FXML private void initialize() { viewModel = new ManageCitationsDialogViewModel(ooBase, dialogService); citation.setCellValueFactory(cellData -> cellData.getValue().citationProperty()); new ValueTableCellFactory<CitationEntryViewModel, String>().withGraphic(this::getText).install(citation); extraInfo.setCellValueFactory(cellData -> cellData.getValue().extraInformationProperty()); extraInfo.setEditable(true); citationsTableView.setEditable(true); citationsTableView.itemsProperty().bindBidirectional(viewModel.citationsProperty()); extraInfo.setOnEditCommit((CellEditEvent<CitationEntryViewModel, String> cell) -> cell.getRowValue().setExtraInfo(cell.getNewValue())); extraInfo.setCellFactory(TextFieldTableCell.forTableColumn()); } private Node getText(String citationContext) { String inBetween = StringUtil.substringBetween(citationContext, HTML_BOLD_START_TAG, HTML_BOLD_END_TAG); String start = citationContext.substring(0, citationContext.indexOf(HTML_BOLD_START_TAG)); String end = citationContext.substring(citationContext.lastIndexOf(HTML_BOLD_END_TAG) + HTML_BOLD_END_TAG.length()); Text startText = new Text(start); Text inBetweenText = new Text(inBetween); inBetweenText.setStyle("-fx-font-weight: bold"); Text endText = new Text(end); return new FlowPane(startText, inBetweenText, endText); } public boolean isOkToShowThisDialog() { return viewModel != null && !viewModel.failedToGetCitationEntries; } }
3,268
35.322222
124
java
null
jabref-main/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java
package org.jabref.gui.openoffice; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import javafx.beans.property.ListProperty; import javafx.beans.property.SimpleListProperty; import javafx.collections.FXCollections; import org.jabref.gui.DialogService; import org.jabref.model.openoffice.CitationEntry; public class ManageCitationsDialogViewModel { public final boolean failedToGetCitationEntries; private final ListProperty<CitationEntryViewModel> citations = new SimpleListProperty<>(FXCollections.observableArrayList()); private final OOBibBase ooBase; private final DialogService dialogService; public ManageCitationsDialogViewModel(OOBibBase ooBase, DialogService dialogService) { this.ooBase = ooBase; this.dialogService = dialogService; Optional<List<CitationEntry>> citationEntries = ooBase.guiActionGetCitationEntries(); this.failedToGetCitationEntries = citationEntries.isEmpty(); if (citationEntries.isEmpty()) { return; } for (CitationEntry entry : citationEntries.get()) { CitationEntryViewModel itemViewModelEntry = new CitationEntryViewModel(entry); citations.add(itemViewModelEntry); } } public void storeSettings() { List<CitationEntry> citationEntries = citations.stream().map(CitationEntryViewModel::toCitationEntry).collect(Collectors.toList()); ooBase.guiActionApplyCitationEntries(citationEntries); } public ListProperty<CitationEntryViewModel> citationsProperty() { return citations; } }
1,624
33.574468
139
java
null
jabref-main/src/main/java/org/jabref/gui/openoffice/OOBibBase.java
package org.jabref.gui.openoffice; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.Supplier; import java.util.stream.Collectors; import org.jabref.gui.DialogService; import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; import org.jabref.logic.openoffice.NoDocumentFoundException; import org.jabref.logic.openoffice.action.EditInsert; import org.jabref.logic.openoffice.action.EditMerge; import org.jabref.logic.openoffice.action.EditSeparate; import org.jabref.logic.openoffice.action.ExportCited; import org.jabref.logic.openoffice.action.ManageCitations; import org.jabref.logic.openoffice.action.Update; import org.jabref.logic.openoffice.frontend.OOFrontend; import org.jabref.logic.openoffice.frontend.RangeForOverlapCheck; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.openoffice.CitationEntry; import org.jabref.model.openoffice.rangesort.FunctionalTextViewCursor; import org.jabref.model.openoffice.style.CitationGroupId; import org.jabref.model.openoffice.style.CitationType; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; import org.jabref.model.openoffice.uno.UnoCrossRef; import org.jabref.model.openoffice.uno.UnoCursor; import org.jabref.model.openoffice.uno.UnoRedlines; import org.jabref.model.openoffice.uno.UnoStyle; import org.jabref.model.openoffice.uno.UnoUndo; import org.jabref.model.openoffice.util.OOResult; import org.jabref.model.openoffice.util.OOVoidResult; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; import com.sun.star.beans.PropertyVetoException; import com.sun.star.comp.helper.BootstrapException; import com.sun.star.container.NoSuchElementException; import com.sun.star.lang.DisposedException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextDocument; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Class for manipulating the Bibliography of the currently started document in OpenOffice. */ class OOBibBase { private static final Logger LOGGER = LoggerFactory.getLogger(OOBibBase.class); private final DialogService dialogService; // After inserting a citation, if ooPrefs.getSyncWhenCiting() returns true, shall we also update the bibliography? private final boolean refreshBibliographyDuringSyncWhenCiting; // Shall we add "Cited on pages: ..." to resolved bibliography entries? private final boolean alwaysAddCitedOnPages; private final OOBibBaseConnect connection; public OOBibBase(Path loPath, DialogService dialogService) throws BootstrapException, CreationException { this.dialogService = dialogService; this.connection = new OOBibBaseConnect(loPath, dialogService); this.refreshBibliographyDuringSyncWhenCiting = false; this.alwaysAddCitedOnPages = false; } public void guiActionSelectDocument(boolean autoSelectForSingle) { final String errorTitle = Localization.lang("Problem connecting"); try { this.connection.selectDocument(autoSelectForSingle); } catch (NoDocumentFoundException ex) { OOError.from(ex).showErrorDialog(dialogService); } catch (DisposedException ex) { OOError.from(ex).setTitle(errorTitle).showErrorDialog(dialogService); } catch (WrappedTargetException | IndexOutOfBoundsException | NoSuchElementException ex) { LOGGER.warn("Problem connecting", ex); OOError.fromMisc(ex).setTitle(errorTitle).showErrorDialog(dialogService); } if (this.isConnectedToDocument()) { dialogService.notify(Localization.lang("Connected to document") + ": " + this.getCurrentDocumentTitle().orElse("")); } } /** * A simple test for document availability. * <p> * See also `isDocumentConnectionMissing` for a test actually attempting to use the connection. */ public boolean isConnectedToDocument() { return this.connection.isConnectedToDocument(); } /** * @return true if we are connected to a document */ public boolean isDocumentConnectionMissing() { return this.connection.isDocumentConnectionMissing(); } /** * Either return an XTextDocument or return JabRefException. */ public OOResult<XTextDocument, OOError> getXTextDocument() { return this.connection.getXTextDocument(); } /** * The title of the current document, or Optional.empty() */ public Optional<String> getCurrentDocumentTitle() { return this.connection.getCurrentDocumentTitle(); } /* ****************************************************** * * Tools to collect and show precondition test results * * ******************************************************/ void showDialog(OOError err) { err.showErrorDialog(dialogService); } void showDialog(String errorTitle, OOError err) { err.setTitle(errorTitle).showErrorDialog(dialogService); } OOVoidResult<OOError> collectResults(String errorTitle, List<OOVoidResult<OOError>> results) { String msg = results.stream() .filter(OOVoidResult::isError) .map(e -> e.getError().getLocalizedMessage()) .collect(Collectors.joining("\n\n")); if (msg.isEmpty()) { return OOVoidResult.ok(); } else { return OOVoidResult.error(new OOError(errorTitle, msg)); } } boolean testDialog(OOVoidResult<OOError> res) { return res.ifError(ex -> ex.showErrorDialog(dialogService)).isError(); } boolean testDialog(String errorTitle, OOVoidResult<OOError> res) { return res.ifError(e -> showDialog(e.setTitle(errorTitle))).isError(); } boolean testDialog(String errorTitle, List<OOVoidResult<OOError>> results) { return testDialog(errorTitle, collectResults(errorTitle, results)); } @SafeVarargs final boolean testDialog(String errorTitle, OOVoidResult<OOError>... results) { List<OOVoidResult<OOError>> resultList = Arrays.asList(results); return testDialog(collectResults(errorTitle, resultList)); } /** * Get the cursor positioned by the user for inserting text. */ OOResult<XTextCursor, OOError> getUserCursorForTextInsertion(XTextDocument doc, String errorTitle) { // Get the cursor positioned by the user. XTextCursor cursor = UnoCursor.getViewCursor(doc).orElse(null); // Check for crippled XTextViewCursor Objects.requireNonNull(cursor); try { cursor.getStart(); } catch (com.sun.star.uno.RuntimeException ex) { String msg = Localization.lang("Please move the cursor" + " to the location for the new citation.") + "\n" + Localization.lang("I cannot insert to the cursors current location."); return OOResult.error(new OOError(errorTitle, msg, ex)); } return OOResult.ok(cursor); } /** * This may move the view cursor. */ OOResult<FunctionalTextViewCursor, OOError> getFunctionalTextViewCursor(XTextDocument doc, String errorTitle) { String messageOnFailureToObtain = Localization.lang("Please move the cursor into the document text.") + "\n" + Localization.lang("To get the visual positions of your citations" + " I need to move the cursor around," + " but could not get it."); OOResult<FunctionalTextViewCursor, String> result = FunctionalTextViewCursor.get(doc); if (result.isError()) { LOGGER.warn(result.getError()); } return result.mapError(detail -> new OOError(errorTitle, messageOnFailureToObtain)); } private static OOVoidResult<OOError> checkRangeOverlaps(XTextDocument doc, OOFrontend frontend) { final String errorTitle = "Overlapping ranges"; boolean requireSeparation = false; int maxReportedOverlaps = 10; try { return frontend.checkRangeOverlaps(doc, new ArrayList<>(), requireSeparation, maxReportedOverlaps) .mapError(OOError::from); } catch (NoDocumentException ex) { return OOVoidResult.error(OOError.from(ex).setTitle(errorTitle)); } catch (WrappedTargetException ex) { return OOVoidResult.error(OOError.fromMisc(ex).setTitle(errorTitle)); } } private static OOVoidResult<OOError> checkRangeOverlapsWithCursor(XTextDocument doc, OOFrontend frontend) { final String errorTitle = "Ranges overlapping with cursor"; List<RangeForOverlapCheck<CitationGroupId>> userRanges; userRanges = frontend.viewCursorRanges(doc); boolean requireSeparation = false; OOVoidResult<JabRefException> res; try { res = frontend.checkRangeOverlapsWithCursor(doc, userRanges, requireSeparation); } catch (NoDocumentException ex) { return OOVoidResult.error(OOError.from(ex).setTitle(errorTitle)); } catch (WrappedTargetException ex) { return OOVoidResult.error(OOError.fromMisc(ex).setTitle(errorTitle)); } if (res.isError()) { final String xtitle = Localization.lang("The cursor is in a protected area."); return OOVoidResult.error( new OOError(xtitle, xtitle + "\n" + res.getError().getLocalizedMessage() + "\n")); } return res.mapError(OOError::from); } /* ****************************************************** * * Tests for preconditions. * * ******************************************************/ private static OOVoidResult<OOError> checkIfOpenOfficeIsRecordingChanges(XTextDocument doc) { String errorTitle = Localization.lang("Recording and/or Recorded changes"); try { boolean recordingChanges = UnoRedlines.getRecordChanges(doc); int nRedlines = UnoRedlines.countRedlines(doc); if (recordingChanges || (nRedlines > 0)) { String msg = ""; if (recordingChanges) { msg += Localization.lang("Cannot work with" + " [Edit]/[Track Changes]/[Record] turned on."); } if (nRedlines > 0) { if (recordingChanges) { msg += "\n"; } msg += Localization.lang("Changes by JabRef" + " could result in unexpected interactions with" + " recorded changes."); msg += "\n"; msg += Localization.lang("Use [Edit]/[Track Changes]/[Manage] to resolve them first."); } return OOVoidResult.error(new OOError(errorTitle, msg)); } } catch (WrappedTargetException ex) { String msg = Localization.lang("Error while checking if Writer" + " is recording changes or has recorded changes."); return OOVoidResult.error(new OOError(errorTitle, msg, ex)); } return OOVoidResult.ok(); } OOVoidResult<OOError> styleIsRequired(OOBibStyle style) { if (style == null) { return OOVoidResult.error(OOError.noValidStyleSelected()); } else { return OOVoidResult.ok(); } } OOResult<OOFrontend, OOError> getFrontend(XTextDocument doc) { final String errorTitle = "Unable to get frontend"; try { return OOResult.ok(new OOFrontend(doc)); } catch (NoDocumentException ex) { return OOResult.error(OOError.from(ex).setTitle(errorTitle)); } catch (WrappedTargetException | RuntimeException ex) { return OOResult.error(OOError.fromMisc(ex).setTitle(errorTitle)); } } OOVoidResult<OOError> databaseIsRequired(List<BibDatabase> databases, Supplier<OOError> fun) { if (databases == null || databases.isEmpty()) { return OOVoidResult.error(fun.get()); } else { return OOVoidResult.ok(); } } OOVoidResult<OOError> selectedBibEntryIsRequired(List<BibEntry> entries, Supplier<OOError> fun) { if (entries == null || entries.isEmpty()) { return OOVoidResult.error(fun.get()); } else { return OOVoidResult.ok(); } } /* * Checks existence and also checks if it is not an internal name. */ private OOVoidResult<OOError> checkStyleExistsInTheDocument(String familyName, String styleName, XTextDocument doc, String labelInJstyleFile, String pathToStyleFile) throws WrappedTargetException { Optional<String> internalName = UnoStyle.getInternalNameOfStyle(doc, familyName, styleName); if (internalName.isEmpty()) { String msg = switch (familyName) { case UnoStyle.PARAGRAPH_STYLES -> Localization.lang("The %0 paragraph style '%1' is missing from the document", labelInJstyleFile, styleName); case UnoStyle.CHARACTER_STYLES -> Localization.lang("The %0 character style '%1' is missing from the document", labelInJstyleFile, styleName); default -> throw new IllegalArgumentException("Expected " + UnoStyle.CHARACTER_STYLES + " or " + UnoStyle.PARAGRAPH_STYLES + " for familyName"); } + "\n" + Localization.lang("Please create it in the document or change in the file:") + "\n" + pathToStyleFile; return OOVoidResult.error(new OOError("StyleIsNotKnown", msg)); } if (!internalName.get().equals(styleName)) { String msg = switch (familyName) { case UnoStyle.PARAGRAPH_STYLES -> Localization.lang("The %0 paragraph style '%1' is a display name for '%2'.", labelInJstyleFile, styleName, internalName.get()); case UnoStyle.CHARACTER_STYLES -> Localization.lang("The %0 character style '%1' is a display name for '%2'.", labelInJstyleFile, styleName, internalName.get()); default -> throw new IllegalArgumentException("Expected " + UnoStyle.CHARACTER_STYLES + " or " + UnoStyle.PARAGRAPH_STYLES + " for familyName"); } + "\n" + Localization.lang("Please use the latter in the style file below" + " to avoid localization problems.") + "\n" + pathToStyleFile; return OOVoidResult.error(new OOError("StyleNameIsNotInternal", msg)); } return OOVoidResult.ok(); } public OOVoidResult<OOError> checkStylesExistInTheDocument(OOBibStyle style, XTextDocument doc) { String pathToStyleFile = style.getPath(); List<OOVoidResult<OOError>> results = new ArrayList<>(); try { results.add(checkStyleExistsInTheDocument(UnoStyle.PARAGRAPH_STYLES, style.getReferenceHeaderParagraphFormat(), doc, "ReferenceHeaderParagraphFormat", pathToStyleFile)); results.add(checkStyleExistsInTheDocument(UnoStyle.PARAGRAPH_STYLES, style.getReferenceParagraphFormat(), doc, "ReferenceParagraphFormat", pathToStyleFile)); if (style.isFormatCitations()) { results.add(checkStyleExistsInTheDocument(UnoStyle.CHARACTER_STYLES, style.getCitationCharacterFormat(), doc, "CitationCharacterFormat", pathToStyleFile)); } } catch (WrappedTargetException ex) { results.add(OOVoidResult.error(new OOError("Other error in checkStyleExistsInTheDocument", ex.getMessage(), ex))); } return collectResults("checkStyleExistsInTheDocument failed", results); } /* ****************************************************** * * ManageCitationsDialogView * * ******************************************************/ public Optional<List<CitationEntry>> guiActionGetCitationEntries() { final Optional<List<CitationEntry>> FAIL = Optional.empty(); final String errorTitle = Localization.lang("Problem collecting citations"); OOResult<XTextDocument, OOError> odoc = getXTextDocument(); if (testDialog(errorTitle, odoc.asVoidResult())) { return FAIL; } XTextDocument doc = odoc.get(); if (testDialog(errorTitle, checkIfOpenOfficeIsRecordingChanges(doc))) { LOGGER.warn(errorTitle); return FAIL; } try { return Optional.of(ManageCitations.getCitationEntries(doc)); } catch (NoDocumentException ex) { OOError.from(ex).setTitle(errorTitle).showErrorDialog(dialogService); return FAIL; } catch (DisposedException ex) { OOError.from(ex).setTitle(errorTitle).showErrorDialog(dialogService); return FAIL; } catch (WrappedTargetException ex) { LOGGER.warn(errorTitle, ex); OOError.fromMisc(ex).setTitle(errorTitle).showErrorDialog(dialogService); return FAIL; } } /** * Apply editable parts of citationEntries to the document: store pageInfo. * <p> * Does not change presentation. * <p> * Note: we use no undo context here, because only DocumentConnection.setUserDefinedStringPropertyValue() is called, and Undo in LO will not undo that. * <p> * GUI: "Manage citations" dialog "OK" button. Called from: ManageCitationsDialogViewModel.storeSettings * * <p> * Currently the only editable part is pageInfo. * <p> * Since the only call to applyCitationEntries() only changes pageInfo w.r.t those returned by getCitationEntries(), we can do with the following restrictions: * <ul> * <li> Missing pageInfo means no action.</li> * <li> Missing CitationEntry means no action (no attempt to remove * citation from the text).</li> * </ul> */ public void guiActionApplyCitationEntries(List<CitationEntry> citationEntries) { final String errorTitle = Localization.lang("Problem modifying citation"); OOResult<XTextDocument, OOError> odoc = getXTextDocument(); if (testDialog(errorTitle, odoc.asVoidResult())) { return; } XTextDocument doc = odoc.get(); try { ManageCitations.applyCitationEntries(doc, citationEntries); } catch (NoDocumentException ex) { OOError.from(ex).setTitle(errorTitle).showErrorDialog(dialogService); } catch (DisposedException ex) { OOError.from(ex).setTitle(errorTitle).showErrorDialog(dialogService); } catch (PropertyVetoException | IllegalTypeException | WrappedTargetException | com.sun.star.lang.IllegalArgumentException ex) { LOGGER.warn(errorTitle, ex); OOError.fromMisc(ex).setTitle(errorTitle).showErrorDialog(dialogService); } } /** * Creates a citation group from {@code entries} at the cursor. * <p> * Uses LO undo context "Insert citation". * <p> * Note: Undo does not remove or reestablish custom properties. * * @param entries The entries to cite. * @param database The database the entries belong to (all of them). Used when creating the citation mark. * <p> * Consistency: for each entry in {@code entries}: looking it up in {@code syncOptions.get().databases} (if present) should yield {@code database}. * @param style The bibliography style we are using. * @param citationType Indicates whether it is an in-text citation, a citation in parenthesis or an invisible citation. * @param pageInfo A single page-info for these entries. Attributed to the last entry. * @param syncOptions Indicates whether in-text citations should be refreshed in the document. Optional.empty() indicates no refresh. Otherwise provides options for refreshing the reference list. */ public void guiActionInsertEntry(List<BibEntry> entries, BibDatabase database, OOBibStyle style, CitationType citationType, String pageInfo, Optional<Update.SyncOptions> syncOptions) { final String errorTitle = "Could not insert citation"; OOResult<XTextDocument, OOError> odoc = getXTextDocument(); if (testDialog(errorTitle, odoc.asVoidResult(), styleIsRequired(style), selectedBibEntryIsRequired(entries, OOError::noEntriesSelectedForCitation))) { return; } XTextDocument doc = odoc.get(); OOResult<OOFrontend, OOError> frontend = getFrontend(doc); if (testDialog(errorTitle, frontend.asVoidResult())) { return; } OOResult<XTextCursor, OOError> cursor = getUserCursorForTextInsertion(doc, errorTitle); if (testDialog(errorTitle, cursor.asVoidResult())) { return; } if (testDialog(errorTitle, checkRangeOverlapsWithCursor(doc, frontend.get()))) { return; } if (testDialog(errorTitle, checkStylesExistInTheDocument(style, doc), checkIfOpenOfficeIsRecordingChanges(doc))) { return; } /* * For sync we need a FunctionalTextViewCursor. */ OOResult<FunctionalTextViewCursor, OOError> fcursor = null; if (syncOptions.isPresent()) { fcursor = getFunctionalTextViewCursor(doc, errorTitle); if (testDialog(errorTitle, fcursor.asVoidResult())) { return; } } syncOptions .map(e -> e.setUpdateBibliography(this.refreshBibliographyDuringSyncWhenCiting)) .map(e -> e.setAlwaysAddCitedOnPages(this.alwaysAddCitedOnPages)); if (syncOptions.isPresent()) { if (testDialog(databaseIsRequired(syncOptions.get().databases, OOError::noDataBaseIsOpenForSyncingAfterCitation))) { return; } } try { UnoUndo.enterUndoContext(doc, "Insert citation"); EditInsert.insertCitationGroup(doc, frontend.get(), cursor.get(), entries, database, style, citationType, pageInfo); if (syncOptions.isPresent()) { Update.resyncDocument(doc, style, fcursor.get(), syncOptions.get()); } } catch (NoDocumentException ex) { OOError.from(ex).setTitle(errorTitle).showErrorDialog(dialogService); } catch (DisposedException ex) { OOError.from(ex).setTitle(errorTitle).showErrorDialog(dialogService); } catch (CreationException | IllegalTypeException | NotRemoveableException | PropertyVetoException | WrappedTargetException ex) { LOGGER.warn("Could not insert entry", ex); OOError.fromMisc(ex).setTitle(errorTitle).showErrorDialog(dialogService); } finally { UnoUndo.leaveUndoContext(doc); } } /** * GUI action "Merge citations" */ public void guiActionMergeCitationGroups(List<BibDatabase> databases, OOBibStyle style) { final String errorTitle = Localization.lang("Problem combining cite markers"); OOResult<XTextDocument, OOError> odoc = getXTextDocument(); if (testDialog(errorTitle, odoc.asVoidResult(), styleIsRequired(style), databaseIsRequired(databases, OOError::noDataBaseIsOpen))) { return; } XTextDocument doc = odoc.get(); OOResult<FunctionalTextViewCursor, OOError> fcursor = getFunctionalTextViewCursor(doc, errorTitle); if (testDialog(errorTitle, fcursor.asVoidResult(), checkStylesExistInTheDocument(style, doc), checkIfOpenOfficeIsRecordingChanges(doc))) { return; } try { UnoUndo.enterUndoContext(doc, "Merge citations"); OOFrontend frontend = new OOFrontend(doc); boolean madeModifications = EditMerge.mergeCitationGroups(doc, frontend, style); if (madeModifications) { UnoCrossRef.refresh(doc); Update.SyncOptions syncOptions = new Update.SyncOptions(databases); Update.resyncDocument(doc, style, fcursor.get(), syncOptions); } } catch (NoDocumentException ex) { OOError.from(ex).setTitle(errorTitle).showErrorDialog(dialogService); } catch (DisposedException ex) { OOError.from(ex).setTitle(errorTitle).showErrorDialog(dialogService); } catch (CreationException | IllegalTypeException | NotRemoveableException | PropertyVetoException | WrappedTargetException | com.sun.star.lang.IllegalArgumentException ex) { LOGGER.warn("Problem combining cite markers", ex); OOError.fromMisc(ex).setTitle(errorTitle).showErrorDialog(dialogService); } finally { UnoUndo.leaveUndoContext(doc); fcursor.get().restore(doc); } } // MergeCitationGroups /** * GUI action "Separate citations". * <p> * Do the opposite of MergeCitationGroups. Combined markers are split, with a space inserted between. */ public void guiActionSeparateCitations(List<BibDatabase> databases, OOBibStyle style) { final String errorTitle = Localization.lang("Problem during separating cite markers"); OOResult<XTextDocument, OOError> odoc = getXTextDocument(); if (testDialog(errorTitle, odoc.asVoidResult(), styleIsRequired(style), databaseIsRequired(databases, OOError::noDataBaseIsOpen))) { return; } XTextDocument doc = odoc.get(); OOResult<FunctionalTextViewCursor, OOError> fcursor = getFunctionalTextViewCursor(doc, errorTitle); if (testDialog(errorTitle, fcursor.asVoidResult(), checkStylesExistInTheDocument(style, doc), checkIfOpenOfficeIsRecordingChanges(doc))) { return; } try { UnoUndo.enterUndoContext(doc, "Separate citations"); OOFrontend frontend = new OOFrontend(doc); boolean madeModifications = EditSeparate.separateCitations(doc, frontend, databases, style); if (madeModifications) { UnoCrossRef.refresh(doc); Update.SyncOptions syncOptions = new Update.SyncOptions(databases); Update.resyncDocument(doc, style, fcursor.get(), syncOptions); } } catch (NoDocumentException ex) { OOError.from(ex).setTitle(errorTitle).showErrorDialog(dialogService); } catch (DisposedException ex) { OOError.from(ex).setTitle(errorTitle).showErrorDialog(dialogService); } catch (CreationException | IllegalTypeException | NotRemoveableException | PropertyVetoException | WrappedTargetException | com.sun.star.lang.IllegalArgumentException ex) { LOGGER.warn("Problem during separating cite markers", ex); OOError.fromMisc(ex).setTitle(errorTitle).showErrorDialog(dialogService); } finally { UnoUndo.leaveUndoContext(doc); fcursor.get().restore(doc); } } /** * GUI action for "Export cited" * <p> * Does not refresh the bibliography. * * @param returnPartialResult If there are some unresolved keys, shall we return an otherwise nonempty result, or Optional.empty()? */ public Optional<BibDatabase> exportCitedHelper(List<BibDatabase> databases, boolean returnPartialResult) { final Optional<BibDatabase> FAIL = Optional.empty(); final String errorTitle = Localization.lang("Unable to generate new library"); OOResult<XTextDocument, OOError> odoc = getXTextDocument(); if (testDialog(errorTitle, odoc.asVoidResult(), databaseIsRequired(databases, OOError::noDataBaseIsOpenForExport))) { return FAIL; } XTextDocument doc = odoc.get(); try { ExportCited.GenerateDatabaseResult result; try { UnoUndo.enterUndoContext(doc, "Changes during \"Export cited\""); result = ExportCited.generateDatabase(doc, databases); } finally { // There should be no changes, thus no Undo entry should appear // in LibreOffice. UnoUndo.leaveUndoContext(doc); } if (!result.newDatabase.hasEntries()) { dialogService.showErrorDialogAndWait( Localization.lang("Unable to generate new library"), Localization.lang("Your OpenOffice/LibreOffice document references" + " no citation keys" + " which could also be found in your current library.")); return FAIL; } List<String> unresolvedKeys = result.unresolvedKeys; if (!unresolvedKeys.isEmpty()) { dialogService.showErrorDialogAndWait( Localization.lang("Unable to generate new library"), Localization.lang("Your OpenOffice/LibreOffice document references" + " at least %0 citation keys" + " which could not be found in your current library." + " Some of these are %1.", String.valueOf(unresolvedKeys.size()), String.join(", ", unresolvedKeys))); if (returnPartialResult) { return Optional.of(result.newDatabase); } else { return FAIL; } } return Optional.of(result.newDatabase); } catch (NoDocumentException ex) { OOError.from(ex).showErrorDialog(dialogService); } catch (DisposedException ex) { OOError.from(ex).setTitle(errorTitle).showErrorDialog(dialogService); } catch (WrappedTargetException | com.sun.star.lang.IllegalArgumentException ex) { LOGGER.warn("Problem generating new database.", ex); OOError.fromMisc(ex).setTitle(errorTitle).showErrorDialog(dialogService); } return FAIL; } /** * GUI action, refreshes citation markers and bibliography. * * @param databases Must have at least one. * @param style Style. */ public void guiActionUpdateDocument(List<BibDatabase> databases, OOBibStyle style) { final String errorTitle = Localization.lang("Unable to synchronize bibliography"); try { OOResult<XTextDocument, OOError> odoc = getXTextDocument(); if (testDialog(errorTitle, odoc.asVoidResult(), styleIsRequired(style))) { return; } XTextDocument doc = odoc.get(); OOResult<FunctionalTextViewCursor, OOError> fcursor = getFunctionalTextViewCursor(doc, errorTitle); if (testDialog(errorTitle, fcursor.asVoidResult(), checkStylesExistInTheDocument(style, doc), checkIfOpenOfficeIsRecordingChanges(doc))) { return; } OOFrontend frontend = new OOFrontend(doc); if (testDialog(errorTitle, checkRangeOverlaps(doc, frontend))) { return; } List<String> unresolvedKeys; try { UnoUndo.enterUndoContext(doc, "Refresh bibliography"); Update.SyncOptions syncOptions = new Update.SyncOptions(databases); syncOptions .setUpdateBibliography(true) .setAlwaysAddCitedOnPages(this.alwaysAddCitedOnPages); unresolvedKeys = Update.synchronizeDocument(doc, frontend, style, fcursor.get(), syncOptions); } finally { UnoUndo.leaveUndoContext(doc); fcursor.get().restore(doc); } if (!unresolvedKeys.isEmpty()) { String msg = Localization.lang( "Your OpenOffice/LibreOffice document references the citation key '%0'," + " which could not be found in your current library.", unresolvedKeys.get(0)); dialogService.showErrorDialogAndWait(errorTitle, msg); } } catch (NoDocumentException ex) { OOError.from(ex).setTitle(errorTitle).showErrorDialog(dialogService); } catch (DisposedException ex) { OOError.from(ex).setTitle(errorTitle).showErrorDialog(dialogService); } catch (CreationException | WrappedTargetException | com.sun.star.lang.IllegalArgumentException ex) { LOGGER.warn("Could not update bibliography", ex); OOError.fromMisc(ex).setTitle(errorTitle).showErrorDialog(dialogService); } } }
36,062
41.228337
200
java
null
jabref-main/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java
package org.jabref.gui.openoffice; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.jabref.gui.DialogService; import org.jabref.logic.l10n.Localization; import org.jabref.logic.openoffice.NoDocumentFoundException; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.model.openoffice.uno.NoDocumentException; import org.jabref.model.openoffice.uno.UnoCast; import org.jabref.model.openoffice.uno.UnoTextDocument; import org.jabref.model.openoffice.util.OOResult; import com.sun.star.bridge.XBridge; import com.sun.star.bridge.XBridgeFactory; import com.sun.star.comp.helper.BootstrapException; import com.sun.star.container.NoSuchElementException; import com.sun.star.container.XEnumeration; import com.sun.star.container.XEnumerationAccess; import com.sun.star.frame.XDesktop; import com.sun.star.lang.WrappedTargetException; import com.sun.star.lang.XComponent; import com.sun.star.lang.XMultiComponentFactory; import com.sun.star.text.XTextDocument; import com.sun.star.uno.XComponentContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.sun.star.uno.UnoRuntime.queryInterface; /** * Establish connection to a document opened in OpenOffice or LibreOffice. */ public class OOBibBaseConnect { private static final Logger LOGGER = LoggerFactory.getLogger(OOBibBaseConnect.class); private final DialogService dialogService; private final XDesktop xDesktop; /** * Created when connected to a document. * <p> * Cleared (to null) when we discover we lost the connection. */ private XTextDocument xTextDocument; public OOBibBaseConnect(Path loPath, DialogService dialogService) throws BootstrapException, CreationException { this.dialogService = dialogService; this.xDesktop = simpleBootstrap(loPath); } private XDesktop simpleBootstrap(Path loPath) throws CreationException, BootstrapException { // Get the office component context: XComponentContext context = org.jabref.gui.openoffice.Bootstrap.bootstrap(loPath); XMultiComponentFactory sem = context.getServiceManager(); // Create the desktop, which is the root frame of the // hierarchy of frames that contain viewable components: Object desktop; try { desktop = sem.createInstanceWithContext("com.sun.star.frame.Desktop", context); } catch (com.sun.star.uno.Exception e) { throw new CreationException(e.getMessage()); } return UnoCast.cast(XDesktop.class, desktop).get(); } /** * Close any open office connection, if none exists does nothing */ public static void closeOfficeConnection() { try { // get the bridge factory from the local service manager XBridgeFactory bridgeFactory = queryInterface(XBridgeFactory.class, org.jabref.gui.openoffice.Bootstrap.createSimpleServiceManager() .createInstance("com.sun.star.bridge.BridgeFactory")); if (bridgeFactory != null) { for (XBridge bridge : bridgeFactory.getExistingBridges()) { // dispose of this bridge after closing its connection queryInterface(XComponent.class, bridge).dispose(); } } } catch (Exception ex) { LOGGER.error("Exception disposing office process connection bridge", ex); } } private static List<XTextDocument> getTextDocuments(XDesktop desktop) throws NoSuchElementException, WrappedTargetException { List<XTextDocument> result = new ArrayList<>(); XEnumerationAccess enumAccess = desktop.getComponents(); XEnumeration compEnum = enumAccess.createEnumeration(); while (compEnum.hasMoreElements()) { Object next = compEnum.nextElement(); XComponent comp = UnoCast.cast(XComponent.class, next).get(); Optional<XTextDocument> doc = UnoCast.cast(XTextDocument.class, comp); doc.ifPresent(result::add); } return result; } /** * Run a dialog allowing the user to choose among the documents in `list`. * * @return Null if no document was selected. Otherwise the document selected. */ private static XTextDocument selectDocumentDialog(List<XTextDocument> list, DialogService dialogService) { class DocumentTitleViewModel { private final XTextDocument xTextDocument; private final String description; public DocumentTitleViewModel(XTextDocument xTextDocument) { this.xTextDocument = xTextDocument; this.description = UnoTextDocument.getFrameTitle(xTextDocument).orElse(""); } public XTextDocument getXtextDocument() { return xTextDocument; } @Override public String toString() { return description; } } List<DocumentTitleViewModel> viewModel = list.stream() .map(DocumentTitleViewModel::new) .collect(Collectors.toList()); // This whole method is part of a background task when // auto-detecting instances, so we need to show dialog in FX // thread Optional<DocumentTitleViewModel> selectedDocument = dialogService .showChoiceDialogAndWait(Localization.lang("Select document"), Localization.lang("Found documents:"), Localization.lang("Use selected document"), viewModel); return selectedDocument .map(DocumentTitleViewModel::getXtextDocument) .orElse(null); } /** * Choose a document to work with. * <p> * Assumes we have already connected to LibreOffice or OpenOffice. * <p> * If there is a single document to choose from, selects that. If there are more than one, shows selection dialog. If there are none, throws NoDocumentFoundException * <p> * After successful selection connects to the selected document and extracts some frequently used parts (starting points for managing its content). * <p> * Finally initializes this.xTextDocument with the selected document and parts extracted. */ public void selectDocument(boolean autoSelectForSingle) throws NoDocumentFoundException, NoSuchElementException, WrappedTargetException { XTextDocument selected; List<XTextDocument> textDocumentList = getTextDocuments(this.xDesktop); if (textDocumentList.isEmpty()) { throw new NoDocumentFoundException("No Writer documents found"); } else if ((textDocumentList.size() == 1) && autoSelectForSingle) { selected = textDocumentList.get(0); // Get the only one } else { // Bring up a dialog selected = OOBibBaseConnect.selectDocumentDialog(textDocumentList, this.dialogService); } if (selected == null) { return; } this.xTextDocument = selected; } /** * Mark the current document as missing. */ private void forgetDocument() { this.xTextDocument = null; } /** * A simple test for document availability. * <p> * See also `isDocumentConnectionMissing` for a test actually attempting to use teh connection. */ public boolean isConnectedToDocument() { return this.xTextDocument != null; } /** * @return true if we are connected to a document */ public boolean isDocumentConnectionMissing() { XTextDocument doc = this.xTextDocument; if (doc == null) { return true; } if (UnoTextDocument.isDocumentConnectionMissing(doc)) { forgetDocument(); return true; } return false; } /** * Either return a valid XTextDocument or throw NoDocumentException. */ public XTextDocument getXTextDocumentOrThrow() throws NoDocumentException { if (isDocumentConnectionMissing()) { throw new NoDocumentException("Not connected to document"); } return this.xTextDocument; } public OOResult<XTextDocument, OOError> getXTextDocument() { if (isDocumentConnectionMissing()) { return OOResult.error(OOError.from(new NoDocumentException())); } return OOResult.ok(this.xTextDocument); } /** * The title of the current document, or Optional.empty() */ public Optional<String> getCurrentDocumentTitle() { if (isDocumentConnectionMissing()) { return Optional.empty(); } else { return UnoTextDocument.getFrameTitle(this.xTextDocument); } } }
9,365
34.210526
169
java
null
jabref-main/src/main/java/org/jabref/gui/openoffice/OOError.java
package org.jabref.gui.openoffice; import org.jabref.gui.DialogService; import org.jabref.logic.JabRefException; import org.jabref.logic.l10n.Localization; import org.jabref.logic.openoffice.NoDocumentFoundException; import org.jabref.model.openoffice.uno.NoDocumentException; import com.sun.star.lang.DisposedException; class OOError extends JabRefException { private String localizedTitle; public OOError(String title, String localizedMessage) { super(localizedMessage, localizedMessage); this.localizedTitle = title; } public OOError(String title, String localizedMessage, Throwable cause) { super(localizedMessage, localizedMessage, cause); this.localizedTitle = title; } public String getTitle() { return localizedTitle; } public OOError setTitle(String title) { localizedTitle = title; return this; } public void showErrorDialog(DialogService dialogService) { dialogService.showErrorDialogAndWait(getTitle(), getLocalizedMessage()); } /* * Conversions from exception caught */ public static OOError from(JabRefException err) { return new OOError( Localization.lang("JabRefException"), err.getLocalizedMessage(), err); } // For DisposedException public static OOError from(DisposedException err) { return new OOError( Localization.lang("Connection lost"), Localization.lang("Connection to OpenOffice/LibreOffice has been lost." + " Please make sure OpenOffice/LibreOffice is running," + " and try to reconnect."), err); } // For NoDocumentException public static OOError from(NoDocumentException err) { return new OOError( Localization.lang("Not connected to document"), Localization.lang("Not connected to any Writer document." + " Please make sure a document is open," + " and use the 'Select Writer document' button" + " to connect to it."), err); } // For NoDocumentFoundException public static OOError from(NoDocumentFoundException err) { return new OOError( Localization.lang("No Writer documents found"), Localization.lang("Could not connect to any Writer document." + " Please make sure a document is open" + " before using the 'Select Writer document' button" + " to connect to it."), err); } public static OOError fromMisc(Exception err) { return new OOError( "Exception", err.getMessage(), err); } /* * Messages for error dialog. These are not thrown. */ // noDataBaseIsOpenForCiting public static OOError noDataBaseIsOpenForCiting() { return new OOError( Localization.lang("No database"), Localization.lang("No bibliography database is open for citation.") + "\n" + Localization.lang("Open one before citing.")); } public static OOError noDataBaseIsOpenForSyncingAfterCitation() { return new OOError( Localization.lang("No database"), Localization.lang("No database is open for updating citation markers after citing.") + "\n" + Localization.lang("Open one before citing.")); } // noDataBaseIsOpenForExport public static OOError noDataBaseIsOpenForExport() { return new OOError( Localization.lang("No database is open"), Localization.lang("We need a database to export from. Open one.")); } // noDataBaseIsOpenForExport public static OOError noDataBaseIsOpen() { return new OOError( Localization.lang("No database is open"), Localization.lang("This operation requires a bibliography database.")); } // noValidStyleSelected public static OOError noValidStyleSelected() { return new OOError(Localization.lang("No valid style file defined"), Localization.lang("No bibliography style is selected for citation.") + "\n" + Localization.lang("Select one before citing.") + "\n" + Localization.lang("You must select either a valid style file," + " or use one of the default styles.")); } // noEntriesSelectedForCitation public static OOError noEntriesSelectedForCitation() { return new OOError(Localization.lang("No entries selected for citation"), Localization.lang("No bibliography entries are selected for citation.") + "\n" + Localization.lang("Select some before citing.")); } }
5,115
35.028169
100
java
null
jabref-main/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java
package org.jabref.gui.openoffice; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Optional; import javax.swing.undo.UndoManager; import javafx.concurrent.Task; import javafx.geometry.Insets; import javafx.geometry.Side; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.CheckMenuItem; import javafx.scene.control.ContextMenu; import javafx.scene.control.MenuItem; import javafx.scene.control.ProgressBar; import javafx.scene.control.RadioMenuItem; import javafx.scene.control.SeparatorMenuItem; import javafx.scene.control.ToggleGroup; import javafx.scene.control.Tooltip; import javafx.scene.layout.FlowPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import javafx.scene.layout.VBox; import org.jabref.gui.DialogService; import org.jabref.gui.JabRefGUI; import org.jabref.gui.StateManager; import org.jabref.gui.actions.ActionFactory; import org.jabref.gui.actions.StandardActions; import org.jabref.gui.help.HelpAction; import org.jabref.gui.icon.IconTheme; import org.jabref.gui.keyboard.KeyBindingRepository; import org.jabref.gui.undo.NamedCompound; import org.jabref.gui.undo.UndoableKeyChange; import org.jabref.gui.util.BackgroundTask; import org.jabref.gui.util.DirectoryDialogConfiguration; import org.jabref.gui.util.TaskExecutor; import org.jabref.logic.citationkeypattern.CitationKeyGenerator; import org.jabref.logic.citationkeypattern.CitationKeyPatternPreferences; import org.jabref.logic.help.HelpFile; import org.jabref.logic.journals.JournalAbbreviationRepository; import org.jabref.logic.l10n.Localization; import org.jabref.logic.openoffice.OpenOfficeFileSearch; import org.jabref.logic.openoffice.OpenOfficePreferences; import org.jabref.logic.openoffice.action.Update; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.logic.openoffice.style.StyleLoader; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.openoffice.style.CitationType; import org.jabref.model.openoffice.uno.CreationException; import org.jabref.preferences.PreferencesService; import com.sun.star.comp.helper.BootstrapException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Pane to manage the interaction between JabRef and OpenOffice. */ public class OpenOfficePanel { private static final Logger LOGGER = LoggerFactory.getLogger(OpenOfficePanel.class); private final DialogService dialogService; private final Button connect; private final Button manualConnect; private final Button selectDocument; private final Button setStyleFile = new Button(Localization.lang("Select style")); private final Button pushEntries = new Button(Localization.lang("Cite")); private final Button pushEntriesInt = new Button(Localization.lang("Cite in-text")); private final Button pushEntriesEmpty = new Button(Localization.lang("Insert empty citation")); private final Button pushEntriesAdvanced = new Button(Localization.lang("Cite special")); private final Button update; private final Button merge = new Button(Localization.lang("Merge citations")); private final Button unmerge = new Button(Localization.lang("Separate citations")); private final Button manageCitations = new Button(Localization.lang("Manage citations")); private final Button exportCitations = new Button(Localization.lang("Export cited")); private final Button settingsB = new Button(Localization.lang("Settings")); private final Button help; private final VBox vbox = new VBox(); private final PreferencesService preferencesService; private final StateManager stateManager; private final UndoManager undoManager; private final TaskExecutor taskExecutor; private final StyleLoader loader; private OOBibBase ooBase; private OOBibStyle style; public OpenOfficePanel(PreferencesService preferencesService, KeyBindingRepository keyBindingRepository, JournalAbbreviationRepository abbreviationRepository, TaskExecutor taskExecutor, DialogService dialogService, StateManager stateManager, UndoManager undoManager) { ActionFactory factory = new ActionFactory(keyBindingRepository); this.preferencesService = preferencesService; this.taskExecutor = taskExecutor; this.dialogService = dialogService; this.stateManager = stateManager; this.undoManager = undoManager; connect = new Button(); connect.setGraphic(IconTheme.JabRefIcons.CONNECT_OPEN_OFFICE.getGraphicNode()); connect.setTooltip(new Tooltip(Localization.lang("Connect"))); connect.setMaxWidth(Double.MAX_VALUE); manualConnect = new Button(); manualConnect.setGraphic(IconTheme.JabRefIcons.CONNECT_OPEN_OFFICE.getGraphicNode()); manualConnect.setTooltip(new Tooltip(Localization.lang("Manual connect"))); manualConnect.setMaxWidth(Double.MAX_VALUE); help = factory.createIconButton(StandardActions.HELP, new HelpAction(HelpFile.OPENOFFICE_LIBREOFFICE, dialogService)); help.setMaxWidth(Double.MAX_VALUE); selectDocument = new Button(); selectDocument.setGraphic(IconTheme.JabRefIcons.OPEN.getGraphicNode()); selectDocument.setTooltip(new Tooltip(Localization.lang("Select Writer document"))); selectDocument.setMaxWidth(Double.MAX_VALUE); update = new Button(); update.setGraphic(IconTheme.JabRefIcons.REFRESH.getGraphicNode()); update.setTooltip(new Tooltip(Localization.lang("Sync OpenOffice/LibreOffice bibliography"))); update.setMaxWidth(Double.MAX_VALUE); loader = new StyleLoader( preferencesService.getOpenOfficePreferences(), preferencesService.getLayoutFormatterPreferences(), abbreviationRepository); initPanel(); } public Node getContent() { return vbox; } /* Note: the style may still be null on return. * * Return true if failed. In this case the dialog is already shown. */ private boolean getOrUpdateTheStyle(String title) { final boolean FAIL = true; final boolean PASS = false; if (style == null) { style = loader.getUsedStyle(); } else { try { style.ensureUpToDate(); } catch (IOException ex) { LOGGER.warn("Unable to reload style file '" + style.getPath() + "'", ex); String msg = Localization.lang("Unable to reload style file") + "'" + style.getPath() + "'" + "\n" + ex.getMessage(); new OOError(title, msg, ex).showErrorDialog(dialogService); return FAIL; } } return PASS; } private void initPanel() { connect.setOnAction(e -> connectAutomatically()); manualConnect.setOnAction(e -> connectManually()); selectDocument.setTooltip(new Tooltip(Localization.lang("Select which open Writer document to work on"))); selectDocument.setOnAction(e -> ooBase.guiActionSelectDocument(false)); setStyleFile.setMaxWidth(Double.MAX_VALUE); setStyleFile.setOnAction(event -> dialogService.showCustomDialogAndWait(new StyleSelectDialogView(loader)) .ifPresent(selectedStyle -> { style = selectedStyle; try { style.ensureUpToDate(); } catch (IOException e) { LOGGER.warn("Unable to reload style file '" + style.getPath() + "'", e); } dialogService.notify(Localization.lang("Current style is '%0'", style.getName())); })); pushEntries.setTooltip(new Tooltip(Localization.lang("Cite selected entries between parenthesis"))); pushEntries.setOnAction(e -> pushEntries(CitationType.AUTHORYEAR_PAR, false)); pushEntries.setMaxWidth(Double.MAX_VALUE); pushEntriesInt.setTooltip(new Tooltip(Localization.lang("Cite selected entries with in-text citation"))); pushEntriesInt.setOnAction(e -> pushEntries(CitationType.AUTHORYEAR_INTEXT, false)); pushEntriesInt.setMaxWidth(Double.MAX_VALUE); pushEntriesEmpty.setTooltip(new Tooltip(Localization.lang("Insert a citation without text (the entry will appear in the reference list)"))); pushEntriesEmpty.setOnAction(e -> pushEntries(CitationType.INVISIBLE_CIT, false)); pushEntriesEmpty.setMaxWidth(Double.MAX_VALUE); pushEntriesAdvanced.setTooltip(new Tooltip(Localization.lang("Cite selected entries with extra information"))); pushEntriesAdvanced.setOnAction(e -> pushEntries(CitationType.AUTHORYEAR_INTEXT, true)); pushEntriesAdvanced.setMaxWidth(Double.MAX_VALUE); update.setTooltip(new Tooltip(Localization.lang("Ensure that the bibliography is up-to-date"))); update.setOnAction(event -> { String title = Localization.lang("Could not update bibliography"); if (getOrUpdateTheStyle(title)) { return; } List<BibDatabase> databases = getBaseList(); ooBase.guiActionUpdateDocument(databases, style); }); merge.setMaxWidth(Double.MAX_VALUE); merge.setTooltip(new Tooltip(Localization.lang("Combine pairs of citations that are separated by spaces only"))); merge.setOnAction(e -> ooBase.guiActionMergeCitationGroups(getBaseList(), style)); unmerge.setMaxWidth(Double.MAX_VALUE); unmerge.setTooltip(new Tooltip(Localization.lang("Separate merged citations"))); unmerge.setOnAction(e -> ooBase.guiActionSeparateCitations(getBaseList(), style)); ContextMenu settingsMenu = createSettingsPopup(); settingsB.setMaxWidth(Double.MAX_VALUE); settingsB.setContextMenu(settingsMenu); settingsB.setOnAction(e -> settingsMenu.show(settingsB, Side.BOTTOM, 0, 0)); manageCitations.setMaxWidth(Double.MAX_VALUE); manageCitations.setOnAction(e -> { ManageCitationsDialogView dialog = new ManageCitationsDialogView(ooBase); if (dialog.isOkToShowThisDialog()) { dialogService.showCustomDialogAndWait(dialog); } }); exportCitations.setMaxWidth(Double.MAX_VALUE); exportCitations.setOnAction(event -> exportEntries()); updateButtonAvailability(); HBox hbox = new HBox(); hbox.getChildren().addAll(connect, manualConnect, selectDocument, update, help); hbox.getChildren().forEach(btn -> HBox.setHgrow(btn, Priority.ALWAYS)); FlowPane flow = new FlowPane(); flow.setPadding(new Insets(5, 5, 5, 5)); flow.setVgap(4); flow.setHgap(4); flow.setPrefWrapLength(200); flow.getChildren().addAll(setStyleFile, pushEntries, pushEntriesInt); flow.getChildren().addAll(pushEntriesAdvanced, pushEntriesEmpty, merge, unmerge); flow.getChildren().addAll(manageCitations, exportCitations, settingsB); vbox.setFillWidth(true); vbox.getChildren().addAll(hbox, flow); } private void exportEntries() { List<BibDatabase> databases = getBaseList(); boolean returnPartialResult = false; Optional<BibDatabase> newDatabase = ooBase.exportCitedHelper(databases, returnPartialResult); if (newDatabase.isPresent()) { BibDatabaseContext databaseContext = new BibDatabaseContext(newDatabase.get()); JabRefGUI.getMainFrame().addTab(databaseContext, true); } } private List<BibDatabase> getBaseList() { List<BibDatabase> databases = new ArrayList<>(); if (preferencesService.getOpenOfficePreferences().getUseAllDatabases()) { for (BibDatabaseContext database : stateManager.getOpenDatabases()) { databases.add(database.getDatabase()); } } else { databases.add(stateManager.getActiveDatabase() .map(BibDatabaseContext::getDatabase) .orElse(new BibDatabase())); } return databases; } private void connectAutomatically() { DetectOpenOfficeInstallation officeInstallation = new DetectOpenOfficeInstallation(preferencesService.getOpenOfficePreferences(), dialogService); if (officeInstallation.isExecutablePathDefined()) { connect(); } else { Task<List<Path>> taskConnectIfInstalled = new Task<>() { @Override protected List<Path> call() { return OpenOfficeFileSearch.detectInstallations(); } }; taskConnectIfInstalled.setOnSucceeded(evt -> { var installations = new ArrayList<>(taskConnectIfInstalled.getValue()); if (installations.isEmpty()) { officeInstallation.selectInstallationPath().ifPresent(installations::add); } Optional<Path> actualFile = officeInstallation.chooseAmongInstallations(installations); if (actualFile.isPresent() && officeInstallation.setOpenOfficePreferences(actualFile.get())) { connect(); } }); taskConnectIfInstalled.setOnFailed(value -> dialogService.showErrorDialogAndWait(Localization.lang("Autodetection failed"), Localization.lang("Autodetection failed"), taskConnectIfInstalled.getException())); dialogService.showProgressDialog(Localization.lang("Autodetecting paths..."), Localization.lang("Autodetecting paths..."), taskConnectIfInstalled); taskExecutor.execute(taskConnectIfInstalled); } } private void connectManually() { var fileDialogConfiguration = new DirectoryDialogConfiguration.Builder().withInitialDirectory(System.getProperty("user.home")).build(); Optional<Path> selectedPath = dialogService.showDirectorySelectionDialog(fileDialogConfiguration); DetectOpenOfficeInstallation officeInstallation = new DetectOpenOfficeInstallation(preferencesService.getOpenOfficePreferences(), dialogService); if (selectedPath.isPresent()) { BackgroundTask.wrap(() -> officeInstallation.setOpenOfficePreferences(selectedPath.get())) .withInitialMessage("Searching for executable") .onFailure(dialogService::showErrorDialogAndWait).onSuccess(value -> { if (value) { connect(); } else { dialogService.showErrorDialogAndWait(Localization.lang("Could not connect to running OpenOffice/LibreOffice."), Localization.lang("If connecting manually, please verify program and library paths.")); } }) .executeWith(taskExecutor); } else { dialogService.showErrorDialogAndWait(Localization.lang("Could not connect to running OpenOffice/LibreOffice."), Localization.lang("If connecting manually, please verify program and library paths.")); } } private void updateButtonAvailability() { boolean isConnected = ooBase != null; boolean isConnectedToDocument = isConnected && !ooBase.isDocumentConnectionMissing(); // For these, we need to watch something boolean hasStyle = true; // (style != null); boolean hasDatabase = true; // !getBaseList().isEmpty(); boolean hasSelectedBibEntry = true; selectDocument.setDisable(!isConnected); pushEntries.setDisable(!(isConnectedToDocument && hasStyle && hasDatabase)); boolean canCite = isConnectedToDocument && hasStyle && hasSelectedBibEntry; pushEntriesInt.setDisable(!canCite); pushEntriesEmpty.setDisable(!canCite); pushEntriesAdvanced.setDisable(!canCite); boolean canRefreshDocument = isConnectedToDocument && hasStyle; update.setDisable(!canRefreshDocument); merge.setDisable(!canRefreshDocument); unmerge.setDisable(!canRefreshDocument); manageCitations.setDisable(!canRefreshDocument); exportCitations.setDisable(!(isConnectedToDocument && hasDatabase)); } private void connect() { Task<OOBibBase> connectTask = new Task<>() { @Override protected OOBibBase call() throws Exception { updateProgress(ProgressBar.INDETERMINATE_PROGRESS, ProgressBar.INDETERMINATE_PROGRESS); var path = Path.of(preferencesService.getOpenOfficePreferences().getExecutablePath()); return createBibBase(path); } }; connectTask.setOnSucceeded(value -> { ooBase = connectTask.getValue(); ooBase.guiActionSelectDocument(true); // Enable actions that depend on Connect: updateButtonAvailability(); }); connectTask.setOnFailed(value -> { Throwable ex = connectTask.getException(); LOGGER.error("autodetect failed", ex); if (ex instanceof UnsatisfiedLinkError) { LOGGER.warn("Could not connect to running OpenOffice/LibreOffice", ex); dialogService.showErrorDialogAndWait(Localization.lang("Unable to connect. One possible reason is that JabRef " + "and OpenOffice/LibreOffice are not both running in either 32 bit mode or 64 bit mode.")); } else if (ex instanceof IOException) { LOGGER.warn("Could not connect to running OpenOffice/LibreOffice", ex); dialogService.showErrorDialogAndWait(Localization.lang("Could not connect to running OpenOffice/LibreOffice."), Localization.lang("Could not connect to running OpenOffice/LibreOffice.") + "\n" + Localization.lang("Make sure you have installed OpenOffice/LibreOffice with Java support.") + "\n" + Localization.lang("If connecting manually, please verify program and library paths.") + "\n" + "\n" + Localization.lang("Error message:"), ex); } else if (ex instanceof BootstrapException bootstrapEx) { LOGGER.error("Exception boostrap cause", bootstrapEx.getTargetException()); dialogService.showErrorDialogAndWait("Bootstrap error", bootstrapEx.getTargetException()); } else { dialogService.showErrorDialogAndWait(Localization.lang("Autodetection failed"), Localization.lang("Autodetection failed"), ex); } }); dialogService.showProgressDialog(Localization.lang("Autodetecting paths..."), Localization.lang("Autodetecting paths..."), connectTask); taskExecutor.execute(connectTask); } private OOBibBase createBibBase(Path loPath) throws BootstrapException, CreationException { return new OOBibBase(loPath, dialogService); } /** * Given the withText and inParenthesis options, return the corresponding citationType. * * @param withText False means invisible citation (no text). * @param inParenthesis True means "(Au and Thor 2000)". False means "Au and Thor (2000)". */ private static CitationType citationTypeFromOptions(boolean withText, boolean inParenthesis) { if (!withText) { return CitationType.INVISIBLE_CIT; } return inParenthesis ? CitationType.AUTHORYEAR_PAR : CitationType.AUTHORYEAR_INTEXT; } private void pushEntries(CitationType citationType, boolean addPageInfo) { final String errorDialogTitle = Localization.lang("Error pushing entries"); if (stateManager.getActiveDatabase().isEmpty() || (stateManager.getActiveDatabase().get().getDatabase() == null)) { OOError.noDataBaseIsOpenForCiting() .setTitle(errorDialogTitle) .showErrorDialog(dialogService); return; } final BibDatabase database = stateManager.getActiveDatabase().get().getDatabase(); if (database == null) { OOError.noDataBaseIsOpenForCiting() .setTitle(errorDialogTitle) .showErrorDialog(dialogService); return; } List<BibEntry> entries = stateManager.getSelectedEntries(); if (entries.isEmpty()) { OOError.noEntriesSelectedForCitation() .setTitle(errorDialogTitle) .showErrorDialog(dialogService); return; } if (getOrUpdateTheStyle(errorDialogTitle)) { return; } String pageInfo = null; if (addPageInfo) { boolean withText = citationType.withText(); Optional<AdvancedCiteDialogViewModel> citeDialogViewModel = dialogService.showCustomDialogAndWait(new AdvancedCiteDialogView()); if (citeDialogViewModel.isPresent()) { AdvancedCiteDialogViewModel model = citeDialogViewModel.get(); if (!model.pageInfoProperty().getValue().isEmpty()) { pageInfo = model.pageInfoProperty().getValue(); } citationType = citationTypeFromOptions(withText, model.citeInParProperty().getValue()); } else { // user canceled return; } } if (!checkThatEntriesHaveKeys(entries)) { // Not all entries have keys and key generation was declined. return; } Optional<Update.SyncOptions> syncOptions = preferencesService.getOpenOfficePreferences().getSyncWhenCiting() ? Optional.of(new Update.SyncOptions(getBaseList())) : Optional.empty(); ooBase.guiActionInsertEntry(entries, database, style, citationType, pageInfo, syncOptions); } /** * Check that all entries in the list have citation keys, if not ask if they should be generated * * @param entries A list of entries to be checked * @return true if all entries have citation keys, if it so may be after generating them */ private boolean checkThatEntriesHaveKeys(List<BibEntry> entries) { // Check if there are empty keys boolean emptyKeys = false; for (BibEntry entry : entries) { if (entry.getCitationKey().isEmpty()) { // Found one, no need to look further for now emptyKeys = true; break; } } // If no empty keys, return true if (!emptyKeys) { return true; } // Ask if keys should be generated boolean citePressed = dialogService.showConfirmationDialogAndWait(Localization.lang("Cite"), Localization.lang("Cannot cite entries without citation keys. Generate keys now?"), Localization.lang("Generate keys"), Localization.lang("Cancel")); Optional<BibDatabaseContext> databaseContext = stateManager.getActiveDatabase(); if (citePressed && databaseContext.isPresent()) { // Generate keys CitationKeyPatternPreferences prefs = preferencesService.getCitationKeyPatternPreferences(); NamedCompound undoCompound = new NamedCompound(Localization.lang("Cite")); for (BibEntry entry : entries) { if (entry.getCitationKey().isEmpty()) { // Generate key new CitationKeyGenerator(databaseContext.get(), prefs) .generateAndSetKey(entry) .ifPresent(change -> undoCompound.addEdit(new UndoableKeyChange(change))); } } undoCompound.end(); // Add all undos undoManager.addEdit(undoCompound); // Now every entry has a key return true; } else { // No, we canceled (or there is no panel to get the database from, highly unlikely) return false; } } private ContextMenu createSettingsPopup() { OpenOfficePreferences openOfficePreferences = preferencesService.getOpenOfficePreferences(); ContextMenu contextMenu = new ContextMenu(); CheckMenuItem autoSync = new CheckMenuItem(Localization.lang("Automatically sync bibliography when inserting citations")); autoSync.selectedProperty().set(preferencesService.getOpenOfficePreferences().getSyncWhenCiting()); ToggleGroup toggleGroup = new ToggleGroup(); RadioMenuItem useActiveBase = new RadioMenuItem(Localization.lang("Look up BibTeX entries in the active tab only")); RadioMenuItem useAllBases = new RadioMenuItem(Localization.lang("Look up BibTeX entries in all open libraries")); useActiveBase.setToggleGroup(toggleGroup); useAllBases.setToggleGroup(toggleGroup); MenuItem clearConnectionSettings = new MenuItem(Localization.lang("Clear connection settings")); if (openOfficePreferences.getUseAllDatabases()) { useAllBases.setSelected(true); } else { useActiveBase.setSelected(true); } autoSync.setOnAction(e -> openOfficePreferences.setSyncWhenCiting(autoSync.isSelected())); useAllBases.setOnAction(e -> openOfficePreferences.setUseAllDatabases(useAllBases.isSelected())); useActiveBase.setOnAction(e -> openOfficePreferences.setUseAllDatabases(!useActiveBase.isSelected())); clearConnectionSettings.setOnAction(e -> { openOfficePreferences.clearConnectionSettings(); dialogService.notify(Localization.lang("Cleared connection settings")); }); contextMenu.getItems().addAll( autoSync, new SeparatorMenuItem(), useActiveBase, useAllBases, new SeparatorMenuItem(), clearConnectionSettings); return contextMenu; } }
26,885
44.802385
233
java
null
jabref-main/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogView.java
package org.jabref.gui.openoffice; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.ContextMenu; import javafx.scene.control.MenuItem; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.layout.VBox; import org.jabref.gui.DialogService; import org.jabref.gui.StateManager; import org.jabref.gui.icon.IconTheme; import org.jabref.gui.preview.PreviewViewer; import org.jabref.gui.theme.ThemeManager; import org.jabref.gui.util.BaseDialog; import org.jabref.gui.util.ValueTableCellFactory; import org.jabref.gui.util.ViewModelTableRowFactory; import org.jabref.logic.l10n.Localization; import org.jabref.logic.layout.TextBasedPreviewLayout; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.logic.openoffice.style.StyleLoader; import org.jabref.logic.util.TestEntry; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.types.StandardEntryType; import org.jabref.preferences.PreferencesService; import com.airhacks.afterburner.views.ViewLoader; import com.tobiasdiez.easybind.EasyBind; import jakarta.inject.Inject; public class StyleSelectDialogView extends BaseDialog<OOBibStyle> { private final MenuItem edit = new MenuItem(Localization.lang("Edit")); private final MenuItem reload = new MenuItem(Localization.lang("Reload")); private final StyleLoader loader; @FXML private TableColumn<StyleSelectItemViewModel, String> colName; @FXML private TableView<StyleSelectItemViewModel> tvStyles; @FXML private TableColumn<StyleSelectItemViewModel, String> colJournals; @FXML private TableColumn<StyleSelectItemViewModel, String> colFile; @FXML private TableColumn<StyleSelectItemViewModel, Boolean> colDeleteIcon; @FXML private Button add; @FXML private VBox vbox; @Inject private PreferencesService preferencesService; @Inject private DialogService dialogService; @Inject private StateManager stateManager; @Inject private ThemeManager themeManager; private StyleSelectDialogViewModel viewModel; private PreviewViewer previewArticle; private PreviewViewer previewBook; public StyleSelectDialogView(StyleLoader loader) { this.loader = loader; ViewLoader.view(this) .load() .setAsDialogPane(this); setResultConverter(button -> { if (button == ButtonType.OK) { viewModel.storePrefs(); return tvStyles.getSelectionModel().getSelectedItem().getStyle(); } return null; }); setTitle(Localization.lang("Style selection")); } @FXML private void initialize() { viewModel = new StyleSelectDialogViewModel(dialogService, loader, preferencesService); previewArticle = new PreviewViewer(new BibDatabaseContext(), dialogService, stateManager, themeManager); previewArticle.setEntry(TestEntry.getTestEntry()); vbox.getChildren().add(previewArticle); previewBook = new PreviewViewer(new BibDatabaseContext(), dialogService, stateManager, themeManager); previewBook.setEntry(TestEntry.getTestEntryBook()); vbox.getChildren().add(previewBook); colName.setCellValueFactory(cellData -> cellData.getValue().nameProperty()); colJournals.setCellValueFactory(cellData -> cellData.getValue().journalsProperty()); colFile.setCellValueFactory(cellData -> cellData.getValue().fileProperty()); colDeleteIcon.setCellValueFactory(cellData -> cellData.getValue().internalStyleProperty()); new ValueTableCellFactory<StyleSelectItemViewModel, Boolean>() .withGraphic(internalStyle -> { if (!internalStyle) { return IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode(); } return null; }) .withOnMouseClickedEvent(item -> evt -> viewModel.deleteStyle()) .withTooltip(item -> Localization.lang("Remove style")) .install(colDeleteIcon); edit.setOnAction(e -> viewModel.editStyle()); new ViewModelTableRowFactory<StyleSelectItemViewModel>() .withOnMouseClickedEvent((item, event) -> { if (event.getClickCount() == 2) { viewModel.viewStyle(item); } }) .withContextMenu(item -> createContextMenu()) .install(tvStyles); tvStyles.getSelectionModel().selectedItemProperty().addListener((observable, oldvalue, newvalue) -> { if (newvalue == null) { viewModel.selectedItemProperty().setValue(oldvalue); } else { viewModel.selectedItemProperty().setValue(newvalue); } }); tvStyles.setItems(viewModel.stylesProperty()); add.setGraphic(IconTheme.JabRefIcons.ADD.getGraphicNode()); EasyBind.subscribe(viewModel.selectedItemProperty(), style -> { tvStyles.getSelectionModel().select(style); previewArticle.setLayout(new TextBasedPreviewLayout(style.getStyle().getReferenceFormat(StandardEntryType.Article))); previewBook.setLayout(new TextBasedPreviewLayout(style.getStyle().getReferenceFormat(StandardEntryType.Book))); }); } private ContextMenu createContextMenu() { ContextMenu contextMenu = new ContextMenu(); contextMenu.getItems().addAll(edit, reload); return contextMenu; } @FXML private void addStyleFile() { viewModel.addStyleFile(); } }
5,732
39.373239
129
java
null
jabref-main/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java
package org.jabref.gui.openoffice; import java.io.IOException; import java.nio.file.Path; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import javafx.beans.property.ListProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleListProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.FXCollections; import javafx.scene.control.ButtonType; import javafx.scene.control.DialogPane; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextArea; import org.jabref.gui.DialogService; import org.jabref.gui.desktop.JabRefDesktop; import org.jabref.gui.externalfiletype.ExternalFileType; import org.jabref.gui.externalfiletype.ExternalFileTypes; import org.jabref.gui.util.FileDialogConfiguration; import org.jabref.logic.l10n.Localization; import org.jabref.logic.openoffice.OpenOfficePreferences; import org.jabref.logic.openoffice.style.OOBibStyle; import org.jabref.logic.openoffice.style.StyleLoader; import org.jabref.logic.util.StandardFileType; import org.jabref.model.database.BibDatabaseContext; import org.jabref.preferences.PreferencesService; public class StyleSelectDialogViewModel { private final DialogService dialogService; private final StyleLoader styleLoader; private final OpenOfficePreferences openOfficePreferences; private final PreferencesService preferencesService; private final ListProperty<StyleSelectItemViewModel> styles = new SimpleListProperty<>(FXCollections.observableArrayList()); private final ObjectProperty<StyleSelectItemViewModel> selectedItem = new SimpleObjectProperty<>(); public StyleSelectDialogViewModel(DialogService dialogService, StyleLoader styleLoader, PreferencesService preferencesService) { this.dialogService = dialogService; this.preferencesService = preferencesService; this.openOfficePreferences = preferencesService.getOpenOfficePreferences(); this.styleLoader = styleLoader; styles.addAll(loadStyles()); String currentStyle = openOfficePreferences.getCurrentStyle(); selectedItem.setValue(getStyleOrDefault(currentStyle)); } public StyleSelectItemViewModel fromOOBibStyle(OOBibStyle style) { return new StyleSelectItemViewModel(style.getName(), String.join(", ", style.getJournals()), style.isInternalStyle() ? Localization.lang("Internal style") : style.getPath(), style); } public OOBibStyle toOOBibStyle(StyleSelectItemViewModel item) { return item.getStyle(); } public void addStyleFile() { FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() .addExtensionFilter(Localization.lang("Style file"), StandardFileType.JSTYLE) .withDefaultExtension(Localization.lang("Style file"), StandardFileType.JSTYLE) .withInitialDirectory(preferencesService.getFilePreferences().getWorkingDirectory()) .build(); Optional<Path> path = dialogService.showFileOpenDialog(fileDialogConfiguration); path.map(Path::toAbsolutePath).map(Path::toString).ifPresent(stylePath -> { if (styleLoader.addStyleIfValid(stylePath)) { openOfficePreferences.setCurrentStyle(stylePath); styles.setAll(loadStyles()); selectedItem.setValue(getStyleOrDefault(stylePath)); } else { dialogService.showErrorDialogAndWait(Localization.lang("Invalid style selected"), Localization.lang("You must select a valid style file. Your style is probably missing a line for the type \"default\".")); } }); } public List<StyleSelectItemViewModel> loadStyles() { return styleLoader.getStyles().stream().map(this::fromOOBibStyle).collect(Collectors.toList()); } public ListProperty<StyleSelectItemViewModel> stylesProperty() { return styles; } public void deleteStyle() { OOBibStyle style = selectedItem.getValue().getStyle(); if (styleLoader.removeStyle(style)) { styles.remove(selectedItem.get()); } } public void editStyle() { OOBibStyle style = selectedItem.getValue().getStyle(); Optional<ExternalFileType> type = ExternalFileTypes.getExternalFileTypeByExt("jstyle", preferencesService.getFilePreferences()); try { JabRefDesktop.openExternalFileAnyFormat(new BibDatabaseContext(), preferencesService, style.getPath(), type); } catch (IOException e) { dialogService.showErrorDialogAndWait(e); } } public void viewStyle(StyleSelectItemViewModel item) { DialogPane pane = new DialogPane(); ScrollPane scrollPane = new ScrollPane(); scrollPane.setFitToHeight(true); scrollPane.setFitToWidth(true); TextArea styleView = new TextArea(item.getStyle().getLocalCopy()); scrollPane.setContent(styleView); pane.setContent(scrollPane); dialogService.showCustomDialogAndWait(item.getStyle().getName(), pane, ButtonType.OK); } public ObjectProperty<StyleSelectItemViewModel> selectedItemProperty() { return selectedItem; } public void storePrefs() { List<String> externalStyles = styles.stream() .map(this::toOOBibStyle) .filter(style -> !style.isInternalStyle()) .map(OOBibStyle::getPath) .collect(Collectors.toList()); openOfficePreferences.setExternalStyles(externalStyles); openOfficePreferences.setCurrentStyle(selectedItem.getValue().getStylePath()); } private StyleSelectItemViewModel getStyleOrDefault(String stylePath) { return styles.stream().filter(style -> style.getStylePath().equals(stylePath)).findFirst().orElse(styles.get(0)); } }
5,999
44.112782
220
java
null
jabref-main/src/main/java/org/jabref/gui/openoffice/StyleSelectItemViewModel.java
package org.jabref.gui.openoffice; 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.Node; import org.jabref.gui.icon.IconTheme; import org.jabref.logic.openoffice.style.OOBibStyle; public class StyleSelectItemViewModel { private final StringProperty name = new SimpleStringProperty(""); private final StringProperty journals = new SimpleStringProperty(""); private final StringProperty file = new SimpleStringProperty(""); private final ObjectProperty<Node> icon = new SimpleObjectProperty<>(IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode()); private final OOBibStyle style; private final BooleanProperty internalStyle = new SimpleBooleanProperty(); public StyleSelectItemViewModel(String name, String journals, String file, OOBibStyle style) { this.name.setValue(name); this.journals.setValue(journals); this.file.setValue(file); this.style = style; this.internalStyle.set(style.isInternalStyle()); } public StringProperty nameProperty() { return name; } public StringProperty journalsProperty() { return journals; } public ObjectProperty<Node> iconProperty() { return icon; } public StringProperty fileProperty() { return file; } public OOBibStyle getStyle() { return style; } public BooleanProperty internalStyleProperty() { return internalStyle; } public String getStylePath() { return style.getPath(); } }
1,771
29.033898
126
java
null
jabref-main/src/main/java/org/jabref/gui/preferences/AbstractPreferenceTabView.java
package org.jabref.gui.preferences; import java.util.List; import javafx.scene.Node; import javafx.scene.layout.VBox; import org.jabref.gui.DialogService; import org.jabref.gui.util.TaskExecutor; import org.jabref.preferences.PreferencesService; import jakarta.inject.Inject; public abstract class AbstractPreferenceTabView<T extends PreferenceTabViewModel> extends VBox implements PreferencesTab { @Inject protected TaskExecutor taskExecutor; @Inject protected DialogService dialogService; @Inject protected PreferencesService preferencesService; protected T viewModel; @Override public Node getBuilder() { return this; } @Override public void setValues() { viewModel.setValues(); } @Override public void storeSettings() { viewModel.storeSettings(); } @Override public boolean validateSettings() { return viewModel.validateSettings(); } @Override public List<String> getRestartWarnings() { return viewModel.getRestartWarnings(); } }
1,062
21.617021
122
java
null
jabref-main/src/main/java/org/jabref/gui/preferences/PreferenceTabViewModel.java
package org.jabref.gui.preferences; import java.util.Collections; import java.util.List; public interface PreferenceTabViewModel { /** * This method is called when the dialog is opened, or if it is made * visible after being hidden. The tab should update all its values. * * This is the ONLY PLACE to set values for the fields in the tab. It * is ILLEGAL to set values only at construction time, because the dialog * will be reused and updated. */ void setValues(); /** * This method is called when the user presses OK in the * Preferences dialog. Implementing classes must make sure all * settings presented get stored in PreferencesService. */ void storeSettings(); /** * This method is called before the {@link #storeSettings()} method, * to check if there are illegal settings in the tab, or if is ready * to be closed. * If the tab is *not* ready, it should display a message to the user * informing about the illegal setting. */ default boolean validateSettings() { return true; } /** * This method should be called after storing the preferences, to * collect the properties, which require a restart of JabRef to load * * @return The messages for the changed properties (e. g. "Changed language: English") */ default List<String> getRestartWarnings() { return Collections.emptyList(); } }
1,467
30.913043
90
java