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/fieldeditors/OwnerEditorViewModel.java
|
package org.jabref.gui.fieldeditors;
import org.jabref.gui.autocompleter.SuggestionProvider;
import org.jabref.logic.integrity.FieldCheckers;
import org.jabref.model.entry.field.Field;
import org.jabref.preferences.PreferencesService;
public class OwnerEditorViewModel extends AbstractEditorViewModel {
private final PreferencesService preferences;
public OwnerEditorViewModel(Field field,
SuggestionProvider<?> suggestionProvider,
PreferencesService preferences,
FieldCheckers fieldCheckers) {
super(field, suggestionProvider, fieldCheckers);
this.preferences = preferences;
}
public void setOwner() {
text.set(preferences.getOwnerPreferences().getDefaultOwner());
}
}
| 814
| 34.434783
| 73
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/PaginationEditorViewModel.java
|
package org.jabref.gui.fieldeditors;
import org.jabref.gui.autocompleter.SuggestionProvider;
import org.jabref.logic.integrity.FieldCheckers;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.entry.field.Field;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
public class PaginationEditorViewModel extends MapBasedEditorViewModel<String> {
private BiMap<String, String> itemMap = HashBiMap.create(7);
public PaginationEditorViewModel(Field field, SuggestionProvider<?> suggestionProvider, FieldCheckers fieldCheckers) {
super(field, suggestionProvider, fieldCheckers);
itemMap.put("page", Localization.lang("Page"));
itemMap.put("column", Localization.lang("Column"));
itemMap.put("line", Localization.lang("Line"));
itemMap.put("verse", Localization.lang("Verse"));
itemMap.put("section", Localization.lang("Section"));
itemMap.put("paragraph", Localization.lang("Paragraph"));
itemMap.put("none", Localization.lang("None"));
}
@Override
protected BiMap<String, String> getItemMap() {
return itemMap;
}
@Override
public String convertToDisplayText(String object) {
return object;
}
}
| 1,262
| 33.135135
| 122
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/PatentTypeEditorViewModel.java
|
package org.jabref.gui.fieldeditors;
import org.jabref.gui.autocompleter.SuggestionProvider;
import org.jabref.logic.integrity.FieldCheckers;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.entry.field.Field;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
public class PatentTypeEditorViewModel extends MapBasedEditorViewModel<String> {
private BiMap<String, String> itemMap = HashBiMap.create(12);
public PatentTypeEditorViewModel(Field field, SuggestionProvider<?> suggestionProvider, FieldCheckers fieldCheckers) {
super(field, suggestionProvider, fieldCheckers);
itemMap.put("patent", Localization.lang("Patent"));
itemMap.put("patentde", Localization.lang("German patent"));
itemMap.put("patenteu", Localization.lang("European patent"));
itemMap.put("patentfr", Localization.lang("French patent"));
itemMap.put("patentuk", Localization.lang("British patent"));
itemMap.put("patentus", Localization.lang("U.S. patent"));
itemMap.put("patreq", Localization.lang("Patent request"));
itemMap.put("patreqde", Localization.lang("German patent request"));
itemMap.put("patreqeu", Localization.lang("European patent request"));
itemMap.put("patreqfr", Localization.lang("French patent request"));
itemMap.put("patrequk", Localization.lang("British patent request"));
itemMap.put("patrequs", Localization.lang("U.S. patent request"));
}
@Override
protected BiMap<String, String> getItemMap() {
return itemMap;
}
@Override
public String convertToDisplayText(String object) {
return object;
}
}
| 1,709
| 39.714286
| 122
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/PersonsEditor.java
|
package org.jabref.gui.fieldeditors;
import javafx.scene.Parent;
import javafx.scene.control.TextInputControl;
import javafx.scene.layout.HBox;
import org.jabref.gui.autocompleter.AutoCompletionTextInputBinding;
import org.jabref.gui.autocompleter.SuggestionProvider;
import org.jabref.gui.fieldeditors.contextmenu.EditorMenus;
import org.jabref.gui.util.uithreadaware.UiThreadStringProperty;
import org.jabref.logic.integrity.FieldCheckers;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.Field;
import org.jabref.preferences.PreferencesService;
public class PersonsEditor extends HBox implements FieldEditorFX {
private final PersonsEditorViewModel viewModel;
private final TextInputControl textInput;
private final UiThreadStringProperty decoratedStringProperty;
public PersonsEditor(final Field field,
final SuggestionProvider<?> suggestionProvider,
final PreferencesService preferences,
final FieldCheckers fieldCheckers,
final boolean isMultiLine) {
this.viewModel = new PersonsEditorViewModel(field, suggestionProvider, preferences.getAutoCompletePreferences(), fieldCheckers);
textInput = isMultiLine ? new EditorTextArea() : new EditorTextField();
decoratedStringProperty = new UiThreadStringProperty(viewModel.textProperty());
textInput.textProperty().bindBidirectional(decoratedStringProperty);
((ContextMenuAddable) textInput).initContextMenu(EditorMenus.getNameMenu(textInput));
this.getChildren().add(textInput);
AutoCompletionTextInputBinding.autoComplete(textInput, viewModel::complete, viewModel.getAutoCompletionConverter(), viewModel.getAutoCompletionStrategy());
new EditorValidator(preferences).configureValidation(viewModel.getFieldValidator().getValidationStatus(), textInput);
}
@Override
public void bindToEntry(BibEntry entry) {
viewModel.bindToEntry(entry);
}
@Override
public Parent getNode() {
return this;
}
@Override
public void requestFocus() {
textInput.requestFocus();
}
}
| 2,191
| 38.142857
| 163
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/PersonsEditorViewModel.java
|
package org.jabref.gui.fieldeditors;
import java.util.Collection;
import javafx.util.StringConverter;
import org.jabref.gui.autocompleter.AppendPersonNamesStrategy;
import org.jabref.gui.autocompleter.AutoCompletePreferences;
import org.jabref.gui.autocompleter.AutoCompletionStrategy;
import org.jabref.gui.autocompleter.PersonNameStringConverter;
import org.jabref.gui.autocompleter.SuggestionProvider;
import org.jabref.logic.integrity.FieldCheckers;
import org.jabref.model.entry.Author;
import org.jabref.model.entry.field.Field;
import org.controlsfx.control.textfield.AutoCompletionBinding;
public class PersonsEditorViewModel extends AbstractEditorViewModel {
private final AutoCompletePreferences preferences;
public PersonsEditorViewModel(Field field, SuggestionProvider<?> suggestionProvider, AutoCompletePreferences preferences, FieldCheckers fieldCheckers) {
super(field, suggestionProvider, fieldCheckers);
this.preferences = preferences;
}
public StringConverter<Author> getAutoCompletionConverter() {
return new PersonNameStringConverter(preferences);
}
@SuppressWarnings("unchecked")
public Collection<Author> complete(AutoCompletionBinding.ISuggestionRequest request) {
return (Collection<Author>) super.complete(request);
}
public AutoCompletionStrategy getAutoCompletionStrategy() {
return new AppendPersonNamesStrategy();
}
}
| 1,437
| 34.95
| 156
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/SimpleEditor.java
|
package org.jabref.gui.fieldeditors;
import javafx.scene.Parent;
import javafx.scene.control.TextInputControl;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import org.jabref.gui.autocompleter.AutoCompletionTextInputBinding;
import org.jabref.gui.autocompleter.ContentSelectorSuggestionProvider;
import org.jabref.gui.autocompleter.SuggestionProvider;
import org.jabref.gui.fieldeditors.contextmenu.DefaultMenu;
import org.jabref.logic.integrity.FieldCheckers;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.Field;
import org.jabref.preferences.PreferencesService;
public class SimpleEditor extends HBox implements FieldEditorFX {
private final SimpleEditorViewModel viewModel;
private final TextInputControl textInput;
public SimpleEditor(final Field field,
final SuggestionProvider<?> suggestionProvider,
final FieldCheckers fieldCheckers,
final PreferencesService preferences,
final boolean isMultiLine) {
this.viewModel = new SimpleEditorViewModel(field, suggestionProvider, fieldCheckers);
textInput = isMultiLine ? new EditorTextArea() : new EditorTextField();
HBox.setHgrow(textInput, Priority.ALWAYS);
textInput.textProperty().bindBidirectional(viewModel.textProperty());
((ContextMenuAddable) textInput).initContextMenu(new DefaultMenu(textInput));
this.getChildren().add(textInput);
if (!isMultiLine) {
AutoCompletionTextInputBinding<?> autoCompleter = AutoCompletionTextInputBinding.autoComplete(textInput, viewModel::complete, viewModel.getAutoCompletionStrategy());
if (suggestionProvider instanceof ContentSelectorSuggestionProvider) {
// If content selector values are present, then we want to show the auto complete suggestions immediately on focus
autoCompleter.setShowOnFocus(true);
}
}
new EditorValidator(preferences).configureValidation(viewModel.getFieldValidator().getValidationStatus(), textInput);
}
public SimpleEditor(final Field field,
final SuggestionProvider<?> suggestionProvider,
final FieldCheckers fieldCheckers,
final PreferencesService preferences) {
this(field, suggestionProvider, fieldCheckers, preferences, false);
}
@Override
public void bindToEntry(BibEntry entry) {
viewModel.bindToEntry(entry);
}
@Override
public Parent getNode() {
return this;
}
@Override
public void requestFocus() {
textInput.requestFocus();
}
}
| 2,727
| 38.536232
| 177
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/SimpleEditorViewModel.java
|
package org.jabref.gui.fieldeditors;
import org.jabref.gui.autocompleter.AppendWordsStrategy;
import org.jabref.gui.autocompleter.AutoCompletionStrategy;
import org.jabref.gui.autocompleter.SuggestionProvider;
import org.jabref.logic.integrity.FieldCheckers;
import org.jabref.model.entry.field.Field;
public class SimpleEditorViewModel extends AbstractEditorViewModel {
public SimpleEditorViewModel(Field field, SuggestionProvider<?> suggestionProvider, FieldCheckers fieldCheckers) {
super(field, suggestionProvider, fieldCheckers);
}
public AutoCompletionStrategy getAutoCompletionStrategy() {
return new AppendWordsStrategy();
}
}
| 671
| 34.368421
| 118
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/TextInputControlBehavior.java
|
package org.jabref.gui.fieldeditors;
import javafx.geometry.Point2D;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.skin.TextAreaSkin;
import javafx.scene.control.skin.TextFieldSkin;
import javafx.scene.input.ContextMenuEvent;
import javafx.stage.Screen;
import javafx.stage.Window;
import com.sun.javafx.scene.control.Properties;
/**
* This class contains some code taken from {@link com.sun.javafx.scene.control.behavior.TextInputControlBehavior},
* witch is not accessible and thus we have no other choice.
* TODO: remove this ugly workaround as soon as control behavior is made public
* reported at https://github.com/javafxports/openjdk-jfx/issues/583
*/
public class TextInputControlBehavior {
/**
* taken from {@link com.sun.javafx.scene.control.behavior.TextFieldBehavior#contextMenuRequested(javafx.scene.input.ContextMenuEvent)}
*/
public static void showContextMenu(TextField textField, ContextMenu contextMenu, ContextMenuEvent e) {
double screenX = e.getScreenX();
double screenY = e.getScreenY();
double sceneX = e.getSceneX();
TextFieldSkin skin = (TextFieldSkin) textField.getSkin();
if (Properties.IS_TOUCH_SUPPORTED) {
Point2D menuPos;
if (textField.getSelection().getLength() == 0) {
skin.positionCaret(skin.getIndex(e.getX(), e.getY()), false);
menuPos = skin.getMenuPosition();
} else {
menuPos = skin.getMenuPosition();
if (menuPos != null && (menuPos.getX() <= 0 || menuPos.getY() <= 0)) {
skin.positionCaret(skin.getIndex(e.getX(), e.getY()), false);
menuPos = skin.getMenuPosition();
}
}
if (menuPos != null) {
Point2D p = textField.localToScene(menuPos);
Scene scene = textField.getScene();
Window window = scene.getWindow();
Point2D location = new Point2D(window.getX() + scene.getX() + p.getX(),
window.getY() + scene.getY() + p.getY());
screenX = location.getX();
sceneX = p.getX();
screenY = location.getY();
}
}
double menuWidth = contextMenu.prefWidth(-1);
double menuX = screenX - (Properties.IS_TOUCH_SUPPORTED ? (menuWidth / 2) : 0);
Screen currentScreen = Screen.getPrimary();
Rectangle2D bounds = currentScreen.getBounds();
if (menuX < bounds.getMinX()) {
textField.getProperties().put("CONTEXT_MENU_SCREEN_X", screenX);
textField.getProperties().put("CONTEXT_MENU_SCENE_X", sceneX);
contextMenu.show(textField, bounds.getMinX(), screenY);
} else if (screenX + menuWidth > bounds.getMaxX()) {
double leftOver = menuWidth - (bounds.getMaxX() - screenX);
textField.getProperties().put("CONTEXT_MENU_SCREEN_X", screenX);
textField.getProperties().put("CONTEXT_MENU_SCENE_X", sceneX);
contextMenu.show(textField, screenX - leftOver, screenY);
} else {
textField.getProperties().put("CONTEXT_MENU_SCREEN_X", 0);
textField.getProperties().put("CONTEXT_MENU_SCENE_X", 0);
contextMenu.show(textField, menuX, screenY);
}
e.consume();
}
/**
* taken from {@link com.sun.javafx.scene.control.behavior.TextAreaBehavior#contextMenuRequested(javafx.scene.input.ContextMenuEvent)}
*/
public static void showContextMenu(TextArea textArea, ContextMenu contextMenu, ContextMenuEvent e) {
double screenX = e.getScreenX();
double screenY = e.getScreenY();
double sceneX = e.getSceneX();
TextAreaSkin skin = (TextAreaSkin) textArea.getSkin();
if (Properties.IS_TOUCH_SUPPORTED) {
Point2D menuPos;
if (textArea.getSelection().getLength() == 0) {
skin.positionCaret(skin.getIndex(e.getX(), e.getY()), false);
menuPos = skin.getMenuPosition();
} else {
menuPos = skin.getMenuPosition();
if (menuPos != null && (menuPos.getX() <= 0 || menuPos.getY() <= 0)) {
skin.positionCaret(skin.getIndex(e.getX(), e.getY()), false);
menuPos = skin.getMenuPosition();
}
}
if (menuPos != null) {
Point2D p = textArea.localToScene(menuPos);
Scene scene = textArea.getScene();
Window window = scene.getWindow();
Point2D location = new Point2D(window.getX() + scene.getX() + p.getX(),
window.getY() + scene.getY() + p.getY());
screenX = location.getX();
sceneX = p.getX();
screenY = location.getY();
}
}
double menuWidth = contextMenu.prefWidth(-1);
double menuX = screenX - (Properties.IS_TOUCH_SUPPORTED ? (menuWidth / 2) : 0);
Screen currentScreen = Screen.getPrimary();
Rectangle2D bounds = currentScreen.getBounds();
if (menuX < bounds.getMinX()) {
textArea.getProperties().put("CONTEXT_MENU_SCREEN_X", screenX);
textArea.getProperties().put("CONTEXT_MENU_SCENE_X", sceneX);
contextMenu.show(textArea, bounds.getMinX(), screenY);
} else if (screenX + menuWidth > bounds.getMaxX()) {
double leftOver = menuWidth - (bounds.getMaxX() - screenX);
textArea.getProperties().put("CONTEXT_MENU_SCREEN_X", screenX);
textArea.getProperties().put("CONTEXT_MENU_SCENE_X", sceneX);
contextMenu.show(textArea, screenX - leftOver, screenY);
} else {
textArea.getProperties().put("CONTEXT_MENU_SCREEN_X", 0);
textArea.getProperties().put("CONTEXT_MENU_SCENE_X", 0);
contextMenu.show(textArea, menuX, screenY);
}
e.consume();
}
}
| 6,176
| 42.808511
| 139
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/TypeEditorViewModel.java
|
package org.jabref.gui.fieldeditors;
import org.jabref.gui.autocompleter.SuggestionProvider;
import org.jabref.logic.integrity.FieldCheckers;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.entry.field.Field;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
public class TypeEditorViewModel extends MapBasedEditorViewModel<String> {
private BiMap<String, String> itemMap = HashBiMap.create(8);
public TypeEditorViewModel(Field field, SuggestionProvider<?> suggestionProvider, FieldCheckers fieldCheckers) {
super(field, suggestionProvider, fieldCheckers);
itemMap.put("mathesis", Localization.lang("Master's thesis"));
itemMap.put("phdthesis", Localization.lang("PhD thesis"));
itemMap.put("candthesis", Localization.lang("Candidate thesis"));
itemMap.put("techreport", Localization.lang("Technical report"));
itemMap.put("resreport", Localization.lang("Research report"));
itemMap.put("software", Localization.lang("Software"));
itemMap.put("datacd", Localization.lang("Data CD"));
itemMap.put("audiocd", Localization.lang("Audio CD"));
}
@Override
protected BiMap<String, String> getItemMap() {
return itemMap;
}
@Override
public String convertToDisplayText(String object) {
return object;
}
}
| 1,382
| 35.394737
| 116
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/URLUtil.java
|
package org.jabref.gui.fieldeditors;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.Optional;
import org.jabref.gui.externalfiletype.ExternalFileTypes;
import org.jabref.preferences.FilePreferences;
public class URLUtil {
private static final String URL_EXP = "^(https?|ftp)://.+";
// Detect Google search URL
private static final String GOOGLE_SEARCH_EXP = "^https?://(?:www\\.)?google\\.[\\.a-z]+?/url.*";
private URLUtil() {
}
/**
* Cleans URLs returned by Google search.
*
* <example>
* If you copy links from search results from Google, all links will be enriched with search meta data, e.g.
* https://www.google.de/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&&url=http%3A%2F%2Fwww.inrg.csie.ntu.edu.tw%2Falgorithm2014%2Fhomework%2FWagner-74.pdf&ei=DifeVYHkDYWqU5W0j6gD&usg=AFQjCNFl638rl5KVta1jIMWLyb4CPSZidg&sig2=0hSSMw9XZXL3HJWwEcJtOg
* </example>
*
* @param url the Google search URL string
* @return the cleaned Google URL or @code{url} if no search URL was detected
*/
public static String cleanGoogleSearchURL(String url) {
Objects.requireNonNull(url);
if (!url.matches(GOOGLE_SEARCH_EXP)) {
return url;
}
// Extract destination URL
try {
URL searchURL = new URL(url);
// URL parameters
String query = searchURL.getQuery();
// no parameters
if (query == null) {
return url;
}
// extract url parameter
String[] pairs = query.split("&");
for (String pair : pairs) {
// "clean" url is decoded value of "url" parameter
if (pair.startsWith("url=")) {
String value = pair.substring(pair.indexOf('=') + 1);
String decode = URLDecoder.decode(value, StandardCharsets.UTF_8);
// url?
if (decode.matches(URL_EXP)) {
return decode;
}
}
}
return url;
} catch (MalformedURLException e) {
return url;
}
}
/**
* Checks whether the given String is a URL.
* <p>
* Currently only checks for a protocol String.
*
* @param url the String to check for a URL
* @return true if <c>url</c> contains a valid URL
*/
public static boolean isURL(String url) {
try {
new URL(url);
return true;
} catch (MalformedURLException e) {
return false;
}
}
/**
* Look for the last '.' in the link, and return the following characters.
* <p>
* This gives the extension for most reasonably named links.
*
* @param link The link
* @return The suffix, excluding the dot (e.g. "pdf")
*/
public static Optional<String> getSuffix(final String link, FilePreferences filePreferences) {
String strippedLink = link;
try {
// Try to strip the query string, if any, to get the correct suffix:
URL url = new URL(link);
if ((url.getQuery() != null) && (url.getQuery().length() < (link.length() - 1))) {
strippedLink = link.substring(0, link.length() - url.getQuery().length() - 1);
}
} catch (MalformedURLException e) {
// Don't report this error, since this getting the suffix is a non-critical
// operation, and this error will be triggered and reported elsewhere.
}
// First see if the stripped link gives a reasonable suffix:
String suffix;
int strippedLinkIndex = strippedLink.lastIndexOf('.');
if ((strippedLinkIndex <= 0) || (strippedLinkIndex == (strippedLink.length() - 1))) {
suffix = null;
} else {
suffix = strippedLink.substring(strippedLinkIndex + 1);
}
if (!ExternalFileTypes.isExternalFileTypeByExt(suffix, filePreferences)) {
// If the suffix doesn't seem to give any reasonable file type, try
// with the non-stripped link:
int index = link.lastIndexOf('.');
if ((index <= 0) || (index == (link.length() - 1))) {
// No occurrence, or at the end
// Check if there are path separators in the suffix - if so, it is definitely
// not a proper suffix, so we should give up:
if (strippedLink.substring(strippedLinkIndex + 1).indexOf('/') >= 1) {
return Optional.empty();
} else {
return Optional.of(suffix); // return the first one we found, anyway.
}
} else {
// Check if there are path separators in the suffix - if so, it is definitely
// not a proper suffix, so we should give up:
if (link.substring(index + 1).indexOf('/') >= 1) {
return Optional.empty();
} else {
return Optional.of(link.substring(index + 1));
}
}
} else {
return Optional.ofNullable(suffix);
}
}
}
| 5,384
| 37.191489
| 262
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/UrlEditor.java
|
package org.jabref.gui.fieldeditors;
import java.util.List;
import java.util.function.Supplier;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Parent;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.HBox;
import org.jabref.gui.DialogService;
import org.jabref.gui.autocompleter.SuggestionProvider;
import org.jabref.gui.fieldeditors.contextmenu.EditorMenus;
import org.jabref.logic.formatter.bibtexfields.CleanupUrlFormatter;
import org.jabref.logic.formatter.bibtexfields.TrimWhitespaceFormatter;
import org.jabref.logic.integrity.FieldCheckers;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.Field;
import org.jabref.preferences.PreferencesService;
import com.airhacks.afterburner.views.ViewLoader;
public class UrlEditor extends HBox implements FieldEditorFX {
@FXML private final UrlEditorViewModel viewModel;
@FXML private EditorTextArea textArea;
public UrlEditor(Field field,
DialogService dialogService,
SuggestionProvider<?> suggestionProvider,
FieldCheckers fieldCheckers,
PreferencesService preferences) {
this.viewModel = new UrlEditorViewModel(field, suggestionProvider, dialogService, fieldCheckers);
ViewLoader.view(this)
.root(this)
.load();
textArea.textProperty().bindBidirectional(viewModel.textProperty());
Supplier<List<MenuItem>> contextMenuSupplier = EditorMenus.getCleanupUrlMenu(textArea);
textArea.initContextMenu(contextMenuSupplier);
// init paste handler for UrlEditor to format pasted url link in textArea
textArea.setPasteActionHandler(() -> textArea.setText(new CleanupUrlFormatter().format(new TrimWhitespaceFormatter().format(textArea.getText()))));
new EditorValidator(preferences).configureValidation(viewModel.getFieldValidator().getValidationStatus(), textArea);
}
public UrlEditorViewModel getViewModel() {
return viewModel;
}
@Override
public void bindToEntry(BibEntry entry) {
viewModel.bindToEntry(entry);
}
@Override
public Parent getNode() {
return this;
}
@FXML
private void openExternalLink(ActionEvent event) {
viewModel.openExternalLink();
}
}
| 2,360
| 33.217391
| 155
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/UrlEditorViewModel.java
|
package org.jabref.gui.fieldeditors;
import java.io.IOException;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import org.jabref.gui.DialogService;
import org.jabref.gui.autocompleter.SuggestionProvider;
import org.jabref.gui.desktop.JabRefDesktop;
import org.jabref.logic.integrity.FieldCheckers;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.entry.field.Field;
import org.jabref.model.strings.StringUtil;
import com.tobiasdiez.easybind.EasyBind;
public class UrlEditorViewModel extends AbstractEditorViewModel {
private final DialogService dialogService;
private final BooleanProperty validUrlIsNotPresent = new SimpleBooleanProperty(true);
public UrlEditorViewModel(Field field, SuggestionProvider<?> suggestionProvider, DialogService dialogService, FieldCheckers fieldCheckers) {
super(field, suggestionProvider, fieldCheckers);
this.dialogService = dialogService;
validUrlIsNotPresent.bind(
EasyBind.map(text, input -> StringUtil.isBlank(input) || !URLUtil.isURL(input))
);
}
public boolean isValidUrlIsNotPresent() {
return validUrlIsNotPresent.get();
}
public BooleanProperty validUrlIsNotPresentProperty() {
return validUrlIsNotPresent;
}
public void openExternalLink() {
if (StringUtil.isBlank(text.get())) {
return;
}
try {
JabRefDesktop.openBrowser(text.get());
} catch (IOException ex) {
dialogService.notify(Localization.lang("Unable to open link."));
}
}
}
| 1,635
| 31.078431
| 144
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/WriteMetadataToPdfCommand.java
|
package org.jabref.gui.fieldeditors;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Optional;
import javax.xml.transform.TransformerException;
import org.jabref.gui.DialogService;
import org.jabref.gui.Globals;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.exporter.EmbeddedBibFilePdfExporter;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.xmp.XmpUtilWriter;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.LinkedFile;
import org.jabref.preferences.PreferencesService;
import org.slf4j.Logger;
public class WriteMetadataToPdfCommand extends SimpleCommand {
private final LinkedFile linkedFile;
private final BibDatabaseContext databaseContext;
private final PreferencesService preferences;
private final DialogService dialogService;
private final BibEntry entry;
private final Logger logger;
private final TaskExecutor taskExecutor;
public WriteMetadataToPdfCommand(LinkedFile linkedFile, BibDatabaseContext databaseContext, PreferencesService preferences, DialogService dialogService, BibEntry entry, Logger logger, TaskExecutor taskExecutor) {
this.linkedFile = linkedFile;
this.databaseContext = databaseContext;
this.preferences = preferences;
this.dialogService = dialogService;
this.entry = entry;
this.logger = logger;
this.taskExecutor = taskExecutor;
}
@Override
public void execute() {
BackgroundTask<Void> writeTask = BackgroundTask.wrap(() -> {
Optional<Path> file = linkedFile.findIn(databaseContext, preferences.getFilePreferences());
if (file.isEmpty()) {
dialogService.notify(Localization.lang("Failed to write metadata, file %1 not found.", file.map(Path::toString).orElse("")));
} else {
synchronized (linkedFile) {
try {
// Similar code can be found at {@link org.jabref.gui.exporter.WriteMetadataToPdfAction.writeMetadataToFile}
new XmpUtilWriter(preferences.getXmpPreferences()).writeXmp(file.get(), entry, databaseContext.getDatabase());
EmbeddedBibFilePdfExporter embeddedBibExporter = new EmbeddedBibFilePdfExporter(databaseContext.getMode(), Globals.entryTypesManager, preferences.getFieldPreferences());
embeddedBibExporter.exportToFileByPath(databaseContext, databaseContext.getDatabase(), preferences.getFilePreferences(), file.get(), Globals.journalAbbreviationRepository);
dialogService.notify(Localization.lang("Success! Finished writing metadata."));
} catch (IOException | TransformerException ex) {
dialogService.notify(Localization.lang("Error while writing metadata. See the error log for details."));
logger.error("Error while writing metadata to {}", file.map(Path::toString).orElse(""), ex);
}
}
}
return null;
});
writeTask
.onRunning(() -> setExecutable(false))
.onFinished(() -> setExecutable(true));
taskExecutor.execute(writeTask);
}
}
| 3,421
| 45.876712
| 216
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/YesNoEditorViewModel.java
|
package org.jabref.gui.fieldeditors;
import org.jabref.gui.autocompleter.SuggestionProvider;
import org.jabref.logic.integrity.FieldCheckers;
import org.jabref.model.entry.field.Field;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
public class YesNoEditorViewModel extends MapBasedEditorViewModel<String> {
private BiMap<String, String> itemMap = HashBiMap.create(2);
public YesNoEditorViewModel(Field field, SuggestionProvider<?> suggestionProvider, FieldCheckers fieldCheckers) {
super(field, suggestionProvider, fieldCheckers);
itemMap.put("yes", "Yes");
itemMap.put("no", "No");
}
@Override
protected BiMap<String, String> getItemMap() {
return itemMap;
}
@Override
public String convertToDisplayText(String object) {
return object;
}
}
| 863
| 26.870968
| 117
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/contextmenu/DefaultMenu.java
|
package org.jabref.gui.fieldeditors.contextmenu;
import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;
import javafx.scene.control.CustomMenuItem;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.TextInputControl;
import javafx.scene.control.Tooltip;
import org.jabref.logic.cleanup.Formatter;
import org.jabref.logic.formatter.Formatters;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.strings.StringUtil;
import com.tobiasdiez.easybind.EasyBind;
public class DefaultMenu implements Supplier<List<MenuItem>> {
TextInputControl textInputControl;
/**
* The default menu that contains functions for changing the case of text and doing several conversions.
*
* @param textInputControl that this menu will be connected to
*/
public DefaultMenu(TextInputControl textInputControl) {
this.textInputControl = textInputControl;
}
public List<MenuItem> get() {
return List.of(
getCaseChangeMenu(textInputControl),
getConversionMenu(textInputControl),
new SeparatorMenuItem(),
new ProtectedTermsMenu(textInputControl),
new SeparatorMenuItem(),
getClearFieldMenuItem(textInputControl));
}
private static Menu getCaseChangeMenu(TextInputControl textInputControl) {
Objects.requireNonNull(textInputControl.textProperty());
Menu submenu = new Menu(Localization.lang("Change case"));
for (final Formatter caseChanger : Formatters.getCaseChangers()) {
CustomMenuItem menuItem = new CustomMenuItem(new Label(caseChanger.getName()));
Tooltip toolTip = new Tooltip(caseChanger.getDescription());
Tooltip.install(menuItem.getContent(), toolTip);
EasyBind.subscribe(textInputControl.textProperty(), value -> menuItem.setDisable(StringUtil.isNullOrEmpty(value)));
menuItem.setOnAction(event ->
textInputControl.textProperty().set(caseChanger.format(textInputControl.textProperty().get())));
submenu.getItems().add(menuItem);
}
return submenu;
}
private static Menu getConversionMenu(TextInputControl textInputControl) {
Menu submenu = new Menu(Localization.lang("Convert"));
for (Formatter converter : Formatters.getConverters()) {
CustomMenuItem menuItem = new CustomMenuItem(new Label(converter.getName()));
Tooltip toolTip = new Tooltip(converter.getDescription());
Tooltip.install(menuItem.getContent(), toolTip);
EasyBind.subscribe(textInputControl.textProperty(), value -> menuItem.setDisable(StringUtil.isNullOrEmpty(value)));
menuItem.setOnAction(event ->
textInputControl.textProperty().set(converter.format(textInputControl.textProperty().get())));
submenu.getItems().add(menuItem);
}
return submenu;
}
// Icon: DELETE_SWEEP
private static MenuItem getClearFieldMenuItem(TextInputControl textInputControl) {
MenuItem menuItem = new MenuItem(Localization.lang("Clear"));
menuItem.setOnAction(event -> textInputControl.setText(""));
return menuItem;
}
}
| 3,403
| 38.581395
| 127
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/contextmenu/EditorContextAction.java
|
package org.jabref.gui.fieldeditors.contextmenu;
import java.util.List;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.property.BooleanProperty;
import javafx.scene.control.MenuItem;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextInputControl;
import javafx.scene.input.Clipboard;
import org.jabref.gui.actions.ActionFactory;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.actions.StandardActions;
import org.jabref.gui.keyboard.KeyBindingRepository;
import org.jabref.gui.util.BindingsHelper;
import org.jabref.logic.util.OS;
import com.sun.javafx.scene.control.Properties;
public class EditorContextAction extends SimpleCommand {
private static final boolean SHOW_HANDLES = Properties.IS_TOUCH_SUPPORTED && !OS.OS_X;
private final StandardActions command;
private final TextInputControl textInputControl;
public EditorContextAction(StandardActions command, TextInputControl textInputControl) {
this.command = command;
this.textInputControl = textInputControl;
BooleanProperty editableBinding = textInputControl.editableProperty();
BooleanBinding hasTextBinding = Bindings.createBooleanBinding(() -> textInputControl.getLength() > 0, textInputControl.textProperty());
BooleanBinding hasStringInClipboardBinding = (BooleanBinding) BindingsHelper.constantOf(Clipboard.getSystemClipboard().hasString());
BooleanBinding hasSelectionBinding = Bindings.createBooleanBinding(() -> textInputControl.getSelection().getLength() > 0, textInputControl.selectionProperty());
BooleanBinding allSelectedBinding = Bindings.createBooleanBinding(() -> textInputControl.getSelection().getLength() == textInputControl.getLength());
BooleanBinding maskTextBinding = (BooleanBinding) BindingsHelper.constantOf(textInputControl instanceof PasswordField); // (maskText("A") != "A");
this.executable.bind(
switch (command) {
case COPY -> editableBinding.and(maskTextBinding.not()).and(hasSelectionBinding);
case CUT -> maskTextBinding.not().and(hasSelectionBinding);
case PASTE -> editableBinding.and(hasStringInClipboardBinding);
case DELETE -> editableBinding.and(hasSelectionBinding);
case SELECT_ALL -> {
if (SHOW_HANDLES) {
yield hasTextBinding.and(allSelectedBinding.not());
} else {
yield BindingsHelper.constantOf(true);
}
}
default -> BindingsHelper.constantOf(true);
});
}
@Override
public void execute() {
switch (command) {
case COPY -> textInputControl.copy();
case CUT -> textInputControl.cut();
case PASTE -> textInputControl.paste();
case DELETE -> textInputControl.deleteText(textInputControl.getSelection());
case SELECT_ALL -> textInputControl.selectAll();
}
textInputControl.requestFocus();
}
/**
* Returns the default context menu items (except undo/redo)
*/
public static List<MenuItem> getDefaultContextMenuItems(TextInputControl textInputControl,
KeyBindingRepository keyBindingRepository) {
ActionFactory factory = new ActionFactory(keyBindingRepository);
MenuItem selectAllMenuItem = factory.createMenuItem(StandardActions.SELECT_ALL,
new EditorContextAction(StandardActions.SELECT_ALL, textInputControl));
if (SHOW_HANDLES) {
selectAllMenuItem.getProperties().put("refreshMenu", Boolean.TRUE);
}
return List.of(
factory.createMenuItem(StandardActions.CUT, new EditorContextAction(StandardActions.CUT, textInputControl)),
factory.createMenuItem(StandardActions.COPY, new EditorContextAction(StandardActions.COPY, textInputControl)),
factory.createMenuItem(StandardActions.PASTE, new EditorContextAction(StandardActions.PASTE, textInputControl)),
factory.createMenuItem(StandardActions.DELETE, new EditorContextAction(StandardActions.DELETE, textInputControl)),
selectAllMenuItem);
}
}
| 4,422
| 48.144444
| 168
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/contextmenu/EditorMenus.java
|
package org.jabref.gui.fieldeditors.contextmenu;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
import javafx.scene.control.CustomMenuItem;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextInputControl;
import javafx.scene.control.Tooltip;
import org.jabref.gui.Globals;
import org.jabref.gui.actions.ActionFactory;
import org.jabref.gui.actions.StandardActions;
import org.jabref.gui.edit.CopyDoiUrlAction;
import org.jabref.logic.formatter.bibtexfields.CleanupUrlFormatter;
import org.jabref.logic.formatter.bibtexfields.NormalizeNamesFormatter;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.strings.StringUtil;
import com.tobiasdiez.easybind.EasyBind;
/**
* Provides context menus for the text fields of the entry editor. Note that we use {@link Supplier} to prevent an early
* instantiation of the menus. Therefore, they are attached to each text field but instantiation happens on the first
* right-click of the user in that field. The late instantiation is done by {@link
* org.jabref.gui.fieldeditors.EditorTextArea#initContextMenu(java.util.function.Supplier)}.
*/
public class EditorMenus {
/**
* The default context menu with a specific menu for normalizing person names regarding to BibTex rules.
*
* @param textInput text-input-control that this menu will be connected to
* @return menu containing items of the default menu and an item for normalizing person names
*/
public static Supplier<List<MenuItem>> getNameMenu(final TextInputControl textInput) {
return () -> {
CustomMenuItem normalizeNames = new CustomMenuItem(new Label(Localization.lang("Normalize to BibTeX name format")));
EasyBind.subscribe(textInput.textProperty(), value -> normalizeNames.setDisable(StringUtil.isNullOrEmpty(value)));
normalizeNames.setOnAction(event -> textInput.setText(new NormalizeNamesFormatter().format(textInput.getText())));
Tooltip toolTip = new Tooltip(Localization.lang("If possible, normalize this list of names to conform to standard BibTeX name formatting"));
Tooltip.install(normalizeNames.getContent(), toolTip);
List<MenuItem> menuItems = new ArrayList<>(6);
menuItems.add(normalizeNames);
menuItems.addAll(new DefaultMenu(textInput).get());
return menuItems;
};
}
/**
* The default context menu with a specific menu copying a DOI/ DOI URL.
*
* @param textArea text-area that this menu will be connected to
* @return menu containing items of the default menu and an item for copying a DOI/DOI URL
*/
public static Supplier<List<MenuItem>> getDOIMenu(TextArea textArea) {
return () -> {
ActionFactory factory = new ActionFactory(Globals.getKeyPrefs());
MenuItem copyDoiMenuItem = factory.createMenuItem(StandardActions.COPY_DOI, new CopyDoiUrlAction(textArea, StandardActions.COPY_DOI));
MenuItem copyDoiUrlMenuItem = factory.createMenuItem(StandardActions.COPY_DOI_URL, new CopyDoiUrlAction(textArea, StandardActions.COPY_DOI_URL));
List<MenuItem> menuItems = new ArrayList<>();
menuItems.add(copyDoiMenuItem);
menuItems.add(copyDoiUrlMenuItem);
menuItems.add(new SeparatorMenuItem());
menuItems.addAll(new DefaultMenu(textArea).get());
return menuItems;
};
}
/**
* The default context menu with a specific menu item to cleanup URL.
*
* @param textArea text-area that this menu will be connected to
* @return menu containing items of the default menu and an item to cleanup a URL
*/
public static Supplier<List<MenuItem>> getCleanupUrlMenu(TextArea textArea) {
return () -> {
CustomMenuItem cleanupURL = new CustomMenuItem(new Label(Localization.lang("Cleanup URL link")));
cleanupURL.setDisable(textArea.textProperty().isEmpty().get());
cleanupURL.setOnAction(event -> textArea.setText(new CleanupUrlFormatter().format(textArea.getText())));
List<MenuItem> menuItems = new ArrayList<>();
menuItems.add(cleanupURL);
return menuItems;
};
}
}
| 4,416
| 47.538462
| 157
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/contextmenu/ProtectedTermsMenu.java
|
package org.jabref.gui.fieldeditors.contextmenu;
import java.util.Objects;
import java.util.Optional;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.TextInputControl;
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.cleanup.Formatter;
import org.jabref.logic.formatter.casechanger.ProtectTermsFormatter;
import org.jabref.logic.formatter.casechanger.UnprotectTermsFormatter;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.protectedterms.ProtectedTermsList;
class ProtectedTermsMenu extends Menu {
private static final Formatter FORMATTER = new ProtectTermsFormatter(Globals.protectedTermsLoader);
private final TextInputControl textInputControl;
private final ActionFactory factory = new ActionFactory(Globals.getKeyPrefs());
private final Action protectSelectionActionInformation = new Action() {
@Override
public String getText() {
return Localization.lang("Protect selection");
}
@Override
public Optional<JabRefIcon> getIcon() {
return Optional.of(IconTheme.JabRefIcons.PROTECT_STRING);
}
@Override
public String getDescription() {
return Localization.lang("Add {} around selected text");
}
};
private final Action unprotectSelectionActionInformation = new Action() {
@Override
public String getText() {
return Localization.lang("Unprotect selection");
}
@Override
public String getDescription() {
return Localization.lang("Remove all {} in selected text");
}
};
private class ProtectSelectionAction extends SimpleCommand {
ProtectSelectionAction() {
this.executable.bind(textInputControl.selectedTextProperty().isNotEmpty());
}
@Override
public void execute() {
String selectedText = textInputControl.getSelectedText();
textInputControl.replaceSelection("{" + selectedText + "}");
}
}
private class UnprotectSelectionAction extends SimpleCommand {
public UnprotectSelectionAction() {
this.executable.bind(textInputControl.selectedTextProperty().isNotEmpty());
}
@Override
public void execute() {
String selectedText = textInputControl.getSelectedText();
String formattedString = new UnprotectTermsFormatter().format(selectedText);
textInputControl.replaceSelection(formattedString);
}
}
private class FormatFieldAction extends SimpleCommand {
FormatFieldAction() {
this.executable.bind(textInputControl.textProperty().isNotEmpty());
}
@Override
public void execute() {
textInputControl.setText(FORMATTER.format(textInputControl.getText()));
}
}
private class AddToProtectedTermsAction extends SimpleCommand {
ProtectedTermsList list;
public AddToProtectedTermsAction(ProtectedTermsList list) {
Objects.requireNonNull(list);
this.list = list;
this.executable.bind(textInputControl.selectedTextProperty().isNotEmpty());
}
@Override
public void execute() {
list.addProtectedTerm(textInputControl.getSelectedText());
}
}
public ProtectedTermsMenu(final TextInputControl textInputControl) {
super(Localization.lang("Protect terms"));
this.textInputControl = textInputControl;
getItems().addAll(factory.createMenuItem(protectSelectionActionInformation, new ProtectSelectionAction()),
getExternalFilesMenu(),
new SeparatorMenuItem(),
factory.createMenuItem(() -> Localization.lang("Format field"), new FormatFieldAction()),
factory.createMenuItem(unprotectSelectionActionInformation, new UnprotectSelectionAction()));
}
private Menu getExternalFilesMenu() {
Menu protectedTermsMenu = factory.createSubMenu(() -> Localization.lang("Add selected text to list"));
Globals.protectedTermsLoader.getProtectedTermsLists().stream()
.filter(list -> !list.isInternalList())
.forEach(list -> protectedTermsMenu.getItems().add(
factory.createMenuItem(list::getDescription, new AddToProtectedTermsAction(list))));
if (protectedTermsMenu.getItems().isEmpty()) {
MenuItem emptyItem = new MenuItem(Localization.lang("No list enabled"));
emptyItem.setDisable(true);
protectedTermsMenu.getItems().add(emptyItem);
}
return protectedTermsMenu;
}
}
| 5,044
| 35.294964
| 128
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/identifier/BaseIdentifierEditorViewModel.java
|
package org.jabref.gui.fieldeditors.identifier;
import java.io.IOException;
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 org.jabref.gui.DialogService;
import org.jabref.gui.autocompleter.SuggestionProvider;
import org.jabref.gui.desktop.JabRefDesktop;
import org.jabref.gui.fieldeditors.AbstractEditorViewModel;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.importer.FetcherClientException;
import org.jabref.logic.importer.FetcherServerException;
import org.jabref.logic.importer.IdFetcher;
import org.jabref.logic.importer.util.IdentifierParser;
import org.jabref.logic.integrity.FieldCheckers;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.identifier.Identifier;
import org.jabref.preferences.PreferencesService;
import com.tobiasdiez.easybind.EasyBind;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class BaseIdentifierEditorViewModel<T extends Identifier> extends AbstractEditorViewModel {
private static final Logger LOGGER = LoggerFactory.getLogger(BaseIdentifierEditorViewModel.class);
protected BooleanProperty isInvalidIdentifier = new SimpleBooleanProperty();
protected final BooleanProperty identifierLookupInProgress = new SimpleBooleanProperty(false);
protected final BooleanProperty canLookupIdentifier = new SimpleBooleanProperty(true);
protected final BooleanProperty canFetchBibliographyInformationById = new SimpleBooleanProperty();
protected IdentifierParser identifierParser;
protected final ObjectProperty<Optional<T>> identifier = new SimpleObjectProperty<>(Optional.empty());
protected DialogService dialogService;
protected TaskExecutor taskExecutor;
protected PreferencesService preferences;
public BaseIdentifierEditorViewModel(Field field, SuggestionProvider<?> suggestionProvider, FieldCheckers fieldCheckers, DialogService dialogService, TaskExecutor taskExecutor, PreferencesService preferences) {
super(field, suggestionProvider, fieldCheckers);
this.dialogService = dialogService;
this.taskExecutor = taskExecutor;
this.preferences = preferences;
}
/**
* Since it's not possible to perform the same actions on all identifiers, specific implementations can call the {@code configure}
* method to tell the actions they can perform and the actions they can't. Based on this configuration, the view will enable/disable or
* show/hide certain UI elements for certain identifier editors.
* <p>
* <b>NOTE: This method MUST be called by all the implementation view models in their principal constructor</b>
* */
protected final void configure(boolean canFetchBibliographyInformationById, boolean canLookupIdentifier) {
this.canLookupIdentifier.set(canLookupIdentifier);
this.canFetchBibliographyInformationById.set(canFetchBibliographyInformationById);
}
protected Optional<T> updateIdentifier() {
if (identifierParser == null) {
return Optional.empty();
}
identifier.set((Optional<T>) identifierParser.parse(field));
return identifier.get();
}
protected void handleIdentifierFetchingError(Exception exception, IdFetcher<T> fetcher) {
LOGGER.error("Error while fetching identifier", exception);
if (exception instanceof FetcherClientException) {
dialogService.showInformationDialogAndWait(Localization.lang("Look up %0", fetcher.getName()), Localization.lang("No data was found for the identifier"));
} else if (exception instanceof FetcherServerException) {
dialogService.showInformationDialogAndWait(Localization.lang("Look up %0", fetcher.getName()), Localization.lang("Server not available"));
} else if (exception.getCause() != null) {
dialogService.showWarningDialogAndWait(Localization.lang("Look up %0", fetcher.getName()), Localization.lang("Error occurred %0", exception.getCause().getMessage()));
} else {
dialogService.showWarningDialogAndWait(Localization.lang("Look up %0", fetcher.getName()), Localization.lang("Error occurred %0", exception.getCause().getMessage()));
}
}
public BooleanProperty canFetchBibliographyInformationByIdProperty() {
return canFetchBibliographyInformationById;
}
public boolean getCanFetchBibliographyInformationById() {
return canFetchBibliographyInformationById.get();
}
public BooleanProperty canLookupIdentifierProperty() {
return canLookupIdentifier;
}
public boolean getCanLookupIdentifier() {
return canLookupIdentifier.get();
}
public BooleanProperty isInvalidIdentifierProperty() {
return isInvalidIdentifier;
}
public boolean getIsInvalidIdentifier() {
return isInvalidIdentifier.get();
}
public boolean getIdentifierLookupInProgress() {
return identifierLookupInProgress.get();
}
public BooleanProperty identifierLookupInProgressProperty() {
return identifierLookupInProgress;
}
public void fetchBibliographyInformation(BibEntry bibEntry) {
LOGGER.warn("Unable to fetch bibliography information using the '{}' identifier", field.getDisplayName());
}
public void lookupIdentifier(BibEntry bibEntry) {
LOGGER.warn("Unable to lookup identifier for '{}'", field.getDisplayName());
}
public void openExternalLink() {
identifier.get().flatMap(Identifier::getExternalURI).ifPresent(url -> {
try {
JabRefDesktop.openBrowser(url);
} catch (IOException ex) {
dialogService.showErrorDialogAndWait(Localization.lang("Unable to open link."), ex);
}
}
);
}
@Override
public void bindToEntry(BibEntry entry) {
super.bindToEntry(entry);
identifierParser = new IdentifierParser(entry);
EasyBind.subscribe(textProperty(), ignored -> updateIdentifier());
EasyBind.subscribe(identifier, newIdentifier -> isInvalidIdentifier.set(newIdentifier.isEmpty()));
}
}
| 6,424
| 43.93007
| 214
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/identifier/DoiIdentifierEditorViewModel.java
|
package org.jabref.gui.fieldeditors.identifier;
import org.jabref.gui.DialogService;
import org.jabref.gui.JabRefGUI;
import org.jabref.gui.autocompleter.SuggestionProvider;
import org.jabref.gui.desktop.JabRefDesktop;
import org.jabref.gui.mergeentries.FetchAndMergeEntry;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.importer.fetcher.CrossRef;
import org.jabref.logic.integrity.FieldCheckers;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.identifier.DOI;
import org.jabref.preferences.PreferencesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DoiIdentifierEditorViewModel extends BaseIdentifierEditorViewModel<DOI> {
public static final Logger LOGGER = LoggerFactory.getLogger(DoiIdentifierEditorViewModel.class);
public DoiIdentifierEditorViewModel(SuggestionProvider<?> suggestionProvider, FieldCheckers fieldCheckers, DialogService dialogService, TaskExecutor taskExecutor, PreferencesService preferences) {
super(StandardField.DOI, suggestionProvider, fieldCheckers, dialogService, taskExecutor, preferences);
configure(true, true);
}
@Override
public void lookupIdentifier(BibEntry bibEntry) {
CrossRef doiFetcher = new CrossRef();
BackgroundTask.wrap(() -> doiFetcher.findIdentifier(entry))
.onRunning(() -> identifierLookupInProgress.setValue(true))
.onFinished(() -> identifierLookupInProgress.setValue(false))
.onSuccess(identifier -> {
if (identifier.isPresent()) {
entry.setField(field, identifier.get().getNormalized());
} else {
dialogService.notify(Localization.lang("No %0 found", field.getDisplayName()));
}
}).onFailure(e -> handleIdentifierFetchingError(e, doiFetcher)).executeWith(taskExecutor);
}
@Override
public void fetchBibliographyInformation(BibEntry bibEntry) {
new FetchAndMergeEntry(JabRefGUI.getMainFrame().getCurrentLibraryTab(), taskExecutor, preferences, dialogService).fetchAndMerge(entry, field);
}
@Override
public void openExternalLink() {
identifier.get().map(DOI::getDOI)
.ifPresent(s -> JabRefDesktop.openCustomDoi(s, preferences, dialogService));
}
}
| 2,465
| 43.035714
| 200
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/identifier/EprintIdentifierEditorViewModel.java
|
package org.jabref.gui.fieldeditors.identifier;
import javafx.collections.MapChangeListener;
import javafx.collections.WeakMapChangeListener;
import org.jabref.gui.DialogService;
import org.jabref.gui.autocompleter.SuggestionProvider;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.integrity.FieldCheckers;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.identifier.ARK;
import org.jabref.model.entry.identifier.ArXivIdentifier;
import org.jabref.model.entry.identifier.EprintIdentifier;
import org.jabref.preferences.PreferencesService;
import com.tobiasdiez.easybind.EasyBind;
public class EprintIdentifierEditorViewModel extends BaseIdentifierEditorViewModel<EprintIdentifier> {
// The following listener will be wrapped in a weak reference change listener, thus it will be garbage collected
// automatically once this object is disposed.
// https://en.wikipedia.org/wiki/Lapsed_listener_problem
private MapChangeListener<Field, String> eprintTypeFieldListener = change -> {
Field changedField = change.getKey();
if (StandardField.EPRINTTYPE == changedField) {
updateIdentifier();
}
};
public EprintIdentifierEditorViewModel(SuggestionProvider<?> suggestionProvider, FieldCheckers fieldCheckers, DialogService dialogService, TaskExecutor taskExecutor, PreferencesService preferences) {
super(StandardField.EPRINT, suggestionProvider, fieldCheckers, dialogService, taskExecutor, preferences);
configure(false, false);
EasyBind.subscribe(identifier, newIdentifier -> {
newIdentifier.ifPresent(id -> {
// TODO: We already have a common superclass between ArXivIdentifier and ARK. This could be refactored further.
if (id instanceof ArXivIdentifier) {
configure(true, false);
} else if (id instanceof ARK) {
configure(false, false);
}
});
});
}
@Override
public void bindToEntry(BibEntry entry) {
super.bindToEntry(entry);
// Unlike other identifiers (they only depend on their own field value), eprint depends on eprinttype thus
// its identity changes whenever the eprinttype field changes .e.g. If eprinttype equals 'arxiv' then the eprint identity
// will be of type ArXivIdentifier and if it equals 'ark' then it switches to type ARK.
entry.getFieldsObservable().addListener(new WeakMapChangeListener<>(eprintTypeFieldListener));
}
}
| 2,656
| 46.446429
| 203
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/identifier/ISBNIdentifierEditorViewModel.java
|
package org.jabref.gui.fieldeditors.identifier;
import org.jabref.gui.DialogService;
import org.jabref.gui.JabRefGUI;
import org.jabref.gui.autocompleter.SuggestionProvider;
import org.jabref.gui.mergeentries.FetchAndMergeEntry;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.integrity.FieldCheckers;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.identifier.ISBN;
import org.jabref.preferences.PreferencesService;
public class ISBNIdentifierEditorViewModel extends BaseIdentifierEditorViewModel<ISBN> {
public ISBNIdentifierEditorViewModel(SuggestionProvider<?> suggestionProvider, FieldCheckers fieldCheckers, DialogService dialogService, TaskExecutor taskExecutor, PreferencesService preferences) {
super(StandardField.ISBN, suggestionProvider, fieldCheckers, dialogService, taskExecutor, preferences);
configure(true, false);
}
@Override
public void fetchBibliographyInformation(BibEntry bibEntry) {
new FetchAndMergeEntry(JabRefGUI.getMainFrame().getCurrentLibraryTab(), taskExecutor, preferences, dialogService).fetchAndMerge(entry, field);
}
}
| 1,190
| 46.64
| 201
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/identifier/IdentifierEditor.java
|
package org.jabref.gui.fieldeditors.identifier;
import java.util.Optional;
import javafx.fxml.FXML;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.HBox;
import org.jabref.gui.DialogService;
import org.jabref.gui.autocompleter.SuggestionProvider;
import org.jabref.gui.fieldeditors.EditorTextArea;
import org.jabref.gui.fieldeditors.EditorValidator;
import org.jabref.gui.fieldeditors.FieldEditorFX;
import org.jabref.gui.fieldeditors.contextmenu.DefaultMenu;
import org.jabref.gui.fieldeditors.contextmenu.EditorMenus;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.integrity.FieldCheckers;
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;
import com.airhacks.afterburner.views.ViewLoader;
public class IdentifierEditor extends HBox implements FieldEditorFX {
@FXML private BaseIdentifierEditorViewModel<?> viewModel;
@FXML private EditorTextArea textArea;
@FXML private Button fetchInformationByIdentifierButton;
@FXML private Button lookupIdentifierButton;
private Optional<BibEntry> entry;
public IdentifierEditor(Field field,
TaskExecutor taskExecutor,
DialogService dialogService,
SuggestionProvider<?> suggestionProvider,
FieldCheckers fieldCheckers,
PreferencesService preferences) {
if (StandardField.DOI == field) {
this.viewModel = new DoiIdentifierEditorViewModel(suggestionProvider, fieldCheckers, dialogService, taskExecutor, preferences);
} else if (StandardField.ISBN == field) {
this.viewModel = new ISBNIdentifierEditorViewModel(suggestionProvider, fieldCheckers, dialogService, taskExecutor, preferences);
} else if (StandardField.EPRINT == field) {
this.viewModel = new EprintIdentifierEditorViewModel(suggestionProvider, fieldCheckers, dialogService, taskExecutor, preferences);
} else {
throw new IllegalStateException(String.format("Unable to instantiate a view model for identifier field editor '%s'", field.getDisplayName()));
}
ViewLoader.view(this)
.root(this)
.load();
textArea.textProperty().bindBidirectional(viewModel.textProperty());
fetchInformationByIdentifierButton.setTooltip(
new Tooltip(Localization.lang("Get bibliographic data from %0", field.getDisplayName())));
lookupIdentifierButton.setTooltip(
new Tooltip(Localization.lang("Look up %0", field.getDisplayName())));
if (field.equals(StandardField.DOI)) {
textArea.initContextMenu(EditorMenus.getDOIMenu(textArea));
} else {
textArea.initContextMenu(new DefaultMenu(textArea));
}
new EditorValidator(preferences).configureValidation(viewModel.getFieldValidator().getValidationStatus(), textArea);
}
public BaseIdentifierEditorViewModel<?> getViewModel() {
return viewModel;
}
@Override
public void bindToEntry(BibEntry entry) {
this.entry = Optional.of(entry);
viewModel.bindToEntry(entry);
}
@Override
public Parent getNode() {
return this;
}
@FXML
private void fetchInformationByIdentifier() {
entry.ifPresent(viewModel::fetchBibliographyInformation);
}
@FXML
private void lookupIdentifier() {
entry.ifPresent(viewModel::lookupIdentifier);
}
@FXML
private void openExternalLink() {
viewModel.openExternalLink();
}
}
| 3,841
| 36.666667
| 154
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/groups/GroupDescriptions.java
|
package org.jabref.gui.groups;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.groups.ExplicitGroup;
import org.jabref.model.groups.KeywordGroup;
import org.jabref.model.groups.SearchGroup;
import org.jabref.model.strings.StringUtil;
public class GroupDescriptions {
private GroupDescriptions() {
}
public static String getShortDescriptionKeywordGroup(KeywordGroup keywordGroup, boolean showDynamic) {
StringBuilder sb = new StringBuilder();
sb.append("<b>");
if (showDynamic) {
sb.append("<i>").append(StringUtil.quoteForHTML(keywordGroup.getName())).append("</i>");
} else {
sb.append(StringUtil.quoteForHTML(keywordGroup.getName()));
}
sb.append("</b> - ");
sb.append(Localization.lang("dynamic group"));
sb.append(" <b>");
sb.append(keywordGroup.getSearchField());
sb.append("</b> ");
sb.append(Localization.lang("contains"));
sb.append(" <b>");
sb.append(StringUtil.quoteForHTML(keywordGroup.getSearchExpression()));
sb.append("</b>)");
switch (keywordGroup.getHierarchicalContext()) {
case INCLUDING:
sb.append(", ").append(Localization.lang("includes subgroups"));
break;
case REFINING:
sb.append(", ").append(Localization.lang("refines supergroup"));
break;
default:
break;
}
return sb.toString();
}
public static String getShortDescriptionExplicitGroup(ExplicitGroup explicitGroup) {
StringBuilder sb = new StringBuilder();
sb.append("<b>").append(explicitGroup.getName()).append("</b> - ").append(Localization.lang("static group"));
switch (explicitGroup.getHierarchicalContext()) {
case INCLUDING:
sb.append(", ").append(Localization.lang("includes subgroups"));
break;
case REFINING:
sb.append(", ").append(Localization.lang("refines supergroup"));
break;
default:
break;
}
return sb.toString();
}
public static String getShortDescriptionAllEntriesGroup() {
return Localization.lang("<b>All Entries</b> (this group cannot be edited or removed)");
}
public static String getShortDescription(SearchGroup searchGroup, boolean showDynamic) {
StringBuilder sb = new StringBuilder();
sb.append("<b>");
if (showDynamic) {
sb.append("<i>").append(StringUtil.quoteForHTML(searchGroup.getName())).append("</i>");
} else {
sb.append(StringUtil.quoteForHTML(searchGroup.getName()));
}
sb.append("</b> - ");
sb.append(Localization.lang("dynamic group"));
sb.append(" (");
sb.append(Localization.lang("search expression"));
sb.append(" <b>").append(StringUtil.quoteForHTML(searchGroup.getSearchExpression())).append("</b>)");
switch (searchGroup.getHierarchicalContext()) {
case INCLUDING:
sb.append(", ").append(Localization.lang("includes subgroups"));
break;
case REFINING:
sb.append(", ").append(Localization.lang("refines supergroup"));
break;
default:
break;
}
return sb.toString();
}
}
| 3,441
| 37.244444
| 117
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/groups/GroupDialogHeader.java
|
package org.jabref.gui.groups;
public enum GroupDialogHeader {
GROUP, SUBGROUP
}
| 86
| 13.5
| 31
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/groups/GroupDialogView.java
|
package org.jabref.gui.groups;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.ServiceLoader;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ColorPicker;
import javafx.scene.control.ComboBox;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.layout.Border;
import javafx.scene.layout.BorderStroke;
import javafx.scene.layout.BorderStrokeStyle;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import org.jabref.gui.DialogService;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.icon.JabrefIconProvider;
import org.jabref.gui.util.BaseDialog;
import org.jabref.gui.util.IconValidationDecorator;
import org.jabref.gui.util.ViewModelListCellFactory;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.groups.AbstractGroup;
import org.jabref.model.groups.GroupHierarchyType;
import org.jabref.model.search.rules.SearchRules;
import org.jabref.model.search.rules.SearchRules.SearchFlags;
import org.jabref.model.util.FileUpdateMonitor;
import org.jabref.preferences.PreferencesService;
import com.airhacks.afterburner.views.ViewLoader;
import de.saxsys.mvvmfx.utils.validation.visualization.ControlsFxVisualizer;
import jakarta.inject.Inject;
import org.controlsfx.control.GridCell;
import org.controlsfx.control.GridView;
import org.controlsfx.control.PopOver;
import org.controlsfx.control.textfield.CustomTextField;
import org.kordamp.ikonli.Ikon;
import org.kordamp.ikonli.IkonProvider;
import org.kordamp.ikonli.javafx.FontIcon;
public class GroupDialogView extends BaseDialog<AbstractGroup> {
// Basic Settings
@FXML private TextField nameField;
@FXML private TextField descriptionField;
@FXML private TextField iconField;
@FXML private Button iconPickerButton;
@FXML private ColorPicker colorField;
@FXML private ComboBox<GroupHierarchyType> hierarchicalContextCombo;
// Type
@FXML private RadioButton explicitRadioButton;
@FXML private RadioButton keywordsRadioButton;
@FXML private RadioButton searchRadioButton;
@FXML private RadioButton autoRadioButton;
@FXML private RadioButton texRadioButton;
// Option Groups
@FXML private TextField keywordGroupSearchTerm;
@FXML private TextField keywordGroupSearchField;
@FXML private CheckBox keywordGroupCaseSensitive;
@FXML private CheckBox keywordGroupRegex;
@FXML private TextField searchGroupSearchTerm;
@FXML private CheckBox searchGroupCaseSensitive;
@FXML private CheckBox searchGroupRegex;
@FXML private RadioButton autoGroupKeywordsOption;
@FXML private TextField autoGroupKeywordsField;
@FXML private TextField autoGroupKeywordsDeliminator;
@FXML private TextField autoGroupKeywordsHierarchicalDeliminator;
@FXML private RadioButton autoGroupPersonsOption;
@FXML private TextField autoGroupPersonsField;
@FXML private TextField texGroupFilePath;
@Inject private FileUpdateMonitor fileUpdateMonitor;
private final EnumMap<GroupHierarchyType, String> hierarchyText = new EnumMap<>(GroupHierarchyType.class);
private final EnumMap<GroupHierarchyType, String> hierarchyToolTip = new EnumMap<>(GroupHierarchyType.class);
private final ControlsFxVisualizer validationVisualizer = new ControlsFxVisualizer();
private final GroupDialogViewModel viewModel;
public GroupDialogView(DialogService dialogService,
BibDatabaseContext currentDatabase,
PreferencesService preferencesService,
AbstractGroup editedGroup,
GroupDialogHeader groupDialogHeader) {
viewModel = new GroupDialogViewModel(dialogService, currentDatabase, preferencesService, editedGroup, fileUpdateMonitor);
ViewLoader.view(this)
.load()
.setAsDialogPane(this);
if (editedGroup == null) {
if (groupDialogHeader == GroupDialogHeader.GROUP) {
this.setTitle(Localization.lang("Add group"));
} else if (groupDialogHeader == GroupDialogHeader.SUBGROUP) {
this.setTitle(Localization.lang("Add subgroup"));
}
} else {
this.setTitle(Localization.lang("Edit group") + " " + editedGroup.getName());
}
setResultConverter(viewModel::resultConverter);
getDialogPane().getButtonTypes().setAll(ButtonType.OK, ButtonType.CANCEL);
final Button confirmDialogButton = (Button) getDialogPane().lookupButton(ButtonType.OK);
confirmDialogButton.disableProperty().bind(viewModel.validationStatus().validProperty().not());
// handle validation before closing dialog and calling resultConverter
confirmDialogButton.addEventFilter(ActionEvent.ACTION, viewModel::validationHandler);
}
@FXML
public void initialize() {
hierarchyText.put(GroupHierarchyType.INCLUDING, Localization.lang("Union"));
hierarchyToolTip.put(GroupHierarchyType.INCLUDING, Localization.lang("Include subgroups: When selected, view entries contained in this group or its subgroups"));
hierarchyText.put(GroupHierarchyType.REFINING, Localization.lang("Intersection"));
hierarchyToolTip.put(GroupHierarchyType.REFINING, Localization.lang("Refine supergroup: When selected, view entries contained in both this group and its supergroup"));
hierarchyText.put(GroupHierarchyType.INDEPENDENT, Localization.lang("Independent"));
hierarchyToolTip.put(GroupHierarchyType.INDEPENDENT, Localization.lang("Independent group: When selected, view only this group's entries"));
nameField.textProperty().bindBidirectional(viewModel.nameProperty());
descriptionField.textProperty().bindBidirectional(viewModel.descriptionProperty());
iconField.textProperty().bindBidirectional(viewModel.iconProperty());
colorField.valueProperty().bindBidirectional(viewModel.colorFieldProperty());
hierarchicalContextCombo.itemsProperty().bind(viewModel.groupHierarchyListProperty());
new ViewModelListCellFactory<GroupHierarchyType>()
.withText(hierarchyText::get)
.withStringTooltip(hierarchyToolTip::get)
.install(hierarchicalContextCombo);
hierarchicalContextCombo.valueProperty().bindBidirectional(viewModel.groupHierarchySelectedProperty());
explicitRadioButton.selectedProperty().bindBidirectional(viewModel.typeExplicitProperty());
keywordsRadioButton.selectedProperty().bindBidirectional(viewModel.typeKeywordsProperty());
searchRadioButton.selectedProperty().bindBidirectional(viewModel.typeSearchProperty());
autoRadioButton.selectedProperty().bindBidirectional(viewModel.typeAutoProperty());
texRadioButton.selectedProperty().bindBidirectional(viewModel.typeTexProperty());
keywordGroupSearchTerm.textProperty().bindBidirectional(viewModel.keywordGroupSearchTermProperty());
keywordGroupSearchField.textProperty().bindBidirectional(viewModel.keywordGroupSearchFieldProperty());
keywordGroupCaseSensitive.selectedProperty().bindBidirectional(viewModel.keywordGroupCaseSensitiveProperty());
keywordGroupRegex.selectedProperty().bindBidirectional(viewModel.keywordGroupRegexProperty());
searchGroupSearchTerm.textProperty().bindBidirectional(viewModel.searchGroupSearchTermProperty());
searchGroupCaseSensitive.selectedProperty().addListener((observable, oldValue, newValue) -> {
EnumSet<SearchFlags> searchFlags = viewModel.searchFlagsProperty().get();
if (newValue) {
searchFlags.add(SearchRules.SearchFlags.CASE_SENSITIVE);
} else {
searchFlags.remove(SearchRules.SearchFlags.CASE_SENSITIVE);
}
viewModel.searchFlagsProperty().set(searchFlags);
});
searchGroupRegex.selectedProperty().addListener((observable, oldValue, newValue) -> {
EnumSet<SearchFlags> searchFlags = viewModel.searchFlagsProperty().get();
if (newValue) {
searchFlags.add(SearchRules.SearchFlags.REGULAR_EXPRESSION);
} else {
searchFlags.remove(SearchRules.SearchFlags.REGULAR_EXPRESSION);
}
viewModel.searchFlagsProperty().set(searchFlags);
});
autoGroupKeywordsOption.selectedProperty().bindBidirectional(viewModel.autoGroupKeywordsOptionProperty());
autoGroupKeywordsField.textProperty().bindBidirectional(viewModel.autoGroupKeywordsFieldProperty());
autoGroupKeywordsDeliminator.textProperty().bindBidirectional(viewModel.autoGroupKeywordsDeliminatorProperty());
autoGroupKeywordsHierarchicalDeliminator.textProperty().bindBidirectional(viewModel.autoGroupKeywordsHierarchicalDeliminatorProperty());
autoGroupPersonsOption.selectedProperty().bindBidirectional(viewModel.autoGroupPersonsOptionProperty());
autoGroupPersonsField.textProperty().bindBidirectional(viewModel.autoGroupPersonsFieldProperty());
texGroupFilePath.textProperty().bindBidirectional(viewModel.texGroupFilePathProperty());
validationVisualizer.setDecoration(new IconValidationDecorator());
Platform.runLater(() -> {
validationVisualizer.initVisualization(viewModel.nameValidationStatus(), nameField);
validationVisualizer.initVisualization(viewModel.nameContainsDelimiterValidationStatus(), nameField, false);
validationVisualizer.initVisualization(viewModel.sameNameValidationStatus(), nameField);
validationVisualizer.initVisualization(viewModel.searchRegexValidationStatus(), searchGroupSearchTerm);
validationVisualizer.initVisualization(viewModel.searchSearchTermEmptyValidationStatus(), searchGroupSearchTerm);
validationVisualizer.initVisualization(viewModel.keywordRegexValidationStatus(), keywordGroupSearchTerm);
validationVisualizer.initVisualization(viewModel.keywordSearchTermEmptyValidationStatus(), keywordGroupSearchTerm);
validationVisualizer.initVisualization(viewModel.keywordFieldEmptyValidationStatus(), keywordGroupSearchField);
validationVisualizer.initVisualization(viewModel.texGroupFilePathValidatonStatus(), texGroupFilePath);
nameField.requestFocus();
});
}
@FXML
private void texGroupBrowse() {
viewModel.texGroupBrowse();
}
@FXML
private void openHelp() {
viewModel.openHelpPage();
}
@FXML
private void openIconPicker() {
ObservableList<Ikon> ikonList = FXCollections.observableArrayList();
FilteredList<Ikon> filteredList = new FilteredList<>(ikonList);
for (IkonProvider provider : ServiceLoader.load(IkonProvider.class.getModule().getLayer(), IkonProvider.class)) {
if (provider.getClass() != JabrefIconProvider.class) {
ikonList.addAll(EnumSet.allOf(provider.getIkon()));
}
}
CustomTextField searchBox = new CustomTextField();
searchBox.setPromptText(Localization.lang("Search") + "...");
searchBox.setLeft(IconTheme.JabRefIcons.SEARCH.getGraphicNode());
searchBox.textProperty().addListener((obs, oldValue, newValue) ->
filteredList.setPredicate(ikon -> newValue.isEmpty() || ikon.getDescription().toLowerCase()
.contains(newValue.toLowerCase())));
GridView<Ikon> ikonGridView = new GridView<>(FXCollections.observableArrayList());
ikonGridView.setCellFactory(gridView -> new IkonliCell());
ikonGridView.setPrefWidth(520);
ikonGridView.setPrefHeight(400);
ikonGridView.setHorizontalCellSpacing(4);
ikonGridView.setVerticalCellSpacing(4);
VBox vBox = new VBox(10, searchBox, ikonGridView);
vBox.setPadding(new Insets(10));
// Necessary because of a bug in controlsfx GridView
// https://github.com/controlsfx/controlsfx/issues/1400
Platform.runLater(() -> {
ikonGridView.setItems(filteredList);
});
PopOver popOver = new PopOver(vBox);
popOver.setDetachable(false);
popOver.setArrowSize(0);
popOver.setCornerRadius(0);
popOver.setTitle("Icon picker");
popOver.show(iconPickerButton);
}
public class IkonliCell extends GridCell<Ikon> {
@Override
protected void updateItem(Ikon ikon, boolean empty) {
super.updateItem(ikon, empty);
if (empty || (ikon == null)) {
setText(null);
setGraphic(null);
} else {
FontIcon fontIcon = FontIcon.of(ikon);
fontIcon.getStyleClass().setAll("font-icon");
fontIcon.setIconSize(22);
setGraphic(fontIcon);
setAlignment(Pos.BASELINE_CENTER);
setPadding(new Insets(1));
setBorder(new Border(new BorderStroke(Color.BLACK, BorderStrokeStyle.SOLID, CornerRadii.EMPTY, BorderStroke.THIN)));
setOnMouseClicked(event -> {
iconField.textProperty().setValue(String.valueOf(fontIcon.getIconCode()));
PopOver stage = (PopOver) this.getGridView().getParent().getScene().getWindow();
stage.hide();
});
}
}
}
}
| 14,003
| 48.836299
| 175
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/groups/GroupDialogViewModel.java
|
package org.jabref.gui.groups;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Optional;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
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.event.Event;
import javafx.scene.control.ButtonType;
import javafx.scene.paint.Color;
import org.jabref.gui.DialogService;
import org.jabref.gui.help.HelpAction;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.util.FileDialogConfiguration;
import org.jabref.logic.auxparser.DefaultAuxParser;
import org.jabref.logic.help.HelpFile;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.StandardFileType;
import org.jabref.logic.util.io.FileUtil;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.Keyword;
import org.jabref.model.entry.field.FieldFactory;
import org.jabref.model.groups.AbstractGroup;
import org.jabref.model.groups.AutomaticGroup;
import org.jabref.model.groups.AutomaticKeywordGroup;
import org.jabref.model.groups.AutomaticPersonsGroup;
import org.jabref.model.groups.ExplicitGroup;
import org.jabref.model.groups.GroupHierarchyType;
import org.jabref.model.groups.GroupTreeNode;
import org.jabref.model.groups.RegexKeywordGroup;
import org.jabref.model.groups.SearchGroup;
import org.jabref.model.groups.TexGroup;
import org.jabref.model.groups.WordKeywordGroup;
import org.jabref.model.metadata.MetaData;
import org.jabref.model.search.rules.SearchRules;
import org.jabref.model.search.rules.SearchRules.SearchFlags;
import org.jabref.model.strings.StringUtil;
import org.jabref.model.util.FileUpdateMonitor;
import org.jabref.preferences.PreferencesService;
import de.saxsys.mvvmfx.utils.validation.CompositeValidator;
import de.saxsys.mvvmfx.utils.validation.FunctionBasedValidator;
import de.saxsys.mvvmfx.utils.validation.ValidationMessage;
import de.saxsys.mvvmfx.utils.validation.ValidationStatus;
import de.saxsys.mvvmfx.utils.validation.Validator;
public class GroupDialogViewModel {
// Basic Settings
private final StringProperty nameProperty = new SimpleStringProperty("");
private final StringProperty descriptionProperty = new SimpleStringProperty("");
private final StringProperty iconProperty = new SimpleStringProperty("");
private final ObjectProperty<Color> colorProperty = new SimpleObjectProperty<>();
private final ListProperty<GroupHierarchyType> groupHierarchyListProperty = new SimpleListProperty<>();
private final ObjectProperty<GroupHierarchyType> groupHierarchySelectedProperty = new SimpleObjectProperty<>();
// Type
private final BooleanProperty typeExplicitProperty = new SimpleBooleanProperty();
private final BooleanProperty typeKeywordsProperty = new SimpleBooleanProperty();
private final BooleanProperty typeSearchProperty = new SimpleBooleanProperty();
private final BooleanProperty typeAutoProperty = new SimpleBooleanProperty();
private final BooleanProperty typeTexProperty = new SimpleBooleanProperty();
// Option Groups
private final StringProperty keywordGroupSearchTermProperty = new SimpleStringProperty("");
private final StringProperty keywordGroupSearchFieldProperty = new SimpleStringProperty("");
private final BooleanProperty keywordGroupCaseSensitiveProperty = new SimpleBooleanProperty();
private final BooleanProperty keywordGroupRegexProperty = new SimpleBooleanProperty();
private final StringProperty searchGroupSearchTermProperty = new SimpleStringProperty("");
private final ObjectProperty<EnumSet<SearchFlags>> searchFlagsProperty = new SimpleObjectProperty<>(EnumSet.noneOf(SearchFlags.class));
private final BooleanProperty autoGroupKeywordsOptionProperty = new SimpleBooleanProperty();
private final StringProperty autoGroupKeywordsFieldProperty = new SimpleStringProperty("");
private final StringProperty autoGroupKeywordsDelimiterProperty = new SimpleStringProperty("");
private final StringProperty autoGroupKeywordsHierarchicalDelimiterProperty = new SimpleStringProperty("");
private final BooleanProperty autoGroupPersonsOptionProperty = new SimpleBooleanProperty();
private final StringProperty autoGroupPersonsFieldProperty = new SimpleStringProperty("");
private final StringProperty texGroupFilePathProperty = new SimpleStringProperty("");
private Validator nameValidator;
private Validator nameContainsDelimiterValidator;
private Validator sameNameValidator;
private Validator keywordRegexValidator;
private Validator keywordFieldEmptyValidator;
private Validator keywordSearchTermEmptyValidator;
private Validator searchRegexValidator;
private Validator searchSearchTermEmptyValidator;
private Validator texGroupFilePathValidator;
private final CompositeValidator validator = new CompositeValidator();
private final DialogService dialogService;
private final PreferencesService preferencesService;
private final BibDatabaseContext currentDatabase;
private final AbstractGroup editedGroup;
private final FileUpdateMonitor fileUpdateMonitor;
public GroupDialogViewModel(DialogService dialogService,
BibDatabaseContext currentDatabase,
PreferencesService preferencesService,
AbstractGroup editedGroup,
FileUpdateMonitor fileUpdateMonitor) {
this.dialogService = dialogService;
this.preferencesService = preferencesService;
this.currentDatabase = currentDatabase;
this.editedGroup = editedGroup;
this.fileUpdateMonitor = fileUpdateMonitor;
setupValidation();
setValues();
}
private void setupValidation() {
nameValidator = new FunctionBasedValidator<>(
nameProperty,
StringUtil::isNotBlank,
ValidationMessage.error(Localization.lang("Please enter a name for the group.")));
nameContainsDelimiterValidator = new FunctionBasedValidator<>(
nameProperty,
name -> !name.contains(Character.toString(preferencesService.getBibEntryPreferences().getKeywordSeparator())),
ValidationMessage.warning(
Localization.lang(
"The group name contains the keyword separator \"%0\" and thus probably does not work as expected.",
Character.toString(preferencesService.getBibEntryPreferences().getKeywordSeparator())
)));
sameNameValidator = new FunctionBasedValidator<>(
nameProperty,
name -> {
Optional<GroupTreeNode> rootGroup = currentDatabase.getMetaData().getGroups();
if (rootGroup.isPresent()) {
int groupsWithSameName = rootGroup.get().findChildrenSatisfying(group -> group.getName().equals(name)).size();
if ((editedGroup == null) && (groupsWithSameName > 0)) {
// New group but there is already one group with the same name
return false;
}
// Edit group, changed name to something that is already present
return (editedGroup == null) || editedGroup.getName().equals(name) || (groupsWithSameName <= 0);
}
return true;
},
ValidationMessage.warning(
Localization.lang("There exists already a group with the same name.") + "\n" +
Localization.lang("If you use it, it will inherit all entries from this other group.")
)
);
keywordRegexValidator = new FunctionBasedValidator<>(
keywordGroupSearchTermProperty,
input -> {
if (!keywordGroupRegexProperty.getValue()) {
return true;
}
if (StringUtil.isNullOrEmpty(input)) {
return false;
}
try {
Pattern.compile(input);
return true;
} catch (PatternSyntaxException ignored) {
return false;
}
},
ValidationMessage.error(String.format("%s > %n %s %n %n %s",
Localization.lang("Searching for a keyword"),
Localization.lang("Keywords"),
Localization.lang("Invalid regular expression."))));
keywordFieldEmptyValidator = new FunctionBasedValidator<>(
keywordGroupSearchFieldProperty,
StringUtil::isNotBlank,
ValidationMessage.error(Localization.lang("Please enter a field name to search for a keyword.")));
keywordSearchTermEmptyValidator = new FunctionBasedValidator<>(
keywordGroupSearchTermProperty,
input -> !StringUtil.isNullOrEmpty(input),
ValidationMessage.error(String.format("%s > %n %s %n %n %s",
Localization.lang("Searching for a keyword"),
Localization.lang("Keywords"),
Localization.lang("Search term is empty.")
)));
searchRegexValidator = new FunctionBasedValidator<>(
searchGroupSearchTermProperty,
input -> {
if (!searchFlagsProperty.getValue().contains(SearchRules.SearchFlags.CASE_SENSITIVE)) {
return true;
}
if (StringUtil.isNullOrEmpty(input)) {
return false;
}
try {
Pattern.compile(input);
return true;
} catch (PatternSyntaxException e) {
// Ignored
return false;
}
},
ValidationMessage.error(String.format("%s > %n %s",
Localization.lang("Free search expression"),
Localization.lang("Invalid regular expression."))));
searchSearchTermEmptyValidator = new FunctionBasedValidator<>(
searchGroupSearchTermProperty,
input -> !StringUtil.isNullOrEmpty(input),
ValidationMessage.error(String.format("%s > %n %s",
Localization.lang("Free search expression"),
Localization.lang("Search term is empty."))));
texGroupFilePathValidator = new FunctionBasedValidator<>(
texGroupFilePathProperty,
input -> {
if (StringUtil.isBlank(input)) {
return false;
} else {
Path inputPath = getAbsoluteTexGroupPath(input);
if (!inputPath.isAbsolute() || !Files.isRegularFile(inputPath)) {
return false;
}
return FileUtil.getFileExtension(input)
.map(extension -> extension.equalsIgnoreCase("aux"))
.orElse(false);
}
},
ValidationMessage.error(Localization.lang("Please provide a valid aux file.")));
typeSearchProperty.addListener((obs, _oldValue, isSelected) -> {
if (isSelected) {
validator.addValidators(searchRegexValidator, searchSearchTermEmptyValidator);
} else {
validator.removeValidators(searchRegexValidator, searchSearchTermEmptyValidator);
}
});
typeKeywordsProperty.addListener((obs, _oldValue, isSelected) -> {
if (isSelected) {
validator.addValidators(keywordFieldEmptyValidator, keywordRegexValidator, keywordSearchTermEmptyValidator);
} else {
validator.removeValidators(keywordFieldEmptyValidator, keywordRegexValidator, keywordSearchTermEmptyValidator);
}
});
typeTexProperty.addListener((obs, oldValue, isSelected) -> {
if (isSelected) {
validator.addValidators(texGroupFilePathValidator);
} else {
validator.removeValidators(texGroupFilePathValidator);
}
});
}
/**
* Gets the absolute path relative to the LatexFileDirectory, if given a relative path
*
* @param input the user input path
* @return an absolute path if LatexFileDirectory exists; otherwise, returns input
*/
private Path getAbsoluteTexGroupPath(String input) {
Optional<Path> latexFileDirectory = currentDatabase.getMetaData().getLatexFileDirectory(preferencesService.getFilePreferences().getUserAndHost());
return latexFileDirectory.map(path -> path.resolve(input)).orElse(Path.of(input));
}
public void validationHandler(Event event) {
ValidationStatus validationStatus = validator.getValidationStatus();
if (validationStatus.getHighestMessage().isPresent()) {
dialogService.showErrorDialogAndWait(validationStatus.getHighestMessage().get().getMessage());
// consume the event to prevent the dialog to close
event.consume();
}
}
public AbstractGroup resultConverter(ButtonType button) {
if (button != ButtonType.OK) {
return null;
}
AbstractGroup resultingGroup = null;
try {
String groupName = nameProperty.getValue().trim();
if (typeExplicitProperty.getValue()) {
resultingGroup = new ExplicitGroup(
groupName,
groupHierarchySelectedProperty.getValue(),
preferencesService.getBibEntryPreferences().getKeywordSeparator());
} else if (typeKeywordsProperty.getValue()) {
if (keywordGroupRegexProperty.getValue()) {
resultingGroup = new RegexKeywordGroup(
groupName,
groupHierarchySelectedProperty.getValue(),
FieldFactory.parseField(keywordGroupSearchFieldProperty.getValue().trim()),
keywordGroupSearchTermProperty.getValue().trim(),
keywordGroupCaseSensitiveProperty.getValue());
} else {
resultingGroup = new WordKeywordGroup(
groupName,
groupHierarchySelectedProperty.getValue(),
FieldFactory.parseField(keywordGroupSearchFieldProperty.getValue().trim()),
keywordGroupSearchTermProperty.getValue().trim(),
keywordGroupCaseSensitiveProperty.getValue(),
preferencesService.getBibEntryPreferences().getKeywordSeparator(),
false);
}
} else if (typeSearchProperty.getValue()) {
resultingGroup = new SearchGroup(
groupName,
groupHierarchySelectedProperty.getValue(),
searchGroupSearchTermProperty.getValue().trim(),
searchFlagsProperty.getValue());
} else if (typeAutoProperty.getValue()) {
if (autoGroupKeywordsOptionProperty.getValue()) {
// Set default value for delimiters: ',' for base and '>' for hierarchical
char delimiter = ',';
char hierarDelimiter = Keyword.DEFAULT_HIERARCHICAL_DELIMITER;
// Modify values for delimiters if user provided customized values
if (!autoGroupKeywordsDelimiterProperty.getValue().isEmpty()) {
delimiter = autoGroupKeywordsDelimiterProperty.getValue().charAt(0);
}
if (!autoGroupKeywordsHierarchicalDelimiterProperty.getValue().isEmpty()) {
hierarDelimiter = autoGroupKeywordsHierarchicalDelimiterProperty.getValue().charAt(0);
}
resultingGroup = new AutomaticKeywordGroup(
groupName,
groupHierarchySelectedProperty.getValue(),
FieldFactory.parseField(autoGroupKeywordsFieldProperty.getValue().trim()),
delimiter,
hierarDelimiter);
} else {
resultingGroup = new AutomaticPersonsGroup(
groupName,
groupHierarchySelectedProperty.getValue(),
FieldFactory.parseField(autoGroupPersonsFieldProperty.getValue().trim()));
}
} else if (typeTexProperty.getValue()) {
resultingGroup = TexGroup.create(
groupName,
groupHierarchySelectedProperty.getValue(),
Path.of(texGroupFilePathProperty.getValue().trim()),
new DefaultAuxParser(new BibDatabase()),
fileUpdateMonitor,
currentDatabase.getMetaData());
}
if (resultingGroup != null) {
preferencesService.getGroupsPreferences().setDefaultHierarchicalContext(groupHierarchySelectedProperty.getValue());
resultingGroup.setColor(colorProperty.getValue());
resultingGroup.setDescription(descriptionProperty.getValue());
resultingGroup.setIconName(iconProperty.getValue());
return resultingGroup;
}
return null;
} catch (IllegalArgumentException | IOException exception) {
dialogService.showErrorDialogAndWait(exception.getLocalizedMessage(), exception);
return null;
}
}
public void setValues() {
groupHierarchyListProperty.setValue(FXCollections.observableArrayList(GroupHierarchyType.values()));
if (editedGroup == null) {
// creating new group -> defaults!
colorProperty.setValue(IconTheme.getDefaultGroupColor());
typeExplicitProperty.setValue(true);
groupHierarchySelectedProperty.setValue(preferencesService.getGroupsPreferences().getDefaultHierarchicalContext());
} else {
nameProperty.setValue(editedGroup.getName());
colorProperty.setValue(editedGroup.getColor().orElse(IconTheme.getDefaultGroupColor()));
descriptionProperty.setValue(editedGroup.getDescription().orElse(""));
iconProperty.setValue(editedGroup.getIconName().orElse(""));
groupHierarchySelectedProperty.setValue(editedGroup.getHierarchicalContext());
if (editedGroup.getClass() == WordKeywordGroup.class) {
typeKeywordsProperty.setValue(true);
WordKeywordGroup group = (WordKeywordGroup) editedGroup;
keywordGroupSearchFieldProperty.setValue(group.getSearchField().getName());
keywordGroupSearchTermProperty.setValue(group.getSearchExpression());
keywordGroupCaseSensitiveProperty.setValue(group.isCaseSensitive());
keywordGroupRegexProperty.setValue(false);
} else if (editedGroup.getClass() == RegexKeywordGroup.class) {
typeKeywordsProperty.setValue(true);
RegexKeywordGroup group = (RegexKeywordGroup) editedGroup;
keywordGroupSearchFieldProperty.setValue(group.getSearchField().getName());
keywordGroupSearchTermProperty.setValue(group.getSearchExpression());
keywordGroupCaseSensitiveProperty.setValue(group.isCaseSensitive());
keywordGroupRegexProperty.setValue(true);
} else if (editedGroup.getClass() == SearchGroup.class) {
typeSearchProperty.setValue(true);
SearchGroup group = (SearchGroup) editedGroup;
searchGroupSearchTermProperty.setValue(group.getSearchExpression());
searchFlagsProperty.setValue(group.getSearchFlags());
} else if (editedGroup.getClass() == ExplicitGroup.class) {
typeExplicitProperty.setValue(true);
} else if (editedGroup instanceof AutomaticGroup) {
typeAutoProperty.setValue(true);
if (editedGroup.getClass() == AutomaticKeywordGroup.class) {
AutomaticKeywordGroup group = (AutomaticKeywordGroup) editedGroup;
autoGroupKeywordsDelimiterProperty.setValue(group.getKeywordDelimiter().toString());
autoGroupKeywordsHierarchicalDelimiterProperty.setValue(group.getKeywordHierarchicalDelimiter().toString());
autoGroupKeywordsFieldProperty.setValue(group.getField().getName());
} else if (editedGroup.getClass() == AutomaticPersonsGroup.class) {
AutomaticPersonsGroup group = (AutomaticPersonsGroup) editedGroup;
autoGroupPersonsFieldProperty.setValue(group.getField().getName());
}
} else if (editedGroup.getClass() == TexGroup.class) {
typeTexProperty.setValue(true);
TexGroup group = (TexGroup) editedGroup;
texGroupFilePathProperty.setValue(group.getFilePath().toString());
}
}
}
public void texGroupBrowse() {
FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
.addExtensionFilter(StandardFileType.AUX)
.withDefaultExtension(StandardFileType.AUX)
.withInitialDirectory(currentDatabase.getMetaData()
.getLatexFileDirectory(preferencesService.getFilePreferences().getUserAndHost())
.orElse(FileUtil.getInitialDirectory(currentDatabase, preferencesService.getFilePreferences().getWorkingDirectory()))).build();
dialogService.showFileOpenDialog(fileDialogConfiguration)
.ifPresent(file -> texGroupFilePathProperty.setValue(
FileUtil.relativize(file.toAbsolutePath(), getFileDirectoriesAsPaths()).toString()
));
}
public void openHelpPage() {
new HelpAction(HelpFile.GROUPS, dialogService).execute();
}
private List<Path> getFileDirectoriesAsPaths() {
List<Path> fileDirs = new ArrayList<>();
MetaData metaData = currentDatabase.getMetaData();
metaData.getLatexFileDirectory(preferencesService.getFilePreferences().getUserAndHost()).ifPresent(fileDirs::add);
return fileDirs;
}
public ValidationStatus validationStatus() {
return validator.getValidationStatus();
}
public ValidationStatus nameValidationStatus() {
return nameValidator.getValidationStatus();
}
public ValidationStatus nameContainsDelimiterValidationStatus() {
return nameContainsDelimiterValidator.getValidationStatus();
}
public ValidationStatus sameNameValidationStatus() {
return sameNameValidator.getValidationStatus();
}
public ValidationStatus searchRegexValidationStatus() {
return searchRegexValidator.getValidationStatus();
}
public ValidationStatus searchSearchTermEmptyValidationStatus() {
return searchSearchTermEmptyValidator.getValidationStatus();
}
public ValidationStatus keywordRegexValidationStatus() {
return keywordRegexValidator.getValidationStatus();
}
public ValidationStatus keywordFieldEmptyValidationStatus() {
return keywordFieldEmptyValidator.getValidationStatus();
}
public ValidationStatus keywordSearchTermEmptyValidationStatus() {
return keywordSearchTermEmptyValidator.getValidationStatus();
}
public ValidationStatus texGroupFilePathValidatonStatus() {
return texGroupFilePathValidator.getValidationStatus();
}
public StringProperty nameProperty() {
return nameProperty;
}
public StringProperty descriptionProperty() {
return descriptionProperty;
}
public StringProperty iconProperty() {
return iconProperty;
}
public ObjectProperty<Color> colorFieldProperty() {
return colorProperty;
}
public ListProperty<GroupHierarchyType> groupHierarchyListProperty() {
return groupHierarchyListProperty;
}
public ObjectProperty<GroupHierarchyType> groupHierarchySelectedProperty() {
return groupHierarchySelectedProperty;
}
public BooleanProperty typeExplicitProperty() {
return typeExplicitProperty;
}
public BooleanProperty typeKeywordsProperty() {
return typeKeywordsProperty;
}
public BooleanProperty typeSearchProperty() {
return typeSearchProperty;
}
public BooleanProperty typeAutoProperty() {
return typeAutoProperty;
}
public BooleanProperty typeTexProperty() {
return typeTexProperty;
}
public StringProperty keywordGroupSearchTermProperty() {
return keywordGroupSearchTermProperty;
}
public StringProperty keywordGroupSearchFieldProperty() {
return keywordGroupSearchFieldProperty;
}
public BooleanProperty keywordGroupCaseSensitiveProperty() {
return keywordGroupCaseSensitiveProperty;
}
public BooleanProperty keywordGroupRegexProperty() {
return keywordGroupRegexProperty;
}
public StringProperty searchGroupSearchTermProperty() {
return searchGroupSearchTermProperty;
}
public ObjectProperty<EnumSet<SearchFlags>> searchFlagsProperty() {
return searchFlagsProperty;
}
public BooleanProperty autoGroupKeywordsOptionProperty() {
return autoGroupKeywordsOptionProperty;
}
public StringProperty autoGroupKeywordsFieldProperty() {
return autoGroupKeywordsFieldProperty;
}
public StringProperty autoGroupKeywordsDeliminatorProperty() {
return autoGroupKeywordsDelimiterProperty;
}
public StringProperty autoGroupKeywordsHierarchicalDeliminatorProperty() {
return autoGroupKeywordsHierarchicalDelimiterProperty;
}
public BooleanProperty autoGroupPersonsOptionProperty() {
return autoGroupPersonsOptionProperty;
}
public StringProperty autoGroupPersonsFieldProperty() {
return autoGroupPersonsFieldProperty;
}
public StringProperty texGroupFilePathProperty() {
return texGroupFilePathProperty;
}
}
| 27,634
| 44.829187
| 180
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/groups/GroupModeViewModel.java
|
package org.jabref.gui.groups;
import javafx.scene.Node;
import javafx.scene.control.Tooltip;
import org.jabref.gui.icon.IconTheme.JabRefIcons;
import org.jabref.logic.l10n.Localization;
public class GroupModeViewModel {
private final GroupViewMode mode;
public GroupModeViewModel(GroupViewMode mode) {
this.mode = mode;
}
public Node getUnionIntersectionGraphic() {
if (mode == GroupViewMode.UNION) {
return JabRefIcons.GROUP_UNION.getGraphicNode();
} else if (mode == GroupViewMode.INTERSECTION) {
return JabRefIcons.GROUP_INTERSECTION.getGraphicNode();
}
// As there is no concept like an empty node/icon, we return simply the other icon
return JabRefIcons.GROUP_INTERSECTION.getGraphicNode();
}
public Tooltip getUnionIntersectionTooltip() {
if (mode == GroupViewMode.UNION) {
return new Tooltip(Localization.lang("Toggle intersection"));
} else if (mode == GroupViewMode.INTERSECTION) {
return new Tooltip(Localization.lang("Toggle union"));
}
return new Tooltip();
}
}
| 1,139
| 29.810811
| 90
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/groups/GroupNodeViewModel.java
|
package org.jabref.gui.groups;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import javafx.beans.InvalidationListener;
import javafx.beans.WeakInvalidationListener;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.binding.IntegerBinding;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.scene.input.Dragboard;
import javafx.scene.paint.Color;
import org.jabref.gui.DragAndDropDataFormats;
import org.jabref.gui.StateManager;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.icon.JabRefIcon;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.gui.util.CustomLocalDragboard;
import org.jabref.gui.util.DefaultTaskExecutor;
import org.jabref.gui.util.DroppingMouseLocation;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.groups.DefaultGroupsFactory;
import org.jabref.logic.layout.format.LatexToUnicodeFormatter;
import org.jabref.model.FieldChange;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.groups.AbstractGroup;
import org.jabref.model.groups.AllEntriesGroup;
import org.jabref.model.groups.AutomaticGroup;
import org.jabref.model.groups.AutomaticKeywordGroup;
import org.jabref.model.groups.AutomaticPersonsGroup;
import org.jabref.model.groups.ExplicitGroup;
import org.jabref.model.groups.GroupEntryChanger;
import org.jabref.model.groups.GroupTreeNode;
import org.jabref.model.groups.KeywordGroup;
import org.jabref.model.groups.LastNameGroup;
import org.jabref.model.groups.RegexKeywordGroup;
import org.jabref.model.groups.SearchGroup;
import org.jabref.model.groups.TexGroup;
import org.jabref.model.strings.StringUtil;
import org.jabref.preferences.PreferencesService;
import com.tobiasdiez.easybind.EasyBind;
import com.tobiasdiez.easybind.EasyObservableList;
public class GroupNodeViewModel {
private final String displayName;
private final boolean isRoot;
private final ObservableList<GroupNodeViewModel> children;
private final BibDatabaseContext databaseContext;
private final StateManager stateManager;
private final GroupTreeNode groupNode;
private final ObservableList<BibEntry> matchedEntries = FXCollections.observableArrayList();
private final SimpleBooleanProperty hasChildren;
private final SimpleBooleanProperty expandedProperty = new SimpleBooleanProperty();
private final BooleanBinding anySelectedEntriesMatched;
private final BooleanBinding allSelectedEntriesMatched;
private final TaskExecutor taskExecutor;
private final CustomLocalDragboard localDragBoard;
private final ObservableList<BibEntry> entriesList;
private final PreferencesService preferencesService;
private final InvalidationListener onInvalidatedGroup = listener -> refreshGroup();
public GroupNodeViewModel(BibDatabaseContext databaseContext, StateManager stateManager, TaskExecutor taskExecutor, GroupTreeNode groupNode, CustomLocalDragboard localDragBoard, PreferencesService preferencesService) {
this.databaseContext = Objects.requireNonNull(databaseContext);
this.taskExecutor = Objects.requireNonNull(taskExecutor);
this.stateManager = Objects.requireNonNull(stateManager);
this.groupNode = Objects.requireNonNull(groupNode);
this.localDragBoard = Objects.requireNonNull(localDragBoard);
this.preferencesService = preferencesService;
displayName = new LatexToUnicodeFormatter().format(groupNode.getName());
isRoot = groupNode.isRoot();
if (groupNode.getGroup() instanceof AutomaticGroup automaticGroup) {
children = automaticGroup.createSubgroups(this.databaseContext.getDatabase().getEntries())
.stream()
.map(this::toViewModel)
.sorted((group1, group2) -> group1.getDisplayName().compareToIgnoreCase(group2.getDisplayName()))
.collect(Collectors.toCollection(FXCollections::observableArrayList));
} else {
children = EasyBind.mapBacked(groupNode.getChildren(), this::toViewModel);
}
if (groupNode.getGroup() instanceof TexGroup) {
databaseContext.getMetaData().groupsBinding().addListener(new WeakInvalidationListener(onInvalidatedGroup));
}
hasChildren = new SimpleBooleanProperty();
hasChildren.bind(Bindings.isNotEmpty(children));
EasyBind.subscribe(preferencesService.getGroupsPreferences().displayGroupCountProperty(), shouldDisplay -> updateMatchedEntries());
expandedProperty.set(groupNode.getGroup().isExpanded());
expandedProperty.addListener((observable, oldValue, newValue) -> groupNode.getGroup().setExpanded(newValue));
// Register listener
// The wrapper created by the FXCollections will set a weak listener on the wrapped list. This weak listener gets garbage collected. Hence, we need to maintain a reference to this list.
entriesList = databaseContext.getDatabase().getEntries();
entriesList.addListener(this::onDatabaseChanged);
EasyObservableList<Boolean> selectedEntriesMatchStatus = EasyBind.map(stateManager.getSelectedEntries(), groupNode::matches);
anySelectedEntriesMatched = selectedEntriesMatchStatus.anyMatch(matched -> matched);
// 'all' returns 'true' for empty streams, so this has to be checked explicitly
allSelectedEntriesMatched = selectedEntriesMatchStatus.isEmptyBinding().not().and(selectedEntriesMatchStatus.allMatch(matched -> matched));
}
public GroupNodeViewModel(BibDatabaseContext databaseContext, StateManager stateManager, TaskExecutor taskExecutor, AbstractGroup group, CustomLocalDragboard localDragboard, PreferencesService preferencesService) {
this(databaseContext, stateManager, taskExecutor, new GroupTreeNode(group), localDragboard, preferencesService);
}
static GroupNodeViewModel getAllEntriesGroup(BibDatabaseContext newDatabase, StateManager stateManager, TaskExecutor taskExecutor, CustomLocalDragboard localDragBoard, PreferencesService preferencesService) {
return new GroupNodeViewModel(newDatabase, stateManager, taskExecutor, DefaultGroupsFactory.getAllEntriesGroup(), localDragBoard, preferencesService);
}
private GroupNodeViewModel toViewModel(GroupTreeNode child) {
return new GroupNodeViewModel(databaseContext, stateManager, taskExecutor, child, localDragBoard, preferencesService);
}
public List<FieldChange> addEntriesToGroup(List<BibEntry> entries) {
// TODO: warn if assignment has undesired side effects (modifies a field != keywords)
// if (!WarnAssignmentSideEffects.warnAssignmentSideEffects(group, groupSelector.frame))
// {
// return; // user aborted operation
// }
var changes = groupNode.addEntriesToGroup(entries);
// Update appearance of group
anySelectedEntriesMatched.invalidate();
allSelectedEntriesMatched.invalidate();
return changes;
// TODO: Store undo
// if (!undo.isEmpty()) {
// groupSelector.concludeAssignment(UndoableChangeEntriesOfGroup.getUndoableEdit(target, undo), target.getNode(), assignedEntries);
}
public SimpleBooleanProperty expandedProperty() {
return expandedProperty;
}
public BooleanBinding anySelectedEntriesMatchedProperty() {
return anySelectedEntriesMatched;
}
public BooleanBinding allSelectedEntriesMatchedProperty() {
return allSelectedEntriesMatched;
}
public SimpleBooleanProperty hasChildrenProperty() {
return hasChildren;
}
public String getDisplayName() {
return displayName;
}
public boolean isRoot() {
return isRoot;
}
public String getDescription() {
return groupNode.getGroup().getDescription().orElse("");
}
public IntegerBinding getHits() {
return Bindings.size(matchedEntries);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if ((o == null) || (getClass() != o.getClass())) {
return false;
}
GroupNodeViewModel that = (GroupNodeViewModel) o;
return groupNode.equals(that.groupNode);
}
@Override
public String toString() {
return "GroupNodeViewModel{" +
"displayName='" + displayName + '\'' +
", isRoot=" + isRoot +
", icon='" + getIcon() + '\'' +
", children=" + children +
", databaseContext=" + databaseContext +
", groupNode=" + groupNode +
", matchedEntries=" + matchedEntries +
'}';
}
@Override
public int hashCode() {
return groupNode.hashCode();
}
public JabRefIcon getIcon() {
Optional<String> iconName = groupNode.getGroup().getIconName();
return iconName.flatMap(this::parseIcon)
.orElseGet(this::createDefaultIcon);
}
private JabRefIcon createDefaultIcon() {
Color color = groupNode.getGroup().getColor().orElse(IconTheme.getDefaultGroupColor());
return IconTheme.JabRefIcons.DEFAULT_GROUP_ICON_COLORED.withColor(color);
}
private Optional<JabRefIcon> parseIcon(String iconCode) {
return IconTheme.findIcon(iconCode, getColor());
}
public ObservableList<GroupNodeViewModel> getChildren() {
return children;
}
public GroupTreeNode getGroupNode() {
return groupNode;
}
/**
* Gets invoked if an entry in the current database changes.
*/
private void onDatabaseChanged(ListChangeListener.Change<? extends BibEntry> change) {
while (change.next()) {
if (change.wasPermutated()) {
// Nothing to do, as permutation doesn't change matched entries
} else if (change.wasUpdated()) {
for (BibEntry changedEntry : change.getList().subList(change.getFrom(), change.getTo())) {
if (groupNode.matches(changedEntry)) {
if (!matchedEntries.contains(changedEntry)) {
matchedEntries.add(changedEntry);
}
} else {
matchedEntries.remove(changedEntry);
}
}
} else {
for (BibEntry removedEntry : change.getRemoved()) {
matchedEntries.remove(removedEntry);
}
for (BibEntry addedEntry : change.getAddedSubList()) {
if (groupNode.matches(addedEntry)) {
if (!matchedEntries.contains(addedEntry)) {
matchedEntries.add(addedEntry);
}
}
}
}
}
}
private void refreshGroup() {
DefaultTaskExecutor.runInJavaFXThread(() -> {
updateMatchedEntries(); // Update the entries matched by the group
// "Re-add" to the selected groups if it were selected, this refreshes the entries the user views
ObservableList<GroupTreeNode> selectedGroups = this.stateManager.getSelectedGroup(this.databaseContext);
if (selectedGroups.remove(this.groupNode)) {
selectedGroups.add(this.groupNode);
}
});
}
private void updateMatchedEntries() {
// We calculate the new hit value
// We could be more intelligent and try to figure out the new number of hits based on the entry change
// for example, a previously matched entry gets removed -> hits = hits - 1
if (preferencesService.getGroupsPreferences().shouldDisplayGroupCount()) {
BackgroundTask
.wrap(() -> groupNode.findMatches(databaseContext.getDatabase()))
.onSuccess(entries -> {
matchedEntries.clear();
matchedEntries.addAll(entries);
})
.executeWith(taskExecutor);
}
}
public GroupTreeNode addSubgroup(AbstractGroup subgroup) {
return groupNode.addSubgroup(subgroup);
}
void toggleExpansion() {
expandedProperty().set(!expandedProperty().get());
}
boolean isMatchedBy(String searchString) {
return StringUtil.isBlank(searchString) || StringUtil.containsIgnoreCase(getDisplayName(), searchString);
}
public Color getColor() {
return groupNode.getGroup().getColor().orElse(IconTheme.getDefaultGroupColor());
}
public String getPath() {
return groupNode.getPath();
}
public Optional<GroupNodeViewModel> getChildByPath(String pathToSource) {
return groupNode.getChildByPath(pathToSource).map(this::toViewModel);
}
/**
* Decides if the content stored in the given {@link Dragboard} can be dropped on the given target row. Currently, the following sources are allowed:
* <ul>
* <li>another group (will be added as subgroup on drop)</li>
* <li>entries if the group implements {@link GroupEntryChanger} (will be assigned to group on drop)</li>
* </ul>
*/
public boolean acceptableDrop(Dragboard dragboard) {
// TODO: we should also check isNodeDescendant
boolean canDropOtherGroup = dragboard.hasContent(DragAndDropDataFormats.GROUP);
boolean canDropEntries = localDragBoard.hasBibEntries() && (groupNode.getGroup() instanceof GroupEntryChanger);
return canDropOtherGroup || canDropEntries;
}
public void moveTo(GroupNodeViewModel target) {
// TODO: Add undo and display message
// MoveGroupChange undo = new MoveGroupChange(((GroupTreeNodeViewModel)source.getParent()).getNode(),
// source.getNode().getPositionInParent(), target.getNode(), target.getChildCount());
getGroupNode().moveTo(target.getGroupNode());
// panel.getUndoManager().addEdit(new UndoableMoveGroup(this.groupsRoot, moveChange));
// panel.markBaseChanged();
// frame.output(Localization.lang("Moved group \"%0\".", node.getNode().getGroup().getName()));
}
public void moveTo(GroupTreeNode target, int targetIndex) {
getGroupNode().moveTo(target, targetIndex);
}
public Optional<GroupTreeNode> getParent() {
return groupNode.getParent();
}
public void draggedOn(GroupNodeViewModel target, DroppingMouseLocation mouseLocation) {
// No action, if the target is the same as the source
if (this.equals(target)) {
return;
}
Optional<GroupTreeNode> targetParent = target.getParent();
if (targetParent.isPresent()) {
int targetIndex = target.getPositionInParent();
// In case we want to move an item in the same parent
// and the item is moved down, we need to adjust the target index
if (targetParent.equals(getParent())) {
int sourceIndex = this.getPositionInParent();
if (sourceIndex < targetIndex) {
targetIndex--;
}
}
// Different actions depending on where the user releases the drop in the target row
// Bottom + top -> insert source row before / after this row
// Center -> add as child
switch (mouseLocation) {
case BOTTOM -> this.moveTo(targetParent.get(), targetIndex + 1);
case CENTER -> this.moveTo(target);
case TOP -> this.moveTo(targetParent.get(), targetIndex);
}
} else {
// No parent = root -> just add
this.moveTo(target);
}
}
private int getPositionInParent() {
return groupNode.getPositionInParent();
}
public boolean hasSubgroups() {
return !getChildren().isEmpty();
}
public boolean canAddEntriesIn() {
AbstractGroup group = groupNode.getGroup();
if (group instanceof AllEntriesGroup) {
return false;
} else if (group instanceof ExplicitGroup) {
return true;
} else if (group instanceof LastNameGroup || group instanceof RegexKeywordGroup) {
return groupNode.getParent()
.map(parent -> parent.getGroup())
.map(groupParent -> groupParent instanceof AutomaticKeywordGroup || groupParent instanceof AutomaticPersonsGroup)
.orElse(false);
} else if (group instanceof KeywordGroup) {
// also covers WordKeywordGroup
return true;
} else if (group instanceof SearchGroup) {
return false;
} else if (group instanceof AutomaticKeywordGroup) {
return false;
} else if (group instanceof AutomaticPersonsGroup) {
return false;
} else if (group instanceof TexGroup) {
return false;
} else {
throw new UnsupportedOperationException("canAddEntriesIn method not yet implemented in group: " + group.getClass().getName());
}
}
public boolean canBeDragged() {
AbstractGroup group = groupNode.getGroup();
if (group instanceof AllEntriesGroup) {
return false;
} else if (group instanceof ExplicitGroup) {
return true;
} else if (group instanceof KeywordGroup) {
// KeywordGroup is parent of LastNameGroup, RegexKeywordGroup and WordKeywordGroup
return groupNode.getParent()
.map(parent -> parent.getGroup())
.map(groupParent -> !(groupParent instanceof AutomaticKeywordGroup || groupParent instanceof AutomaticPersonsGroup))
.orElse(false);
} else if (group instanceof SearchGroup) {
return true;
} else if (group instanceof AutomaticKeywordGroup) {
return true;
} else if (group instanceof AutomaticPersonsGroup) {
return true;
} else if (group instanceof TexGroup) {
return true;
} else {
throw new UnsupportedOperationException("canBeDragged method not yet implemented in group: " + group.getClass().getName());
}
}
public boolean canAddGroupsIn() {
AbstractGroup group = groupNode.getGroup();
if (group instanceof AllEntriesGroup) {
return true;
} else if (group instanceof ExplicitGroup) {
return true;
} else if (group instanceof KeywordGroup) {
// KeywordGroup is parent of LastNameGroup, RegexKeywordGroup and WordKeywordGroup
return groupNode.getParent()
.map(parent -> parent.getGroup())
.map(groupParent -> !(groupParent instanceof AutomaticKeywordGroup || groupParent instanceof AutomaticPersonsGroup))
.orElse(false);
} else if (group instanceof SearchGroup) {
return true;
} else if (group instanceof AutomaticKeywordGroup) {
return false;
} else if (group instanceof AutomaticPersonsGroup) {
return false;
} else if (group instanceof TexGroup) {
return true;
} else {
throw new UnsupportedOperationException("canAddGroupsIn method not yet implemented in group: " + group.getClass().getName());
}
}
public boolean canRemove() {
AbstractGroup group = groupNode.getGroup();
if (group instanceof AllEntriesGroup) {
return false;
} else if (group instanceof ExplicitGroup) {
return true;
} else if (group instanceof KeywordGroup) {
// KeywordGroup is parent of LastNameGroup, RegexKeywordGroup and WordKeywordGroup
return groupNode.getParent()
.map(parent -> parent.getGroup())
.map(groupParent -> !(groupParent instanceof AutomaticKeywordGroup || groupParent instanceof AutomaticPersonsGroup))
.orElse(false);
} else if (group instanceof SearchGroup) {
return true;
} else if (group instanceof AutomaticKeywordGroup) {
return true;
} else if (group instanceof AutomaticPersonsGroup) {
return true;
} else if (group instanceof TexGroup) {
return true;
} else {
throw new UnsupportedOperationException("canRemove method not yet implemented in group: " + group.getClass().getName());
}
}
public boolean isEditable() {
AbstractGroup group = groupNode.getGroup();
if (group instanceof AllEntriesGroup) {
return false;
} else if (group instanceof ExplicitGroup) {
return true;
} else if (group instanceof KeywordGroup) {
// KeywordGroup is parent of LastNameGroup, RegexKeywordGroup and WordKeywordGroup
return groupNode.getParent()
.map(parent -> parent.getGroup())
.map(groupParent -> !(groupParent instanceof AutomaticKeywordGroup || groupParent instanceof AutomaticPersonsGroup))
.orElse(false);
} else if (group instanceof SearchGroup) {
return true;
} else if (group instanceof AutomaticKeywordGroup) {
return true;
} else if (group instanceof AutomaticPersonsGroup) {
return true;
} else if (group instanceof TexGroup) {
return true;
} else {
throw new UnsupportedOperationException("isEditable method not yet implemented in group: " + group.getClass().getName());
}
}
}
| 22,233
| 42.510763
| 222
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/groups/GroupTreeNodeViewModel.java
|
package org.jabref.gui.groups;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import javax.swing.undo.AbstractUndoableEdit;
import javax.swing.undo.UndoManager;
import org.jabref.gui.undo.CountingUndoManager;
import org.jabref.model.FieldChange;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.groups.AbstractGroup;
import org.jabref.model.groups.AllEntriesGroup;
import org.jabref.model.groups.ExplicitGroup;
import org.jabref.model.groups.GroupEntryChanger;
import org.jabref.model.groups.GroupTreeNode;
import org.jabref.model.groups.KeywordGroup;
import org.jabref.model.groups.SearchGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GroupTreeNodeViewModel {
private static final Logger LOGGER = LoggerFactory.getLogger(GroupTreeNodeViewModel.class);
private final GroupTreeNode node;
public GroupTreeNodeViewModel(GroupTreeNode node) {
this.node = node;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("GroupTreeNodeViewModel{");
sb.append("node=").append(node);
sb.append('}');
return sb.toString();
}
public GroupTreeNode getNode() {
return node;
}
public List<GroupTreeNodeViewModel> getChildren() {
List<GroupTreeNodeViewModel> children = new ArrayList<>();
for (GroupTreeNode child : node.getChildren()) {
children.add(new GroupTreeNodeViewModel(child));
}
return children;
}
protected boolean printInItalics() {
return node.getGroup().isDynamic();
}
public String getDescription() {
AbstractGroup group = node.getGroup();
String shortDescription = "";
boolean showDynamic = true;
if (group instanceof ExplicitGroup explicitGroup) {
shortDescription = GroupDescriptions.getShortDescriptionExplicitGroup(explicitGroup);
} else if (group instanceof KeywordGroup keywordGroup) {
shortDescription = GroupDescriptions.getShortDescriptionKeywordGroup(keywordGroup, showDynamic);
} else if (group instanceof SearchGroup searchGroup) {
shortDescription = GroupDescriptions.getShortDescription(searchGroup, showDynamic);
} else {
shortDescription = GroupDescriptions.getShortDescriptionAllEntriesGroup();
}
return "<html>" + shortDescription + "</html>";
}
public boolean canAddEntries(List<BibEntry> entries) {
return (getNode().getGroup() instanceof GroupEntryChanger) && !getNode().getGroup().containsAll(entries);
}
public boolean canRemoveEntries(List<BibEntry> entries) {
return (getNode().getGroup() instanceof GroupEntryChanger) && getNode().getGroup().containsAny(entries);
}
public void sortChildrenByName(boolean recursive) {
getNode().sortChildren(
(node1, node2) -> node1.getGroup().getName().compareToIgnoreCase(node2.getGroup().getName()),
recursive);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if ((o == null) || (getClass() != o.getClass())) {
return false;
}
GroupTreeNodeViewModel viewModel = (GroupTreeNodeViewModel) o;
return node.equals(viewModel.node);
}
@Override
public int hashCode() {
return node.hashCode();
}
public String getName() {
return getNode().getGroup().getName();
}
public boolean canBeEdited() {
return getNode().getGroup() instanceof AllEntriesGroup;
}
public boolean canMoveUp() {
return (getNode().getPreviousSibling() != null)
&& !(getNode().getGroup() instanceof AllEntriesGroup);
}
public boolean canMoveDown() {
return (getNode().getNextSibling() != null)
&& !(getNode().getGroup() instanceof AllEntriesGroup);
}
public boolean canMoveLeft() {
return !(getNode().getGroup() instanceof AllEntriesGroup)
// TODO: Null!
&& !(getNode().getParent().get().getGroup() instanceof AllEntriesGroup);
}
public boolean canMoveRight() {
return (getNode().getPreviousSibling() != null)
&& !(getNode().getGroup() instanceof AllEntriesGroup);
}
public void changeEntriesTo(List<BibEntry> entries, UndoManager undoManager) {
AbstractGroup group = node.getGroup();
List<FieldChange> changesRemove = new ArrayList<>();
List<FieldChange> changesAdd = new ArrayList<>();
// Sort entries into current members and non-members of the group
// Current members will be removed
// Current non-members will be added
List<BibEntry> toRemove = new ArrayList<>(entries.size());
List<BibEntry> toAdd = new ArrayList<>(entries.size());
for (BibEntry entry : entries) {
// Sort according to current state of the entries
if (group.contains(entry)) {
toRemove.add(entry);
} else {
toAdd.add(entry);
}
}
// If there are entries to remove
if (!toRemove.isEmpty()) {
changesRemove = removeEntriesFromGroup(toRemove);
}
// If there are entries to add
if (!toAdd.isEmpty()) {
changesAdd = addEntriesToGroup(toAdd);
}
// Remember undo information
if (!changesRemove.isEmpty()) {
AbstractUndoableEdit undoRemove = UndoableChangeEntriesOfGroup.getUndoableEdit(this, changesRemove);
if (!changesAdd.isEmpty() && (undoRemove != null)) {
// we removed and added entries
undoRemove.addEdit(UndoableChangeEntriesOfGroup.getUndoableEdit(this, changesAdd));
}
undoManager.addEdit(undoRemove);
} else if (!changesAdd.isEmpty()) {
undoManager.addEdit(UndoableChangeEntriesOfGroup.getUndoableEdit(this, changesAdd));
}
}
public List<FieldChange> removeEntriesFromGroup(List<BibEntry> entries) {
return node.removeEntriesFromGroup(entries);
}
public boolean isAllEntriesGroup() {
return getNode().getGroup() instanceof AllEntriesGroup;
}
public void addNewGroup(AbstractGroup newGroup, CountingUndoManager undoManager) {
GroupTreeNode newNode = GroupTreeNode.fromGroup(newGroup);
this.getNode().addChild(newNode);
UndoableAddOrRemoveGroup undo = new UndoableAddOrRemoveGroup(
this,
new GroupTreeNodeViewModel(newNode),
UndoableAddOrRemoveGroup.ADD_NODE);
undoManager.addEdit(undo);
}
/**
* Adds the given entries to this node's group.
*/
public List<FieldChange> addEntriesToGroup(List<BibEntry> entries) {
return node.addEntriesToGroup(entries);
}
public void subscribeToDescendantChanged(Consumer<GroupTreeNodeViewModel> subscriber) {
getNode().subscribeToDescendantChanged(node -> subscriber.accept(new GroupTreeNodeViewModel(node)));
}
}
| 7,193
| 33.753623
| 113
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/groups/GroupTreeView.java
|
package org.jabref.gui.groups;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.time.Duration;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.beans.property.ObjectProperty;
import javafx.css.PseudoClass;
import javafx.geometry.Orientation;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Control;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.ScrollBar;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeTableColumn;
import javafx.scene.control.TreeTableRow;
import javafx.scene.control.TreeTableView;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Text;
import org.jabref.gui.DialogService;
import org.jabref.gui.DragAndDropDataFormats;
import org.jabref.gui.Globals;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.ActionFactory;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.actions.StandardActions;
import org.jabref.gui.util.BindingsHelper;
import org.jabref.gui.util.ControlHelper;
import org.jabref.gui.util.CustomLocalDragboard;
import org.jabref.gui.util.RecursiveTreeItem;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.gui.util.ViewModelTreeTableCellFactory;
import org.jabref.gui.util.ViewModelTreeTableRowFactory;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.groups.AllEntriesGroup;
import org.jabref.preferences.PreferencesService;
import com.tobiasdiez.easybind.EasyBind;
import org.controlsfx.control.textfield.CustomTextField;
import org.controlsfx.control.textfield.TextFields;
import org.reactfx.util.FxTimer;
import org.reactfx.util.Timer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GroupTreeView extends BorderPane {
private static final Logger LOGGER = LoggerFactory.getLogger(GroupTreeView.class);
private static final PseudoClass PSEUDOCLASS_ANYSELECTED = PseudoClass.getPseudoClass("any-selected");
private static final PseudoClass PSEUDOCLASS_ALLSELECTED = PseudoClass.getPseudoClass("all-selected");
private static final PseudoClass PSEUDOCLASS_ROOTELEMENT = PseudoClass.getPseudoClass("root");
private static final PseudoClass PSEUDOCLASS_SUBELEMENT = PseudoClass.getPseudoClass("sub"); // > 1 deep
private static final double SCROLL_SPEED = 50;
private TreeTableView<GroupNodeViewModel> groupTree;
private TreeTableColumn<GroupNodeViewModel, GroupNodeViewModel> mainColumn;
private TreeTableColumn<GroupNodeViewModel, GroupNodeViewModel> numberColumn;
private TreeTableColumn<GroupNodeViewModel, GroupNodeViewModel> expansionNodeColumn;
private CustomTextField searchField;
private final StateManager stateManager;
private final DialogService dialogService;
private final TaskExecutor taskExecutor;
private final PreferencesService preferencesService;
private GroupTreeViewModel viewModel;
private CustomLocalDragboard localDragboard;
private DragExpansionHandler dragExpansionHandler;
private Timer scrollTimer;
private double scrollVelocity = 0;
/**
* Note: This panel is deliberately not created in fxml, since parsing equivalent fxml takes about 500 msecs
*/
public GroupTreeView(TaskExecutor taskExecutor,
StateManager stateManager,
PreferencesService preferencesService,
DialogService dialogService) {
this.taskExecutor = taskExecutor;
this.stateManager = stateManager;
this.preferencesService = preferencesService;
this.dialogService = dialogService;
createNodes();
this.getStylesheets().add(Objects.requireNonNull(GroupTreeView.class.getResource("GroupTree.css")).toExternalForm());
initialize();
}
private void createNodes() {
searchField = new CustomTextField();
searchField.setPromptText(Localization.lang("Filter groups"));
searchField.setId("searchField");
HBox.setHgrow(searchField, Priority.ALWAYS);
HBox groupFilterBar = new HBox(searchField);
groupFilterBar.setId("groupFilterBar");
this.setTop(groupFilterBar);
mainColumn = new TreeTableColumn<>();
mainColumn.setId("mainColumn");
mainColumn.setResizable(true);
numberColumn = new TreeTableColumn<>();
numberColumn.getStyleClass().add("numberColumn");
numberColumn.setMinWidth(60d);
numberColumn.setMaxWidth(60d);
numberColumn.setPrefWidth(60d);
numberColumn.setResizable(false);
expansionNodeColumn = new TreeTableColumn<>();
expansionNodeColumn.getStyleClass().add("expansionNodeColumn");
expansionNodeColumn.setMaxWidth(20d);
expansionNodeColumn.setMinWidth(20d);
expansionNodeColumn.setPrefWidth(20d);
expansionNodeColumn.setResizable(false);
groupTree = new TreeTableView<>();
groupTree.setId("groupTree");
groupTree.setColumnResizePolicy(TreeTableView.CONSTRAINED_RESIZE_POLICY);
groupTree.getColumns().addAll(List.of(mainColumn, numberColumn, expansionNodeColumn));
this.setCenter(groupTree);
mainColumn.prefWidthProperty().bind(groupTree.widthProperty().subtract(80d).subtract(15d));
Button addNewGroup = new Button(Localization.lang("Add group"));
addNewGroup.setId("addNewGroup");
addNewGroup.setMaxWidth(Double.MAX_VALUE);
HBox.setHgrow(addNewGroup, Priority.ALWAYS);
addNewGroup.setTooltip(new Tooltip(Localization.lang("New group")));
addNewGroup.setOnAction(event -> addNewGroup());
HBox groupBar = new HBox(addNewGroup);
groupBar.setId("groupBar");
this.setBottom(groupBar);
}
private void initialize() {
this.localDragboard = stateManager.getLocalDragboard();
viewModel = new GroupTreeViewModel(stateManager, dialogService, preferencesService, taskExecutor, localDragboard);
// Set-up groups tree
groupTree.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
dragExpansionHandler = new DragExpansionHandler();
// Set-up bindings
Platform.runLater(() ->
BindingsHelper.bindContentBidirectional(
groupTree.getSelectionModel().getSelectedItems(),
viewModel.selectedGroupsProperty(),
newSelectedGroups -> newSelectedGroups.forEach(this::selectNode),
this::updateSelection
));
// We try to prevent publishing changes in the search field directly to the search task that takes some time
// for larger group structures.
final Timer searchTask = FxTimer.create(Duration.ofMillis(400), () -> {
LOGGER.debug("Run group search " + searchField.getText());
viewModel.filterTextProperty().setValue(searchField.textProperty().getValue());
});
searchField.textProperty().addListener((observable, oldValue, newValue) -> searchTask.restart());
groupTree.rootProperty().bind(
EasyBind.map(viewModel.rootGroupProperty(),
group -> {
if (group == null) {
return null;
} else {
return new RecursiveTreeItem<>(
group,
GroupNodeViewModel::getChildren,
GroupNodeViewModel::expandedProperty,
viewModel.filterPredicateProperty());
}
}));
// Icon and group name
new ViewModelTreeTableCellFactory<GroupNodeViewModel>()
.withText(GroupNodeViewModel::getDisplayName)
.withIcon(GroupNodeViewModel::getIcon)
.withTooltip(GroupNodeViewModel::getDescription)
.install(mainColumn);
// Number of hits (only if user wants to see them)
new ViewModelTreeTableCellFactory<GroupNodeViewModel>()
.withGraphic(this::createNumberCell)
.install(numberColumn);
// Arrow indicating expanded status
new ViewModelTreeTableCellFactory<GroupNodeViewModel>()
.withGraphic(this::getArrowCell)
.withOnMouseClickedEvent(group -> event -> {
group.toggleExpansion();
event.consume();
})
.install(expansionNodeColumn);
new ViewModelTreeTableRowFactory<GroupNodeViewModel>()
.withContextMenu(this::createContextMenuForGroup)
.withOnMousePressedEvent((row, event) -> {
if (event.getTarget() instanceof StackPane pane) {
if (pane.getStyleClass().contains("arrow") || pane.getStyleClass().contains("tree-disclosure-node")) {
event.consume();
}
}
})
.withCustomInitializer(row -> {
// Remove disclosure node since we display custom version in separate column
// Simply setting to null is not enough since it would be replaced by the default node on every change
row.setDisclosureNode(null);
row.disclosureNodeProperty().addListener((observable, oldValue, newValue) -> row.setDisclosureNode(null));
})
.setOnDragDetected(this::handleOnDragDetected)
.setOnDragDropped(this::handleOnDragDropped)
.setOnDragExited(this::handleOnDragExited)
.setOnDragOver(this::handleOnDragOver)
.withPseudoClass(PSEUDOCLASS_ROOTELEMENT, row -> Bindings.createBooleanBinding(
() -> (row != null) && (groupTree.getRoot() != null) && (row.getItem() == groupTree.getRoot().getValue()), row.treeItemProperty()))
.withPseudoClass(PSEUDOCLASS_SUBELEMENT, row -> Bindings.createBooleanBinding(
() -> (row != null) && (groupTree.getTreeItemLevel(row.getTreeItem()) > 1), row.treeItemProperty()))
.install(groupTree);
setupDragScrolling();
// Filter text field
setupClearButtonField(searchField);
}
private StackPane getArrowCell(GroupNodeViewModel viewModel) {
final StackPane disclosureNode = new StackPane();
disclosureNode.visibleProperty().bind(viewModel.hasChildrenProperty());
disclosureNode.getStyleClass().setAll("tree-disclosure-node");
final StackPane disclosureNodeArrow = new StackPane();
disclosureNodeArrow.getStyleClass().setAll("arrow");
disclosureNode.getChildren().add(disclosureNodeArrow);
return disclosureNode;
}
private StackPane createNumberCell(GroupNodeViewModel group) {
final StackPane node = new StackPane();
if (!group.isRoot()) {
BindingsHelper.includePseudoClassWhen(node, PSEUDOCLASS_ANYSELECTED,
group.anySelectedEntriesMatchedProperty());
BindingsHelper.includePseudoClassWhen(node, PSEUDOCLASS_ALLSELECTED,
group.allSelectedEntriesMatchedProperty());
}
Text text = new Text();
EasyBind.subscribe(preferencesService.getGroupsPreferences().displayGroupCountProperty(),
shouldDisplayGroupCount -> {
if (text.textProperty().isBound()) {
text.textProperty().unbind();
text.setText("");
}
node.getStyleClass().clear();
if (shouldDisplayGroupCount) {
node.getStyleClass().add("hits");
text.textProperty().bind(group.getHits().map(Number::intValue).map(this::getFormattedNumber));
}
});
text.getStyleClass().setAll("text");
text.styleProperty().bind(Bindings.createStringBinding(() -> {
double reducedFontSize;
double font_size = preferencesService.getWorkspacePreferences().getMainFontSize();
// For each breaking point, the font size is reduced 0.20 em to fix issue 8797
if (font_size > 26.0) {
reducedFontSize = 0.25;
} else if (font_size > 22.0) {
reducedFontSize = 0.35;
} else if (font_size > 18.0) {
reducedFontSize = 0.55;
} else {
reducedFontSize = 0.75;
}
return String.format("-fx-font-size: %fem;", reducedFontSize);
}, preferencesService.getWorkspacePreferences().mainFontSizeProperty()));
node.getChildren().add(text);
node.setMaxWidth(Control.USE_PREF_SIZE);
return node;
}
private void handleOnDragExited(TreeTableRow<GroupNodeViewModel> row, GroupNodeViewModel fieldViewModel, DragEvent dragEvent) {
ControlHelper.removeDroppingPseudoClasses(row);
}
private void handleOnDragDetected(TreeTableRow<GroupNodeViewModel> row, GroupNodeViewModel groupViewModel, MouseEvent event) {
List<String> groupsToMove = new ArrayList<>();
for (TreeItem<GroupNodeViewModel> selectedItem : row.getTreeTableView().getSelectionModel().getSelectedItems()) {
if ((selectedItem != null) && (selectedItem.getValue() != null)) {
groupsToMove.add(selectedItem.getValue().getPath());
}
}
if (groupsToMove.size() > 0) {
localDragboard.clearAll();
}
// Put the group nodes as content
Dragboard dragboard = row.startDragAndDrop(TransferMode.MOVE);
// Display the group when dragging
dragboard.setDragView(row.snapshot(null, null));
ClipboardContent content = new ClipboardContent();
content.put(DragAndDropDataFormats.GROUP, groupsToMove);
dragboard.setContent(content);
event.consume();
}
private void handleOnDragDropped(TreeTableRow<GroupNodeViewModel> row, GroupNodeViewModel originalItem, DragEvent event) {
Dragboard dragboard = event.getDragboard();
boolean success = false;
if (dragboard.hasContent(DragAndDropDataFormats.GROUP) && row.getItem().canAddGroupsIn()) {
List<String> pathToSources = (List<String>) dragboard.getContent(DragAndDropDataFormats.GROUP);
List<GroupNodeViewModel> changedGroups = new LinkedList<>();
for (String pathToSource : pathToSources) {
Optional<GroupNodeViewModel> source = viewModel
.rootGroupProperty().get()
.getChildByPath(pathToSource);
if (source.isPresent() && source.get().canBeDragged()) {
source.get().draggedOn(row.getItem(), ControlHelper.getDroppingMouseLocation(row, event));
changedGroups.add(source.get());
success = true;
}
}
groupTree.getSelectionModel().clearSelection();
changedGroups.forEach(value -> selectNode(value, true));
if (success) {
viewModel.writeGroupChangesToMetaData();
}
}
if (localDragboard.hasBibEntries()) {
List<BibEntry> entries = localDragboard.getBibEntries();
row.getItem().addEntriesToGroup(entries);
success = true;
}
event.setDropCompleted(success);
event.consume();
}
private void handleOnDragOver(TreeTableRow<GroupNodeViewModel> row, GroupNodeViewModel originalItem, DragEvent event) {
Dragboard dragboard = event.getDragboard();
if ((event.getGestureSource() != row) && (row.getItem() != null) && row.getItem().acceptableDrop(dragboard)) {
event.acceptTransferModes(TransferMode.MOVE, TransferMode.LINK);
// expand node and all children on drag over
dragExpansionHandler.expandGroup(row.getTreeItem());
if (localDragboard.hasBibEntries()) {
ControlHelper.setDroppingPseudoClasses(row);
} else {
ControlHelper.setDroppingPseudoClasses(row, event);
}
}
event.consume();
}
private void updateSelection(List<TreeItem<GroupNodeViewModel>> newSelectedGroups) {
if ((newSelectedGroups == null) || newSelectedGroups.isEmpty()) {
viewModel.selectedGroupsProperty().clear();
} else {
List<GroupNodeViewModel> list = newSelectedGroups.stream().filter(model -> (model != null) && !(model.getValue().getGroupNode().getGroup() instanceof AllEntriesGroup)).map(TreeItem::getValue).collect(Collectors.toList());
viewModel.selectedGroupsProperty().setAll(list);
}
}
private void selectNode(GroupNodeViewModel value) {
selectNode(value, false);
}
private void selectNode(GroupNodeViewModel value, boolean expandParents) {
getTreeItemByValue(value)
.ifPresent(treeItem -> {
if (expandParents) {
TreeItem<GroupNodeViewModel> parent = treeItem.getParent();
while (parent != null) {
parent.setExpanded(true);
parent = parent.getParent();
}
}
groupTree.getSelectionModel().select(treeItem);
});
}
private Optional<TreeItem<GroupNodeViewModel>> getTreeItemByValue(GroupNodeViewModel value) {
return getTreeItemByValue(groupTree.getRoot(), value);
}
private Optional<TreeItem<GroupNodeViewModel>> getTreeItemByValue(TreeItem<GroupNodeViewModel> root,
GroupNodeViewModel value) {
if (root == null) {
return Optional.empty();
}
if (root.getValue().equals(value)) {
return Optional.of(root);
}
Optional<TreeItem<GroupNodeViewModel>> node = Optional.empty();
for (TreeItem<GroupNodeViewModel> child : root.getChildren()) {
node = getTreeItemByValue(child, value);
if (node.isPresent()) {
break;
}
}
return node;
}
// see http://programmingtipsandtraps.blogspot.com/2015/10/drag-and-drop-in-treetableview-with.html
private void setupDragScrolling() {
scrollTimer = FxTimer.createPeriodic(Duration.ofMillis(20), () ->
getVerticalScrollbar().ifPresent(scrollBar -> {
double newValue = scrollBar.getValue() + scrollVelocity;
newValue = Math.min(newValue, 1d);
newValue = Math.max(newValue, 0d);
scrollBar.setValue(newValue);
}));
groupTree.setOnScroll(event -> scrollTimer.stop());
groupTree.setOnDragDone(event -> scrollTimer.stop());
groupTree.setOnDragEntered(event -> scrollTimer.stop());
groupTree.setOnDragDropped(event -> scrollTimer.stop());
groupTree.setOnDragExited(event -> {
if (event.getY() > 0) {
scrollVelocity = 1.0 / SCROLL_SPEED;
} else {
scrollVelocity = -1.0 / SCROLL_SPEED;
}
scrollTimer.restart();
});
}
private Optional<ScrollBar> getVerticalScrollbar() {
for (Node node : groupTree.lookupAll(".scroll-bar")) {
if (node instanceof ScrollBar scrollbar
&& scrollbar.getOrientation().equals(Orientation.VERTICAL)) {
return Optional.of(scrollbar);
}
}
return Optional.empty();
}
private ContextMenu createContextMenuForGroup(GroupNodeViewModel group) {
if (group == null) {
return null;
}
ContextMenu contextMenu = new ContextMenu();
ActionFactory factory = new ActionFactory(Globals.getKeyPrefs());
MenuItem removeGroup;
if (group.hasSubgroups() && group.canAddGroupsIn() && !group.isRoot()) {
removeGroup = new Menu(Localization.lang("Remove group"), null,
factory.createMenuItem(StandardActions.GROUP_REMOVE_KEEP_SUBGROUPS,
new GroupTreeView.ContextAction(StandardActions.GROUP_REMOVE_KEEP_SUBGROUPS, group)),
factory.createMenuItem(StandardActions.GROUP_REMOVE_WITH_SUBGROUPS,
new GroupTreeView.ContextAction(StandardActions.GROUP_REMOVE_WITH_SUBGROUPS, group))
);
} else {
removeGroup = factory.createMenuItem(StandardActions.GROUP_REMOVE, new GroupTreeView.ContextAction(StandardActions.GROUP_REMOVE, group));
}
contextMenu.getItems().addAll(
factory.createMenuItem(StandardActions.GROUP_EDIT, new ContextAction(StandardActions.GROUP_EDIT, group)),
removeGroup,
new SeparatorMenuItem(),
factory.createMenuItem(StandardActions.GROUP_SUBGROUP_ADD, new ContextAction(StandardActions.GROUP_SUBGROUP_ADD, group)),
factory.createMenuItem(StandardActions.GROUP_SUBGROUP_REMOVE, new ContextAction(StandardActions.GROUP_SUBGROUP_REMOVE, group)),
factory.createMenuItem(StandardActions.GROUP_SUBGROUP_SORT, new ContextAction(StandardActions.GROUP_SUBGROUP_SORT, group)),
new SeparatorMenuItem(),
factory.createMenuItem(StandardActions.GROUP_ENTRIES_ADD, new ContextAction(StandardActions.GROUP_ENTRIES_ADD, group)),
factory.createMenuItem(StandardActions.GROUP_ENTRIES_REMOVE, new ContextAction(StandardActions.GROUP_ENTRIES_REMOVE, group))
);
contextMenu.getItems().forEach(item -> item.setGraphic(null));
contextMenu.getStyleClass().add("context-menu");
return contextMenu;
}
private void addNewGroup() {
viewModel.addNewGroupToRoot();
}
private String getFormattedNumber(int hits) {
if (hits >= 1000000) {
double millions = hits / 1000000.0;
return new DecimalFormat("#,##0.#").format(millions) + "m";
} else if (hits >= 1000) {
double thousands = hits / 1000.0;
return new DecimalFormat("#,##0.#").format(thousands) + "k";
}
return Integer.toString(hits);
}
// ToDo: reflective access, should be removed
// Workaround taken from https://github.com/controlsfx/controlsfx/issues/330
private void setupClearButtonField(CustomTextField customTextField) {
try {
Method m = TextFields.class.getDeclaredMethod("setupClearButtonField", TextField.class, ObjectProperty.class);
m.setAccessible(true);
m.invoke(null, customTextField, customTextField.rightProperty());
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) {
LOGGER.error("Failed to decorate text field with clear button", ex);
}
}
private static class DragExpansionHandler {
private static final long DRAG_TIME_BEFORE_EXPANDING_MS = 1000;
private TreeItem<GroupNodeViewModel> draggedItem;
private long dragStarted;
public void expandGroup(TreeItem<GroupNodeViewModel> treeItem) {
if (!treeItem.equals(draggedItem)) {
this.draggedItem = treeItem;
this.dragStarted = System.currentTimeMillis();
this.draggedItem.setExpanded(this.draggedItem.isExpanded());
return;
}
if ((System.currentTimeMillis() - this.dragStarted) > DRAG_TIME_BEFORE_EXPANDING_MS) {
// expand or collapse the tree item and reset the time
this.dragStarted = System.currentTimeMillis();
this.draggedItem.setExpanded(!this.draggedItem.isExpanded());
} else {
// leave the expansion state of the tree item as it is
this.draggedItem.setExpanded(this.draggedItem.isExpanded());
}
}
}
private class ContextAction extends SimpleCommand {
private final StandardActions command;
private final GroupNodeViewModel group;
public ContextAction(StandardActions command, GroupNodeViewModel group) {
this.command = command;
this.group = group;
this.executable.bind(BindingsHelper.constantOf(
switch (command) {
case GROUP_EDIT ->
group.isEditable();
case GROUP_REMOVE, GROUP_REMOVE_WITH_SUBGROUPS, GROUP_REMOVE_KEEP_SUBGROUPS ->
group.isEditable() && group.canRemove();
case GROUP_SUBGROUP_ADD ->
group.isEditable() && group.canAddGroupsIn()
|| group.isRoot();
case GROUP_SUBGROUP_REMOVE ->
group.isEditable() && group.hasSubgroups() && group.canRemove()
|| group.isRoot();
case GROUP_SUBGROUP_SORT ->
group.isEditable() && group.hasSubgroups() && group.canAddEntriesIn()
|| group.isRoot();
case GROUP_ENTRIES_ADD, GROUP_ENTRIES_REMOVE ->
group.canAddEntriesIn();
default ->
true;
}));
}
@Override
public void execute() {
switch (command) {
case GROUP_REMOVE ->
viewModel.removeGroupNoSubgroups(group);
case GROUP_REMOVE_KEEP_SUBGROUPS ->
viewModel.removeGroupKeepSubgroups(group);
case GROUP_REMOVE_WITH_SUBGROUPS ->
viewModel.removeGroupAndSubgroups(group);
case GROUP_EDIT -> {
viewModel.editGroup(group);
groupTree.refresh();
}
case GROUP_SUBGROUP_ADD ->
viewModel.addNewSubgroup(group, GroupDialogHeader.SUBGROUP);
case GROUP_SUBGROUP_REMOVE ->
viewModel.removeSubgroups(group);
case GROUP_SUBGROUP_SORT ->
viewModel.sortAlphabeticallyRecursive(group.getGroupNode());
case GROUP_ENTRIES_ADD ->
viewModel.addSelectedEntries(group);
case GROUP_ENTRIES_REMOVE ->
viewModel.removeSelectedEntries(group);
}
}
}
/**
* Focus on GroupTree
*/
public void requestFocusGroupTree() {
groupTree.requestFocus();
}
}
| 28,080
| 43.714968
| 233
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/groups/GroupTreeViewModel.java
|
package org.jabref.gui.groups;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Predicate;
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.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonType;
import org.jabref.gui.AbstractViewModel;
import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.util.CustomLocalDragboard;
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.groups.AbstractGroup;
import org.jabref.model.groups.AutomaticKeywordGroup;
import org.jabref.model.groups.AutomaticPersonsGroup;
import org.jabref.model.groups.ExplicitGroup;
import org.jabref.model.groups.GroupTreeNode;
import org.jabref.model.groups.RegexKeywordGroup;
import org.jabref.model.groups.SearchGroup;
import org.jabref.model.groups.TexGroup;
import org.jabref.model.groups.WordKeywordGroup;
import org.jabref.model.metadata.MetaData;
import org.jabref.preferences.PreferencesService;
import com.tobiasdiez.easybind.EasyBind;
public class GroupTreeViewModel extends AbstractViewModel {
private final ObjectProperty<GroupNodeViewModel> rootGroup = new SimpleObjectProperty<>();
private final ListProperty<GroupNodeViewModel> selectedGroups = new SimpleListProperty<>(FXCollections.observableArrayList());
private final StateManager stateManager;
private final DialogService dialogService;
private final PreferencesService preferences;
private final TaskExecutor taskExecutor;
private final CustomLocalDragboard localDragboard;
private final ObjectProperty<Predicate<GroupNodeViewModel>> filterPredicate = new SimpleObjectProperty<>();
private final StringProperty filterText = new SimpleStringProperty();
private final Comparator<GroupTreeNode> compAlphabetIgnoreCase = (GroupTreeNode v1, GroupTreeNode v2) -> v1
.getName()
.compareToIgnoreCase(v2.getName());
private Optional<BibDatabaseContext> currentDatabase;
public GroupTreeViewModel(StateManager stateManager, DialogService dialogService, PreferencesService preferencesService, TaskExecutor taskExecutor, CustomLocalDragboard localDragboard) {
this.stateManager = Objects.requireNonNull(stateManager);
this.dialogService = Objects.requireNonNull(dialogService);
this.preferences = Objects.requireNonNull(preferencesService);
this.taskExecutor = Objects.requireNonNull(taskExecutor);
this.localDragboard = Objects.requireNonNull(localDragboard);
// Register listener
EasyBind.subscribe(stateManager.activeDatabaseProperty(), this::onActiveDatabaseChanged);
EasyBind.subscribe(selectedGroups, this::onSelectedGroupChanged);
// Set-up bindings
filterPredicate.bind(EasyBind.map(filterText, text -> group -> group.isMatchedBy(text)));
// Init
refresh();
}
private void refresh() {
onActiveDatabaseChanged(stateManager.activeDatabaseProperty().getValue());
}
public ObjectProperty<GroupNodeViewModel> rootGroupProperty() {
return rootGroup;
}
public ListProperty<GroupNodeViewModel> selectedGroupsProperty() {
return selectedGroups;
}
public ObjectProperty<Predicate<GroupNodeViewModel>> filterPredicateProperty() {
return filterPredicate;
}
public StringProperty filterTextProperty() {
return filterText;
}
/**
* Gets invoked if the user selects a different group.
* We need to notify the {@link StateManager} about this change so that the main table gets updated.
*/
private void onSelectedGroupChanged(ObservableList<GroupNodeViewModel> newValue) {
if (!currentDatabase.equals(stateManager.activeDatabaseProperty().getValue())) {
// Switch of database occurred -> do nothing
return;
}
currentDatabase.ifPresent(database -> {
if ((newValue == null) || newValue.isEmpty()) {
stateManager.clearSelectedGroups(database);
} else {
stateManager.setSelectedGroups(database, newValue.stream().map(GroupNodeViewModel::getGroupNode).collect(Collectors.toList()));
}
});
}
/**
* Opens "New Group Dialog" and add the resulting group to the root
*/
public void addNewGroupToRoot() {
if (currentDatabase.isPresent()) {
addNewSubgroup(rootGroup.get(), GroupDialogHeader.GROUP);
} else {
dialogService.showWarningDialogAndWait(Localization.lang("Cannot create group"), Localization.lang("Cannot create group. Please create a library first."));
}
}
/**
* Gets invoked if the user changes the active database.
* We need to get the new group tree and update the view
*/
private void onActiveDatabaseChanged(Optional<BibDatabaseContext> newDatabase) {
if (newDatabase.isPresent()) {
GroupNodeViewModel newRoot = newDatabase
.map(BibDatabaseContext::getMetaData)
.flatMap(MetaData::getGroups)
.map(root -> new GroupNodeViewModel(newDatabase.get(), stateManager, taskExecutor, root, localDragboard, preferences))
.orElse(GroupNodeViewModel.getAllEntriesGroup(newDatabase.get(), stateManager, taskExecutor, localDragboard, preferences));
rootGroup.setValue(newRoot);
if (stateManager.getSelectedGroup(newDatabase.get()).isEmpty()) {
stateManager.setSelectedGroups(newDatabase.get(), Collections.singletonList(newRoot.getGroupNode()));
}
selectedGroups.setAll(
stateManager.getSelectedGroup(newDatabase.get()).stream()
.map(selectedGroup -> new GroupNodeViewModel(newDatabase.get(), stateManager, taskExecutor, selectedGroup, localDragboard, preferences))
.collect(Collectors.toList()));
} else {
rootGroup.setValue(null);
}
currentDatabase = newDatabase;
}
/**
* Opens "New Group Dialog" and adds the resulting group as subgroup to the specified group
*/
public void addNewSubgroup(GroupNodeViewModel parent, GroupDialogHeader groupDialogHeader) {
currentDatabase.ifPresent(database -> {
Optional<AbstractGroup> newGroup = dialogService.showCustomDialogAndWait(new GroupDialogView(
dialogService,
database,
preferences,
null,
groupDialogHeader));
newGroup.ifPresent(group -> {
parent.addSubgroup(group);
// TODO: Add undo
// UndoableAddOrRemoveGroup undo = new UndoableAddOrRemoveGroup(parent, new GroupTreeNodeViewModel(newGroupNode), UndoableAddOrRemoveGroup.ADD_NODE);
// panel.getUndoManager().addEdit(undo);
// TODO: Expand parent to make new group visible
// parent.expand();
dialogService.notify(Localization.lang("Added group \"%0\".", group.getName()));
writeGroupChangesToMetaData();
});
});
}
public void writeGroupChangesToMetaData() {
currentDatabase.ifPresent(database -> database.getMetaData().setGroups(rootGroup.get().getGroupNode()));
}
private boolean isGroupTypeEqual(AbstractGroup oldGroup, AbstractGroup newGroup) {
return oldGroup.getClass().equals(newGroup.getClass());
}
/**
* Check if it is necessary to show a group modified, reassign entry dialog <br>
* Group name change is handled separately
*
* @param oldGroup Original Group
* @param newGroup Edited group
* @return true if just trivial modifications (e.g. color or description) or the relevant group properties are equal, false otherwise
*/
boolean onlyMinorChanges(AbstractGroup oldGroup, AbstractGroup newGroup) {
// we need to use getclass here because we have different subclass inheritance e.g. ExplicitGroup is a subclass of WordKeyWordGroup
if (oldGroup.getClass() == WordKeywordGroup.class) {
WordKeywordGroup oldWordKeywordGroup = (WordKeywordGroup) oldGroup;
WordKeywordGroup newWordKeywordGroup = (WordKeywordGroup) newGroup;
return Objects.equals(oldWordKeywordGroup.getSearchField().getName(), newWordKeywordGroup.getSearchField().getName())
&& Objects.equals(oldWordKeywordGroup.getSearchExpression(), newWordKeywordGroup.getSearchExpression())
&& Objects.equals(oldWordKeywordGroup.isCaseSensitive(), newWordKeywordGroup.isCaseSensitive());
} else if (oldGroup.getClass() == RegexKeywordGroup.class) {
RegexKeywordGroup oldRegexKeywordGroup = (RegexKeywordGroup) oldGroup;
RegexKeywordGroup newRegexKeywordGroup = (RegexKeywordGroup) newGroup;
return Objects.equals(oldRegexKeywordGroup.getSearchField().getName(), newRegexKeywordGroup.getSearchField().getName())
&& Objects.equals(oldRegexKeywordGroup.getSearchExpression(), newRegexKeywordGroup.getSearchExpression())
&& Objects.equals(oldRegexKeywordGroup.isCaseSensitive(), newRegexKeywordGroup.isCaseSensitive());
} else if (oldGroup.getClass() == SearchGroup.class) {
SearchGroup oldSearchGroup = (SearchGroup) oldGroup;
SearchGroup newSearchGroup = (SearchGroup) newGroup;
return Objects.equals(oldSearchGroup.getSearchExpression(), newSearchGroup.getSearchExpression())
&& Objects.equals(oldSearchGroup.getSearchFlags(), newSearchGroup.getSearchFlags());
} else if (oldGroup.getClass() == AutomaticKeywordGroup.class) {
AutomaticKeywordGroup oldAutomaticKeywordGroup = (AutomaticKeywordGroup) oldGroup;
AutomaticKeywordGroup newAutomaticKeywordGroup = (AutomaticKeywordGroup) oldGroup;
return Objects.equals(oldAutomaticKeywordGroup.getKeywordDelimiter(), newAutomaticKeywordGroup.getKeywordDelimiter())
&& Objects.equals(oldAutomaticKeywordGroup.getKeywordHierarchicalDelimiter(), newAutomaticKeywordGroup.getKeywordHierarchicalDelimiter())
&& Objects.equals(oldAutomaticKeywordGroup.getField().getName(), newAutomaticKeywordGroup.getField().getName());
} else if (oldGroup.getClass() == AutomaticPersonsGroup.class) {
AutomaticPersonsGroup oldAutomaticPersonsGroup = (AutomaticPersonsGroup) oldGroup;
AutomaticPersonsGroup newAutomaticPersonsGroup = (AutomaticPersonsGroup) newGroup;
return Objects.equals(oldAutomaticPersonsGroup.getField().getName(), newAutomaticPersonsGroup.getField().getName());
} else if (oldGroup.getClass() == TexGroup.class) {
TexGroup oldTexGroup = (TexGroup) oldGroup;
TexGroup newTexGroup = (TexGroup) newGroup;
return Objects.equals(oldTexGroup.getFilePath().toString(), newTexGroup.getFilePath().toString());
}
return true;
}
/**
* Opens "Edit Group Dialog" and changes the given group to the edited one.
*/
public void editGroup(GroupNodeViewModel oldGroup) {
currentDatabase.ifPresent(database -> {
Optional<AbstractGroup> newGroup = dialogService.showCustomDialogAndWait(new GroupDialogView(
dialogService,
database,
preferences,
oldGroup.getGroupNode().getGroup(),
GroupDialogHeader.SUBGROUP));
newGroup.ifPresent(group -> {
AbstractGroup oldGroupDef = oldGroup.getGroupNode().getGroup();
String oldGroupName = oldGroupDef.getName();
boolean groupTypeEqual = isGroupTypeEqual(oldGroupDef, group);
boolean onlyMinorModifications = groupTypeEqual && onlyMinorChanges(oldGroupDef, group);
// dialog already warns us about this if the new group is named like another existing group
// We need to check if only the name changed as this is relevant for the entry's group field
if (groupTypeEqual && !group.getName().equals(oldGroupName) && onlyMinorModifications) {
int groupsWithSameName = 0;
Optional<GroupTreeNode> databaseRootGroup = currentDatabase.get().getMetaData().getGroups();
if (databaseRootGroup.isPresent()) {
// we need to check the old name for duplicates. If the new group name occurs more than once, it won't matter
groupsWithSameName = databaseRootGroup.get().findChildrenSatisfying(g -> g.getName().equals(oldGroupName)).size();
}
boolean removePreviousAssignments = true;
// We found more than 2 groups, so we cannot simply remove old assignment
if (groupsWithSameName >= 2) {
removePreviousAssignments = false;
}
oldGroup.getGroupNode().setGroup(
group,
true,
removePreviousAssignments,
database.getEntries());
dialogService.notify(Localization.lang("Modified group \"%0\".", group.getName()));
writeGroupChangesToMetaData();
// This is ugly but we have no proper update mechanism in place to propagate the changes, so redraw everything
refresh();
return;
}
if (groupTypeEqual && onlyMinorChanges(oldGroup.getGroupNode().getGroup(), group)) {
oldGroup.getGroupNode().setGroup(
group,
true,
true,
database.getEntries());
writeGroupChangesToMetaData();
refresh();
return;
}
// Major modifications
String content = Localization.lang("Assign the original group's entries to this group?");
ButtonType keepAssignments = new ButtonType(Localization.lang("Assign"), ButtonBar.ButtonData.YES);
ButtonType removeAssignments = new ButtonType(Localization.lang("Do not assign"), ButtonBar.ButtonData.NO);
ButtonType cancel = new ButtonType(Localization.lang("Cancel"), ButtonBar.ButtonData.CANCEL_CLOSE);
if (newGroup.get().getClass() == WordKeywordGroup.class) {
content = content + "\n\n" +
Localization.lang("(Note: If original entries lack keywords to qualify for the new group configuration, confirming here will add them)");
}
Optional<ButtonType> previousAssignments = dialogService.showCustomButtonDialogAndWait(Alert.AlertType.WARNING,
Localization.lang("Change of Grouping Method"),
content,
keepAssignments,
removeAssignments,
cancel);
boolean removePreviousAssignments = (oldGroup.getGroupNode().getGroup() instanceof ExplicitGroup)
&& (group instanceof ExplicitGroup);
int groupsWithSameName = 0;
Optional<GroupTreeNode> databaseRootGroup = currentDatabase.get().getMetaData().getGroups();
if (databaseRootGroup.isPresent()) {
String name = oldGroup.getGroupNode().getGroup().getName();
groupsWithSameName = databaseRootGroup.get().findChildrenSatisfying(g -> g.getName().equals(name)).size();
}
// okay we found more than 2 groups with the same name
// If we only found one we can still do it
if (groupsWithSameName >= 2) {
removePreviousAssignments = false;
}
if (previousAssignments.isPresent() && (previousAssignments.get().getButtonData() == ButtonBar.ButtonData.YES)) {
oldGroup.getGroupNode().setGroup(
group,
true,
removePreviousAssignments,
database.getEntries());
} else if (previousAssignments.isPresent() && (previousAssignments.get().getButtonData() == ButtonBar.ButtonData.NO)) {
oldGroup.getGroupNode().setGroup(
group,
false,
removePreviousAssignments,
database.getEntries());
} else if (previousAssignments.isPresent() && (previousAssignments.get().getButtonData() == ButtonBar.ButtonData.CANCEL_CLOSE)) {
return;
}
// stateManager.getEntriesInCurrentDatabase());
// TODO: Add undo
// Store undo information.
// AbstractUndoableEdit undoAddPreviousEntries = null;
// UndoableModifyGroup undo = new UndoableModifyGroup(GroupSelector.this, groupsRoot, node, newGroup);
// if (undoAddPreviousEntries == null) {
// panel.getUndoManager().addEdit(undo);
// } else {
// NamedCompound nc = new NamedCompound("Modify Group");
// nc.addEdit(undo);
// nc.addEdit(undoAddPreviousEntries);
// nc.end();/
// panel.getUndoManager().addEdit(nc);
// }
// if (!addChange.isEmpty()) {
// undoAddPreviousEntries = UndoableChangeEntriesOfGroup.getUndoableEdit(null, addChange);
// }
dialogService.notify(Localization.lang("Modified group \"%0\".", group.getName()));
writeGroupChangesToMetaData();
// This is ugly but we have no proper update mechanism in place to propagate the changes, so redraw everything
refresh();
});
});
}
public void removeSubgroups(GroupNodeViewModel group) {
boolean confirmation = dialogService.showConfirmationDialogAndWait(
Localization.lang("Remove subgroups"),
Localization.lang("Remove all subgroups of \"%0\"?", group.getDisplayName()));
if (confirmation) {
/// TODO: Add undo
// final UndoableModifySubtree undo = new UndoableModifySubtree(getGroupTreeRoot(), node, "Remove subgroups");
// panel.getUndoManager().addEdit(undo);
for (GroupNodeViewModel child : group.getChildren()) {
removeGroupsAndSubGroupsFromEntries(child);
}
group.getGroupNode().removeAllChildren();
dialogService.notify(Localization.lang("Removed all subgroups of group \"%0\".", group.getDisplayName()));
writeGroupChangesToMetaData();
}
}
public void removeGroupKeepSubgroups(GroupNodeViewModel group) {
boolean confirmed;
if (selectedGroups.size() <= 1) {
confirmed = dialogService.showConfirmationDialogAndWait(
Localization.lang("Remove group"),
Localization.lang("Remove group \"%0\" and keep its subgroups?", group.getDisplayName()),
Localization.lang("Remove"));
} else {
confirmed = dialogService.showConfirmationDialogAndWait(
Localization.lang("Remove groups"),
Localization.lang("Remove all selected groups and keep their subgroups?"),
Localization.lang("Remove all"));
}
if (confirmed) {
// TODO: Add undo
// final UndoableAddOrRemoveGroup undo = new UndoableAddOrRemoveGroup(groupsRoot, node, UndoableAddOrRemoveGroup.REMOVE_NODE_KEEP_CHILDREN);
// panel.getUndoManager().addEdit(undo);
List<GroupNodeViewModel> selectedGroupNodes = new ArrayList<>(selectedGroups);
selectedGroupNodes.forEach(eachNode -> {
GroupTreeNode groupNode = eachNode.getGroupNode();
groupNode.getParent()
.ifPresent(parent -> groupNode.moveAllChildrenTo(parent, parent.getIndexOfChild(groupNode).get()));
groupNode.removeFromParent();
});
if (selectedGroupNodes.size() > 1) {
dialogService.notify(Localization.lang("Removed all selected groups."));
} else {
dialogService.notify(Localization.lang("Removed group \"%0\".", group.getDisplayName()));
}
writeGroupChangesToMetaData();
}
}
/**
* Removes the specified group and its subgroups (after asking for confirmation).
*/
public void removeGroupAndSubgroups(GroupNodeViewModel group) {
boolean confirmed;
if (selectedGroups.size() <= 1) {
confirmed = dialogService.showConfirmationDialogAndWait(
Localization.lang("Remove group and subgroups"),
Localization.lang("Remove group \"%0\" and its subgroups?", group.getDisplayName()),
Localization.lang("Remove"));
} else {
confirmed = dialogService.showConfirmationDialogAndWait(
Localization.lang("Remove groups and subgroups"),
Localization.lang("Remove all selected groups and their subgroups?"),
Localization.lang("Remove all"));
}
if (confirmed) {
// TODO: Add undo
// final UndoableAddOrRemoveGroup undo = new UndoableAddOrRemoveGroup(groupsRoot, node, UndoableAddOrRemoveGroup.REMOVE_NODE_AND_CHILDREN);
// panel.getUndoManager().addEdit(undo);
ArrayList<GroupNodeViewModel> selectedGroupNodes = new ArrayList<>(selectedGroups);
selectedGroupNodes.forEach(eachNode -> {
removeGroupsAndSubGroupsFromEntries(eachNode);
eachNode.getGroupNode().removeFromParent();
});
if (selectedGroupNodes.size() > 1) {
dialogService.notify(Localization.lang("Removed all selected groups and their subgroups."));
} else {
dialogService.notify(Localization.lang("Removed group \"%0\" and its subgroups.", group.getDisplayName()));
}
writeGroupChangesToMetaData();
}
}
/**
* Removes the specified group (after asking for confirmation).
*/
public void removeGroupNoSubgroups(GroupNodeViewModel group) {
boolean confirmed;
if (selectedGroups.size() <= 1) {
confirmed = dialogService.showConfirmationDialogAndWait(
Localization.lang("Remove group"),
Localization.lang("Remove group \"%0\"?", group.getDisplayName()),
Localization.lang("Remove"));
} else {
confirmed = dialogService.showConfirmationDialogAndWait(
Localization.lang("Remove groups and subgroups"),
Localization.lang("Remove all selected groups and their subgroups?"),
Localization.lang("Remove all"));
}
if (confirmed) {
// TODO: Add undo
// final UndoableAddOrRemoveGroup undo = new UndoableAddOrRemoveGroup(groupsRoot, node, UndoableAddOrRemoveGroup.REMOVE_NODE_WITHOUT_CHILDREN);
// panel.getUndoManager().addEdit(undo);
ArrayList<GroupNodeViewModel> selectedGroupNodes = new ArrayList<>(selectedGroups);
selectedGroupNodes.forEach(eachNode -> {
removeGroupsAndSubGroupsFromEntries(eachNode);
eachNode.getGroupNode().removeFromParent();
});
if (selectedGroupNodes.size() > 1) {
dialogService.notify(Localization.lang("Removed all selected groups."));
} else {
dialogService.notify(Localization.lang("Removed group \"%0\".", group.getDisplayName()));
}
writeGroupChangesToMetaData();
}
}
void removeGroupsAndSubGroupsFromEntries(GroupNodeViewModel group) {
for (GroupNodeViewModel child : group.getChildren()) {
removeGroupsAndSubGroupsFromEntries(child);
}
// only remove explicit groups from the entries, keyword groups should not be deleted
if (group.getGroupNode().getGroup() instanceof ExplicitGroup) {
int groupsWithSameName = 0;
String name = group.getGroupNode().getGroup().getName();
Optional<GroupTreeNode> rootGroup = currentDatabase.get().getMetaData().getGroups();
if (rootGroup.isPresent()) {
groupsWithSameName = rootGroup.get().findChildrenSatisfying(g -> g.getName().equals(name)).size();
}
if (groupsWithSameName < 2) {
List<BibEntry> entriesInGroup = group.getGroupNode().getEntriesInGroup(this.currentDatabase.get().getEntries());
group.getGroupNode().removeEntriesFromGroup(entriesInGroup);
}
}
}
public void addSelectedEntries(GroupNodeViewModel group) {
// TODO: Warn
// if (!WarnAssignmentSideEffects.warnAssignmentSideEffects(node.getNode().getGroup(), panel.frame())) {
// return; // user aborted operation
group.getGroupNode().addEntriesToGroup(stateManager.getSelectedEntries());
// TODO: Add undo
// NamedCompound undoAll = new NamedCompound(Localization.lang("change assignment of entries"));
// if (!undoAdd.isEmpty()) { undo.addEdit(UndoableChangeEntriesOfGroup.getUndoableEdit(node, undoAdd)); }
// panel.getUndoManager().addEdit(undoAll);
// TODO Display massages
// if (undo == null) {
// frame.output(Localization.lang("The group \"%0\" already contains the selection.",
// node.getGroup().getName()));
// return;
// }
// panel.getUndoManager().addEdit(undo);
// final String groupName = node.getGroup().getName();
// if (assignedEntries == 1) {
// frame.output(Localization.lang("Assigned 1 entry to group \"%0\".", groupName));
// } else {
// frame.output(Localization.lang("Assigned %0 entries to group \"%1\".", String.valueOf(assignedEntries),
// groupName));
// }
}
public void removeSelectedEntries(GroupNodeViewModel group) {
// TODO: warn if assignment has undesired side effects (modifies a field != keywords)
// if (!WarnAssignmentSideEffects.warnAssignmentSideEffects(mNode.getNode().getGroup(), mPanel.frame())) {
// return; // user aborted operation
group.getGroupNode().removeEntriesFromGroup(stateManager.getSelectedEntries());
// TODO: Add undo
// if (!undo.isEmpty()) {
// mPanel.getUndoManager().addEdit(UndoableChangeEntriesOfGroup.getUndoableEdit(mNode, undo));
}
public void sortAlphabeticallyRecursive(GroupTreeNode group) {
group.sortChildren(compAlphabetIgnoreCase, true);
}
}
| 28,229
| 48.700704
| 190
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/groups/GroupViewMode.java
|
package org.jabref.gui.groups;
public enum GroupViewMode { INTERSECTION, UNION }
| 83
| 15.8
| 49
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/groups/GroupsPreferences.java
|
package org.jabref.gui.groups;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;
import org.jabref.model.groups.GroupHierarchyType;
public class GroupsPreferences {
private final ObjectProperty<GroupViewMode> groupViewMode;
private final BooleanProperty shouldAutoAssignGroup;
private final BooleanProperty shouldDisplayGroupCount;
private final ObjectProperty<GroupHierarchyType> defaultHierarchicalContext;
public GroupsPreferences(GroupViewMode groupViewMode,
boolean shouldAutoAssignGroup,
boolean shouldDisplayGroupCount,
GroupHierarchyType defaultHierarchicalContext) {
this.groupViewMode = new SimpleObjectProperty<>(groupViewMode);
this.shouldAutoAssignGroup = new SimpleBooleanProperty(shouldAutoAssignGroup);
this.shouldDisplayGroupCount = new SimpleBooleanProperty(shouldDisplayGroupCount);
this.defaultHierarchicalContext = new SimpleObjectProperty<>(defaultHierarchicalContext);
}
public GroupViewMode getGroupViewMode() {
return groupViewMode.getValue();
}
public ObjectProperty<GroupViewMode> groupViewModeProperty() {
return groupViewMode;
}
public void setGroupViewMode(GroupViewMode groupViewMode) {
this.groupViewMode.set(groupViewMode);
}
public boolean shouldAutoAssignGroup() {
return shouldAutoAssignGroup.getValue();
}
public BooleanProperty autoAssignGroupProperty() {
return shouldAutoAssignGroup;
}
public void setAutoAssignGroup(boolean shouldAutoAssignGroup) {
this.shouldAutoAssignGroup.set(shouldAutoAssignGroup);
}
public boolean shouldDisplayGroupCount() {
return shouldDisplayGroupCount.getValue();
}
public BooleanProperty displayGroupCountProperty() {
return shouldDisplayGroupCount;
}
public void setDisplayGroupCount(boolean shouldDisplayGroupCount) {
this.shouldDisplayGroupCount.set(shouldDisplayGroupCount);
}
public GroupHierarchyType getDefaultHierarchicalContext() {
return defaultHierarchicalContext.get();
}
public ObjectProperty<GroupHierarchyType> defaultHierarchicalContextProperty() {
return defaultHierarchicalContext;
}
public void setDefaultHierarchicalContext(GroupHierarchyType defaultHierarchicalContext) {
this.defaultHierarchicalContext.set(defaultHierarchicalContext);
}
}
| 2,629
| 33.605263
| 97
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/groups/MoveGroupChange.java
|
package org.jabref.gui.groups;
import org.jabref.model.groups.GroupTreeNode;
public class MoveGroupChange {
private GroupTreeNode oldParent;
private int oldChildIndex;
private GroupTreeNode newParent;
private int newChildIndex;
/**
* @param newParent The new parent node to which the node will be moved.
* @param newChildIndex The child index at newParent to which the node will be moved.
*/
public MoveGroupChange(GroupTreeNode oldParent, int oldChildIndex, GroupTreeNode newParent, int newChildIndex) {
this.oldParent = oldParent;
this.oldChildIndex = oldChildIndex;
this.newParent = newParent;
this.newChildIndex = newChildIndex;
}
public GroupTreeNode getOldParent() {
return oldParent;
}
public int getOldChildIndex() {
return oldChildIndex;
}
public GroupTreeNode getNewParent() {
return newParent;
}
public int getNewChildIndex() {
return newChildIndex;
}
}
| 1,016
| 25.076923
| 116
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/groups/UndoableAddOrRemoveGroup.java
|
package org.jabref.gui.groups;
import java.util.List;
import org.jabref.gui.undo.AbstractUndoableJabRefEdit;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.groups.GroupTreeNode;
public class UndoableAddOrRemoveGroup extends AbstractUndoableJabRefEdit {
/**
* Adding of a single node (group).
*/
public static final int ADD_NODE = 0;
/**
* Removal of a single node. Children, if any, are kept.
*/
public static final int REMOVE_NODE_KEEP_CHILDREN = 1;
/**
* Removal of a node and all of its children.
*/
public static final int REMOVE_NODE_AND_CHILDREN = 2;
/**
* The root of the global groups tree
*/
private final GroupTreeNodeViewModel m_groupsRootHandle;
/**
* The subtree that was added or removed
*/
private final GroupTreeNode m_subtreeBackup;
/**
* In case of removing a node but keeping all of its children, the number of children has to be stored.
*/
private final int m_subtreeRootChildCount;
/**
* The path to the edited subtree's root node
*/
private final List<Integer> m_pathToNode;
/**
* The type of the editing (ADD_NODE, REMOVE_NODE_KEEP_CHILDREN, REMOVE_NODE_AND_CHILDREN)
*/
private final int m_editType;
/**
* Creates an object that can undo/redo an edit event.
*
* @param groupsRoot
* The global groups root.
* @param editType
* The type of editing (ADD_NODE, REMOVE_NODE_KEEP_CHILDREN,
* REMOVE_NODE_AND_CHILDREN)
* @param editedNode
* The edited node (which was added or will be removed). The node
* must be a descendant of node <b>groupsRoot</b>! This means
* that, in case of adding, you first have to add it to the tree,
* then call this constructor. When removing, you first have to
* call this constructor, then remove the node.
*/
public UndoableAddOrRemoveGroup(GroupTreeNodeViewModel groupsRoot,
GroupTreeNodeViewModel editedNode, int editType) {
m_groupsRootHandle = groupsRoot;
m_editType = editType;
m_subtreeRootChildCount = editedNode.getChildren().size();
// storing a backup of the whole subtree is not required when children
// are kept
m_subtreeBackup = editType != UndoableAddOrRemoveGroup.REMOVE_NODE_KEEP_CHILDREN ?
editedNode.getNode()
.copySubtree()
: GroupTreeNode.fromGroup(editedNode.getNode().getGroup().deepCopy());
// remember path to edited node. this cannot be stored as a reference,
// because the reference itself might change. the method below is more
// robust.
m_pathToNode = editedNode.getNode().getIndexedPathFromRoot();
}
@Override
public String getPresentationName() {
switch (m_editType) {
case ADD_NODE:
return Localization.lang("Add group");
case REMOVE_NODE_KEEP_CHILDREN:
return Localization.lang("Keep subgroups)");
case REMOVE_NODE_AND_CHILDREN:
return Localization.lang("Also remove subgroups");
default:
break;
}
return "? (" + Localization.lang("unknown edit") + ")";
}
@Override
public void undo() {
super.undo();
doOperation(true);
}
@Override
public void redo() {
super.redo();
doOperation(false);
}
private void doOperation(boolean undo) {
GroupTreeNode cursor = m_groupsRootHandle.getNode();
final int childIndex = m_pathToNode.get(m_pathToNode.size() - 1);
// traverse path up to but last element
for (int i = 0; i < (m_pathToNode.size() - 1); ++i) {
cursor = cursor.getChildAt(m_pathToNode.get(i)).get();
}
if (undo) {
switch (m_editType) {
case ADD_NODE:
cursor.removeChild(childIndex);
break;
case REMOVE_NODE_KEEP_CHILDREN:
// move all children to newNode, then add newNode
GroupTreeNode newNode = m_subtreeBackup.copySubtree();
for (int i = childIndex; i < (childIndex
+ m_subtreeRootChildCount); ++i) {
cursor.getChildAt(childIndex).get().moveTo(newNode);
}
newNode.moveTo(cursor, childIndex);
break;
case REMOVE_NODE_AND_CHILDREN:
m_subtreeBackup.copySubtree().moveTo(cursor, childIndex);
break;
default:
break;
}
} else { // redo
switch (m_editType) {
case ADD_NODE:
m_subtreeBackup.copySubtree().moveTo(cursor, childIndex);
break;
case REMOVE_NODE_KEEP_CHILDREN:
// remove node, then insert all children
GroupTreeNode removedNode = cursor
.getChildAt(childIndex).get();
cursor.removeChild(childIndex);
while (removedNode.getNumberOfChildren() > 0) {
removedNode.getFirstChild().get().moveTo(cursor, childIndex);
}
break;
case REMOVE_NODE_AND_CHILDREN:
cursor.removeChild(childIndex);
break;
default:
break;
}
}
}
}
| 5,734
| 34.84375
| 107
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/groups/UndoableChangeEntriesOfGroup.java
|
package org.jabref.gui.groups;
import java.util.List;
import javax.swing.undo.AbstractUndoableEdit;
import org.jabref.gui.undo.NamedCompound;
import org.jabref.gui.undo.UndoableFieldChange;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.FieldChange;
public class UndoableChangeEntriesOfGroup {
private UndoableChangeEntriesOfGroup() {
}
public static AbstractUndoableEdit getUndoableEdit(GroupTreeNodeViewModel node, List<FieldChange> changes) {
boolean hasEntryChanges = false;
NamedCompound entryChangeCompound = new NamedCompound(Localization.lang("change entries of group"));
for (FieldChange fieldChange : changes) {
hasEntryChanges = true;
entryChangeCompound.addEdit(new UndoableFieldChange(fieldChange));
}
if (hasEntryChanges) {
entryChangeCompound.end();
return entryChangeCompound;
}
return null;
}
}
| 958
| 29.935484
| 112
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/groups/UndoableModifySubtree.java
|
package org.jabref.gui.groups;
import java.util.ArrayList;
import java.util.List;
import org.jabref.gui.undo.AbstractUndoableJabRefEdit;
import org.jabref.model.groups.GroupTreeNode;
public class UndoableModifySubtree extends AbstractUndoableJabRefEdit {
/**
* A backup of the groups before the modification
*/
private final GroupTreeNode m_groupRoot;
private final GroupTreeNode m_subtreeBackup;
/**
* The path to the global groups root node
*/
private final List<Integer> m_subtreeRootPath;
/**
* This holds the new subtree (the root's modified children) to allow redo.
*/
private final List<GroupTreeNode> m_modifiedSubtree = new ArrayList<>();
private final String m_name;
/**
* @param subtree The root node of the subtree that was modified (this node may not be modified, it is just used as a convenience handle).
*/
public UndoableModifySubtree(GroupTreeNodeViewModel groupRoot,
GroupTreeNodeViewModel subtree, String name) {
m_subtreeBackup = subtree.getNode().copySubtree();
m_groupRoot = groupRoot.getNode();
m_subtreeRootPath = subtree.getNode().getIndexedPathFromRoot();
m_name = name;
}
@Override
public String getPresentationName() {
return m_name;
}
@Override
public void undo() {
super.undo();
// remember modified children for redo
m_modifiedSubtree.clear();
// get node to edit
final GroupTreeNode subtreeRoot = m_groupRoot.getDescendant(m_subtreeRootPath).get(); // TODO: NULL
m_modifiedSubtree.addAll(subtreeRoot.getChildren());
// keep subtree handle, but restore everything else from backup
subtreeRoot.removeAllChildren();
for (GroupTreeNode child : m_subtreeBackup.getChildren()) {
child.copySubtree().moveTo(subtreeRoot);
}
}
@Override
public void redo() {
super.redo();
final GroupTreeNode subtreeRoot = m_groupRoot.getDescendant(m_subtreeRootPath).get(); // TODO: NULL
subtreeRoot.removeAllChildren();
for (GroupTreeNode modifiedNode : m_modifiedSubtree) {
modifiedNode.moveTo(subtreeRoot);
}
}
}
| 2,272
| 31.014085
| 142
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/groups/UndoableMoveGroup.java
|
package org.jabref.gui.groups;
import java.util.List;
import java.util.Objects;
import org.jabref.gui.undo.AbstractUndoableJabRefEdit;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.groups.GroupTreeNode;
class UndoableMoveGroup extends AbstractUndoableJabRefEdit {
private final GroupTreeNodeViewModel root;
private final List<Integer> pathToNewParent;
private final int newChildIndex;
private final List<Integer> pathToOldParent;
private final int oldChildIndex;
public UndoableMoveGroup(GroupTreeNodeViewModel root, MoveGroupChange moveChange) {
this.root = Objects.requireNonNull(root);
Objects.requireNonNull(moveChange);
pathToOldParent = moveChange.getOldParent().getIndexedPathFromRoot();
pathToNewParent = moveChange.getNewParent().getIndexedPathFromRoot();
oldChildIndex = moveChange.getOldChildIndex();
newChildIndex = moveChange.getNewChildIndex();
}
@Override
public String getPresentationName() {
return Localization.lang("move group");
}
@Override
public void undo() {
super.undo();
GroupTreeNode newParent = root.getNode().getDescendant(pathToNewParent).get(); // TODO: NULL
GroupTreeNode node = newParent.getChildAt(newChildIndex).get(); // TODO: Null
// TODO: NULL
node.moveTo(root.getNode().getDescendant(pathToOldParent).get(), oldChildIndex);
}
@Override
public void redo() {
super.redo();
GroupTreeNode oldParent = root.getNode().getDescendant(pathToOldParent).get(); // TODO: NULL
GroupTreeNode node = oldParent.getChildAt(oldChildIndex).get(); // TODO:Null
// TODO: NULL
node.moveTo(root.getNode().getDescendant(pathToNewParent).get(), newChildIndex);
}
}
| 1,809
| 33.807692
| 100
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/help/AboutAction.java
|
package org.jabref.gui.help;
import org.jabref.gui.DialogService;
import org.jabref.gui.actions.SimpleCommand;
import com.airhacks.afterburner.injection.Injector;
public class AboutAction extends SimpleCommand {
private final AboutDialogView aboutDialogView;
public AboutAction() {
this.aboutDialogView = new AboutDialogView();
}
@Override
public void execute() {
DialogService dialogService = Injector.instantiateModelOrService(DialogService.class);
dialogService.showCustomDialog(aboutDialogView);
}
public AboutDialogView getAboutDialogView() {
return aboutDialogView;
}
}
| 647
| 23.923077
| 94
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/help/AboutDialogView.java
|
package org.jabref.gui.help;
import javafx.fxml.FXML;
import javafx.scene.control.ButtonType;
import javafx.scene.control.TextArea;
import org.jabref.gui.ClipBoardManager;
import org.jabref.gui.DialogService;
import org.jabref.gui.util.BaseDialog;
import org.jabref.gui.util.ControlHelper;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.BuildInfo;
import com.airhacks.afterburner.views.ViewLoader;
import jakarta.inject.Inject;
public class AboutDialogView extends BaseDialog<Void> {
@FXML private ButtonType copyVersionButton;
@FXML private TextArea textAreaVersions;
@Inject private DialogService dialogService;
@Inject private ClipBoardManager clipBoardManager;
@Inject private BuildInfo buildInfo;
private AboutDialogViewModel viewModel;
public AboutDialogView() {
this.setTitle(Localization.lang("About JabRef"));
ViewLoader.view(this)
.load()
.setAsDialogPane(this);
ControlHelper.setAction(copyVersionButton, getDialogPane(), event -> copyVersionToClipboard());
}
public AboutDialogViewModel getViewModel() {
return viewModel;
}
@FXML
private void initialize() {
viewModel = new AboutDialogViewModel(dialogService, clipBoardManager, buildInfo);
textAreaVersions.setText(viewModel.getVersionInfo());
this.setResizable(false);
}
@FXML
private void copyVersionToClipboard() {
viewModel.copyVersionToClipboard();
}
@FXML
private void openJabrefWebsite() {
viewModel.openJabrefWebsite();
}
@FXML
private void openExternalLibrariesWebsite() {
viewModel.openExternalLibrariesWebsite();
}
@FXML
private void openGithub() {
viewModel.openGithub();
}
@FXML
public void openChangeLog() {
viewModel.openChangeLog();
}
@FXML
public void openLicense() {
viewModel.openLicense();
}
@FXML
public void openContributors() {
viewModel.openContributors();
}
@FXML
public void openDonation() {
viewModel.openDonation();
}
}
| 2,160
| 23.011111
| 103
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/help/AboutDialogViewModel.java
|
package org.jabref.gui.help;
import java.io.IOException;
import java.util.Locale;
import java.util.Objects;
import java.util.stream.Collectors;
import javafx.beans.property.ReadOnlyBooleanProperty;
import javafx.beans.property.ReadOnlyBooleanWrapper;
import javafx.beans.property.ReadOnlyStringProperty;
import javafx.beans.property.ReadOnlyStringWrapper;
import org.jabref.gui.AbstractViewModel;
import org.jabref.gui.ClipBoardManager;
import org.jabref.gui.DialogService;
import org.jabref.gui.desktop.JabRefDesktop;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.BuildInfo;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AboutDialogViewModel extends AbstractViewModel {
private static final String HOMEPAGE_URL = "https://www.jabref.org";
private static final String DONATION_URL = "https://donations.jabref.org";
private static final String LIBRARIES_URL = "https://github.com/JabRef/jabref/blob/main/external-libraries.md";
private static final String GITHUB_URL = "https://github.com/JabRef/jabref";
private static final String LICENSE_URL = "https://github.com/JabRef/jabref/blob/main/LICENSE.md";
private static final String CONTRIBUTORS_URL = "https://github.com/JabRef/jabref/graphs/contributors";
private final String changelogUrl;
private final String versionInfo;
private final ReadOnlyStringWrapper environmentInfo = new ReadOnlyStringWrapper();
private final Logger logger = LoggerFactory.getLogger(AboutDialogViewModel.class);
private final ReadOnlyStringWrapper heading = new ReadOnlyStringWrapper();
private final ReadOnlyStringWrapper maintainers = new ReadOnlyStringWrapper();
private final ReadOnlyStringWrapper license = new ReadOnlyStringWrapper();
private final ReadOnlyBooleanWrapper isDevelopmentVersion = new ReadOnlyBooleanWrapper();
private final DialogService dialogService;
private final ReadOnlyStringWrapper developmentVersion = new ReadOnlyStringWrapper();
private final ClipBoardManager clipBoardManager;
public AboutDialogViewModel(DialogService dialogService, ClipBoardManager clipBoardManager, BuildInfo buildInfo) {
this.dialogService = Objects.requireNonNull(dialogService);
this.clipBoardManager = Objects.requireNonNull(clipBoardManager);
String[] version = buildInfo.version.getFullVersion().split("--");
heading.set("JabRef " + version[0]);
if (version.length == 1) {
isDevelopmentVersion.set(false);
} else {
isDevelopmentVersion.set(true);
String dev = Lists.newArrayList(version).stream().filter(string -> !string.equals(version[0])).collect(
Collectors.joining("--"));
developmentVersion.set(dev);
}
maintainers.set(buildInfo.maintainers);
license.set(Localization.lang("License") + ":");
changelogUrl = buildInfo.version.getChangelogUrl();
String javafx_version = System.getProperty("javafx.runtime.version", BuildInfo.UNKNOWN_VERSION).toLowerCase(Locale.ROOT);
versionInfo = String.format("JabRef %s%n%s %s %s %nJava %s %nJavaFX %s", buildInfo.version, BuildInfo.OS,
BuildInfo.OS_VERSION, BuildInfo.OS_ARCH, BuildInfo.JAVA_VERSION, javafx_version);
}
public String getDevelopmentVersion() {
return developmentVersion.get();
}
public ReadOnlyStringProperty developmentVersionProperty() {
return developmentVersion.getReadOnlyProperty();
}
public boolean isIsDevelopmentVersion() {
return isDevelopmentVersion.get();
}
public ReadOnlyBooleanProperty isDevelopmentVersionProperty() {
return isDevelopmentVersion.getReadOnlyProperty();
}
public String getVersionInfo() {
return versionInfo;
}
public ReadOnlyStringProperty maintainersProperty() {
return maintainers.getReadOnlyProperty();
}
public String getMaintainers() {
return maintainers.get();
}
public ReadOnlyStringProperty headingProperty() {
return heading.getReadOnlyProperty();
}
public String getHeading() {
return heading.get();
}
public ReadOnlyStringProperty licenseProperty() {
return license.getReadOnlyProperty();
}
public String getLicense() {
return license.get();
}
public String getEnvironmentInfo() {
return environmentInfo.get();
}
public void copyVersionToClipboard() {
clipBoardManager.setContent(versionInfo);
dialogService.notify(Localization.lang("Copied version to clipboard"));
}
public void openJabrefWebsite() {
openWebsite(HOMEPAGE_URL);
}
public void openExternalLibrariesWebsite() {
openWebsite(LIBRARIES_URL);
}
public void openGithub() {
openWebsite(GITHUB_URL);
}
public void openChangeLog() {
openWebsite(changelogUrl);
}
public void openLicense() {
openWebsite(LICENSE_URL);
}
public void openContributors() {
openWebsite(CONTRIBUTORS_URL);
}
public void openDonation() {
openWebsite(DONATION_URL);
}
private void openWebsite(String url) {
try {
JabRefDesktop.openBrowser(url);
} catch (IOException e) {
dialogService.showErrorDialogAndWait(Localization.lang("Could not open website."), e);
logger.error("Could not open default browser.", e);
}
}
}
| 5,558
| 34.183544
| 129
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/help/ErrorConsoleAction.java
|
package org.jabref.gui.help;
import org.jabref.gui.DialogService;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.errorconsole.ErrorConsoleView;
import com.airhacks.afterburner.injection.Injector;
/**
* Such an error console can be
* useful in getting complete bug reports, especially from Windows users,
* without asking users to run JabRef in a command window to catch the error info.
*
* It offers a separate tab for the log output.
*/
public class ErrorConsoleAction extends SimpleCommand {
@Override
public void execute() {
DialogService dialogService = Injector.instantiateModelOrService(DialogService.class);
dialogService.showCustomDialog(new ErrorConsoleView());
}
}
| 733
| 29.583333
| 94
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/help/HelpAction.java
|
package org.jabref.gui.help;
import org.jabref.gui.DialogService;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.desktop.JabRefDesktop;
import org.jabref.logic.help.HelpFile;
/**
* This Action keeps a reference to a URL. When activated, it shows the help
* Dialog unless it is already visible, and shows the URL in it.
*/
public class HelpAction extends SimpleCommand {
private final HelpFile helpPage;
private final DialogService dialogService;
public HelpAction(HelpFile helpPage, DialogService dialogService) {
this.helpPage = helpPage;
this.dialogService = dialogService;
}
void openHelpPage(HelpFile helpPage) {
StringBuilder sb = new StringBuilder("https://docs.jabref.org/");
sb.append(helpPage.getPageName());
JabRefDesktop.openBrowserShowPopup(sb.toString(), dialogService);
}
@Override
public void execute() {
openHelpPage(helpPage);
}
}
| 961
| 28.151515
| 76
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/help/NewVersionDialog.java
|
package org.jabref.gui.help;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import org.jabref.gui.DialogService;
import org.jabref.gui.desktop.JabRefDesktop;
import org.jabref.gui.util.BaseDialog;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.Version;
public class NewVersionDialog extends BaseDialog<Boolean> {
public NewVersionDialog(Version currentVersion, Version latestVersion, DialogService dialogService) {
this.setTitle(Localization.lang("New version available"));
ButtonType btnIgnoreUpdate = new ButtonType(Localization.lang("Ignore this update"), ButtonBar.ButtonData.CANCEL_CLOSE);
ButtonType btnDownloadUpdate = new ButtonType(Localization.lang("Download update"), ButtonBar.ButtonData.APPLY);
ButtonType btnRemindMeLater = new ButtonType(Localization.lang("Remind me later"), ButtonBar.ButtonData.CANCEL_CLOSE);
this.getDialogPane().getButtonTypes().addAll(btnIgnoreUpdate, btnDownloadUpdate, btnRemindMeLater);
this.setResultConverter(button -> {
if (button == btnIgnoreUpdate) {
return false;
} else if (button == btnDownloadUpdate) {
JabRefDesktop.openBrowserShowPopup(Version.JABREF_DOWNLOAD_URL, dialogService);
}
return true;
});
Button defaultButton = (Button) this.getDialogPane().lookupButton(btnDownloadUpdate);
defaultButton.setDefaultButton(true);
Hyperlink lblMoreInformation = new Hyperlink(Localization.lang("To see what is new view the changelog."));
lblMoreInformation.setOnAction(event ->
JabRefDesktop.openBrowserShowPopup(latestVersion.getChangelogUrl(), dialogService)
);
VBox container = new VBox(
new Label(Localization.lang("A new version of JabRef has been released.")),
new Label(Localization.lang("Installed version") + ": " + currentVersion.getFullVersion()),
new Label(Localization.lang("Latest version") + ": " + latestVersion.getFullVersion()),
lblMoreInformation
);
getDialogPane().setContent(container);
getDialogPane().setPrefWidth(450);
}
}
| 2,394
| 45.960784
| 128
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/help/SearchForUpdateAction.java
|
package org.jabref.gui.help;
import org.jabref.gui.DialogService;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.util.BuildInfo;
import org.jabref.preferences.InternalPreferences;
public class SearchForUpdateAction extends SimpleCommand {
private final BuildInfo buildInfo;
private final InternalPreferences internalPreferences;
private final DialogService dialogService;
private final TaskExecutor taskExecutor;
public SearchForUpdateAction(BuildInfo buildInfo, InternalPreferences internalPreferences, DialogService dialogService, TaskExecutor taskExecutor) {
this.buildInfo = buildInfo;
this.internalPreferences = internalPreferences;
this.dialogService = dialogService;
this.taskExecutor = taskExecutor;
}
@Override
public void execute() {
new VersionWorker(buildInfo.version, dialogService, taskExecutor, internalPreferences)
.checkForNewVersionAsync();
}
}
| 1,023
| 34.310345
| 152
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/help/VersionWorker.java
|
package org.jabref.gui.help;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import org.jabref.gui.DialogService;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.Version;
import org.jabref.preferences.InternalPreferences;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This worker checks if there is a new version of JabRef available. If there is it will display a dialog to the user
* offering him multiple options to proceed (see changelog, go to the download page, ignore this version, and remind
* later).
*
* If the versions check is executed manually and this is the latest version it will also display a dialog to inform the
* user.
*/
public class VersionWorker {
private static final Logger LOGGER = LoggerFactory.getLogger(VersionWorker.class);
/**
* The current version of the installed JabRef
*/
private final Version installedVersion;
private final DialogService dialogService;
private final TaskExecutor taskExecutor;
private final InternalPreferences internalPreferences;
public VersionWorker(Version installedVersion,
DialogService dialogService,
TaskExecutor taskExecutor,
InternalPreferences internalPreferences) {
this.installedVersion = Objects.requireNonNull(installedVersion);
this.dialogService = Objects.requireNonNull(dialogService);
this.taskExecutor = Objects.requireNonNull(taskExecutor);
this.internalPreferences = internalPreferences;
}
/**
* Returns a newer version excluding any non-stable versions, except if the installed one is unstable too. If no
* newer version was found, then an empty optional is returned.
*/
private Optional<Version> getNewVersion() throws IOException {
List<Version> availableVersions = Version.getAllAvailableVersions();
return installedVersion.shouldBeUpdatedTo(availableVersions);
}
public void checkForNewVersionAsync() {
BackgroundTask.wrap(this::getNewVersion)
.onSuccess(version -> showUpdateInfo(version, true))
.onFailure(exception -> showConnectionError(exception, true))
.executeWith(taskExecutor);
}
public void checkForNewVersionDelayed() {
BackgroundTask.wrap(this::getNewVersion)
.onSuccess(version -> showUpdateInfo(version, false))
.onFailure(exception -> showConnectionError(exception, false))
.scheduleWith(taskExecutor, 30, TimeUnit.SECONDS);
}
/**
* Prints the connection problem to the status bar and shows a dialog if it was executed manually
*/
private void showConnectionError(Exception exception, boolean manualExecution) {
String couldNotConnect = Localization.lang("Could not connect to the update server.");
String tryLater = Localization.lang("Please try again later and/or check your network connection.");
if (manualExecution) {
dialogService.showErrorDialogAndWait(Localization.lang("Error"), couldNotConnect + "\n" + tryLater, exception);
}
LOGGER.warn(couldNotConnect + " " + tryLater, exception);
}
/**
* Prints up-to-date to the status bar (and shows a dialog it was executed manually) if there is now new version.
* Shows a "New Version" Dialog to the user if there is.
*/
private void showUpdateInfo(Optional<Version> newerVersion, boolean manualExecution) {
// no new version could be found, only respect the ignored version on automated version checks
if (newerVersion.isEmpty() || (newerVersion.get().equals(internalPreferences.getIgnoredVersion()) && !manualExecution)) {
if (manualExecution) {
dialogService.notify(Localization.lang("JabRef is up-to-date."));
}
} else {
// notify the user about a newer version
if (dialogService.showCustomDialogAndWait(new NewVersionDialog(installedVersion, newerVersion.get(), dialogService)).orElse(true)) {
internalPreferences.setIgnoredVersion(newerVersion.get());
}
}
}
}
| 4,435
| 41.653846
| 144
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/icon/IconTheme.java
|
package org.jabref.gui.icon;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.ServiceLoader;
import java.util.Set;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ToggleButton;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;
import org.kordamp.ikonli.Ikon;
import org.kordamp.ikonli.IkonProvider;
import org.kordamp.ikonli.materialdesign2.MaterialDesignA;
import org.kordamp.ikonli.materialdesign2.MaterialDesignB;
import org.kordamp.ikonli.materialdesign2.MaterialDesignC;
import org.kordamp.ikonli.materialdesign2.MaterialDesignD;
import org.kordamp.ikonli.materialdesign2.MaterialDesignE;
import org.kordamp.ikonli.materialdesign2.MaterialDesignF;
import org.kordamp.ikonli.materialdesign2.MaterialDesignG;
import org.kordamp.ikonli.materialdesign2.MaterialDesignH;
import org.kordamp.ikonli.materialdesign2.MaterialDesignI;
import org.kordamp.ikonli.materialdesign2.MaterialDesignK;
import org.kordamp.ikonli.materialdesign2.MaterialDesignL;
import org.kordamp.ikonli.materialdesign2.MaterialDesignM;
import org.kordamp.ikonli.materialdesign2.MaterialDesignN;
import org.kordamp.ikonli.materialdesign2.MaterialDesignO;
import org.kordamp.ikonli.materialdesign2.MaterialDesignP;
import org.kordamp.ikonli.materialdesign2.MaterialDesignR;
import org.kordamp.ikonli.materialdesign2.MaterialDesignS;
import org.kordamp.ikonli.materialdesign2.MaterialDesignT;
import org.kordamp.ikonli.materialdesign2.MaterialDesignU;
import org.kordamp.ikonli.materialdesign2.MaterialDesignV;
import org.kordamp.ikonli.materialdesign2.MaterialDesignW;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static java.util.EnumSet.allOf;
public class IconTheme {
public static final Color DEFAULT_DISABLED_COLOR = Color.web("#c8c8c8");
public static final Color SELECTED_COLOR = Color.web("#50618F");
private static final String DEFAULT_ICON_PATH = "/images/external/red.png";
private static final Logger LOGGER = LoggerFactory.getLogger(IconTheme.class);
private static final Map<String, String> KEY_TO_ICON = readIconThemeFile(IconTheme.class.getResource("/images/Icons.properties"), "/images/external/");
private static final Set<Ikon> ICON_NAMES = new HashSet<>();
public static Color getDefaultGroupColor() {
return Color.web("#8a8a8a");
}
public static Optional<JabRefIcon> findIcon(String code, Color color) {
if (ICON_NAMES.isEmpty()) {
loadAllIkons();
}
return ICON_NAMES.stream().filter(icon -> icon.toString().equals(code.toUpperCase(Locale.ENGLISH)))
.map(internalMat -> new InternalMaterialDesignIcon(internalMat).withColor(color)).findFirst();
}
public static Image getJabRefImage() {
return getImageFX("jabrefIcon48");
}
private static void loadAllIkons() {
ServiceLoader<IkonProvider> providers = ServiceLoader.load(IkonProvider.class);
for (IkonProvider provider : providers) {
ICON_NAMES.addAll(allOf(provider.getIkon()));
}
}
/*
* Constructs an {@link Image} for the image representing the given function, in the resource
* file listing images.
*
* @param name The name of the icon, such as "open", "save", "saveAs" etc.
* @return The {@link Image} for the function.
*/
private static Image getImageFX(String name) {
return new Image(getIconUrl(name).toString());
}
/**
* Looks up the URL for the image representing the given function, in the resource
* file listing images.
*
* @param name The name of the icon, such as "open", "save", "saveAs" etc.
* @return The URL to the actual image to use.
*/
public static URL getIconUrl(String name) {
String key = Objects.requireNonNull(name, "icon name");
if (!KEY_TO_ICON.containsKey(key)) {
LOGGER.warn("Could not find icon url by name " + name + ", so falling back on default icon "
+ DEFAULT_ICON_PATH);
}
String path = KEY_TO_ICON.getOrDefault(key, DEFAULT_ICON_PATH);
return Objects.requireNonNull(IconTheme.class.getResource(path), "Path must not be null for key " + key);
}
/**
* Read a typical java property url into a Map. Currently doesn't support escaping
* of the '=' character - it simply looks for the first '=' to determine where the key ends.
* Both the key and the value is trimmed for whitespace at the ends.
*
* @param url The URL to read information from.
* @param prefix A String to prefix to all values read. Can represent e.g. the directory where icon files are to be
* found.
* @return A Map containing all key-value pairs found.
*/
// FIXME: prefix can be removed?!
private static Map<String, String> readIconThemeFile(URL url, String prefix) {
Objects.requireNonNull(url, "url");
Objects.requireNonNull(prefix, "prefix");
Map<String, String> result = new HashMap<>();
try (BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream(), StandardCharsets.ISO_8859_1))) {
String line;
while ((line = in.readLine()) != null) {
if (!line.contains("=")) {
continue;
}
int index = line.indexOf('=');
String key = line.substring(0, index).trim();
String value = prefix + line.substring(index + 1).trim();
result.put(key, value);
}
} catch (IOException e) {
LOGGER.warn("Unable to read default icon theme.", e);
}
return result;
}
public static List<Image> getLogoSetFX() {
List<Image> jabrefLogos = new ArrayList<>();
jabrefLogos.add(new Image(getIconUrl("jabrefIcon16").toString()));
jabrefLogos.add(new Image(getIconUrl("jabrefIcon20").toString()));
jabrefLogos.add(new Image(getIconUrl("jabrefIcon32").toString()));
jabrefLogos.add(new Image(getIconUrl("jabrefIcon40").toString()));
jabrefLogos.add(new Image(getIconUrl("jabrefIcon48").toString()));
jabrefLogos.add(new Image(getIconUrl("jabrefIcon64").toString()));
jabrefLogos.add(new Image(getIconUrl("jabrefIcon128").toString()));
return jabrefLogos;
}
public enum JabRefIcons implements JabRefIcon {
ADD(MaterialDesignP.PLUS_CIRCLE_OUTLINE),
ADD_FILLED(MaterialDesignP.PLUS_CIRCLE),
ADD_NOBOX(MaterialDesignP.PLUS),
ADD_ARTICLE(MaterialDesignP.PLUS),
ADD_ENTRY(MaterialDesignP.PLAYLIST_PLUS),
EDIT_ENTRY(MaterialDesignT.TOOLTIP_EDIT),
EDIT_STRINGS(MaterialDesignT.TOOLTIP_TEXT),
FOLDER(MaterialDesignF.FOLDER_OUTLINE),
REMOVE(MaterialDesignM.MINUS_BOX),
REMOVE_NOBOX(MaterialDesignM.MINUS),
FILE(MaterialDesignF.FILE_OUTLINE),
PDF_FILE(MaterialDesignF.FILE_PDF),
DOI(MaterialDesignB.BARCODE_SCAN),
DUPLICATE(MaterialDesignC.CONTENT_DUPLICATE),
EDIT(MaterialDesignP.PENCIL),
NEW(MaterialDesignF.FOLDER_PLUS),
SAVE(MaterialDesignC.CONTENT_SAVE),
SAVE_ALL(MaterialDesignC.CONTENT_SAVE_ALL),
CLOSE(MaterialDesignC.CLOSE_CIRCLE),
PASTE(JabRefMaterialDesignIcon.PASTE),
CUT(MaterialDesignC.CONTENT_CUT),
COPY(MaterialDesignC.CONTENT_COPY),
COMMENT(MaterialDesignC.COMMENT),
REDO(MaterialDesignR.REDO),
UNDO(MaterialDesignU.UNDO),
MARKER(MaterialDesignM.MARKER),
REFRESH(MaterialDesignR.REFRESH),
MEMORYSTICK(MaterialDesignU.USB_FLASH_DRIVE_OUTLINE),
DELETE_ENTRY(MaterialDesignD.DELETE),
SEARCH(MaterialDesignM.MAGNIFY),
FILE_SEARCH(MaterialDesignF.FILE_FIND),
PDF_METADATA_READ(MaterialDesignF.FORMAT_ALIGN_TOP),
PDF_METADATA_WRITE(MaterialDesignF.FORMAT_ALIGN_BOTTOM),
ADVANCED_SEARCH(Color.CYAN, MaterialDesignM.MAGNIFY),
PREFERENCES(MaterialDesignC.COG),
SELECTORS(MaterialDesignS.STAR_SETTINGS),
HELP(MaterialDesignH.HELP_CIRCLE),
UP(MaterialDesignA.ARROW_UP),
DOWN(MaterialDesignA.ARROW_DOWN),
LEFT(MaterialDesignA.ARROW_LEFT_BOLD),
RIGHT(MaterialDesignA.ARROW_RIGHT_BOLD),
SOURCE(MaterialDesignC.CODE_BRACES),
MAKE_KEY(MaterialDesignK.KEY_VARIANT),
CLEANUP_ENTRIES(MaterialDesignB.BROOM),
PRIORITY(MaterialDesignF.FLAG),
PRIORITY_HIGH(Color.RED, MaterialDesignF.FLAG),
PRIORITY_MEDIUM(Color.ORANGE, MaterialDesignF.FLAG),
PRIORITY_LOW(Color.rgb(111, 204, 117), MaterialDesignF.FLAG),
PRINTED(MaterialDesignP.PRINTER),
RANKING(MaterialDesignS.STAR),
RANK1(MaterialDesignS.STAR, MaterialDesignS.STAR_OUTLINE, MaterialDesignS.STAR_OUTLINE, MaterialDesignS.STAR_OUTLINE, MaterialDesignS.STAR_OUTLINE),
RANK2(MaterialDesignS.STAR, MaterialDesignS.STAR, MaterialDesignS.STAR_OUTLINE, MaterialDesignS.STAR_OUTLINE, MaterialDesignS.STAR_OUTLINE),
RANK3(MaterialDesignS.STAR, MaterialDesignS.STAR, MaterialDesignS.STAR, MaterialDesignS.STAR_OUTLINE, MaterialDesignS.STAR_OUTLINE),
RANK4(MaterialDesignS.STAR, MaterialDesignS.STAR, MaterialDesignS.STAR, MaterialDesignS.STAR, MaterialDesignS.STAR_OUTLINE),
RANK5(MaterialDesignS.STAR, MaterialDesignS.STAR, MaterialDesignS.STAR, MaterialDesignS.STAR, MaterialDesignS.STAR),
WWW(MaterialDesignW.WEB),
GROUP_INCLUDING(MaterialDesignF.FILTER_OUTLINE),
GROUP_REFINING(MaterialDesignF.FILTER),
AUTO_GROUP(MaterialDesignA.AUTO_FIX),
GROUP_INTERSECTION(JabRefMaterialDesignIcon.SET_CENTER),
GROUP_UNION(JabRefMaterialDesignIcon.SET_ALL),
EMAIL(MaterialDesignE.EMAIL),
EXPORT_TO_CLIPBOARD(MaterialDesignC.CLIPBOARD_ARROW_LEFT),
ATTACH_FILE(MaterialDesignP.PAPERCLIP),
AUTO_FILE_LINK(MaterialDesignF.FILE_FIND),
AUTO_RENAME(MaterialDesignA.AUTO_FIX),
DOWNLOAD_FILE(MaterialDesignD.DOWNLOAD),
MOVE_TO_FOLDER(MaterialDesignF.FILE_SEND),
COPY_TO_FOLDER(MaterialDesignC.CONTENT_COPY),
RENAME(MaterialDesignR.RENAME_BOX),
DELETE_FILE(MaterialDesignD.DELETE_FOREVER),
REMOVE_LINK(MaterialDesignL.LINK_OFF),
AUTO_LINKED_FILE(MaterialDesignL.LINK_PLUS),
QUALITY_ASSURED(MaterialDesignC.CERTIFICATE),
QUALITY(MaterialDesignC.CERTIFICATE),
OPEN(MaterialDesignF.FOLDER_OUTLINE),
OPEN_LIST(MaterialDesignF.FOLDER_OPEN_OUTLINE),
ADD_ROW(MaterialDesignS.SERVER_PLUS),
REMOVE_ROW(MaterialDesignS.SERVER_MINUS),
PICTURE(MaterialDesignF.FILE_IMAGE),
READ_STATUS_READ(Color.rgb(111, 204, 117, 1), MaterialDesignE.EYE),
READ_STATUS_SKIMMED(Color.ORANGE, MaterialDesignE.EYE),
READ_STATUS(MaterialDesignE.EYE),
RELEVANCE(MaterialDesignS.STAR_CIRCLE),
MERGE_ENTRIES(MaterialDesignC.COMPARE),
CONNECT_OPEN_OFFICE(MaterialDesignO.OPEN_IN_APP),
PLAIN_TEXT_IMPORT_TODO(MaterialDesignC.CHECKBOX_BLANK_CIRCLE_OUTLINE),
PLAIN_TEXT_IMPORT_DONE(MaterialDesignC.CHECKBOX_MARKED_CIRCLE_OUTLINE),
DONATE(MaterialDesignG.GIFT),
MOVE_TAB_ARROW(MaterialDesignA.ARROW_UP_BOLD),
OPTIONAL(MaterialDesignL.LABEL_OUTLINE),
REQUIRED(MaterialDesignL.LABEL),
INTEGRITY_FAIL(Color.RED, MaterialDesignC.CLOSE_CIRCLE),
INTEGRITY_INFO(MaterialDesignI.INFORMATION),
INTEGRITY_WARN(MaterialDesignA.ALERT_CIRCLE),
INTEGRITY_SUCCESS(MaterialDesignC.CHECKBOX_MARKED_CIRCLE_OUTLINE),
GITHUB(MaterialDesignG.GITHUB),
TOGGLE_ENTRY_PREVIEW(MaterialDesignL.LIBRARY),
TOGGLE_GROUPS(MaterialDesignV.VIEW_LIST),
SHOW_PREFERENCES_LIST(MaterialDesignV.VIEW_LIST),
WRITE_XMP(MaterialDesignI.IMPORT),
FILE_WORD(MaterialDesignF.FILE_WORD),
FILE_EXCEL(MaterialDesignF.FILE_EXCEL),
FILE_POWERPOINT(MaterialDesignF.FILE_POWERPOINT),
FILE_TEXT(MaterialDesignF.FILE_DOCUMENT),
FILE_MULTIPLE(MaterialDesignF.FILE_MULTIPLE),
FILE_OPENOFFICE(JabRefMaterialDesignIcon.OPEN_OFFICE),
APPLICATION_GENERIC(MaterialDesignA.APPLICATION),
APPLICATION_EMACS(JabRefMaterialDesignIcon.EMACS),
APPLICATION_LYX(JabRefMaterialDesignIcon.LYX),
APPLICATION_TEXSTUDIO(JabRefMaterialDesignIcon.TEX_STUDIO),
APPLICATION_TEXMAKER(JabRefMaterialDesignIcon.TEX_MAKER),
APPLICATION_VIM(JabRefMaterialDesignIcon.VIM),
APPLICATION_WINEDT(JabRefMaterialDesignIcon.WINEDT),
KEY_BINDINGS(MaterialDesignK.KEYBOARD),
FIND_DUPLICATES(MaterialDesignC.CODE_EQUAL),
CONNECT_DB(MaterialDesignC.CLOUD_UPLOAD),
SUCCESS(MaterialDesignC.CHECK_CIRCLE),
CHECK(MaterialDesignC.CHECK),
WARNING(MaterialDesignA.ALERT),
ERROR(MaterialDesignA.ALERT_CIRCLE),
CASE_SENSITIVE(MaterialDesignA.ALPHABETICAL),
REG_EX(MaterialDesignR.REGEX),
FULLTEXT(MaterialDesignF.FILE_EYE),
CONSOLE(MaterialDesignC.CONSOLE),
FORUM(MaterialDesignF.FORUM),
FACEBOOK(MaterialDesignF.FACEBOOK),
TWITTER(MaterialDesignT.TWITTER),
BLOG(MaterialDesignR.RSS),
DATE_PICKER(MaterialDesignC.CALENDAR),
DEFAULT_GROUP_ICON_COLORED(MaterialDesignR.RECORD),
DEFAULT_GROUP_ICON(MaterialDesignL.LABEL_OUTLINE),
ALL_ENTRIES_GROUP_ICON(MaterialDesignD.DATABASE),
IMPORT(MaterialDesignC.CALL_RECEIVED),
EXPORT(MaterialDesignC.CALL_MADE),
PREVIOUS_LEFT(MaterialDesignC.CHEVRON_LEFT),
PREVIOUS_UP(MaterialDesignC.CHEVRON_UP),
NEXT_RIGHT(MaterialDesignC.CHEVRON_RIGHT),
NEXT_DOWN(MaterialDesignC.CHEVRON_DOWN),
LIST_MOVE_LEFT(MaterialDesignC.CHEVRON_LEFT),
LIST_MOVE_UP(MaterialDesignC.CHEVRON_UP),
LIST_MOVE_RIGHT(MaterialDesignC.CHEVRON_RIGHT),
LIST_MOVE_DOWN(MaterialDesignC.CHEVRON_DOWN),
FIT_WIDTH(MaterialDesignA.ARROW_EXPAND_ALL),
FIT_SINGLE_PAGE(MaterialDesignN.NOTE),
ZOOM_OUT(MaterialDesignM.MAGNIFY_MINUS),
ZOOM_IN(MaterialDesignM.MAGNIFY_PLUS),
ENTRY_TYPE(MaterialDesignP.PENCIL),
NEW_GROUP(MaterialDesignP.PLUS),
OPEN_LINK(MaterialDesignO.OPEN_IN_NEW),
LOOKUP_IDENTIFIER(MaterialDesignS.SEARCH_WEB),
LINKED_FILE_ADD(MaterialDesignP.PLUS),
FETCH_FULLTEXT(MaterialDesignS.SEARCH_WEB),
FETCH_BY_IDENTIFIER(MaterialDesignC.CLIPBOARD_ARROW_DOWN),
TOGGLE_ABBREVIATION(MaterialDesignF.FORMAT_ALIGN_CENTER),
NEW_FILE(MaterialDesignP.PLUS),
DOWNLOAD(MaterialDesignD.DOWNLOAD),
OWNER(MaterialDesignA.ACCOUNT),
CLOSE_JABREF(MaterialDesignD.DOOR),
ARTICLE(MaterialDesignF.FILE_DOCUMENT),
BOOK(MaterialDesignB.BOOK_OPEN_PAGE_VARIANT),
LATEX_CITATIONS(JabRefMaterialDesignIcon.TEX_STUDIO),
LATEX_FILE_DIRECTORY(MaterialDesignF.FOLDER_OUTLINE),
LATEX_FILE(MaterialDesignF.FILE_OUTLINE),
LATEX_COMMENT(MaterialDesignC.COMMENT_TEXT_OUTLINE),
LATEX_LINE(MaterialDesignF.FORMAT_LINE_SPACING),
PASSWORD_REVEALED(MaterialDesignE.EYE),
ADD_ABBREVIATION_LIST(MaterialDesignP.PLUS),
OPEN_ABBREVIATION_LIST(MaterialDesignF.FOLDER_OUTLINE),
REMOVE_ABBREVIATION_LIST(MaterialDesignM.MINUS),
ADD_ABBREVIATION(MaterialDesignP.PLAYLIST_PLUS),
REMOVE_ABBREVIATION(MaterialDesignP.PLAYLIST_MINUS),
NEW_ENTRY_FROM_PLAIN_TEXT(MaterialDesignP.PLUS_BOX),
REMOTE_DATABASE(MaterialDesignD.DATABASE),
HOME(MaterialDesignH.HOME),
LINK(MaterialDesignL.LINK),
LINK_VARIANT(MaterialDesignL.LINK_VARIANT),
PROTECT_STRING(MaterialDesignC.CODE_BRACES),
SELECT_ICONS(MaterialDesignA.APPS),
KEEP_SEARCH_STRING(MaterialDesignE.EARTH),
KEEP_ON_TOP(MaterialDesignP.PIN),
KEEP_ON_TOP_OFF(MaterialDesignP.PIN_OFF_OUTLINE),
OPEN_GLOBAL_SEARCH(MaterialDesignO.OPEN_IN_NEW),
REMOVE_TAGS(MaterialDesignC.CLOSE),
ACCEPT_LEFT(MaterialDesignS.SUBDIRECTORY_ARROW_LEFT),
ACCEPT_RIGHT(MaterialDesignS.SUBDIRECTORY_ARROW_RIGHT),
MERGE_GROUPS(MaterialDesignS.SOURCE_MERGE);
private final JabRefIcon icon;
JabRefIcons(Ikon... icons) {
icon = new InternalMaterialDesignIcon(icons);
}
JabRefIcons(Color color, Ikon... icons) {
icon = new InternalMaterialDesignIcon(color, icons);
}
@Override
public Ikon getIkon() {
return icon.getIkon();
}
@Override
public Node getGraphicNode() {
return icon.getGraphicNode();
}
public Button asButton() {
Button button = new Button();
button.setGraphic(getGraphicNode());
button.getStyleClass().add("icon-button");
return button;
}
public ToggleButton asToggleButton() {
ToggleButton button = new ToggleButton();
button.setGraphic(getGraphicNode());
button.getStyleClass().add("icon-button");
return button;
}
@Override
public JabRefIcon withColor(Color color) {
return icon.withColor(color);
}
@Override
public JabRefIcon disabled() {
return icon.disabled();
}
}
}
| 17,855
| 43.864322
| 156
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/icon/InternalMaterialDesignIcon.java
|
package org.jabref.gui.icon;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javafx.scene.Node;
import javafx.scene.paint.Color;
import org.jabref.gui.util.ColorUtil;
import org.kordamp.ikonli.Ikon;
import org.kordamp.ikonli.javafx.FontIcon;
public class InternalMaterialDesignIcon implements JabRefIcon {
private final List<Ikon> icons;
private Optional<Color> color;
private final String unicode;
public InternalMaterialDesignIcon(Color color, Ikon... icons) {
this(color, Arrays.asList(icons));
}
InternalMaterialDesignIcon(Color color, List<Ikon> icons) {
this(icons);
this.color = Optional.of(color);
}
public InternalMaterialDesignIcon(Ikon... icons) {
this(Arrays.asList(icons));
}
public InternalMaterialDesignIcon(List<Ikon> icons) {
this.icons = icons;
this.unicode = icons.stream().map(Ikon::getCode).map(String::valueOf).collect(Collectors.joining());
this.color = Optional.empty();
}
@Override
public Node getGraphicNode() {
Ikon icon = icons.get(0);
FontIcon fontIcon = FontIcon.of(icon);
fontIcon.getStyleClass().add("glyph-icon");
// Override the default color from the css files
color.ifPresent(color -> fontIcon.setStyle(fontIcon.getStyle() +
String.format("-fx-fill: %s;", ColorUtil.toRGBCode(color)) +
String.format("-fx-icon-color: %s;", ColorUtil.toRGBCode(color))));
return fontIcon;
}
@Override
public JabRefIcon disabled() {
return new InternalMaterialDesignIcon(IconTheme.DEFAULT_DISABLED_COLOR, icons);
}
@Override
public JabRefIcon withColor(Color color) {
return new InternalMaterialDesignIcon(color, icons);
}
@Override
public String name() {
return icons.get(0).toString();
}
public String getCode() {
return this.unicode;
}
@Override
public Ikon getIkon() {
return icons.get(0);
}
}
| 2,088
| 25.443038
| 108
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/icon/JabRefIcon.java
|
package org.jabref.gui.icon;
import javafx.scene.Node;
import javafx.scene.paint.Color;
import org.kordamp.ikonli.Ikon;
public interface JabRefIcon {
Node getGraphicNode();
String name();
JabRefIcon withColor(Color color);
JabRefIcon disabled();
Ikon getIkon();
}
| 292
| 13.65
| 38
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/icon/JabRefIconView.java
|
package org.jabref.gui.icon;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.css.Size;
import javafx.css.SizeUnits;
import org.jabref.gui.icon.IconTheme.JabRefIcons;
import com.tobiasdiez.easybind.EasyBind;
import org.kordamp.ikonli.javafx.FontIcon;
public class JabRefIconView extends FontIcon {
/**
* This property is only needed to get proper IDE support in FXML files
* (e.g. validation that parameter passed to "icon" is indeed of type {@link IconTheme.JabRefIcons}).
*/
private final ObjectProperty<IconTheme.JabRefIcons> glyph;
private final ObjectProperty<Number> glyphSize;
public JabRefIconView(JabRefIcons icon, int size) {
super(icon.getIkon());
this.glyph = new SimpleObjectProperty<>(icon);
this.glyphSize = new SimpleObjectProperty<>(size);
EasyBind.subscribe(glyph, glyph -> setIconCode(glyph.getIkon()));
EasyBind.subscribe(glyphSize, glyphsize -> setIconSize(glyphsize.intValue()));
}
public JabRefIconView(IconTheme.JabRefIcons icon) {
super(icon.getIkon());
Size size = new Size(1.0, SizeUnits.EM);
this.glyph = new SimpleObjectProperty<>(icon);
this.glyphSize = new SimpleObjectProperty<>(9);
int px = (int) size.pixels(getFont());
glyphSize.set(px);
EasyBind.subscribe(glyph, glyph -> setIconCode(glyph.getIkon()));
EasyBind.subscribe(glyphSize, glyphsize -> setIconSize(glyphsize.intValue()));
}
public JabRefIconView() {
this(IconTheme.JabRefIcons.ERROR);
}
public IconTheme.JabRefIcons getDefaultGlyph() {
return IconTheme.JabRefIcons.ERROR;
}
public IconTheme.JabRefIcons getGlyph() {
return glyph.get();
}
public void setGlyph(IconTheme.JabRefIcons icon) {
this.glyph.set(icon);
}
public ObjectProperty<IconTheme.JabRefIcons> glyphProperty() {
return glyph;
}
public void setGlyphSize(Number value) {
this.glyphSize.set(value);
}
public ObjectProperty<Number> glyphSizeProperty() {
return glyphSize;
}
public Number getGlyphSize() {
return glyphSize.getValue();
}
}
| 2,247
| 28.973333
| 105
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/icon/JabRefIkonHandler.java
|
package org.jabref.gui.icon;
import java.io.InputStream;
import java.net.URL;
import org.kordamp.ikonli.AbstractIkonHandler;
import org.kordamp.ikonli.Ikon;
public class JabRefIkonHandler extends AbstractIkonHandler {
private static String FONT_RESOURCE = "/fonts/JabRefMaterialDesign.ttf";
@Override
public boolean supports(String description) {
return (description != null) && description.startsWith("jab-");
}
@Override
public Ikon resolve(String description) {
return JabRefMaterialDesignIcon.findByDescription(description);
}
@Override
public URL getFontResource() {
return getClass().getResource(FONT_RESOURCE);
}
@Override
public InputStream getFontResourceAsStream() {
return getClass().getResourceAsStream(FONT_RESOURCE);
}
@Override
public String getFontFamily() {
return "JabRefMaterialDesign";
}
}
| 923
| 23.315789
| 76
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/icon/JabRefMaterialDesignIcon.java
|
package org.jabref.gui.icon;
import org.kordamp.ikonli.Ikon;
/**
* Provides the same true-type font interface as MaterialDesignIcon itself, but uses a font we created ourselves that
* contains icons that are not available in MaterialDesignIcons.
*
* The glyphs of the ttf (speak: the icons) were created with Illustrator and a template from the material design icons
* web-page. The art boards for each icon was exported as SVG and then converted with <a href="https://icomoon.io/app">
* IcoMoon</a>. The final TTF font is located in the resource folder.
*
* @see <a href="https://github.com/JabRef/jabref/wiki/Custom-SVG-Icons-for-JabRef">Tutorial on our Wiki</a>
* @see <a href="https://materialdesignicons.com/custom">Material Design Icon custom page</a>
*/
public enum JabRefMaterialDesignIcon implements Ikon {
TEX_STUDIO("jab-texstudio", '\ue900'),
TEX_MAKER("jab-textmaker", '\ue901'),
EMACS("jab-emacs", '\ue902'),
OPEN_OFFICE("jab-oo", '\ue903'),
VIM("jab-vim", '\ue904'),
VIM2("jab-vim2", '\ue905'),
LYX("jab-lyx", '\ue906'),
WINEDT("jab-winedt", '\ue907'),
ARXIV("jab-arxiv", '\ue908'),
COPY("jab-copy", '\ue909'),
PASTE("jab-paste", '\ue90a'),
SET_CENTER("jab-setcenter", '\ue90b'),
SET_ALL("jab-setall", '\ue90c'),
VSCODE("jab-vsvode", '\ue90d'),
CANCEL("jab-cancel", '\ue90e');
private String description;
private int code;
JabRefMaterialDesignIcon(String description, int code) {
this.description = description;
this.code = code;
}
public static JabRefMaterialDesignIcon findByDescription(String description) {
for (JabRefMaterialDesignIcon font : values()) {
if (font.getDescription().equals(description)) {
return font;
}
}
throw new IllegalArgumentException("Icon description '" + description + "' is invalid!");
}
@Override
public String getDescription() {
return description;
}
@Override
public int getCode() {
return code;
}
}
| 2,070
| 32.95082
| 119
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/icon/JabrefIconProvider.java
|
package org.jabref.gui.icon;
import org.kordamp.ikonli.IkonProvider;
public class JabrefIconProvider implements IkonProvider<JabRefMaterialDesignIcon> {
@Override
public Class<JabRefMaterialDesignIcon> getIkon() {
return JabRefMaterialDesignIcon.class;
}
}
| 280
| 22.416667
| 83
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/importer/BibEntryTypePrefsAndFileViewModel.java
|
package org.jabref.gui.importer;
import org.jabref.logic.exporter.MetaDataSerializer;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.entry.BibEntryType;
public record BibEntryTypePrefsAndFileViewModel(BibEntryType customTypeFromPreferences, BibEntryType customTypeFromFile) {
/**
* Used to render in the UI. This is different from {@link BibEntryType#toString()}, because this is the serialization the user expects
*/
@Override
public String toString() {
return Localization.lang("%0 (from file)\n%1 (current setting)",
MetaDataSerializer.serializeCustomEntryTypes(customTypeFromFile),
MetaDataSerializer.serializeCustomEntryTypes(customTypeFromPreferences));
}
}
| 753
| 38.684211
| 139
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/importer/GenerateEntryFromIdAction.java
|
package org.jabref.gui.importer;
import java.util.Optional;
import org.jabref.gui.DialogService;
import org.jabref.gui.LibraryTab;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.externalfiles.ImportHandler;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.importer.CompositeIdFetcher;
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.entry.BibEntry;
import org.jabref.model.entry.types.StandardEntryType;
import org.jabref.model.util.FileUpdateMonitor;
import org.jabref.preferences.PreferencesService;
import org.controlsfx.control.PopOver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GenerateEntryFromIdAction extends SimpleCommand {
private static final Logger LOGGER = LoggerFactory.getLogger(GenerateEntryFromIdAction.class);
private final LibraryTab libraryTab;
private final DialogService dialogService;
private final PreferencesService preferencesService;
private final String identifier;
private final TaskExecutor taskExecutor;
private final PopOver entryFromIdPopOver;
private final StateManager stateManager;
private final FileUpdateMonitor fileUpdateMonitor;
public GenerateEntryFromIdAction(LibraryTab libraryTab,
DialogService dialogService,
PreferencesService preferencesService,
TaskExecutor taskExecutor,
PopOver entryFromIdPopOver,
String identifier,
StateManager stateManager,
FileUpdateMonitor fileUpdateMonitor) {
this.libraryTab = libraryTab;
this.dialogService = dialogService;
this.preferencesService = preferencesService;
this.identifier = identifier;
this.taskExecutor = taskExecutor;
this.entryFromIdPopOver = entryFromIdPopOver;
this.stateManager = stateManager;
this.fileUpdateMonitor = fileUpdateMonitor;
}
@Override
public void execute() {
BackgroundTask<Optional<BibEntry>> backgroundTask = searchAndImportEntryInBackground();
backgroundTask.titleProperty().set(Localization.lang("Import by ID"));
backgroundTask.showToUser(true);
backgroundTask.onRunning(() -> dialogService.notify("%s".formatted(backgroundTask.messageProperty().get())));
backgroundTask.onFailure(exception -> {
String fetcherExceptionMessage = exception.getMessage();
String msg;
if (exception instanceof FetcherClientException) {
msg = Localization.lang("Bibliographic data not found. Cause is likely the client side. Please check connection and identifier for correctness.") + "\n" + fetcherExceptionMessage;
} else if (exception instanceof FetcherServerException) {
msg = Localization.lang("Bibliographic data not found. Cause is likely the server side. Please try again later.") + "\n" + fetcherExceptionMessage;
} else {
msg = Localization.lang("Error message %0", fetcherExceptionMessage);
}
LOGGER.info(fetcherExceptionMessage, exception);
if (dialogService.showConfirmationDialogAndWait(Localization.lang("Failed to import by ID"), msg, Localization.lang("Add entry manually"))) {
// add entry manually
new NewEntryAction(libraryTab.frame(), StandardEntryType.Article, dialogService,
preferencesService, stateManager).execute();
}
});
backgroundTask.onSuccess(bibEntry -> {
Optional<BibEntry> result = bibEntry;
if (result.isPresent()) {
final BibEntry entry = result.get();
ImportHandler handler = new ImportHandler(
libraryTab.getBibDatabaseContext(),
preferencesService,
fileUpdateMonitor,
libraryTab.getUndoManager(),
stateManager,
dialogService,
taskExecutor);
handler.importEntryWithDuplicateCheck(libraryTab.getBibDatabaseContext(), entry);
} else {
dialogService.notify("No entry found or import canceled");
}
entryFromIdPopOver.hide();
});
backgroundTask.executeWith(taskExecutor);
}
private BackgroundTask<Optional<BibEntry>> searchAndImportEntryInBackground() {
return new BackgroundTask<>() {
@Override
protected Optional<BibEntry> call() throws FetcherException {
if (isCanceled()) {
return Optional.empty();
}
updateMessage(Localization.lang("Searching..."));
return new CompositeIdFetcher(preferencesService.getImportFormatPreferences()).performSearchById(identifier);
}
};
}
}
| 5,350
| 44.735043
| 195
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/importer/GenerateEntryFromIdDialog.java
|
package org.jabref.gui.importer;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.DialogPane;
import javafx.scene.control.TextField;
import org.jabref.gui.DialogService;
import org.jabref.gui.LibraryTab;
import org.jabref.gui.StateManager;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.util.FileUpdateMonitor;
import org.jabref.preferences.PreferencesService;
import com.airhacks.afterburner.views.ViewLoader;
import jakarta.inject.Inject;
import org.controlsfx.control.PopOver;
public class GenerateEntryFromIdDialog {
@FXML DialogPane dialogPane;
@FXML TextField idTextField;
@FXML Button generateButton;
@Inject private FileUpdateMonitor fileUpdateMonitor;
private final PreferencesService preferencesService;
private final DialogService dialogService;
private final LibraryTab libraryTab;
private final TaskExecutor taskExecutor;
private final StateManager stateManager;
private PopOver entryFromIdPopOver;
public GenerateEntryFromIdDialog(LibraryTab libraryTab, DialogService dialogService, PreferencesService preferencesService, TaskExecutor taskExecutor, StateManager stateManager) {
ViewLoader.view(this).load();
this.preferencesService = preferencesService;
this.dialogService = dialogService;
this.libraryTab = libraryTab;
this.taskExecutor = taskExecutor;
this.stateManager = stateManager;
this.generateButton.setGraphic(IconTheme.JabRefIcons.IMPORT.getGraphicNode());
this.generateButton.setDefaultButton(true);
}
@FXML private void generateEntry() {
if (idTextField.getText().isEmpty()) {
dialogService.notify(Localization.lang("Enter a valid ID"));
return;
}
this.idTextField.requestFocus();
GenerateEntryFromIdAction generateEntryFromIdAction = new GenerateEntryFromIdAction(
libraryTab,
dialogService,
preferencesService,
taskExecutor,
entryFromIdPopOver,
idTextField.getText(),
stateManager,
fileUpdateMonitor
);
generateEntryFromIdAction.execute();
}
public void setEntryFromIdPopOver(PopOver entryFromIdPopOver) {
this.entryFromIdPopOver = entryFromIdPopOver;
}
public DialogPane getDialogPane() {
return dialogPane;
}
}
| 2,546
| 32.077922
| 183
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/importer/GrobidOptInDialogHelper.java
|
package org.jabref.gui.importer;
import org.jabref.gui.DialogService;
import org.jabref.logic.importer.fetcher.GrobidPreferences;
import org.jabref.logic.l10n.Localization;
/**
* Metadata extraction from PDFs and plaintext works very well using Grobid, but we do not want to enable it by default
* due to data privacy concerns.
* To make users aware of the feature, we ask each time before querying Grobid, giving the option to opt-out.
*/
public class GrobidOptInDialogHelper {
/**
* If Grobid is not enabled but the user has not explicitly opted-out of Grobid, we ask for permission to send data
* to Grobid using a dialog and giving an opt-out option.
*
* @param dialogService the DialogService to use
* @return if the user enabled Grobid, either in the past or after being asked by the dialog.
*/
public static boolean showAndWaitIfUserIsUndecided(DialogService dialogService, GrobidPreferences preferences) {
if (preferences.isGrobidEnabled()) {
return true;
}
if (preferences.isGrobidOptOut()) {
return false;
}
boolean grobidEnabled = dialogService.showConfirmationDialogWithOptOutAndWait(
Localization.lang("Remote services"),
Localization.lang("Allow sending PDF files and raw citation strings to a JabRef online service (Grobid) to determine Metadata. This produces better results."),
Localization.lang("Do not ask again"),
optOut -> preferences.grobidOptOutProperty().setValue(optOut));
preferences.grobidEnabledProperty().setValue(grobidEnabled);
return grobidEnabled;
}
}
| 1,678
| 44.378378
| 175
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/importer/ImportAction.java
|
package org.jabref.gui.importer;
import java.io.IOException;
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.gui.Globals;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.LibraryTab;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.gui.util.DefaultTaskExecutor;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.JabRefException;
import org.jabref.logic.database.DatabaseMerger;
import org.jabref.logic.importer.ImportException;
import org.jabref.logic.importer.ImportFormatReader;
import org.jabref.logic.importer.Importer;
import org.jabref.logic.importer.ParserResult;
import org.jabref.logic.importer.fileformat.PdfGrobidImporter;
import org.jabref.logic.importer.fileformat.PdfMergeMetadataImporter;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.StandardFileType;
import org.jabref.logic.util.UpdateField;
import org.jabref.logic.util.io.FileUtil;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.util.FileUpdateMonitor;
import org.jabref.preferences.PreferencesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ImportAction {
// FixMe: Command pattern is broken, should extend SimpleCommand
private static final Logger LOGGER = LoggerFactory.getLogger(ImportAction.class);
private final JabRefFrame frame;
private final boolean openInNew;
private final Optional<Importer> importer;
private final DialogService dialogService;
private Exception importError;
private final TaskExecutor taskExecutor = Globals.TASK_EXECUTOR;
private final PreferencesService preferencesService;
private final FileUpdateMonitor fileUpdateMonitor;
public ImportAction(JabRefFrame frame,
boolean openInNew,
Importer importer,
PreferencesService preferencesService,
FileUpdateMonitor fileUpdateMonitor) {
this.importer = Optional.ofNullable(importer);
this.frame = frame;
this.dialogService = frame.getDialogService();
this.openInNew = openInNew;
this.preferencesService = preferencesService;
this.fileUpdateMonitor = fileUpdateMonitor;
}
/**
* Automatically imports the files given as arguments.
*
* @param filenames List of files to import
*/
public void automatedImport(List<String> filenames) {
List<Path> files = filenames.stream().map(Path::of).collect(Collectors.toList());
BackgroundTask<ParserResult> task = BackgroundTask.wrap(() -> {
List<ImportFormatReader.UnknownFormatImport> imports = doImport(files);
// Ok, done. Then try to gather in all we have found. Since we might
// have found
// one or more bibtex results, it's best to gather them in a
// BibDatabase.
ParserResult bibtexResult = mergeImportResults(imports);
// TODO: show parserwarnings, if any (not here)
// for (ImportFormatReader.UnknownFormatImport p : imports) {
// ParserResultWarningDialog.showParserResultWarningDialog(p.parserResult, frame);
// }
if (bibtexResult.isEmpty()) {
if (importError == null) {
// TODO: No control flow using exceptions
throw new JabRefException(Localization.lang("No entries found. Please make sure you are using the correct import filter."));
} else if (importError instanceof ImportException) {
String content = Localization.lang("Please check your library file for wrong syntax.") + "\n\n"
+ importError.getLocalizedMessage();
DefaultTaskExecutor.runAndWaitInJavaFXThread(() -> dialogService.showWarningDialogAndWait(Localization.lang("Import error"), content));
} else {
throw importError;
}
}
return bibtexResult;
});
if (openInNew) {
task.onSuccess(parserResult -> {
frame.addTab(parserResult.getDatabaseContext(), true);
dialogService.notify(Localization.lang("Imported entries") + ": " + parserResult.getDatabase().getEntries().size());
})
.onFailure(ex -> {
LOGGER.error("Error importing", ex);
dialogService.notify(Localization.lang("Error importing. See the error log for details."));
})
.executeWith(taskExecutor);
} else {
final LibraryTab libraryTab = frame.getCurrentLibraryTab();
ImportEntriesDialog dialog = new ImportEntriesDialog(libraryTab.getBibDatabaseContext(), task);
dialog.setTitle(Localization.lang("Import"));
dialogService.showCustomDialogAndWait(dialog);
}
}
private boolean fileIsPdf(Path filename) {
Optional<String> extension = FileUtil.getFileExtension(filename);
return extension.isPresent() && StandardFileType.PDF.getExtensions().contains(extension.get());
}
private List<ImportFormatReader.UnknownFormatImport> doImport(List<Path> files) {
// We import all files and collect their results
List<ImportFormatReader.UnknownFormatImport> imports = new ArrayList<>();
ImportFormatReader importFormatReader = new ImportFormatReader(
preferencesService.getImporterPreferences(),
preferencesService.getImportFormatPreferences(),
fileUpdateMonitor);
for (Path filename : files) {
try {
if (importer.isEmpty()) {
// Unknown format
DefaultTaskExecutor.runAndWaitInJavaFXThread(() -> {
if (fileIsPdf(filename) && GrobidOptInDialogHelper.showAndWaitIfUserIsUndecided(dialogService, preferencesService.getGrobidPreferences())) {
importFormatReader.reset();
}
frame.getDialogService().notify(Localization.lang("Importing in unknown format") + "...");
});
// This import method never throws an IOException
imports.add(importFormatReader.importUnknownFormat(filename, fileUpdateMonitor));
} else {
DefaultTaskExecutor.runAndWaitInJavaFXThread(() -> {
if (((importer.get() instanceof PdfGrobidImporter)
|| (importer.get() instanceof PdfMergeMetadataImporter))
&& GrobidOptInDialogHelper.showAndWaitIfUserIsUndecided(dialogService, preferencesService.getGrobidPreferences())) {
importFormatReader.reset();
}
frame.getDialogService().notify(Localization.lang("Importing in %0 format", importer.get().getName()) + "...");
});
// Specific importer
ParserResult pr = importer.get().importDatabase(filename);
imports.add(new ImportFormatReader.UnknownFormatImport(importer.get().getName(), pr));
}
} catch (ImportException | IOException e) {
// This indicates that a specific importer was specified, and that
// this importer has thrown an IOException. We store the exception,
// so a relevant error message can be displayed.
importError = e;
}
}
return imports;
}
/**
* TODO: Move this to logic package. Blocked by undo functionality.
*/
private ParserResult mergeImportResults(List<ImportFormatReader.UnknownFormatImport> imports) {
BibDatabase resultDatabase = new BibDatabase();
ParserResult result = new ParserResult(resultDatabase);
for (ImportFormatReader.UnknownFormatImport importResult : imports) {
if (importResult == null) {
continue;
}
ParserResult parserResult = importResult.parserResult();
resultDatabase.insertEntries(parserResult.getDatabase().getEntries());
if (ImportFormatReader.BIBTEX_FORMAT.equals(importResult.format())) {
// additional treatment of BibTeX
new DatabaseMerger(preferencesService.getBibEntryPreferences().getKeywordSeparator()).mergeMetaData(
result.getMetaData(),
parserResult.getMetaData(),
importResult.parserResult().getPath().map(path -> path.getFileName().toString()).orElse("unknown"),
parserResult.getDatabase().getEntries());
}
// TODO: collect errors into ParserResult, because they are currently ignored (see caller of this method)
}
// set timestamp and owner
UpdateField.setAutomaticFields(resultDatabase.getEntries(), preferencesService.getOwnerPreferences(), preferencesService.getTimestampPreferences()); // set timestamp and owner
return result;
}
}
| 9,339
| 46.653061
| 183
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/importer/ImportCommand.java
|
package org.jabref.gui.importer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.Optional;
import java.util.SortedSet;
import javafx.stage.FileChooser;
import org.jabref.gui.DialogService;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.util.FileDialogConfiguration;
import org.jabref.gui.util.FileFilterConverter;
import org.jabref.logic.importer.ImportFormatReader;
import org.jabref.logic.importer.Importer;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.util.FileUpdateMonitor;
import org.jabref.preferences.PreferencesService;
import static org.jabref.gui.actions.ActionHelper.needsDatabase;
/**
* Perform import operation
*/
public class ImportCommand extends SimpleCommand {
private final JabRefFrame frame;
private final boolean openInNew;
private final DialogService dialogService;
private final PreferencesService preferences;
private final FileUpdateMonitor fileUpdateMonitor;
/**
* @param openInNew Indicate whether the entries should import into a new database or into the currently open one.
*/
public ImportCommand(JabRefFrame frame,
boolean openInNew,
PreferencesService preferences,
StateManager stateManager,
FileUpdateMonitor fileUpdateMonitor) {
this.frame = frame;
this.openInNew = openInNew;
this.preferences = preferences;
this.fileUpdateMonitor = fileUpdateMonitor;
if (!openInNew) {
this.executable.bind(needsDatabase(stateManager));
}
this.dialogService = frame.getDialogService();
}
@Override
public void execute() {
ImportFormatReader importFormatReader = new ImportFormatReader(
preferences.getImporterPreferences(),
preferences.getImportFormatPreferences(),
fileUpdateMonitor);
SortedSet<Importer> importers = importFormatReader.getImportFormats();
FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
.addExtensionFilter(FileFilterConverter.ANY_FILE)
.addExtensionFilter(FileFilterConverter.forAllImporters(importers))
.addExtensionFilter(FileFilterConverter.importerToExtensionFilter(importers))
.withInitialDirectory(preferences.getImporterPreferences().getImportWorkingDirectory())
.build();
dialogService.showFileOpenDialog(fileDialogConfiguration)
.ifPresent(path -> doImport(path, importers, fileDialogConfiguration.getSelectedExtensionFilter()));
}
private void doImport(Path file, SortedSet<Importer> importers, FileChooser.ExtensionFilter selectedExtensionFilter) {
if (!Files.exists(file)) {
dialogService.showErrorDialogAndWait(Localization.lang("Import"),
Localization.lang("File not found") + ": '" + file.getFileName() + "'.");
return;
}
Optional<Importer> format = FileFilterConverter.getImporter(selectedExtensionFilter, importers);
ImportAction importMenu = new ImportAction(frame, openInNew, format.orElse(null), preferences, fileUpdateMonitor);
importMenu.automatedImport(Collections.singletonList(file.toString()));
// Set last working dir for import
preferences.getImporterPreferences().setImportWorkingDirectory(file.getParent());
}
}
| 3,613
| 40.068182
| 122
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/importer/ImportCustomEntryTypesDialog.java
|
package org.jabref.gui.importer;
import java.util.List;
import javafx.beans.binding.Bindings;
import javafx.fxml.FXML;
import javafx.scene.control.ButtonType;
import javafx.scene.control.cell.CheckBoxListCell;
import javafx.scene.layout.VBox;
import org.jabref.gui.util.BaseDialog;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabaseMode;
import org.jabref.model.entry.BibEntryType;
import org.jabref.preferences.PreferencesService;
import com.airhacks.afterburner.views.ViewLoader;
import jakarta.inject.Inject;
import org.controlsfx.control.CheckListView;
public class ImportCustomEntryTypesDialog extends BaseDialog<Void> {
private final List<BibEntryType> customEntryTypes;
@Inject private PreferencesService preferencesService;
@FXML private VBox boxDifferentCustomization;
@FXML private CheckListView<BibEntryType> unknownEntryTypesCheckList;
@FXML private CheckListView<BibEntryTypePrefsAndFileViewModel> differentCustomizationCheckList;
private final BibDatabaseMode mode;
private ImportCustomEntryTypesDialogViewModel viewModel;
public ImportCustomEntryTypesDialog(BibDatabaseMode mode, List<BibEntryType> customEntryTypes) {
this.mode = mode;
this.customEntryTypes = customEntryTypes;
ViewLoader.view(this)
.load()
.setAsDialogPane(this);
setResultConverter(btn -> {
if (btn == ButtonType.OK) {
viewModel.importBibEntryTypes(
unknownEntryTypesCheckList.getCheckModel().getCheckedItems(),
differentCustomizationCheckList.getCheckModel().getCheckedItems().stream()
.map(BibEntryTypePrefsAndFileViewModel::customTypeFromPreferences)
.toList());
}
return null;
});
setTitle(Localization.lang("Custom entry types"));
}
@FXML
public void initialize() {
viewModel = new ImportCustomEntryTypesDialogViewModel(mode, customEntryTypes, preferencesService);
boxDifferentCustomization.visibleProperty().bind(Bindings.isNotEmpty(viewModel.differentCustomizations()));
boxDifferentCustomization.managedProperty().bind(Bindings.isNotEmpty(viewModel.differentCustomizations()));
unknownEntryTypesCheckList.setItems(viewModel.newTypes());
unknownEntryTypesCheckList.setCellFactory(listView -> new CheckBoxListCell<>(unknownEntryTypesCheckList::getItemBooleanProperty) {
@Override
public void updateItem(BibEntryType bibEntryType, boolean empty) {
super.updateItem(bibEntryType, empty);
setText(bibEntryType == null ? "" : bibEntryType.getType().getDisplayName());
}
});
differentCustomizationCheckList.setItems(viewModel.differentCustomizations());
}
}
| 2,915
| 39.5
| 138
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/importer/ImportCustomEntryTypesDialogViewModel.java
|
package org.jabref.gui.importer;
import java.util.List;
import java.util.Optional;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.jabref.gui.Globals;
import org.jabref.model.database.BibDatabaseMode;
import org.jabref.model.entry.BibEntryType;
import org.jabref.model.entry.types.EntryTypeFactory;
import org.jabref.preferences.PreferencesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ImportCustomEntryTypesDialogViewModel {
private static final Logger LOGGER = LoggerFactory.getLogger(ImportCustomEntryTypesDialogViewModel.class);
private final BibDatabaseMode mode;
private final PreferencesService preferencesService;
private final ObservableList<BibEntryType> newTypes = FXCollections.observableArrayList();
private final ObservableList<BibEntryTypePrefsAndFileViewModel> differentCustomizationTypes = FXCollections.observableArrayList();
public ImportCustomEntryTypesDialogViewModel(BibDatabaseMode mode, List<BibEntryType> entryTypes, PreferencesService preferencesService) {
this.mode = mode;
this.preferencesService = preferencesService;
for (BibEntryType customType : entryTypes) {
Optional<BibEntryType> currentlyStoredType = Globals.entryTypesManager.enrich(customType.getType(), mode);
if (currentlyStoredType.isEmpty()) {
newTypes.add(customType);
} else {
if (!EntryTypeFactory.nameAndFieldsAreEqual(customType, currentlyStoredType.get())) {
LOGGER.info("currently stored type: {}", currentlyStoredType.get());
LOGGER.info("type provided by library: {}", customType);
differentCustomizationTypes.add(new BibEntryTypePrefsAndFileViewModel(currentlyStoredType.get(), customType));
}
}
}
}
public ObservableList<BibEntryType> newTypes() {
return this.newTypes;
}
public ObservableList<BibEntryTypePrefsAndFileViewModel> differentCustomizations() {
return this.differentCustomizationTypes;
}
public void importBibEntryTypes(List<BibEntryType> checkedUnknownEntryTypes, List<BibEntryType> checkedDifferentEntryTypes) {
if (!checkedUnknownEntryTypes.isEmpty()) {
checkedUnknownEntryTypes.forEach(type -> Globals.entryTypesManager.addCustomOrModifiedType(type, mode));
preferencesService.storeCustomEntryTypesRepository(Globals.entryTypesManager);
}
if (!checkedDifferentEntryTypes.isEmpty()) {
checkedUnknownEntryTypes.forEach(type -> Globals.entryTypesManager.addCustomOrModifiedType(type, mode));
preferencesService.storeCustomEntryTypesRepository(Globals.entryTypesManager);
}
}
}
| 2,824
| 42.461538
| 142
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/importer/ImportEntriesDialog.java
|
package org.jabref.gui.importer;
import java.util.EnumSet;
import java.util.Optional;
import javax.swing.undo.UndoManager;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.css.PseudoClass;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
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.util.BackgroundTask;
import org.jabref.gui.util.BaseDialog;
import org.jabref.gui.util.NoSelectionModel;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.gui.util.TextFlowLimited;
import org.jabref.gui.util.ViewModelListCellFactory;
import org.jabref.logic.importer.ParserResult;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.shared.DatabaseLocation;
import org.jabref.logic.util.io.FileUtil;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.BibEntryTypesManager;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.types.EntryType;
import org.jabref.model.entry.types.StandardEntryType;
import org.jabref.model.util.FileUpdateMonitor;
import org.jabref.preferences.PreferencesService;
import com.airhacks.afterburner.views.ViewLoader;
import com.tobiasdiez.easybind.EasyBind;
import jakarta.inject.Inject;
import org.controlsfx.control.CheckListView;
public class ImportEntriesDialog extends BaseDialog<Boolean> {
public CheckListView<BibEntry> entriesListView;
public ComboBox<BibDatabaseContext> libraryListView;
public ButtonType importButton;
public Label totalItems;
public Label selectedItems;
public CheckBox downloadLinkedOnlineFiles;
private final BackgroundTask<ParserResult> task;
private ImportEntriesViewModel viewModel;
@Inject private TaskExecutor taskExecutor;
@Inject private DialogService dialogService;
@Inject private UndoManager undoManager;
@Inject private PreferencesService preferences;
@Inject private StateManager stateManager;
@Inject private BibEntryTypesManager entryTypesManager;
@Inject private FileUpdateMonitor fileUpdateMonitor;
private final BibDatabaseContext database;
/**
* Imports the given entries into the given database. The entries are provided using the BackgroundTask
*
* @param database the database to import into
* @param task the task executed for parsing the selected files(s).
*/
public ImportEntriesDialog(BibDatabaseContext database, BackgroundTask<ParserResult> task) {
this.database = database;
this.task = task;
ViewLoader.view(this)
.load()
.setAsDialogPane(this);
BooleanBinding booleanBind = Bindings.isEmpty(entriesListView.getCheckModel().getCheckedItems());
Button btn = (Button) this.getDialogPane().lookupButton(importButton);
btn.disableProperty().bind(booleanBind);
downloadLinkedOnlineFiles.setSelected(preferences.getFilePreferences().shouldDownloadLinkedFiles());
setResultConverter(button -> {
if (button == importButton) {
viewModel.importEntries(entriesListView.getCheckModel().getCheckedItems(), downloadLinkedOnlineFiles.isSelected());
} else {
dialogService.notify(Localization.lang("Import canceled"));
}
return false;
});
}
@FXML
private void initialize() {
viewModel = new ImportEntriesViewModel(task, taskExecutor, database, dialogService, undoManager, preferences, stateManager, entryTypesManager, fileUpdateMonitor);
Label placeholder = new Label();
placeholder.textProperty().bind(viewModel.messageProperty());
entriesListView.setPlaceholder(placeholder);
entriesListView.setItems(viewModel.getEntries());
libraryListView.setEditable(false);
libraryListView.getItems().addAll(stateManager.getOpenDatabases());
new ViewModelListCellFactory<BibDatabaseContext>()
.withText(database -> {
Optional<String> dbOpt = Optional.empty();
if (database.getDatabasePath().isPresent()) {
dbOpt = FileUtil.getUniquePathFragment(stateManager.collectAllDatabasePaths(), database.getDatabasePath().get());
}
if (database.getLocation() == DatabaseLocation.SHARED) {
return database.getDBMSSynchronizer().getDBName() + " [" + Localization.lang("shared") + "]";
}
if (dbOpt.isEmpty()) {
return Localization.lang("untitled");
}
return dbOpt.get();
})
.install(libraryListView);
viewModel.selectedDbProperty().bind(libraryListView.getSelectionModel().selectedItemProperty());
stateManager.getActiveDatabase().ifPresent(database1 -> libraryListView.getSelectionModel().select(database1));
PseudoClass entrySelected = PseudoClass.getPseudoClass("entry-selected");
new ViewModelListCellFactory<BibEntry>()
.withGraphic(entry -> {
ToggleButton addToggle = IconTheme.JabRefIcons.ADD.asToggleButton();
EasyBind.subscribe(addToggle.selectedProperty(), selected -> {
if (selected) {
addToggle.setGraphic(IconTheme.JabRefIcons.ADD_FILLED.withColor(IconTheme.SELECTED_COLOR).getGraphicNode());
} else {
addToggle.setGraphic(IconTheme.JabRefIcons.ADD.getGraphicNode());
}
});
addToggle.getStyleClass().add("addEntryButton");
addToggle.selectedProperty().bindBidirectional(entriesListView.getItemBooleanProperty(entry));
HBox separator = new HBox();
HBox.setHgrow(separator, Priority.SOMETIMES);
Node entryNode = getEntryNode(entry);
HBox.setHgrow(entryNode, Priority.ALWAYS);
HBox container = new HBox(entryNode, separator, addToggle);
container.getStyleClass().add("entry-container");
BackgroundTask.wrap(() -> viewModel.hasDuplicate(entry)).onSuccess(duplicateFound -> {
if (duplicateFound) {
Button duplicateButton = IconTheme.JabRefIcons.DUPLICATE.asButton();
duplicateButton.setTooltip(new Tooltip(Localization.lang("Possible duplicate of existing entry. Click to resolve.")));
duplicateButton.setOnAction(event -> viewModel.resolveDuplicate(entry));
container.getChildren().add(1, duplicateButton);
}
}).executeWith(taskExecutor);
/*
inserted the if-statement here, since a Platform.runLater() call did not work.
also tried to move it to the end of the initialize method, but it did not select the entry.
*/
if (entriesListView.getItems().size() == 1) {
selectAllNewEntries();
}
return container;
})
.withOnMouseClickedEvent((entry, event) -> entriesListView.getCheckModel().toggleCheckState(entry))
.withPseudoClass(entrySelected, entriesListView::getItemBooleanProperty)
.install(entriesListView);
selectedItems.textProperty().bind(Bindings.size(entriesListView.getCheckModel().getCheckedItems()).asString());
totalItems.textProperty().bind(Bindings.size(entriesListView.getItems()).asString());
entriesListView.setSelectionModel(new NoSelectionModel<>());
}
private Node getEntryNode(BibEntry entry) {
Node entryType = getIcon(entry.getType()).getGraphicNode();
entryType.getStyleClass().add("type");
Label authors = new Label(entry.getFieldOrAliasLatexFree(StandardField.AUTHOR).orElse(""));
authors.getStyleClass().add("authors");
Label title = new Label(entry.getFieldOrAliasLatexFree(StandardField.TITLE).orElse(""));
title.getStyleClass().add("title");
Label year = new Label(entry.getFieldOrAliasLatexFree(StandardField.YEAR).orElse(""));
year.getStyleClass().add("year");
Label journal = new Label(entry.getFieldOrAliasLatexFree(StandardField.JOURNAL).orElse(""));
journal.getStyleClass().add("journal");
VBox entryContainer = new VBox(
new HBox(10, entryType, title),
new HBox(5, year, journal),
authors
);
entry.getFieldOrAliasLatexFree(StandardField.ABSTRACT).ifPresent(summaryText -> {
TextFlowLimited summary = new TextFlowLimited(new Text(summaryText));
summary.getStyleClass().add("summary");
entryContainer.getChildren().add(summary);
});
entryContainer.getStyleClass().add("bibEntry");
return entryContainer;
}
private IconTheme.JabRefIcons getIcon(EntryType type) {
EnumSet<StandardEntryType> crossRefTypes = EnumSet.of(StandardEntryType.InBook, StandardEntryType.InProceedings, StandardEntryType.InCollection);
if (type == StandardEntryType.Book) {
return IconTheme.JabRefIcons.BOOK;
} else if (crossRefTypes.contains(type)) {
return IconTheme.JabRefIcons.OPEN_LINK;
}
return IconTheme.JabRefIcons.ARTICLE;
}
public void unselectAll() {
entriesListView.getCheckModel().clearChecks();
}
public void selectAllNewEntries() {
unselectAll();
for (BibEntry entry : entriesListView.getItems()) {
if (!viewModel.hasDuplicate(entry)) {
entriesListView.getCheckModel().check(entry);
}
}
}
public void selectAllEntries() {
unselectAll();
entriesListView.getCheckModel().checkAll();
}
}
| 10,634
| 44.448718
| 170
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/importer/ImportEntriesViewModel.java
|
package org.jabref.gui.importer;
import java.util.List;
import java.util.Optional;
import javax.swing.undo.UndoManager;
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.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.duplicationFinder.DuplicateResolverDialog;
import org.jabref.gui.externalfiles.ImportHandler;
import org.jabref.gui.fieldeditors.LinkedFileViewModel;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.database.DatabaseMerger;
import org.jabref.logic.database.DuplicateCheck;
import org.jabref.logic.importer.ParserResult;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.BibEntryTypesManager;
import org.jabref.model.entry.LinkedFile;
import org.jabref.model.util.FileUpdateMonitor;
import org.jabref.preferences.PreferencesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ImportEntriesViewModel extends AbstractViewModel {
private static final Logger LOGGER = LoggerFactory.getLogger(ImportAction.class);
private final StringProperty message;
private final TaskExecutor taskExecutor;
private final BibDatabaseContext databaseContext;
private final DialogService dialogService;
private final UndoManager undoManager;
private final StateManager stateManager;
private final FileUpdateMonitor fileUpdateMonitor;
private ParserResult parserResult = null;
private final ObservableList<BibEntry> entries;
private final PreferencesService preferences;
private final BibEntryTypesManager entryTypesManager;
private final ObjectProperty<BibDatabaseContext> selectedDb;
/**
* @param databaseContext the database to import into
* @param task the task executed for parsing the selected files(s).
*/
public ImportEntriesViewModel(BackgroundTask<ParserResult> task,
TaskExecutor taskExecutor,
BibDatabaseContext databaseContext,
DialogService dialogService,
UndoManager undoManager,
PreferencesService preferences,
StateManager stateManager,
BibEntryTypesManager entryTypesManager,
FileUpdateMonitor fileUpdateMonitor) {
this.taskExecutor = taskExecutor;
this.databaseContext = databaseContext;
this.dialogService = dialogService;
this.undoManager = undoManager;
this.preferences = preferences;
this.stateManager = stateManager;
this.entryTypesManager = entryTypesManager;
this.fileUpdateMonitor = fileUpdateMonitor;
this.entries = FXCollections.observableArrayList();
this.message = new SimpleStringProperty();
this.message.bind(task.messageProperty());
this.selectedDb = new SimpleObjectProperty<>();
task.onSuccess(parserResult -> {
// store the complete parser result (to import groups, ... later on)
this.parserResult = parserResult;
// fill in the list for the user, where one can select the entries to import
entries.addAll(parserResult.getDatabase().getEntries());
if (entries.isEmpty()) {
task.updateMessage(Localization.lang("No entries corresponding to given query"));
}
}).onFailure(ex -> {
LOGGER.error("Error importing", ex);
dialogService.showErrorDialogAndWait(ex);
}).executeWith(taskExecutor);
}
public String getMessage() {
return message.get();
}
public StringProperty messageProperty() {
return message;
}
public ObjectProperty<BibDatabaseContext> selectedDbProperty() {
return selectedDb;
}
public BibDatabaseContext getSelectedDb() {
return selectedDb.get();
}
public ObservableList<BibEntry> getEntries() {
return entries;
}
public boolean hasDuplicate(BibEntry entry) {
return findInternalDuplicate(entry).isPresent() ||
new DuplicateCheck(entryTypesManager)
.containsDuplicate(selectedDb.getValue().getDatabase(), entry, selectedDb.getValue().getMode()).isPresent();
}
/**
* Called after the user selected the entries to import. Does the real import stuff.
*
* @param entriesToImport subset of the entries contained in parserResult
*/
public void importEntries(List<BibEntry> entriesToImport, boolean shouldDownloadFiles) {
// Check if we are supposed to warn about duplicates.
// If so, then see if there are duplicates, and warn if yes.
if (preferences.getImporterPreferences().shouldWarnAboutDuplicatesOnImport()) {
BackgroundTask.wrap(() -> entriesToImport.stream()
.anyMatch(this::hasDuplicate)).onSuccess(duplicateFound -> {
if (duplicateFound) {
boolean continueImport = dialogService.showConfirmationDialogWithOptOutAndWait(Localization.lang("Duplicates found"),
Localization.lang("There are possible duplicates that haven't been resolved. Continue?"),
Localization.lang("Continue with import"),
Localization.lang("Cancel import"),
Localization.lang("Do not ask again"),
optOut -> preferences.getImporterPreferences().setWarnAboutDuplicatesOnImport(!optOut));
if (!continueImport) {
dialogService.notify(Localization.lang("Import canceled"));
} else {
buildImportHandlerThenImportEntries(entriesToImport);
}
} else {
buildImportHandlerThenImportEntries(entriesToImport);
}
}).executeWith(taskExecutor);
} else {
buildImportHandlerThenImportEntries(entriesToImport);
}
// Remember the selection in the dialog
preferences.getFilePreferences().setDownloadLinkedFiles(shouldDownloadFiles);
if (shouldDownloadFiles) {
for (BibEntry bibEntry : entriesToImport) {
bibEntry.getFiles().stream().filter(LinkedFile::isOnlineLink).forEach(linkedFile ->
new LinkedFileViewModel(
linkedFile,
bibEntry,
databaseContext,
taskExecutor,
dialogService,
preferences).download());
}
}
new DatabaseMerger(preferences.getBibEntryPreferences().getKeywordSeparator()).mergeStrings(
databaseContext.getDatabase(),
parserResult.getDatabase());
new DatabaseMerger(preferences.getBibEntryPreferences().getKeywordSeparator()).mergeMetaData(
databaseContext.getMetaData(),
parserResult.getMetaData(),
parserResult.getPath().map(path -> path.getFileName().toString()).orElse("unknown"),
parserResult.getDatabase().getEntries());
// JabRefGUI.getMainFrame().getCurrentLibraryTab().markBaseChanged();
}
private void buildImportHandlerThenImportEntries(List<BibEntry> entriesToImport) {
ImportHandler importHandler = new ImportHandler(
selectedDb.getValue(),
preferences,
fileUpdateMonitor,
undoManager,
stateManager,
dialogService,
taskExecutor);
importHandler.importEntries(entriesToImport);
dialogService.notify(Localization.lang("Number of entries successfully imported") + ": " + entriesToImport.size());
}
/**
* Checks if there are duplicates to the given entry in the list of entries to be imported.
*
* @param entry The entry to search for duplicates of.
* @return A possible duplicate, if any, or null if none were found.
*/
private Optional<BibEntry> findInternalDuplicate(BibEntry entry) {
for (BibEntry othEntry : entries) {
if (othEntry.equals(entry)) {
continue; // Don't compare the entry to itself
}
if (new DuplicateCheck(entryTypesManager).isDuplicate(entry, othEntry, databaseContext.getMode())) {
return Optional.of(othEntry);
}
}
return Optional.empty();
}
public void resolveDuplicate(BibEntry entry) {
// First, try to find duplicate in the existing library
Optional<BibEntry> other = new DuplicateCheck(entryTypesManager).containsDuplicate(databaseContext.getDatabase(), entry, databaseContext.getMode());
if (other.isPresent()) {
DuplicateResolverDialog dialog = new DuplicateResolverDialog(other.get(),
entry, DuplicateResolverDialog.DuplicateResolverType.IMPORT_CHECK, databaseContext, stateManager, dialogService, preferences);
DuplicateResolverDialog.DuplicateResolverResult result = dialogService.showCustomDialogAndWait(dialog)
.orElse(DuplicateResolverDialog.DuplicateResolverResult.BREAK);
if (result == DuplicateResolverDialog.DuplicateResolverResult.KEEP_LEFT) {
// TODO: Remove old entry. Or... add it to a list of entries
// to be deleted. We only delete
// it after Ok is clicked.
// entriesToDelete.add(other.get());
} else if (result == DuplicateResolverDialog.DuplicateResolverResult.KEEP_RIGHT) {
// Remove the entry from the import inspection dialog.
entries.remove(entry);
} else if (result == DuplicateResolverDialog.DuplicateResolverResult.KEEP_BOTH) {
// Do nothing.
} else if (result == DuplicateResolverDialog.DuplicateResolverResult.KEEP_MERGE) {
// TODO: Remove old entry. Or... add it to a list of entries
// to be deleted. We only delete
// it after Ok is clicked.
// entriesToDelete.add(other.get());
// Replace entry by merged entry
entries.add(dialog.getMergedEntry());
entries.remove(entry);
}
return;
}
// Second, check if the duplicate is of another entry in the import:
other = findInternalDuplicate(entry);
if (other.isPresent()) {
DuplicateResolverDialog diag = new DuplicateResolverDialog(entry,
other.get(), DuplicateResolverDialog.DuplicateResolverType.DUPLICATE_SEARCH, databaseContext, stateManager, dialogService, preferences);
DuplicateResolverDialog.DuplicateResolverResult answer = dialogService.showCustomDialogAndWait(diag)
.orElse(DuplicateResolverDialog.DuplicateResolverResult.BREAK);
if (answer == DuplicateResolverDialog.DuplicateResolverResult.KEEP_LEFT) {
// Remove other entry
entries.remove(other.get());
} else if (answer == DuplicateResolverDialog.DuplicateResolverResult.KEEP_RIGHT) {
// Remove entry
entries.remove(entry);
} else if (answer == DuplicateResolverDialog.DuplicateResolverResult.KEEP_BOTH) {
// Do nothing
} else if (answer == DuplicateResolverDialog.DuplicateResolverResult.KEEP_MERGE) {
// Replace both entries by merged entry
entries.add(diag.getMergedEntry());
entries.remove(entry);
entries.remove(other.get());
}
}
}
}
| 12,507
| 45.671642
| 156
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/importer/ImporterViewModel.java
|
package org.jabref.gui.importer;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import org.jabref.logic.importer.fileformat.CustomImporter;
public class ImporterViewModel {
private final CustomImporter importer;
private final StringProperty name = new SimpleStringProperty();
private final StringProperty classname = new SimpleStringProperty();
private final StringProperty basePath = new SimpleStringProperty();
public ImporterViewModel(CustomImporter importer) {
this.importer = importer;
this.name.setValue(importer.getName());
this.classname.setValue(importer.getClassName());
this.basePath.setValue(importer.getBasePath().toString());
}
public CustomImporter getLogic() {
return this.importer;
}
public StringProperty name() {
return this.name;
}
public StringProperty className() {
return this.classname;
}
public StringProperty basePath() {
return this.basePath;
}
}
| 1,051
| 27.432432
| 72
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/importer/NewDatabaseAction.java
|
package org.jabref.gui.importer;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.preferences.PreferencesService;
/**
* Create a new, empty, database.
*/
public class NewDatabaseAction extends SimpleCommand {
private final JabRefFrame jabRefFrame;
private final PreferencesService preferencesService;
/**
* Constructs a command to create a new library of the default type
*
* @param jabRefFrame the application frame of JabRef
* @param preferencesService the preferencesService of JabRef
*/
public NewDatabaseAction(JabRefFrame jabRefFrame, PreferencesService preferencesService) {
this.jabRefFrame = jabRefFrame;
this.preferencesService = preferencesService;
}
@Override
public void execute() {
BibDatabaseContext bibDatabaseContext = new BibDatabaseContext();
bibDatabaseContext.setMode(preferencesService.getLibraryPreferences().getDefaultBibDatabaseMode());
jabRefFrame.addTab(bibDatabaseContext, true);
}
}
| 1,125
| 32.117647
| 107
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/importer/NewEntryAction.java
|
package org.jabref.gui.importer;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.jabref.gui.DialogService;
import org.jabref.gui.EntryTypeView;
import org.jabref.gui.Globals;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.types.EntryType;
import org.jabref.preferences.PreferencesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.jabref.gui.actions.ActionHelper.needsDatabase;
public class NewEntryAction extends SimpleCommand {
private static final Logger LOGGER = LoggerFactory.getLogger(NewEntryAction.class);
private final JabRefFrame jabRefFrame;
/**
* The type of the entry to create.
*/
private Optional<EntryType> type;
private final DialogService dialogService;
private final PreferencesService preferences;
public NewEntryAction(JabRefFrame jabRefFrame, DialogService dialogService, PreferencesService preferences, StateManager stateManager) {
this.jabRefFrame = jabRefFrame;
this.dialogService = dialogService;
this.preferences = preferences;
this.type = Optional.empty();
this.executable.bind(needsDatabase(stateManager));
}
public NewEntryAction(JabRefFrame jabRefFrame, EntryType type, DialogService dialogService, PreferencesService preferences, StateManager stateManager) {
this(jabRefFrame, dialogService, preferences, stateManager);
this.type = Optional.of(type);
}
@Override
public void execute() {
if (jabRefFrame.getBasePanelCount() <= 0) {
LOGGER.error("Action 'New entry' must be disabled when no database is open.");
return;
}
if (type.isPresent()) {
jabRefFrame.getCurrentLibraryTab().insertEntry(new BibEntry(type.get()));
} else {
EntryTypeView typeChoiceDialog = new EntryTypeView(jabRefFrame.getCurrentLibraryTab(), dialogService, preferences);
EntryType selectedType = dialogService.showCustomDialogAndWait(typeChoiceDialog).orElse(null);
if (selectedType == null) {
return;
}
trackNewEntry(selectedType);
jabRefFrame.getCurrentLibraryTab().insertEntry(new BibEntry(selectedType));
}
}
private void trackNewEntry(EntryType type) {
Map<String, String> properties = new HashMap<>();
properties.put("EntryType", type.getName());
Globals.getTelemetryClient().ifPresent(client -> client.trackEvent("NewEntry", properties, new HashMap<>()));
}
}
| 2,714
| 32.9375
| 156
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/importer/ParserResultWarningDialog.java
|
package org.jabref.gui.importer;
import java.util.List;
import java.util.Objects;
import org.jabref.gui.JabRefFrame;
import org.jabref.logic.importer.ParserResult;
import org.jabref.logic.l10n.Localization;
/**
* Class for generating a dialog showing warnings from ParserResult
*/
public class ParserResultWarningDialog {
private ParserResultWarningDialog() {
}
/**
* Shows a dialog with the warnings from an import or open of a file
*
* @param parserResult - ParserResult for the current import/open
* @param jabRefFrame - the JabRefFrame
*/
public static void showParserResultWarningDialog(final ParserResult parserResult, final JabRefFrame jabRefFrame) {
Objects.requireNonNull(parserResult);
Objects.requireNonNull(jabRefFrame);
showParserResultWarningDialog(parserResult, jabRefFrame, -1);
}
/**
* Shows a dialog with the warnings from an import or open of a file
*
* @param parserResult - ParserResult for the current import/open
* @param jabRefFrame - the JabRefFrame
* @param dataBaseNumber - Database tab number to activate when showing the warning dialog
*/
public static void showParserResultWarningDialog(final ParserResult parserResult, final JabRefFrame jabRefFrame,
final int dataBaseNumber) {
Objects.requireNonNull(parserResult);
Objects.requireNonNull(jabRefFrame);
// Return if no warnings
if (!(parserResult.hasWarnings())) {
return;
}
// Switch tab if asked to do so
if (dataBaseNumber >= 0) {
jabRefFrame.showLibraryTabAt(dataBaseNumber);
}
// Generate string with warning texts
final List<String> warnings = parserResult.warnings();
final StringBuilder dialogContent = new StringBuilder();
int warningCount = 1;
for (final String warning : warnings) {
dialogContent.append(String.format("%d. %s%n", warningCount++, warning));
}
dialogContent.deleteCharAt(dialogContent.length() - 1);
// Generate dialog title
String dialogTitle;
if (dataBaseNumber < 0 || parserResult.getPath().isEmpty()) {
dialogTitle = Localization.lang("Warnings");
} else {
dialogTitle = Localization.lang("Warnings") + " (" + parserResult.getPath().get().getFileName() + ")";
}
// Show dialog
jabRefFrame.getDialogService().showWarningDialogAndWait(dialogTitle, dialogContent.toString());
}
}
| 2,606
| 35.208333
| 118
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/importer/actions/CheckForNewEntryTypesAction.java
|
package org.jabref.gui.importer.actions;
import java.util.List;
import java.util.stream.Collectors;
import org.jabref.gui.DialogService;
import org.jabref.gui.Globals;
import org.jabref.gui.LibraryTab;
import org.jabref.gui.importer.ImportCustomEntryTypesDialog;
import org.jabref.logic.importer.ParserResult;
import org.jabref.model.database.BibDatabaseMode;
import org.jabref.model.entry.BibEntryType;
import com.airhacks.afterburner.injection.Injector;
/**
* This action checks whether any new custom entry types were loaded from this
* BIB file. If so, an offer to remember these entry types is given.
*/
public class CheckForNewEntryTypesAction implements GUIPostOpenAction {
@Override
public boolean isActionNecessary(ParserResult parserResult) {
return !getListOfUnknownAndUnequalCustomizations(parserResult).isEmpty();
}
@Override
public void performAction(LibraryTab libraryTab, ParserResult parserResult) {
BibDatabaseMode mode = getBibDatabaseModeFromParserResult(parserResult);
DialogService dialogService = Injector.instantiateModelOrService(DialogService.class);
dialogService.showCustomDialogAndWait(new ImportCustomEntryTypesDialog(mode, getListOfUnknownAndUnequalCustomizations(parserResult)));
}
private List<BibEntryType> getListOfUnknownAndUnequalCustomizations(ParserResult parserResult) {
BibDatabaseMode mode = getBibDatabaseModeFromParserResult(parserResult);
return parserResult.getEntryTypes()
.stream()
.filter(type -> Globals.entryTypesManager.isDifferentCustomOrModifiedType(type, mode))
.collect(Collectors.toList());
}
private BibDatabaseMode getBibDatabaseModeFromParserResult(ParserResult parserResult) {
return parserResult.getMetaData().getMode().orElse(Globals.prefs.getLibraryPreferences().getDefaultBibDatabaseMode());
}
}
| 1,950
| 40.510638
| 142
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/importer/actions/GUIPostOpenAction.java
|
package org.jabref.gui.importer.actions;
import org.jabref.gui.LibraryTab;
import org.jabref.logic.importer.ParserResult;
/**
* This interface defines potential actions that may need to be taken after
* opening a BIB file into JabRef. This can for instance be file upgrade actions
* that should be offered due to new features in JabRef, and may depend on e.g.
* which JabRef version the file was last written by.
*
* This interface is introduced in an attempt to add such functionality in a
* flexible manner.
*/
public interface GUIPostOpenAction {
/**
* This method is queried in order to find out whether the action needs to be
* performed or not.
*
* @param pr The result of the BIB parse operation.
* @return true if the action should be called, false otherwise.
*/
boolean isActionNecessary(ParserResult pr);
/**
* This method is called after the new database has been added to the GUI, if
* the isActionNecessary() method returned true.
*
* Note: if several such methods need to be called sequentially, it is
* important that all implementations of this method do not return
* until the operation is finished.
*
* @param panel The BasePanel where the database is shown.
* @param pr The result of the BIB parse operation.
*/
void performAction(LibraryTab panel, ParserResult pr);
}
| 1,411
| 35.205128
| 81
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/importer/actions/MergeReviewIntoCommentAction.java
|
package org.jabref.gui.importer.actions;
import java.util.List;
import org.jabref.gui.LibraryTab;
import org.jabref.logic.importer.ParserResult;
import org.jabref.migrations.MergeReviewIntoCommentMigration;
import org.jabref.model.entry.BibEntry;
public class MergeReviewIntoCommentAction implements GUIPostOpenAction {
@Override
public boolean isActionNecessary(ParserResult parserResult) {
return MergeReviewIntoCommentMigration.needsMigration(parserResult);
}
@Override
public void performAction(LibraryTab libraryTab, ParserResult parserResult) {
MergeReviewIntoCommentMigration migration = new MergeReviewIntoCommentMigration();
migration.performMigration(parserResult);
List<BibEntry> conflicts = MergeReviewIntoCommentMigration.collectConflicts(parserResult);
if (!conflicts.isEmpty() && new MergeReviewIntoCommentConfirmationDialog(libraryTab.frame().getDialogService()).askUserForMerge(conflicts)) {
migration.performConflictingMigration(parserResult);
}
}
}
| 1,058
| 36.821429
| 149
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/importer/actions/MergeReviewIntoCommentConfirmationDialog.java
|
package org.jabref.gui.importer.actions;
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.model.entry.BibEntry;
public class MergeReviewIntoCommentConfirmationDialog {
private final DialogService dialogService;
public MergeReviewIntoCommentConfirmationDialog(DialogService dialogService) {
this.dialogService = dialogService;
}
public boolean askUserForMerge(List<BibEntry> conflicts) {
String bibKeys = conflicts
.stream()
.map(BibEntry::getCitationKey)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.joining(",\n"));
String content = bibKeys + " " +
Localization.lang("has/have both a 'Comment' and a 'Review' field.") + "\n" +
Localization.lang("Since the 'Review' field was deprecated in JabRef 4.2, these two fields are about to be merged into the 'Comment' field.") + "\n" +
Localization.lang("The conflicting fields of these entries will be merged into the 'Comment' field.");
return dialogService.showConfirmationDialogAndWait(
Localization.lang("Review Field Migration"),
content,
Localization.lang("Merge fields")
);
}
}
| 1,432
| 35.74359
| 166
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/importer/actions/OpenDatabaseAction.java
|
package org.jabref.gui.importer.actions;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import org.jabref.gui.DialogService;
import org.jabref.gui.Globals;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.LibraryTab;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.dialogs.BackupUIManager;
import org.jabref.gui.menus.FileHistoryMenu;
import org.jabref.gui.shared.SharedDatabaseUIManager;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.gui.util.DefaultTaskExecutor;
import org.jabref.gui.util.FileDialogConfiguration;
import org.jabref.logic.autosaveandbackup.BackupManager;
import org.jabref.logic.importer.OpenDatabase;
import org.jabref.logic.importer.ParserResult;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.shared.DatabaseNotSupportedException;
import org.jabref.logic.shared.exception.InvalidDBMSConnectionPropertiesException;
import org.jabref.logic.shared.exception.NotASharedDatabaseException;
import org.jabref.logic.util.StandardFileType;
import org.jabref.model.util.FileUpdateMonitor;
import org.jabref.preferences.PreferencesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// The action concerned with opening an existing database.
public class OpenDatabaseAction extends SimpleCommand {
private static final Logger LOGGER = LoggerFactory.getLogger(OpenDatabaseAction.class);
// List of actions that may need to be called after opening the file. Such as
// upgrade actions etc. that may depend on the JabRef version that wrote the file:
private static final List<GUIPostOpenAction> POST_OPEN_ACTIONS = List.of(
// Migrations:
// Warning for migrating the Review into the Comment field
new MergeReviewIntoCommentAction(),
// Check for new custom entry types loaded from the BIB file:
new CheckForNewEntryTypesAction());
private final JabRefFrame frame;
private final PreferencesService preferencesService;
private final StateManager stateManager;
private final FileUpdateMonitor fileUpdateMonitor;
private final DialogService dialogService;
public OpenDatabaseAction(JabRefFrame frame,
PreferencesService preferencesService,
DialogService dialogService,
StateManager stateManager,
FileUpdateMonitor fileUpdateMonitor) {
this.frame = frame;
this.preferencesService = preferencesService;
this.dialogService = dialogService;
this.stateManager = stateManager;
this.fileUpdateMonitor = fileUpdateMonitor;
}
/**
* Go through the list of post open actions, and perform those that need to be performed.
*
* @param libraryTab The BasePanel where the database is shown.
* @param result The result of the BIB file parse operation.
*/
public static void performPostOpenActions(LibraryTab libraryTab, ParserResult result) {
for (GUIPostOpenAction action : OpenDatabaseAction.POST_OPEN_ACTIONS) {
if (action.isActionNecessary(result)) {
action.performAction(libraryTab, result);
libraryTab.frame().showLibraryTab(libraryTab);
}
}
}
@Override
public void execute() {
FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
.addExtensionFilter(StandardFileType.BIBTEX_DB)
.withDefaultExtension(StandardFileType.BIBTEX_DB)
.withInitialDirectory(getInitialDirectory())
.build();
List<Path> filesToOpen = dialogService.showFileOpenDialogAndGetMultipleFiles(fileDialogConfiguration);
openFiles(filesToOpen);
}
/**
* @return Path of current panel database directory or the working directory
*/
private Path getInitialDirectory() {
if (frame.getBasePanelCount() == 0) {
return preferencesService.getFilePreferences().getWorkingDirectory();
} else {
Optional<Path> databasePath = frame.getCurrentLibraryTab().getBibDatabaseContext().getDatabasePath();
return databasePath.map(Path::getParent).orElse(preferencesService.getFilePreferences().getWorkingDirectory());
}
}
/**
* Opens the given file. If null or 404, nothing happens.
* In case the file is already opened, that panel is raised.
*
* @param file the file, may be null or not existing
*/
public void openFile(Path file) {
openFiles(new ArrayList<>(List.of(file)));
}
/**
* Opens the given files. If one of it is null or 404, nothing happens.
* In case the file is already opened, that panel is raised.
*
* @param filesToOpen the filesToOpen, may be null or not existing
*/
public void openFiles(List<Path> filesToOpen) {
LibraryTab toRaise = null;
int initialCount = filesToOpen.size();
int removed = 0;
// Check if any of the files are already open:
for (Iterator<Path> iterator = filesToOpen.iterator(); iterator.hasNext(); ) {
Path file = iterator.next();
for (int i = 0; i < frame.getTabbedPane().getTabs().size(); i++) {
LibraryTab libraryTab = frame.getLibraryTabAt(i);
if ((libraryTab.getBibDatabaseContext().getDatabasePath().isPresent())
&& libraryTab.getBibDatabaseContext().getDatabasePath().get().equals(file)) {
iterator.remove();
removed++;
// See if we removed the final one. If so, we must perhaps
// raise the LibraryTab in question:
if (removed == initialCount) {
toRaise = libraryTab;
}
// no more LibraryTabs to check, we found a matching one
break;
}
}
}
// Run the actual open in a thread to prevent the program
// locking until the file is loaded.
if (!filesToOpen.isEmpty()) {
FileHistoryMenu fileHistory = frame.getFileHistory();
filesToOpen.forEach(theFile -> {
// This method will execute the concrete file opening and loading in a background thread
openTheFile(theFile);
fileHistory.newFile(theFile);
});
} else if (toRaise != null) {
// If no files are remaining to open, this could mean that a file was
// already open. If so, we may have to raise the correct tab:
frame.showLibraryTab(toRaise);
}
}
/**
* This is the real file opening. Should be called via {@link #openFile(Path)}
*
* @param file the file, may be NOT null, but may not be existing
*/
private void openTheFile(Path file) {
Objects.requireNonNull(file);
if (!Files.exists(file)) {
return;
}
BackgroundTask<ParserResult> backgroundTask = BackgroundTask.wrap(() -> loadDatabase(file));
// The backgroundTask is executed within the method createLibraryTab
LibraryTab newTab = LibraryTab.createLibraryTab(backgroundTask, file, preferencesService, stateManager, frame, fileUpdateMonitor);
backgroundTask.onFinished(() -> trackOpenNewDatabase(newTab));
}
/**
* This method is similar to {@link org.jabref.gui.JabRefGUI#openLastEditedDatabases()}.
* This method also has the capability to open remote shared databases
*/
private ParserResult loadDatabase(Path file) throws Exception {
Path fileToLoad = file.toAbsolutePath();
dialogService.notify(Localization.lang("Opening") + ": '" + file + "'");
preferencesService.getFilePreferences().setWorkingDirectory(fileToLoad.getParent());
Path backupDir = preferencesService.getFilePreferences().getBackupDirectory();
ParserResult parserResult = null;
if (BackupManager.backupFileDiffers(fileToLoad, backupDir)) {
// In case the backup differs, ask the user what to do.
// In case the user opted for restoring a backup, the content of the backup is contained in parserResult.
parserResult = BackupUIManager.showRestoreBackupDialog(dialogService, fileToLoad, preferencesService, fileUpdateMonitor)
.orElse(null);
}
try {
if (parserResult == null) {
// No backup was restored, do the "normal" loading
parserResult = OpenDatabase.loadDatabase(fileToLoad,
preferencesService.getImportFormatPreferences(),
fileUpdateMonitor);
}
if (parserResult.hasWarnings()) {
String content = Localization.lang("Please check your library file for wrong syntax.")
+ "\n\n" + parserResult.getErrorMessage();
DefaultTaskExecutor.runInJavaFXThread(() ->
dialogService.showWarningDialogAndWait(Localization.lang("Open library error"), content));
}
} catch (IOException e) {
parserResult = ParserResult.fromError(e);
LOGGER.error("Error opening file '{}'", fileToLoad, e);
}
if (parserResult.getDatabase().isShared()) {
try {
new SharedDatabaseUIManager(frame, preferencesService, fileUpdateMonitor)
.openSharedDatabaseFromParserResult(parserResult);
} catch (SQLException | DatabaseNotSupportedException | InvalidDBMSConnectionPropertiesException |
NotASharedDatabaseException e) {
parserResult.getDatabaseContext().clearDatabasePath(); // do not open the original file
parserResult.getDatabase().clearSharedDatabaseID();
LOGGER.error("Connection error", e);
throw e;
}
}
return parserResult;
}
private void trackOpenNewDatabase(LibraryTab libraryTab) {
Globals.getTelemetryClient().ifPresent(client -> client.trackEvent(
"OpenNewDatabase",
Map.of(),
Map.of("NumberOfEntries", (double) libraryTab.getBibDatabaseContext().getDatabase().getEntryCount())));
}
}
| 10,720
| 42.404858
| 138
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/importer/fetcher/LookupIdentifierAction.java
|
package org.jabref.gui.importer.fetcher;
import java.util.List;
import java.util.Optional;
import javax.swing.undo.UndoManager;
import org.jabref.gui.Globals;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.Action;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.icon.JabRefIcon;
import org.jabref.gui.keyboard.KeyBinding;
import org.jabref.gui.undo.NamedCompound;
import org.jabref.gui.undo.UndoableFieldChange;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.gui.util.BindingsHelper;
import org.jabref.gui.util.DefaultTaskExecutor;
import org.jabref.logic.importer.FetcherException;
import org.jabref.logic.importer.IdFetcher;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.FieldChange;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.identifier.Identifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.jabref.gui.actions.ActionHelper.needsDatabase;
import static org.jabref.gui.actions.ActionHelper.needsEntriesSelected;
public class LookupIdentifierAction<T extends Identifier> extends SimpleCommand {
private static final Logger LOGGER = LoggerFactory.getLogger(LookupIdentifierAction.class);
private final JabRefFrame frame;
private final IdFetcher<T> fetcher;
private final StateManager stateManager;
private UndoManager undoManager;
public LookupIdentifierAction(JabRefFrame frame, IdFetcher<T> fetcher, StateManager stateManager, UndoManager undoManager) {
this.frame = frame;
this.fetcher = fetcher;
this.stateManager = stateManager;
this.undoManager = undoManager;
this.executable.bind(needsDatabase(this.stateManager).and(needsEntriesSelected(this.stateManager)));
this.statusMessage.bind(BindingsHelper.ifThenElse(executable, "", Localization.lang("This operation requires one or more entries to be selected.")));
}
@Override
public void execute() {
try {
BackgroundTask.wrap(() -> lookupIdentifiers(stateManager.getSelectedEntries()))
.onSuccess(frame.getDialogService()::notify)
.executeWith(Globals.TASK_EXECUTOR);
} catch (Exception e) {
LOGGER.error("Problem running ID Worker", e);
}
}
public Action getAction() {
return new Action() {
@Override
public Optional<JabRefIcon> getIcon() {
return Optional.empty();
}
@Override
public Optional<KeyBinding> getKeyBinding() {
return Optional.empty();
}
@Override
public String getText() {
return fetcher.getIdentifierName();
}
@Override
public String getDescription() {
return "";
}
};
}
private String lookupIdentifiers(List<BibEntry> bibEntries) {
String totalCount = Integer.toString(bibEntries.size());
NamedCompound namedCompound = new NamedCompound(Localization.lang("Look up %0", fetcher.getIdentifierName()));
int count = 0;
int foundCount = 0;
for (BibEntry bibEntry : bibEntries) {
count++;
final String statusMessage = Localization.lang("Looking up %0... - entry %1 out of %2 - found %3",
fetcher.getIdentifierName(), Integer.toString(count), totalCount, Integer.toString(foundCount));
DefaultTaskExecutor.runInJavaFXThread(() -> frame.getDialogService().notify(statusMessage));
Optional<T> identifier = Optional.empty();
try {
identifier = fetcher.findIdentifier(bibEntry);
} catch (FetcherException e) {
LOGGER.error("Could not fetch " + fetcher.getIdentifierName(), e);
}
if (identifier.isPresent() && !bibEntry.hasField(identifier.get().getDefaultField())) {
Optional<FieldChange> fieldChange = bibEntry.setField(identifier.get().getDefaultField(), identifier.get().getNormalized());
if (fieldChange.isPresent()) {
namedCompound.addEdit(new UndoableFieldChange(fieldChange.get()));
foundCount++;
final String nextStatusMessage = Localization.lang("Looking up %0... - entry %1 out of %2 - found %3",
fetcher.getIdentifierName(), Integer.toString(count), totalCount, Integer.toString(foundCount));
DefaultTaskExecutor.runInJavaFXThread(() -> frame.getDialogService().notify(nextStatusMessage));
}
}
}
namedCompound.end();
if (foundCount > 0) {
undoManager.addEdit(namedCompound);
}
return Localization.lang("Determined %0 for %1 entries", fetcher.getIdentifierName(), Integer.toString(foundCount));
}
}
| 4,988
| 39.893443
| 157
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/importer/fetcher/WebSearchPaneView.java
|
package org.jabref.gui.importer.fetcher;
import javafx.css.PseudoClass;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import org.jabref.gui.DialogService;
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.search.SearchTextField;
import org.jabref.gui.util.ViewModelListCellFactory;
import org.jabref.logic.importer.SearchBasedFetcher;
import org.jabref.logic.l10n.Localization;
import org.jabref.preferences.PreferencesService;
import com.tobiasdiez.easybind.EasyBind;
public class WebSearchPaneView extends VBox {
private static final PseudoClass QUERY_INVALID = PseudoClass.getPseudoClass("invalid");
private final WebSearchPaneViewModel viewModel;
private final PreferencesService preferences;
private final DialogService dialogService;
public WebSearchPaneView(PreferencesService preferences, DialogService dialogService, StateManager stateManager) {
this.preferences = preferences;
this.dialogService = dialogService;
this.viewModel = new WebSearchPaneViewModel(preferences, dialogService, stateManager);
initialize();
}
private void initialize() {
ComboBox<SearchBasedFetcher> fetchers = new ComboBox<>();
new ViewModelListCellFactory<SearchBasedFetcher>()
.withText(SearchBasedFetcher::getName)
.install(fetchers);
fetchers.itemsProperty().bind(viewModel.fetchersProperty());
fetchers.valueProperty().bindBidirectional(viewModel.selectedFetcherProperty());
fetchers.setMaxWidth(Double.POSITIVE_INFINITY);
// Create help button for currently selected fetcher
StackPane helpButtonContainer = new StackPane();
ActionFactory factory = new ActionFactory(preferences.getKeyBindingRepository());
EasyBind.subscribe(viewModel.selectedFetcherProperty(), fetcher -> {
if ((fetcher != null) && fetcher.getHelpPage().isPresent()) {
Button helpButton = factory.createIconButton(StandardActions.HELP, new HelpAction(fetcher.getHelpPage().get(), dialogService));
helpButtonContainer.getChildren().setAll(helpButton);
} else {
helpButtonContainer.getChildren().clear();
}
});
HBox fetcherContainer = new HBox(fetchers, helpButtonContainer);
HBox.setHgrow(fetchers, Priority.ALWAYS);
// Create text field for query input
TextField query = SearchTextField.create();
query.getStyleClass().add("searchBar");
viewModel.queryProperty().bind(query.textProperty());
EasyBind.subscribe(viewModel.queryValidationStatus().validProperty(),
valid -> {
if (!valid && viewModel.queryValidationStatus().getHighestMessage().isPresent()) {
query.setTooltip(new Tooltip(viewModel.queryValidationStatus().getHighestMessage().get().getMessage()));
query.pseudoClassStateChanged(QUERY_INVALID, true);
} else {
query.setTooltip(null);
query.pseudoClassStateChanged(QUERY_INVALID, false);
}
});
// Allows triggering search on pressing enter
query.setOnKeyPressed(event -> {
if (event.getCode() == KeyCode.ENTER) {
viewModel.search();
}
});
// Create button that triggers search
Button search = new Button(Localization.lang("Search"));
search.setDefaultButton(false);
search.setOnAction(event -> viewModel.search());
search.setMaxWidth(Double.MAX_VALUE);
getChildren().addAll(fetcherContainer, query, search);
}
}
| 4,128
| 42.010417
| 143
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/importer/fetcher/WebSearchPaneViewModel.java
|
package org.jabref.gui.importer.fetcher;
import java.util.Map;
import java.util.SortedSet;
import java.util.concurrent.Callable;
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 javafx.collections.ObservableList;
import org.jabref.gui.DialogService;
import org.jabref.gui.Globals;
import org.jabref.gui.StateManager;
import org.jabref.gui.importer.ImportEntriesDialog;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.logic.importer.CompositeIdFetcher;
import org.jabref.logic.importer.ParserResult;
import org.jabref.logic.importer.SearchBasedFetcher;
import org.jabref.logic.importer.WebFetchers;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.strings.StringUtil;
import org.jabref.model.util.OptionalUtil;
import org.jabref.preferences.PreferencesService;
import org.jabref.preferences.SidePanePreferences;
import com.tobiasdiez.easybind.EasyBind;
import de.saxsys.mvvmfx.utils.validation.FunctionBasedValidator;
import de.saxsys.mvvmfx.utils.validation.ValidationMessage;
import de.saxsys.mvvmfx.utils.validation.ValidationStatus;
import de.saxsys.mvvmfx.utils.validation.Validator;
import org.apache.lucene.queryparser.flexible.core.QueryNodeParseException;
import org.apache.lucene.queryparser.flexible.core.parser.SyntaxParser;
import org.apache.lucene.queryparser.flexible.standard.parser.ParseException;
import org.apache.lucene.queryparser.flexible.standard.parser.StandardSyntaxParser;
import static org.jabref.logic.importer.fetcher.transformers.AbstractQueryTransformer.NO_EXPLICIT_FIELD;
public class WebSearchPaneViewModel {
private final ObjectProperty<SearchBasedFetcher> selectedFetcher = new SimpleObjectProperty<>();
private final ListProperty<SearchBasedFetcher> fetchers = new SimpleListProperty<>(FXCollections.observableArrayList());
private final StringProperty query = new SimpleStringProperty();
private final DialogService dialogService;
private final PreferencesService preferencesService;
private final StateManager stateManager;
private final Validator searchQueryValidator;
private final SyntaxParser parser = new StandardSyntaxParser();
public WebSearchPaneViewModel(PreferencesService preferencesService, DialogService dialogService, StateManager stateManager) {
this.dialogService = dialogService;
this.stateManager = stateManager;
this.preferencesService = preferencesService;
SortedSet<SearchBasedFetcher> allFetchers = WebFetchers.getSearchBasedFetchers(
preferencesService.getImportFormatPreferences(),
preferencesService.getImporterPreferences());
fetchers.setAll(allFetchers);
// Choose last-selected fetcher as default
SidePanePreferences sidePanePreferences = preferencesService.getSidePanePreferences();
int defaultFetcherIndex = sidePanePreferences.getWebSearchFetcherSelected();
if ((defaultFetcherIndex <= 0) || (defaultFetcherIndex >= fetchers.size())) {
selectedFetcherProperty().setValue(fetchers.get(0));
} else {
selectedFetcherProperty().setValue(fetchers.get(defaultFetcherIndex));
}
EasyBind.subscribe(selectedFetcherProperty(), newFetcher -> {
int newIndex = fetchers.indexOf(newFetcher);
sidePanePreferences.setWebSearchFetcherSelected(newIndex);
});
searchQueryValidator = new FunctionBasedValidator<>(
query,
queryText -> {
if (StringUtil.isBlank(queryText)) {
// in case user did not enter something, it is treated as valid (to avoid UI WTFs)
return null;
}
if (CompositeIdFetcher.containsValidId(queryText)) {
// in case the query contains any ID, it is treated as valid
return null;
}
try {
parser.parse(queryText, NO_EXPLICIT_FIELD);
return null;
} catch (ParseException e) {
String element = e.currentToken.image;
int position = e.currentToken.beginColumn;
if (element == null) {
return ValidationMessage.error(Localization.lang("Invalid query. Check position %0.", position));
} else {
return ValidationMessage.error(Localization.lang("Invalid query element '%0' at position %1", element, position));
}
} catch (QueryNodeParseException e) {
return ValidationMessage.error("");
}
});
}
public ObservableList<SearchBasedFetcher> getFetchers() {
return fetchers.get();
}
public ListProperty<SearchBasedFetcher> fetchersProperty() {
return fetchers;
}
public SearchBasedFetcher getSelectedFetcher() {
return selectedFetcher.get();
}
public ObjectProperty<SearchBasedFetcher> selectedFetcherProperty() {
return selectedFetcher;
}
public String getQuery() {
return query.get();
}
public StringProperty queryProperty() {
return query;
}
public void search() {
String query = getQuery().trim();
if (StringUtil.isBlank(query)) {
dialogService.notify(Localization.lang("Please enter a search string"));
return;
}
if (stateManager.getActiveDatabase().isEmpty()) {
dialogService.notify(Localization.lang("Please open or start a new library before searching"));
return;
}
SearchBasedFetcher activeFetcher = getSelectedFetcher();
Callable<ParserResult> parserResultCallable = () -> new ParserResult(activeFetcher.performSearch(query));
String fetcherName = activeFetcher.getName();
if (CompositeIdFetcher.containsValidId(query)) {
CompositeIdFetcher compositeIdFetcher = new CompositeIdFetcher(preferencesService.getImportFormatPreferences());
parserResultCallable = () -> new ParserResult(OptionalUtil.toList(compositeIdFetcher.performSearchById(query)));
fetcherName = compositeIdFetcher.getName();
}
final String finalFetcherName = fetcherName;
Globals.getTelemetryClient().ifPresent(client ->
client.trackEvent("search", Map.of("fetcher", finalFetcherName), Map.of()));
BackgroundTask<ParserResult> task = BackgroundTask.wrap(parserResultCallable)
.withInitialMessage(Localization.lang("Processing %0", query));
task.onFailure(dialogService::showErrorDialogAndWait);
ImportEntriesDialog dialog = new ImportEntriesDialog(stateManager.getActiveDatabase().get(), task);
dialog.setTitle(finalFetcherName);
dialogService.showCustomDialogAndWait(dialog);
}
public ValidationStatus queryValidationStatus() {
return searchQueryValidator.getValidationStatus();
}
}
| 7,422
| 42.664706
| 142
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/integrity/IntegrityCheckAction.java
|
package org.jabref.gui.integrity;
import java.util.ArrayList;
import java.util.List;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
import org.jabref.gui.DialogService;
import org.jabref.gui.Globals;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.integrity.IntegrityCheck;
import org.jabref.logic.integrity.IntegrityMessage;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import static org.jabref.gui.actions.ActionHelper.needsDatabase;
public class IntegrityCheckAction extends SimpleCommand {
private final TaskExecutor taskExecutor;
private final DialogService dialogService;
private final JabRefFrame frame;
private final StateManager stateManager;
public IntegrityCheckAction(JabRefFrame frame, StateManager stateManager, TaskExecutor taskExecutor) {
this.frame = frame;
this.stateManager = stateManager;
this.taskExecutor = taskExecutor;
this.dialogService = frame.getDialogService();
this.executable.bind(needsDatabase(this.stateManager));
}
@Override
public void execute() {
BibDatabaseContext database = stateManager.getActiveDatabase().orElseThrow(() -> new NullPointerException("Database null"));
IntegrityCheck check = new IntegrityCheck(database,
Globals.prefs.getFilePreferences(),
Globals.prefs.getCitationKeyPatternPreferences(),
Globals.journalAbbreviationRepository,
Globals.prefs.getEntryEditorPreferences().shouldAllowIntegerEditionBibtex());
Task<List<IntegrityMessage>> task = new Task<>() {
@Override
protected List<IntegrityMessage> call() {
List<IntegrityMessage> result = new ArrayList<>();
ObservableList<BibEntry> entries = database.getDatabase().getEntries();
result.addAll(check.checkDatabase(database.getDatabase()));
for (int i = 0; i < entries.size(); i++) {
if (isCancelled()) {
break;
}
BibEntry entry = entries.get(i);
result.addAll(check.checkEntry(entry));
updateProgress(i, entries.size());
}
return result;
}
};
task.setOnSucceeded(value -> {
List<IntegrityMessage> messages = task.getValue();
if (messages.isEmpty()) {
dialogService.notify(Localization.lang("No problems found."));
} else {
dialogService.showCustomDialogAndWait(new IntegrityCheckDialog(messages, frame.getCurrentLibraryTab()));
}
});
task.setOnFailed(event -> dialogService.showErrorDialogAndWait("Integrity check failed.", task.getException()));
dialogService.showProgressDialog(
Localization.lang("Checking integrity..."),
Localization.lang("Checking integrity..."),
task);
taskExecutor.execute(task);
}
}
| 3,276
| 37.552941
| 132
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/integrity/IntegrityCheckDialog.java
|
package org.jabref.gui.integrity;
import java.util.List;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.collections.ListChangeListener;
import javafx.fxml.FXML;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuButton;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.input.MouseButton;
import javafx.stage.Modality;
import org.jabref.gui.LibraryTab;
import org.jabref.gui.theme.ThemeManager;
import org.jabref.gui.util.BaseDialog;
import org.jabref.logic.integrity.IntegrityMessage;
import org.jabref.logic.l10n.Localization;
import com.airhacks.afterburner.views.ViewLoader;
import jakarta.inject.Inject;
import org.controlsfx.control.table.TableFilter;
public class IntegrityCheckDialog extends BaseDialog<Void> {
@FXML private TableView<IntegrityMessage> messagesTable;
@FXML private TableColumn<IntegrityMessage, String> keyColumn;
@FXML private TableColumn<IntegrityMessage, String> fieldColumn;
@FXML private TableColumn<IntegrityMessage, String> messageColumn;
@FXML private MenuButton keyFilterButton;
@FXML private MenuButton fieldFilterButton;
@FXML private MenuButton messageFilterButton;
@Inject private ThemeManager themeManager;
private final List<IntegrityMessage> messages;
private final LibraryTab libraryTab;
private IntegrityCheckDialogViewModel viewModel;
private TableFilter<IntegrityMessage> tableFilter;
public IntegrityCheckDialog(List<IntegrityMessage> messages, LibraryTab libraryTab) {
this.messages = messages;
this.libraryTab = libraryTab;
this.setTitle(Localization.lang("Check integrity"));
this.initModality(Modality.NONE);
ViewLoader.view(this)
.load()
.setAsDialogPane(this);
themeManager.updateFontStyle(getDialogPane().getScene());
}
private void onSelectionChanged(ListChangeListener.Change<? extends IntegrityMessage> change) {
if (change.next()) {
change.getAddedSubList().stream().findFirst().ifPresent(message ->
libraryTab.editEntryAndFocusField(message.getEntry(), message.getField()));
}
}
public IntegrityCheckDialogViewModel getViewModel() {
return viewModel;
}
@FXML
private void initialize() {
viewModel = new IntegrityCheckDialogViewModel(messages);
messagesTable.getSelectionModel().getSelectedItems().addListener(this::onSelectionChanged);
messagesTable.setItems(viewModel.getMessages());
keyColumn.setCellValueFactory(row -> new ReadOnlyStringWrapper(row.getValue().getEntry().getCitationKey().orElse("")));
fieldColumn.setCellValueFactory(row -> new ReadOnlyStringWrapper(row.getValue().getField().getDisplayName()));
messageColumn.setCellValueFactory(row -> new ReadOnlyStringWrapper(row.getValue().getMessage()));
tableFilter = TableFilter.forTableView(messagesTable)
.apply();
tableFilter.getColumnFilter(keyColumn).ifPresent(columnFilter -> {
ContextMenu keyContextMenu = keyColumn.getContextMenu();
if (keyContextMenu != null) {
keyFilterButton.setContextMenu(keyContextMenu);
keyFilterButton.setOnMouseClicked(event -> {
if (event.getButton() == MouseButton.PRIMARY) {
if (keyContextMenu.isShowing()) {
keyContextMenu.setX(event.getScreenX());
keyContextMenu.setY(event.getScreenY());
} else {
keyContextMenu.show(keyFilterButton, event.getScreenX(), event.getScreenY());
}
}
});
}
});
tableFilter.getColumnFilter(fieldColumn).ifPresent(columnFilter -> {
ContextMenu fieldContextMenu = fieldColumn.getContextMenu();
if (fieldContextMenu != null) {
fieldFilterButton.setContextMenu(fieldContextMenu);
fieldFilterButton.setOnMouseClicked(event -> {
if (event.getButton() == MouseButton.PRIMARY) {
if (fieldContextMenu.isShowing()) {
fieldContextMenu.setX(event.getScreenX());
fieldContextMenu.setY(event.getScreenY());
} else {
fieldContextMenu.show(fieldFilterButton, event.getScreenX(), event.getScreenY());
}
}
});
}
});
tableFilter.getColumnFilter(messageColumn).ifPresent(columnFilter -> {
ContextMenu messageContextMenu = messageColumn.getContextMenu();
if (messageContextMenu != null) {
messageFilterButton.setContextMenu(messageContextMenu);
messageFilterButton.setOnMouseClicked(event -> {
if (event.getButton() == MouseButton.PRIMARY) {
if (messageContextMenu.isShowing()) {
messageContextMenu.setX(event.getScreenX());
messageContextMenu.setY(event.getScreenY());
} else {
messageContextMenu.show(messageFilterButton, event.getScreenX(), event.getScreenY());
}
}
});
}
});
}
public void clearFilters() {
if (tableFilter != null) {
tableFilter.resetFilter();
messagesTable.getColumns().forEach(column -> {
tableFilter.selectAllValues(column);
column.setGraphic(null);
});
}
}
}
| 5,852
| 40.510638
| 127
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/integrity/IntegrityCheckDialogViewModel.java
|
package org.jabref.gui.integrity;
import java.util.List;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.jabref.gui.AbstractViewModel;
import org.jabref.logic.integrity.IntegrityMessage;
public class IntegrityCheckDialogViewModel extends AbstractViewModel {
private final ObservableList<IntegrityMessage> messages;
public IntegrityCheckDialogViewModel(List<IntegrityMessage> messages) {
this.messages = FXCollections.observableArrayList(messages);
}
public ObservableList<IntegrityMessage> getMessages() {
return messages;
}
}
| 616
| 25.826087
| 75
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/journals/AbbreviateAction.java
|
package org.jabref.gui.journals;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import org.jabref.gui.DialogService;
import org.jabref.gui.Globals;
import org.jabref.gui.JabRefExecutorService;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.ActionHelper;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.actions.StandardActions;
import org.jabref.gui.undo.NamedCompound;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.logic.journals.JournalAbbreviationPreferences;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.FieldFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Converts journal full names to either iso or medline abbreviations for all selected entries.
*/
public class AbbreviateAction extends SimpleCommand {
private static final Logger LOGGER = LoggerFactory.getLogger(AbbreviateAction.class);
private final StandardActions action;
private final JabRefFrame frame;
private final DialogService dialogService;
private final StateManager stateManager;
private final JournalAbbreviationPreferences journalAbbreviationPreferences;
private AbbreviationType abbreviationType;
public AbbreviateAction(StandardActions action,
JabRefFrame frame,
DialogService dialogService,
StateManager stateManager,
JournalAbbreviationPreferences journalAbbreviationPreferences) {
this.action = action;
this.frame = frame;
this.dialogService = dialogService;
this.stateManager = stateManager;
this.journalAbbreviationPreferences = journalAbbreviationPreferences;
switch (action) {
case ABBREVIATE_DEFAULT -> abbreviationType = AbbreviationType.DEFAULT;
case ABBREVIATE_DOTLESS -> abbreviationType = AbbreviationType.DOTLESS;
case ABBREVIATE_SHORTEST_UNIQUE -> abbreviationType = AbbreviationType.SHORTEST_UNIQUE;
default -> LOGGER.debug("Unknown action: " + action.name());
}
this.executable.bind(ActionHelper.needsEntriesSelected(stateManager));
}
@Override
public void execute() {
if ((action == StandardActions.ABBREVIATE_DEFAULT)
|| (action == StandardActions.ABBREVIATE_DOTLESS)
|| (action == StandardActions.ABBREVIATE_SHORTEST_UNIQUE)) {
dialogService.notify(Localization.lang("Abbreviating..."));
stateManager.getActiveDatabase().ifPresent(databaseContext ->
BackgroundTask.wrap(() -> abbreviate(stateManager.getActiveDatabase().get(), stateManager.getSelectedEntries()))
.onSuccess(dialogService::notify)
.executeWith(Globals.TASK_EXECUTOR));
} else if (action == StandardActions.UNABBREVIATE) {
dialogService.notify(Localization.lang("Unabbreviating..."));
stateManager.getActiveDatabase().ifPresent(databaseContext ->
BackgroundTask.wrap(() -> unabbreviate(stateManager.getActiveDatabase().get(), stateManager.getSelectedEntries()))
.onSuccess(dialogService::notify)
.executeWith(Globals.TASK_EXECUTOR));
} else {
LOGGER.debug("Unknown action: " + action.name());
}
}
private String abbreviate(BibDatabaseContext databaseContext, List<BibEntry> entries) {
UndoableAbbreviator undoableAbbreviator = new UndoableAbbreviator(
Globals.journalAbbreviationRepository,
abbreviationType,
journalAbbreviationPreferences.shouldUseFJournalField());
NamedCompound ce = new NamedCompound(Localization.lang("Abbreviate journal names"));
// Collect all callables to execute in one collection.
Set<Callable<Boolean>> tasks = entries.stream().<Callable<Boolean>>map(entry -> () ->
FieldFactory.getJournalNameFields().stream().anyMatch(journalField ->
undoableAbbreviator.abbreviate(databaseContext.getDatabase(), entry, journalField, ce)))
.collect(Collectors.toSet());
// Execute the callables and wait for the results.
List<Future<Boolean>> futures = JabRefExecutorService.INSTANCE.executeAll(tasks);
// Evaluate the results of the callables.
long count = futures.stream().filter(future -> {
try {
return future.get();
} catch (InterruptedException | ExecutionException exception) {
LOGGER.error("Unable to retrieve value.", exception);
return false;
}
}).count();
if (count > 0) {
ce.end();
frame.getUndoManager().addEdit(ce);
frame.getCurrentLibraryTab().markBaseChanged();
return Localization.lang("Abbreviated %0 journal names.", String.valueOf(count));
}
return Localization.lang("No journal names could be abbreviated.");
}
private String unabbreviate(BibDatabaseContext databaseContext, List<BibEntry> entries) {
UndoableUnabbreviator undoableAbbreviator = new UndoableUnabbreviator(Globals.journalAbbreviationRepository);
NamedCompound ce = new NamedCompound(Localization.lang("Unabbreviate journal names"));
int count = entries.stream().mapToInt(entry ->
(int) FieldFactory.getJournalNameFields().stream().filter(journalField ->
undoableAbbreviator.unabbreviate(databaseContext.getDatabase(), entry, journalField, ce)).count()).sum();
if (count > 0) {
ce.end();
frame.getUndoManager().addEdit(ce);
frame.getCurrentLibraryTab().markBaseChanged();
return Localization.lang("Unabbreviated %0 journal names.", String.valueOf(count));
}
return Localization.lang("No journal names could be unabbreviated.");
}
}
| 6,361
| 45.101449
| 134
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/journals/AbbreviationType.java
|
package org.jabref.gui.journals;
/**
* Defines the different abbreviation types that JabRef can operate with.
*/
public enum AbbreviationType {
DEFAULT,
DOTLESS,
SHORTEST_UNIQUE
}
| 195
| 16.818182
| 73
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/journals/UndoableAbbreviator.java
|
package org.jabref.gui.journals;
import javax.swing.undo.CompoundEdit;
import org.jabref.gui.undo.UndoableFieldChange;
import org.jabref.logic.journals.Abbreviation;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.AMSField;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.StandardField;
public class UndoableAbbreviator {
private final JournalAbbreviationRepository journalAbbreviationRepository;
private final AbbreviationType abbreviationType;
private final boolean useFJournalField;
public UndoableAbbreviator(JournalAbbreviationRepository journalAbbreviationRepository, AbbreviationType abbreviationType, boolean useFJournalField) {
this.journalAbbreviationRepository = journalAbbreviationRepository;
this.abbreviationType = abbreviationType;
this.useFJournalField = useFJournalField;
}
/**
* Abbreviate the journal name of the given entry.
*
* @param database The database the entry belongs to, or null if no database.
* @param entry The entry to be treated.
* @param fieldName The field name (e.g. "journal")
* @param ce If the entry is changed, add an edit to this compound.
* @return true if the entry was changed, false otherwise.
*/
public boolean abbreviate(BibDatabase database, BibEntry entry, Field fieldName, CompoundEdit ce) {
if (!entry.hasField(fieldName)) {
return false;
}
String text = entry.getField(fieldName).get();
String origText = text;
if (database != null) {
text = database.resolveForStrings(text);
}
if (!journalAbbreviationRepository.isKnownName(text)) {
return false; // Unknown, cannot abbreviate anything.
}
Abbreviation abbreviation = journalAbbreviationRepository.get(text).get();
String newText = getAbbreviatedName(abbreviation);
if (newText.equals(origText)) {
return false;
}
// Store full name into fjournal but only if it exists
if (useFJournalField && (StandardField.JOURNAL == fieldName || StandardField.JOURNALTITLE == fieldName)) {
entry.setField(AMSField.FJOURNAL, abbreviation.getName());
ce.addEdit(new UndoableFieldChange(entry, AMSField.FJOURNAL, null, abbreviation.getName()));
}
entry.setField(fieldName, newText);
ce.addEdit(new UndoableFieldChange(entry, fieldName, origText, newText));
return true;
}
private String getAbbreviatedName(Abbreviation text) {
switch (abbreviationType) {
case DEFAULT:
return text.getAbbreviation();
case DOTLESS:
return text.getDotlessAbbreviation();
case SHORTEST_UNIQUE:
return text.getShortestUniqueAbbreviation();
default:
throw new IllegalStateException(String.format("Unexpected value: %s", abbreviationType));
}
}
}
| 3,152
| 37.925926
| 154
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/journals/UndoableUnabbreviator.java
|
package org.jabref.gui.journals;
import javax.swing.undo.CompoundEdit;
import org.jabref.gui.undo.UndoableFieldChange;
import org.jabref.logic.journals.Abbreviation;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.AMSField;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.StandardField;
public class UndoableUnabbreviator {
private final JournalAbbreviationRepository journalAbbreviationRepository;
public UndoableUnabbreviator(JournalAbbreviationRepository journalAbbreviationRepository) {
this.journalAbbreviationRepository = journalAbbreviationRepository;
}
/**
* Unabbreviate the journal name of the given entry.
*
* @param entry The entry to be treated.
* @param field The field
* @param ce If the entry is changed, add an edit to this compound.
* @return true if the entry was changed, false otherwise.
*/
public boolean unabbreviate(BibDatabase database, BibEntry entry, Field field, CompoundEdit ce) {
if (!entry.hasField(field)) {
return false;
}
if (restoreFromFJournal(entry, field, ce)) {
return true;
}
String text = entry.getLatexFreeField(field).get();
String origText = text;
if (database != null) {
text = database.resolveForStrings(text);
}
if (!journalAbbreviationRepository.isKnownName(text)) {
return false; // Cannot do anything if it is not known.
}
if (!journalAbbreviationRepository.isAbbreviatedName(text)) {
return false; // Cannot unabbreviate unabbreviated name.
}
Abbreviation abbreviation = journalAbbreviationRepository.get(text).get();
String newText = abbreviation.getName();
entry.setField(field, newText);
ce.addEdit(new UndoableFieldChange(entry, field, origText, newText));
return true;
}
public boolean restoreFromFJournal(BibEntry entry, Field field, CompoundEdit ce) {
if ((StandardField.JOURNAL != field && StandardField.JOURNALTITLE != field) || !entry.hasField(AMSField.FJOURNAL)) {
return false;
}
String origText = entry.getField(field).get();
String newText = entry.getField(AMSField.FJOURNAL).get().trim();
entry.setField(AMSField.FJOURNAL, "");
ce.addEdit(new UndoableFieldChange(entry, AMSField.FJOURNAL, newText, ""));
entry.setField(field, newText);
ce.addEdit(new UndoableFieldChange(entry, field, origText, newText));
return true;
}
}
| 2,732
| 34.493506
| 124
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/keyboard/CodeAreaKeyBindings.java
|
package org.jabref.gui.keyboard;
import javafx.scene.input.KeyEvent;
import org.jabref.logic.util.strings.StringManipulator;
import org.jabref.model.util.ResultingStringState;
import org.fxmisc.richtext.CodeArea;
import org.fxmisc.richtext.NavigationActions;
public class CodeAreaKeyBindings {
public static void call(CodeArea codeArea, KeyEvent event, KeyBindingRepository keyBindingRepository) {
keyBindingRepository.mapToKeyBinding(event).ifPresent(binding -> {
switch (binding) {
case EDITOR_DELETE -> {
codeArea.deleteNextChar();
event.consume();
}
case EDITOR_BACKWARD -> {
codeArea.previousChar(NavigationActions.SelectionPolicy.CLEAR);
event.consume();
}
case EDITOR_FORWARD -> {
codeArea.nextChar(NavigationActions.SelectionPolicy.CLEAR);
event.consume();
}
case EDITOR_WORD_BACKWARD -> {
codeArea.wordBreaksBackwards(2, NavigationActions.SelectionPolicy.CLEAR);
event.consume();
}
case EDITOR_WORD_FORWARD -> {
codeArea.wordBreaksForwards(2, NavigationActions.SelectionPolicy.CLEAR);
event.consume();
}
case EDITOR_BEGINNING_DOC -> {
codeArea.start(NavigationActions.SelectionPolicy.CLEAR);
event.consume();
}
case EDITOR_UP -> {
codeArea.paragraphStart(NavigationActions.SelectionPolicy.CLEAR);
event.consume();
}
case EDITOR_BEGINNING -> {
codeArea.lineStart(NavigationActions.SelectionPolicy.CLEAR);
event.consume();
}
case EDITOR_END_DOC -> {
codeArea.end(NavigationActions.SelectionPolicy.CLEAR);
event.consume();
}
case EDITOR_DOWN -> {
codeArea.paragraphEnd(NavigationActions.SelectionPolicy.CLEAR);
event.consume();
}
case EDITOR_END -> {
codeArea.lineEnd(NavigationActions.SelectionPolicy.CLEAR);
event.consume();
}
case EDITOR_CAPITALIZE -> {
int pos = codeArea.getCaretPosition();
String text = codeArea.getText(0, codeArea.getText().length());
ResultingStringState res = StringManipulator.capitalize(pos, text);
codeArea.replaceText(res.text);
codeArea.displaceCaret(res.caretPosition);
event.consume();
}
case EDITOR_LOWERCASE -> {
int pos = codeArea.getCaretPosition();
String text = codeArea.getText(0, codeArea.getText().length());
ResultingStringState res = StringManipulator.lowercase(pos, text);
codeArea.replaceText(res.text);
codeArea.displaceCaret(res.caretPosition);
event.consume();
}
case EDITOR_UPPERCASE -> {
int pos = codeArea.getCaretPosition();
String text = codeArea.getText(0, codeArea.getText().length());
ResultingStringState res = StringManipulator.uppercase(pos, text);
codeArea.clear();
codeArea.replaceText(res.text);
codeArea.displaceCaret(res.caretPosition);
event.consume();
}
case EDITOR_KILL_LINE -> {
int pos = codeArea.getCaretPosition();
codeArea.replaceText(codeArea.getText(0, pos));
codeArea.displaceCaret(pos);
event.consume();
}
case EDITOR_KILL_WORD -> {
int pos = codeArea.getCaretPosition();
String text = codeArea.getText(0, codeArea.getText().length());
ResultingStringState res = StringManipulator.killWord(pos, text);
codeArea.replaceText(res.text);
codeArea.displaceCaret(res.caretPosition);
event.consume();
}
case EDITOR_KILL_WORD_BACKWARD -> {
int pos = codeArea.getCaretPosition();
String text = codeArea.getText(0, codeArea.getText().length());
ResultingStringState res = StringManipulator.backwardKillWord(pos, text);
codeArea.replaceText(res.text);
codeArea.displaceCaret(res.caretPosition);
event.consume();
}
}
});
}
}
| 5,035
| 43.964286
| 107
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/keyboard/KeyBinding.java
|
package org.jabref.gui.keyboard;
import org.jabref.logic.l10n.Localization;
public enum KeyBinding {
EDITOR_DELETE("Delete", Localization.lang("Delete text"), "", KeyBindingCategory.EDITOR),
// DELETE BACKWARDS = Rubout
EDITOR_BACKWARD("Move caret left", Localization.lang("Move caret left"), "", KeyBindingCategory.EDITOR),
EDITOR_FORWARD("Move caret right", Localization.lang("Move caret right"), "", KeyBindingCategory.EDITOR),
EDITOR_WORD_BACKWARD("Move caret to previous word", Localization.lang("Move caret to previous word"), "", KeyBindingCategory.EDITOR),
EDITOR_WORD_FORWARD("Move caret to next word", Localization.lang("Move caret to next word"), "", KeyBindingCategory.EDITOR),
EDITOR_BEGINNING("Move caret to beginning of line", Localization.lang("Move caret to beginning of line"), "", KeyBindingCategory.EDITOR),
EDITOR_END("Move caret to of line", Localization.lang("Move caret to end of line"), "", KeyBindingCategory.EDITOR),
EDITOR_BEGINNING_DOC("Move caret to beginning of text", Localization.lang("Move the caret to the beginning of text"), "", KeyBindingCategory.EDITOR),
EDITOR_END_DOC("Move caret to end of text", Localization.lang("Move the caret to the end of text"), "", KeyBindingCategory.EDITOR),
EDITOR_UP("Move caret up", Localization.lang("Move the caret up"), "", KeyBindingCategory.EDITOR),
EDITOR_DOWN("Move caret down", Localization.lang("Move the caret down"), "", KeyBindingCategory.EDITOR),
EDITOR_CAPITALIZE("Capitalize word", Localization.lang("Capitalize current word"), "", KeyBindingCategory.EDITOR),
EDITOR_LOWERCASE("Lowercase word", Localization.lang("Make current word lowercase"), "", KeyBindingCategory.EDITOR),
EDITOR_UPPERCASE("Uppercase word", Localization.lang("Make current word uppercase"), "", KeyBindingCategory.EDITOR),
EDITOR_KILL_LINE("Remove all characters caret to end of line", Localization.lang("Remove line after caret"), "", KeyBindingCategory.EDITOR),
EDITOR_KILL_WORD("Remove characters until next word", Localization.lang("Remove characters until next word"), "", KeyBindingCategory.EDITOR),
EDITOR_KILL_WORD_BACKWARD("Characters until previous word", Localization.lang("Remove the current word backwards"), "", KeyBindingCategory.EDITOR),
ABBREVIATE("Abbreviate", Localization.lang("Abbreviate journal names"), "ctrl+alt+A", KeyBindingCategory.TOOLS),
AUTOGENERATE_CITATION_KEYS("Autogenerate citation keys", Localization.lang("Autogenerate citation keys"), "ctrl+G", KeyBindingCategory.QUALITY),
ACCEPT("Accept", Localization.lang("Accept"), "ctrl+ENTER", KeyBindingCategory.EDIT),
AUTOMATICALLY_LINK_FILES("Automatically link files", Localization.lang("Automatically set file links"), "F7", KeyBindingCategory.QUALITY),
CHECK_INTEGRITY("Check integrity", Localization.lang("Check integrity"), "ctrl+F8", KeyBindingCategory.QUALITY),
CLEANUP("Cleanup", Localization.lang("Cleanup entries"), "alt+F8", KeyBindingCategory.QUALITY),
CLOSE_DATABASE("Close library", Localization.lang("Close library"), "ctrl+W", KeyBindingCategory.FILE),
CLOSE("Close dialog", Localization.lang("Close dialog"), "Esc", KeyBindingCategory.VIEW),
COPY("Copy", Localization.lang("Copy"), "ctrl+C", KeyBindingCategory.EDIT),
COPY_TITLE("Copy title", Localization.lang("Copy title"), "ctrl+shift+alt+T", KeyBindingCategory.EDIT),
COPY_CITE_CITATION_KEY("Copy \\cite{citation key}", Localization.lang("Copy \\cite{citation key}"), "ctrl+K", KeyBindingCategory.EDIT),
COPY_CITATION_KEY("Copy citation key", Localization.lang("Copy citation key"), "ctrl+shift+K", KeyBindingCategory.EDIT),
COPY_CITATION_KEY_AND_TITLE("Copy citation key and title", Localization.lang("Copy citation key and title"), "ctrl+shift+alt+K", KeyBindingCategory.EDIT),
COPY_CITATION_KEY_AND_LINK("Copy citation key and link", Localization.lang("Copy citation key and link"), "ctrl+alt+K", KeyBindingCategory.EDIT),
COPY_PREVIEW("Copy preview", Localization.lang("Copy preview"), "ctrl+shift+C", KeyBindingCategory.VIEW),
CUT("Cut", Localization.lang("Cut"), "ctrl+X", KeyBindingCategory.EDIT),
// We have to put Entry Editor Previous before, because otherwise the decrease font size is found first
ENTRY_EDITOR_PREVIOUS_PANEL_2("Entry editor, previous panel 2", Localization.lang("Entry editor, previous panel 2"), "ctrl+MINUS", KeyBindingCategory.VIEW),
DELETE_ENTRY("Delete entry", Localization.lang("Delete entry"), "DELETE", KeyBindingCategory.BIBTEX),
DEFAULT_DIALOG_ACTION("Execute default action in dialog", Localization.lang("Execute default action in dialog"), "ctrl+ENTER", KeyBindingCategory.VIEW),
DOWNLOAD_FULL_TEXT("Download full text documents", Localization.lang("Download full text documents"), "alt+F7", KeyBindingCategory.QUALITY),
EDIT_ENTRY("Open / close entry editor", Localization.lang("Open / close entry editor"), "ctrl+E", KeyBindingCategory.VIEW),
EXPORT("Export", Localization.lang("Export"), "ctrl+alt+e", KeyBindingCategory.FILE),
EXPORT_SELECTED("Export Selected", Localization.lang("Export selected entries"), "ctrl+shift+e", KeyBindingCategory.FILE),
EDIT_STRINGS("Edit strings", Localization.lang("Edit strings"), "ctrl+T", KeyBindingCategory.BIBTEX),
ENTRY_EDITOR_NEXT_ENTRY("Entry editor, next entry", Localization.lang("Entry editor, next entry"), "alt+DOWN", KeyBindingCategory.VIEW),
ENTRY_EDITOR_NEXT_PANEL("Entry editor, next panel", Localization.lang("Entry editor, next panel"), "ctrl+TAB", KeyBindingCategory.VIEW),
ENTRY_EDITOR_NEXT_PANEL_2("Entry editor, next panel 2", Localization.lang("Entry editor, next panel 2"), "ctrl+PLUS", KeyBindingCategory.VIEW),
ENTRY_EDITOR_PREVIOUS_ENTRY("Entry editor, previous entry", Localization.lang("Entry editor, previous entry"), "alt+UP", KeyBindingCategory.VIEW),
ENTRY_EDITOR_PREVIOUS_PANEL("Entry editor, previous panel", Localization.lang("Entry editor, previous panel"), "ctrl+shift+TAB", KeyBindingCategory.VIEW),
FILE_LIST_EDITOR_MOVE_ENTRY_DOWN("File list editor, move entry down", Localization.lang("File list editor, move entry down"), "ctrl+DOWN", KeyBindingCategory.VIEW),
FILE_LIST_EDITOR_MOVE_ENTRY_UP("File list editor, move entry up", Localization.lang("File list editor, move entry up"), "ctrl+UP", KeyBindingCategory.VIEW),
FIND_UNLINKED_FILES("Search for unlinked local files", Localization.lang("Search for unlinked local files"), "shift+F7", KeyBindingCategory.QUALITY),
FOCUS_ENTRY_TABLE("Focus entry table", Localization.lang("Focus entry table"), "alt+1", KeyBindingCategory.VIEW),
FOCUS_GROUP_LIST("Focus group list", Localization.lang("Focus group list"), "alt+s", KeyBindingCategory.VIEW),
HELP("Help", Localization.lang("Help"), "F1", KeyBindingCategory.FILE),
IMPORT_INTO_CURRENT_DATABASE("Import into current library", Localization.lang("Import into current library"), "ctrl+I", KeyBindingCategory.FILE),
IMPORT_INTO_NEW_DATABASE("Import into new library", Localization.lang("Import into new library"), "ctrl+alt+I", KeyBindingCategory.FILE),
MERGE_ENTRIES("Merge entries", Localization.lang("Merge entries"), "ctrl+M", KeyBindingCategory.TOOLS),
NEW_ARTICLE("New article", Localization.lang("New article"), "ctrl+shift+A", KeyBindingCategory.BIBTEX),
NEW_BOOK("New book", Localization.lang("New book"), "ctrl+shift+B", KeyBindingCategory.BIBTEX),
NEW_ENTRY("New entry", Localization.lang("New entry"), "ctrl+N", KeyBindingCategory.BIBTEX),
NEW_ENTRY_FROM_PLAIN_TEXT("New entry from plain text", Localization.lang("New entry from plain text"), "ctrl+shift+N", KeyBindingCategory.BIBTEX),
NEW_INBOOK("New inbook", Localization.lang("New inbook"), "ctrl+shift+I", KeyBindingCategory.BIBTEX),
NEW_MASTERSTHESIS("New mastersthesis", Localization.lang("New mastersthesis"), "ctrl+shift+M", KeyBindingCategory.BIBTEX),
NEW_PHDTHESIS("New phdthesis", Localization.lang("New phdthesis"), "ctrl+shift+T", KeyBindingCategory.BIBTEX),
NEW_PROCEEDINGS("New proceedings", Localization.lang("New proceedings"), "ctrl+shift+P", KeyBindingCategory.BIBTEX),
NEW_UNPUBLISHED("New unpublished", Localization.lang("New unpublished"), "ctrl+shift+U", KeyBindingCategory.BIBTEX),
NEW_TECHREPORT("New technical report", Localization.lang("New technical report"), "", KeyBindingCategory.BIBTEX),
NEW_INPROCEEDINGS("New inproceesings", Localization.lang("New inproceedings"), "", KeyBindingCategory.BIBTEX),
NEXT_PREVIEW_LAYOUT("Next preview layout", Localization.lang("Next preview layout"), "F9", KeyBindingCategory.VIEW),
NEXT_LIBRARY("Next library", Localization.lang("Next library"), "ctrl+PAGE_DOWN", KeyBindingCategory.VIEW),
OPEN_CONSOLE("Open terminal here", Localization.lang("Open terminal here"), "ctrl+shift+L", KeyBindingCategory.TOOLS),
OPEN_DATABASE("Open library", Localization.lang("Open library"), "ctrl+O", KeyBindingCategory.FILE),
OPEN_FILE("Open file", Localization.lang("Open file"), "F4", KeyBindingCategory.TOOLS),
OPEN_FOLDER("Open folder", Localization.lang("Open folder"), "ctrl+shift+O", KeyBindingCategory.TOOLS),
OPEN_OPEN_OFFICE_LIBRE_OFFICE_CONNECTION("Open OpenOffice/LibreOffice connection", Localization.lang("Open OpenOffice/LibreOffice connection"), "alt+0", KeyBindingCategory.TOOLS),
OPEN_URL_OR_DOI("Open URL or DOI", Localization.lang("Open URL or DOI"), "F3", KeyBindingCategory.TOOLS),
PASTE("Paste", Localization.lang("Paste"), "ctrl+V", KeyBindingCategory.EDIT),
PULL_CHANGES_FROM_SHARED_DATABASE("Pull changes from shared database", Localization.lang("Pull changes from shared database"), "ctrl+shift+R", KeyBindingCategory.FILE),
PREVIOUS_PREVIEW_LAYOUT("Previous preview layout", Localization.lang("Previous preview layout"), "shift+F9", KeyBindingCategory.VIEW),
PREVIOUS_LIBRARY("Previous library", Localization.lang("Previous library"), "ctrl+PAGE_UP", KeyBindingCategory.VIEW),
PUSH_TO_APPLICATION("Push to application", Localization.lang("Push to application"), "ctrl+L", KeyBindingCategory.TOOLS),
QUIT_JABREF("Quit JabRef", Localization.lang("Quit JabRef"), "ctrl+Q", KeyBindingCategory.FILE),
REDO("Redo", Localization.lang("Redo"), "ctrl+Y", KeyBindingCategory.EDIT),
REFRESH_OO("Refresh OO", Localization.lang("Refresh OpenOffice/LibreOffice"), "ctrl+alt+O", KeyBindingCategory.TOOLS),
REPLACE_STRING("Replace string", Localization.lang("Replace string"), "ctrl+R", KeyBindingCategory.SEARCH),
RESOLVE_DUPLICATE_CITATION_KEYS("Resolve duplicate citation keys", Localization.lang("Resolve duplicate citation keys"), "ctrl+shift+D", KeyBindingCategory.BIBTEX),
SAVE_ALL("Save all", Localization.lang("Save all"), "ctrl+alt+S", KeyBindingCategory.FILE),
SAVE_DATABASE("Save library", Localization.lang("Save library"), "ctrl+S", KeyBindingCategory.FILE),
SAVE_DATABASE_AS("Save library as ...", Localization.lang("Save library as..."), "ctrl+shift+S", KeyBindingCategory.FILE),
SEARCH("Search", Localization.lang("Search"), "ctrl+F", KeyBindingCategory.SEARCH),
SELECT_ALL("Select all", Localization.lang("Select all"), "ctrl+A", KeyBindingCategory.EDIT),
SELECT_FIRST_ENTRY("Select first entry", Localization.lang("Select first entry"), "HOME", KeyBindingCategory.EDIT),
SELECT_LAST_ENTRY("Select last entry", Localization.lang("Select last entry"), "END", KeyBindingCategory.EDIT),
STRING_DIALOG_ADD_STRING("String dialog, add string", Localization.lang("String dialog, add string"), "ctrl+N", KeyBindingCategory.FILE),
STRING_DIALOG_REMOVE_STRING("String dialog, remove string", Localization.lang("String dialog, remove string"), "shift+DELETE", KeyBindingCategory.FILE),
SYNCHRONIZE_FILES("Synchronize files", Localization.lang("Synchronize files"), "ctrl+shift+F7", KeyBindingCategory.QUALITY),
TOGGLE_GROUPS_INTERFACE("Toggle groups interface", Localization.lang("Toggle groups interface"), "alt+3", KeyBindingCategory.VIEW),
UNABBREVIATE("Unabbreviate", Localization.lang("Unabbreviate"), "ctrl+alt+shift+A", KeyBindingCategory.TOOLS),
UNDO("Undo", Localization.lang("Undo"), "ctrl+Z", KeyBindingCategory.EDIT),
WEB_SEARCH("Web search", Localization.lang("Web search"), "alt+4", KeyBindingCategory.SEARCH),
WRITE_METADATA_TO_PDF("Write metadata to PDF files", Localization.lang("Write metadata to PDF files"), "F6", KeyBindingCategory.TOOLS),
CLEAR_SEARCH("Clear search", Localization.lang("Clear search"), "ESCAPE", KeyBindingCategory.SEARCH),
CLEAR_READ_STATUS("Clear read status", Localization.lang("Clear read status"), "", KeyBindingCategory.EDIT),
READ("Set read status to read", Localization.lang("Set read status to read"), "", KeyBindingCategory.EDIT),
SKIMMED("Set read status to skimmed", Localization.lang("Set read status to skimmed"), "", KeyBindingCategory.EDIT);
private final String constant;
private final String localization;
private final String defaultBinding;
private final KeyBindingCategory category;
KeyBinding(String constantName, String localization, String defaultKeyBinding, KeyBindingCategory category) {
this.constant = constantName;
this.localization = localization;
this.defaultBinding = defaultKeyBinding;
this.category = category;
}
/**
* This method returns the enum constant value
*/
public String getConstant() {
return constant;
}
public String getLocalization() {
return localization;
}
/**
* This method returns the default key binding, the key(s) which are assigned
*
* @return The default key binding
*/
public String getDefaultKeyBinding() {
return defaultBinding;
}
public KeyBindingCategory getCategory() {
return category;
}
}
| 13,838
| 90.649007
| 183
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/keyboard/KeyBindingCategory.java
|
package org.jabref.gui.keyboard;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabaseMode;
public enum KeyBindingCategory {
FILE(Localization.lang("File")),
EDIT(Localization.lang("Edit")),
SEARCH(Localization.lang("Search")),
VIEW(Localization.lang("View")),
BIBTEX(BibDatabaseMode.BIBTEX.getFormattedName()),
QUALITY(Localization.lang("Quality")),
TOOLS(Localization.lang("Tools")),
EDITOR(Localization.lang("Text editor"));
private final String name;
KeyBindingCategory(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
| 660
| 23.481481
| 54
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/keyboard/KeyBindingRepository.java
|
package org.jabref.gui.keyboard;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.stream.Collectors;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyEvent;
import org.jabref.logic.util.OS;
public class KeyBindingRepository {
/**
* sorted by localization
*/
private final SortedMap<KeyBinding, String> bindings;
public KeyBindingRepository() {
this(Collections.emptyList(), Collections.emptyList());
}
public KeyBindingRepository(SortedMap<KeyBinding, String> bindings) {
this.bindings = bindings;
}
public KeyBindingRepository(List<String> bindNames, List<String> bindings) {
this.bindings = new TreeMap<>(Comparator.comparing(KeyBinding::getLocalization));
if ((bindNames.isEmpty()) || (bindings.isEmpty()) || (bindNames.size() != bindings.size())) {
// Use default key bindings
for (KeyBinding keyBinding : KeyBinding.values()) {
put(keyBinding, keyBinding.getDefaultKeyBinding());
}
} else {
for (int i = 0; i < bindNames.size(); i++) {
put(bindNames.get(i), bindings.get(i));
}
}
}
/**
* Check if the given keyCombination equals the given keyEvent
*
* @param combination as KeyCombination
* @param keyEvent as KeEvent
* @return true if matching, else false
*/
public static boolean checkKeyCombinationEquality(KeyCombination combination, KeyEvent keyEvent) {
KeyCode code = keyEvent.getCode();
if (code == KeyCode.UNDEFINED) {
return false;
}
return combination.match(keyEvent);
}
public Optional<String> get(KeyBinding key) {
return Optional.ofNullable(bindings.get(key));
}
public String get(String key) {
Optional<KeyBinding> keyBinding = getKeyBinding(key);
Optional<String> result = keyBinding.flatMap(k -> Optional.ofNullable(bindings.get(k)));
if (result.isPresent()) {
return result.get();
} else if (keyBinding.isPresent()) {
return keyBinding.get().getDefaultKeyBinding();
} else {
return "Not associated";
}
}
/**
* Returns the HashMap containing all key bindings.
*/
public SortedMap<KeyBinding, String> getKeyBindings() {
return new TreeMap<>(bindings);
}
public void put(KeyBinding key, String value) {
bindings.put(key, value);
}
public void put(String key, String value) {
getKeyBinding(key).ifPresent(binding -> put(binding, value));
}
private Optional<KeyBinding> getKeyBinding(String key) {
return Arrays.stream(KeyBinding.values()).filter(b -> b.getConstant().equals(key)).findFirst();
}
public void resetToDefault(String key) {
getKeyBinding(key).ifPresent(b -> bindings.put(b, b.getDefaultKeyBinding()));
}
public void resetToDefault() {
bindings.forEach((b, s) -> bindings.put(b, b.getDefaultKeyBinding()));
}
public int size() {
return this.bindings.size();
}
public Optional<KeyBinding> mapToKeyBinding(KeyEvent keyEvent) {
for (KeyBinding binding : KeyBinding.values()) {
if (checkKeyCombinationEquality(binding, keyEvent)) {
return Optional.of(binding);
}
}
return Optional.empty();
}
public Optional<KeyCombination> getKeyCombination(KeyBinding bindName) {
String binding = get(bindName.getConstant());
if (binding.isEmpty()) {
return Optional.empty();
}
if (OS.OS_X) {
binding = binding.replace("ctrl", "meta");
}
return Optional.of(KeyCombination.valueOf(binding));
}
/**
* Check if the given KeyBinding equals the given keyEvent
*
* @param binding as KeyBinding
* @param keyEvent as KeEvent
* @return true if matching, else false
*/
public boolean checkKeyCombinationEquality(KeyBinding binding, KeyEvent keyEvent) {
return getKeyCombination(binding).filter(combination -> checkKeyCombinationEquality(combination, keyEvent))
.isPresent();
}
public List<String> getBindNames() {
return bindings.keySet().stream().map(KeyBinding::getConstant).collect(Collectors.toList());
}
public List<String> getBindings() {
return new ArrayList<>(bindings.values());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
KeyBindingRepository that = (KeyBindingRepository) o;
return bindings.equals(that.bindings);
}
@Override
public int hashCode() {
return bindings.hashCode();
}
}
| 5,146
| 28.924419
| 115
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/keyboard/TextInputKeyBindings.java
|
package org.jabref.gui.keyboard;
import javafx.scene.Scene;
import javafx.scene.control.TextInputControl;
import javafx.scene.input.KeyEvent;
import org.jabref.gui.Globals;
import org.jabref.logic.util.strings.StringManipulator;
import org.jabref.model.util.ResultingStringState;
public class TextInputKeyBindings {
public static void call(Scene scene, KeyEvent event) {
if (scene.focusOwnerProperty().get() instanceof TextInputControl) {
KeyBindingRepository keyBindingRepository = Globals.getKeyPrefs();
TextInputControl focusedTextField = (TextInputControl) scene.focusOwnerProperty().get();
keyBindingRepository.mapToKeyBinding(event).ifPresent(binding -> {
switch (binding) {
case EDITOR_DELETE -> {
focusedTextField.deleteNextChar();
event.consume();
}
case EDITOR_BACKWARD -> {
focusedTextField.backward();
event.consume();
}
case EDITOR_FORWARD -> {
focusedTextField.forward();
event.consume();
}
case EDITOR_WORD_BACKWARD -> {
focusedTextField.previousWord();
event.consume();
}
case EDITOR_WORD_FORWARD -> {
focusedTextField.nextWord();
event.consume();
}
case EDITOR_BEGINNING, EDITOR_UP, EDITOR_BEGINNING_DOC -> {
focusedTextField.home();
event.consume();
}
case EDITOR_END, EDITOR_DOWN, EDITOR_END_DOC -> {
focusedTextField.end();
event.consume();
}
case EDITOR_CAPITALIZE -> {
int pos = focusedTextField.getCaretPosition();
String text = focusedTextField.getText(0, focusedTextField.getText().length());
ResultingStringState res = StringManipulator.capitalize(pos, text);
focusedTextField.setText(res.text);
focusedTextField.positionCaret(res.caretPosition);
event.consume();
}
case EDITOR_LOWERCASE -> {
int pos = focusedTextField.getCaretPosition();
String text = focusedTextField.getText(0, focusedTextField.getText().length());
ResultingStringState res = StringManipulator.lowercase(pos, text);
focusedTextField.setText(res.text);
focusedTextField.positionCaret(res.caretPosition);
event.consume();
}
case EDITOR_UPPERCASE -> {
int pos = focusedTextField.getCaretPosition();
String text = focusedTextField.getText(0, focusedTextField.getText().length());
ResultingStringState res = StringManipulator.uppercase(pos, text);
focusedTextField.setText(res.text);
focusedTextField.positionCaret(res.caretPosition);
event.consume();
}
case EDITOR_KILL_LINE -> {
int pos = focusedTextField.getCaretPosition();
focusedTextField.setText(focusedTextField.getText(0, pos));
focusedTextField.positionCaret(pos);
event.consume();
}
case EDITOR_KILL_WORD -> {
int pos = focusedTextField.getCaretPosition();
String text = focusedTextField.getText(0, focusedTextField.getText().length());
ResultingStringState res = StringManipulator.killWord(pos, text);
focusedTextField.setText(res.text);
focusedTextField.positionCaret(res.caretPosition);
event.consume();
}
case EDITOR_KILL_WORD_BACKWARD -> {
int pos = focusedTextField.getCaretPosition();
String text = focusedTextField.getText(0, focusedTextField.getText().length());
ResultingStringState res = StringManipulator.backwardKillWord(pos, text);
focusedTextField.setText(res.text);
focusedTextField.positionCaret(res.caretPosition);
event.consume();
}
case CLOSE -> {
focusedTextField.clear();
event.consume();
}
}
});
}
}
}
| 5,046
| 48.480392
| 103
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/libraryproperties/AbstractPropertiesTabView.java
|
package org.jabref.gui.libraryproperties;
import javafx.scene.Node;
import javafx.scene.layout.VBox;
import org.jabref.gui.DialogService;
import org.jabref.model.database.BibDatabaseContext;
import jakarta.inject.Inject;
public abstract class AbstractPropertiesTabView<T extends PropertiesTabViewModel> extends VBox implements PropertiesTab {
@Inject protected DialogService dialogService;
protected BibDatabaseContext databaseContext;
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();
}
}
| 830
| 20.868421
| 121
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/libraryproperties/LibraryPropertiesAction.java
|
package org.jabref.gui.libraryproperties;
import java.util.function.Supplier;
import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.model.database.BibDatabaseContext;
import com.airhacks.afterburner.injection.Injector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.jabref.gui.actions.ActionHelper.needsDatabase;
public class LibraryPropertiesAction extends SimpleCommand {
private static final Logger LOGGER = LoggerFactory.getLogger(LibraryPropertiesAction.class);
private final StateManager stateManager;
private final Supplier<BibDatabaseContext> alternateDatabase;
public LibraryPropertiesAction(StateManager stateManager) {
this(null, stateManager);
this.executable.bind(needsDatabase(stateManager));
}
public LibraryPropertiesAction(Supplier<BibDatabaseContext> databaseContext, StateManager stateManager) {
this.stateManager = stateManager;
this.alternateDatabase = databaseContext;
}
@Override
public void execute() {
DialogService dialogService = Injector.instantiateModelOrService(DialogService.class);
if (alternateDatabase != null) {
dialogService.showCustomDialogAndWait(new LibraryPropertiesView(alternateDatabase.get()));
} else {
if (stateManager.getActiveDatabase().isPresent()) {
dialogService.showCustomDialogAndWait(new LibraryPropertiesView(stateManager.getActiveDatabase().get()));
} else {
LOGGER.warn("No database selected.");
}
}
}
}
| 1,664
| 34.425532
| 121
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/libraryproperties/LibraryPropertiesView.java
|
package org.jabref.gui.libraryproperties;
import javafx.fxml.FXML;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import org.jabref.gui.theme.ThemeManager;
import org.jabref.gui.util.BaseDialog;
import org.jabref.gui.util.ControlHelper;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabaseContext;
import com.airhacks.afterburner.views.ViewLoader;
import jakarta.inject.Inject;
public class LibraryPropertiesView extends BaseDialog<LibraryPropertiesViewModel> {
@FXML private TabPane tabPane;
@FXML private ButtonType saveButton;
@Inject private ThemeManager themeManager;
private final BibDatabaseContext databaseContext;
private LibraryPropertiesViewModel viewModel;
public LibraryPropertiesView(BibDatabaseContext databaseContext) {
this.databaseContext = databaseContext;
ViewLoader.view(this)
.load()
.setAsDialogPane(this);
ControlHelper.setAction(saveButton, getDialogPane(), event -> savePreferencesAndCloseDialog());
if (databaseContext.getDatabasePath().isPresent()) {
setTitle(Localization.lang("%0 - Library properties", databaseContext.getDatabasePath().get().getFileName()));
} else {
setTitle(Localization.lang("Library properties"));
}
themeManager.updateFontStyle(getDialogPane().getScene());
}
@FXML
private void initialize() {
viewModel = new LibraryPropertiesViewModel(databaseContext);
for (PropertiesTab pane : viewModel.getPropertiesTabs()) {
ScrollPane scrollPane = new ScrollPane(pane.getBuilder());
scrollPane.setFitToHeight(true);
scrollPane.setFitToWidth(true);
tabPane.getTabs().add(new Tab(pane.getTabName(), scrollPane));
if (pane instanceof AbstractPropertiesTabView<?> propertiesTab) {
propertiesTab.prefHeightProperty().bind(tabPane.tabMaxHeightProperty());
propertiesTab.prefWidthProperty().bind(tabPane.widthProperty());
propertiesTab.getStyleClass().add("propertiesTab");
}
}
viewModel.setValues();
}
private void savePreferencesAndCloseDialog() {
viewModel.storeAllSettings();
close();
}
}
| 2,414
| 33.5
| 122
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/libraryproperties/LibraryPropertiesViewModel.java
|
package org.jabref.gui.libraryproperties;
import java.util.List;
import org.jabref.gui.libraryproperties.constants.ConstantsPropertiesView;
import org.jabref.gui.libraryproperties.contentselectors.ContentSelectorView;
import org.jabref.gui.libraryproperties.general.GeneralPropertiesView;
import org.jabref.gui.libraryproperties.keypattern.KeyPatternPropertiesView;
import org.jabref.gui.libraryproperties.preamble.PreamblePropertiesView;
import org.jabref.gui.libraryproperties.saving.SavingPropertiesView;
import org.jabref.model.database.BibDatabaseContext;
public class LibraryPropertiesViewModel {
private final List<PropertiesTab> propertiesTabs;
public LibraryPropertiesViewModel(BibDatabaseContext databaseContext) {
propertiesTabs = List.of(
new GeneralPropertiesView(databaseContext),
new SavingPropertiesView(databaseContext),
new KeyPatternPropertiesView(databaseContext),
new ConstantsPropertiesView(databaseContext),
new ContentSelectorView(databaseContext),
new PreamblePropertiesView(databaseContext)
);
}
public void setValues() {
for (PropertiesTab propertiesTab : propertiesTabs) {
propertiesTab.setValues();
}
}
public void storeAllSettings() {
for (PropertiesTab propertiesTab : propertiesTabs) {
propertiesTab.storeSettings();
}
}
public List<PropertiesTab> getPropertiesTabs() {
return propertiesTabs;
}
}
| 1,549
| 34.227273
| 77
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/libraryproperties/PropertiesTab.java
|
package org.jabref.gui.libraryproperties;
import javafx.scene.Node;
public interface PropertiesTab {
Node getBuilder();
String getTabName();
void setValues();
void storeSettings();
boolean validateSettings();
}
| 237
| 13.875
| 41
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/libraryproperties/PropertiesTabViewModel.java
|
package org.jabref.gui.libraryproperties;
public interface PropertiesTabViewModel {
void setValues();
void storeSettings();
default boolean validateSettings() {
return true;
}
}
| 206
| 14.923077
| 41
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/libraryproperties/constants/ConstantsItemModel.java
|
package org.jabref.gui.libraryproperties.constants;
import java.util.regex.Pattern;
import javafx.beans.property.ReadOnlyBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import org.jabref.logic.l10n.Localization;
import de.saxsys.mvvmfx.utils.validation.CompositeValidator;
import de.saxsys.mvvmfx.utils.validation.FunctionBasedValidator;
import de.saxsys.mvvmfx.utils.validation.ValidationMessage;
import de.saxsys.mvvmfx.utils.validation.ValidationStatus;
import de.saxsys.mvvmfx.utils.validation.Validator;
public class ConstantsItemModel {
private final static Pattern IS_NUMBER = Pattern.compile("-?\\d+(\\.\\d+)?");
private final StringProperty labelProperty = new SimpleStringProperty();
private final StringProperty contentProperty = new SimpleStringProperty();
private final Validator labelValidator;
private final Validator contentValidator;
private final CompositeValidator combinedValidator;
public ConstantsItemModel(String label, String content) {
this.labelProperty.setValue(label);
this.contentProperty.setValue(content);
labelValidator = new FunctionBasedValidator<>(this.labelProperty, ConstantsItemModel::validateLabel);
contentValidator = new FunctionBasedValidator<>(this.contentProperty, ConstantsItemModel::validateContent);
combinedValidator = new CompositeValidator(labelValidator, contentValidator);
}
public ValidationStatus labelValidation() {
return labelValidator.getValidationStatus();
}
public ValidationStatus contentValidation() {
return contentValidator.getValidationStatus();
}
public ReadOnlyBooleanProperty combinedValidationValidProperty() {
return combinedValidator.getValidationStatus().validProperty();
}
public StringProperty labelProperty() {
return this.labelProperty;
}
public StringProperty contentProperty() {
return this.contentProperty;
}
public void setLabel(String label) {
this.labelProperty.setValue(label);
}
public void setContent(String content) {
this.contentProperty.setValue(content);
}
private static ValidationMessage validateLabel(String input) {
if (input == null) {
return ValidationMessage.error("May not be null");
} else if (input.trim().isEmpty()) {
return ValidationMessage.error(Localization.lang("Please enter the string's label"));
} else if (IS_NUMBER.matcher(input).matches()) {
return ValidationMessage.error(Localization.lang("The label of the string cannot be a number."));
} else if (input.contains("#")) {
return ValidationMessage.error(Localization.lang("The label of the string cannot contain the '#' character."));
} else if (input.contains(" ")) {
return ValidationMessage.error(Localization.lang("The label of the string cannot contain spaces."));
} else {
return null; // everything is ok
}
}
private static ValidationMessage validateContent(String input) {
if (input == null) {
return ValidationMessage.error(Localization.lang("Must not be empty!"));
} else if (input.trim().isEmpty()) {
return ValidationMessage.error(Localization.lang("Must not be empty!"));
} else {
return null; // everything is ok
}
}
}
| 3,475
| 37.197802
| 123
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/libraryproperties/constants/ConstantsPropertiesView.java
|
package org.jabref.gui.libraryproperties.constants;
import java.util.Optional;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.Tooltip;
import javafx.util.converter.DefaultStringConverter;
import org.jabref.gui.DialogService;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.libraryproperties.AbstractPropertiesTabView;
import org.jabref.gui.libraryproperties.PropertiesTab;
import org.jabref.gui.util.ValueTableCellFactory;
import org.jabref.gui.util.ViewModelTextFieldTableCellVisualizationFactory;
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 ConstantsPropertiesView extends AbstractPropertiesTabView<ConstantsPropertiesViewModel> implements PropertiesTab {
@FXML private TableView<ConstantsItemModel> stringsList;
@FXML private TableColumn<ConstantsItemModel, String> labelColumn;
@FXML private TableColumn<ConstantsItemModel, String> contentColumn;
@FXML private TableColumn<ConstantsItemModel, String> actionsColumn;
@FXML private Button addStringButton;
@FXML private ButtonType saveButton;
@Inject private PreferencesService preferencesService;
@Inject private DialogService dialogService;
public ConstantsPropertiesView(BibDatabaseContext databaseContext) {
this.databaseContext = databaseContext;
ViewLoader.view(this)
.root(this)
.load();
}
@Override
public String getTabName() {
return Localization.lang("String constants");
}
public void initialize() {
this.viewModel = new ConstantsPropertiesViewModel(databaseContext, dialogService);
addStringButton.setTooltip(new Tooltip(Localization.lang("New string")));
labelColumn.setSortable(true);
labelColumn.setReorderable(false);
labelColumn.setCellValueFactory(cellData -> cellData.getValue().labelProperty());
new ViewModelTextFieldTableCellVisualizationFactory<ConstantsItemModel, String>()
.withValidation(ConstantsItemModel::labelValidation)
.install(labelColumn, new DefaultStringConverter());
labelColumn.setOnEditCommit((TableColumn.CellEditEvent<ConstantsItemModel, String> cellEvent) -> {
var tableView = cellEvent.getTableView();
ConstantsItemModel cellItem = tableView.getItems()
.get(cellEvent.getTablePosition().getRow());
Optional<ConstantsItemModel> existingItem = viewModel.labelAlreadyExists(cellEvent.getNewValue());
if (existingItem.isPresent() && !existingItem.get().equals(cellItem)) {
dialogService.showErrorDialogAndWait(Localization.lang(
"A string with the label '%0' already exists.",
cellEvent.getNewValue()));
cellItem.setLabel(cellEvent.getOldValue());
} else {
cellItem.setLabel(cellEvent.getNewValue());
}
// Resort the entries based on the keys and set the focus to the newly-created entry
viewModel.resortStrings();
var selectionModel = tableView.getSelectionModel();
selectionModel.select(cellItem);
selectionModel.focus(selectionModel.getSelectedIndex());
tableView.refresh();
tableView.scrollTo(cellItem);
});
contentColumn.setSortable(true);
contentColumn.setReorderable(false);
contentColumn.setCellValueFactory(cellData -> cellData.getValue().contentProperty());
new ViewModelTextFieldTableCellVisualizationFactory<ConstantsItemModel, String>()
.withValidation(ConstantsItemModel::contentValidation)
.install(contentColumn, new DefaultStringConverter());
contentColumn.setOnEditCommit((TableColumn.CellEditEvent<ConstantsItemModel, String> cell) ->
cell.getRowValue().setContent(cell.getNewValue()));
actionsColumn.setSortable(false);
actionsColumn.setReorderable(false);
actionsColumn.setCellValueFactory(cellData -> cellData.getValue().labelProperty());
new ValueTableCellFactory<ConstantsItemModel, String>()
.withGraphic(label -> IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode())
.withTooltip(label -> Localization.lang("Remove string %0", label))
.withOnMouseClickedEvent(item -> evt ->
viewModel.removeString(stringsList.getFocusModel().getFocusedItem()))
.install(actionsColumn);
stringsList.itemsProperty().bindBidirectional(viewModel.stringsListProperty());
stringsList.setEditable(true);
}
@FXML
private void addString() {
viewModel.addNewString();
stringsList.edit(stringsList.getItems().size() - 1, labelColumn);
}
@FXML
private void openHelp() {
viewModel.openHelpPage();
}
}
| 5,271
| 41.861789
| 127
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/libraryproperties/constants/ConstantsPropertiesViewModel.java
|
package org.jabref.gui.libraryproperties.constants;
import java.util.Comparator;
import java.util.Locale;
import java.util.Optional;
import java.util.stream.Collectors;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.jabref.gui.DialogService;
import org.jabref.gui.help.HelpAction;
import org.jabref.gui.libraryproperties.PropertiesTabViewModel;
import org.jabref.logic.bibtex.comparator.BibtexStringComparator;
import org.jabref.logic.help.HelpFile;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibtexString;
import com.tobiasdiez.easybind.EasyBind;
public class ConstantsPropertiesViewModel implements PropertiesTabViewModel {
private static final String NEW_STRING_LABEL = "NewString"; // must not contain spaces
private final ListProperty<ConstantsItemModel> stringsListProperty =
new SimpleListProperty<>(FXCollections.observableArrayList());
private final BooleanProperty validProperty = new SimpleBooleanProperty();
private final BibDatabaseContext databaseContext;
private final DialogService dialogService;
public ConstantsPropertiesViewModel(BibDatabaseContext databaseContext, DialogService dialogService) {
this.databaseContext = databaseContext;
this.dialogService = dialogService;
ObservableList<ObservableValue<Boolean>> allValidProperty =
EasyBind.map(stringsListProperty, ConstantsItemModel::combinedValidationValidProperty);
validProperty.bind(EasyBind.combine(allValidProperty, stream -> stream.allMatch(valid -> valid)));
}
@Override
public void setValues() {
stringsListProperty.addAll(databaseContext.getDatabase().getStringValues().stream()
.sorted(new BibtexStringComparator(false))
.map(this::convertFromBibTexString)
.toList());
}
public void addNewString() {
ConstantsItemModel newItem;
if (labelAlreadyExists(NEW_STRING_LABEL).isPresent()) {
int i = 1;
while (labelAlreadyExists(NEW_STRING_LABEL + i).isPresent()) {
i++;
}
newItem = new ConstantsItemModel(NEW_STRING_LABEL + i, "");
} else {
newItem = new ConstantsItemModel(NEW_STRING_LABEL, "");
}
stringsListProperty.add(newItem);
}
public void removeString(ConstantsItemModel item) {
stringsListProperty.remove(item);
}
public void resortStrings() {
// Resort the strings list in the same order as setValues() does
stringsListProperty.sort(Comparator.comparing(c -> c.labelProperty().get().toLowerCase(Locale.ROOT)));
}
private ConstantsItemModel convertFromBibTexString(BibtexString bibtexString) {
return new ConstantsItemModel(bibtexString.getName(), bibtexString.getContent());
}
@Override
public void storeSettings() {
databaseContext.getDatabase().setStrings(stringsListProperty.stream()
.map(this::fromBibtexStringViewModel)
.collect(Collectors.toList()));
}
private BibtexString fromBibtexStringViewModel(ConstantsItemModel viewModel) {
String label = viewModel.labelProperty().getValue();
String content = viewModel.contentProperty().getValue();
return new BibtexString(label, content);
}
public Optional<ConstantsItemModel> labelAlreadyExists(String label) {
return stringsListProperty.stream()
.filter(item -> item.labelProperty().getValue().equals(label))
.findFirst();
}
public void openHelpPage() {
new HelpAction(HelpFile.STRING_EDITOR, dialogService).execute();
}
public ListProperty<ConstantsItemModel> stringsListProperty() {
return stringsListProperty;
}
public BooleanProperty validProperty() {
return validProperty;
}
}
| 4,422
| 37.46087
| 110
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/libraryproperties/contentselectors/ContentSelectorView.java
|
package org.jabref.gui.libraryproperties.contentselectors;
import java.util.Optional;
import java.util.function.Supplier;
import javafx.beans.property.ListProperty;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionModel;
import org.jabref.gui.DialogService;
import org.jabref.gui.libraryproperties.AbstractPropertiesTabView;
import org.jabref.gui.util.ViewModelListCellFactory;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.field.Field;
import com.airhacks.afterburner.views.ViewLoader;
import com.tobiasdiez.easybind.EasyBind;
import jakarta.inject.Inject;
public class ContentSelectorView extends AbstractPropertiesTabView<ContentSelectorViewModel> {
@FXML private Button removeFieldNameButton;
@FXML private Button addKeywordButton;
@FXML private Button removeKeywordButton;
@FXML private ListView<Field> fieldsListView;
@FXML private ListView<String> keywordsListView;
@Inject private DialogService dialogService;
private final BibDatabaseContext databaseContext;
public ContentSelectorView(BibDatabaseContext databaseContext) {
this.databaseContext = databaseContext;
ViewLoader.view(this)
.root(this)
.load();
}
@Override
public String getTabName() {
return Localization.lang("Content selectors");
}
@FXML
public void initialize() {
this.viewModel = new ContentSelectorViewModel(databaseContext, dialogService);
initFieldNameComponents();
initKeywordsComponents();
}
private void initFieldNameComponents() {
initListView(fieldsListView, viewModel::getFieldNamesBackingList);
viewModel.selectedFieldProperty().bind(fieldsListView.getSelectionModel().selectedItemProperty());
new ViewModelListCellFactory<Field>()
.withText(Field::getDisplayName)
.install(fieldsListView);
removeFieldNameButton.disableProperty().bind(viewModel.isNoFieldNameSelected());
EasyBind.subscribe(viewModel.selectedFieldProperty(), viewModel::populateKeywords);
}
private void initKeywordsComponents() {
initListView(keywordsListView, viewModel::getKeywordsBackingList);
viewModel.selectedKeywordProperty().bind(keywordsListView.getSelectionModel().selectedItemProperty());
addKeywordButton.disableProperty().bind(viewModel.isFieldNameListEmpty());
removeKeywordButton.disableProperty().bind(viewModel.isNoKeywordSelected());
}
@FXML
private void addNewFieldName() {
viewModel.showInputFieldNameDialog();
}
@FXML
private void removeFieldName() {
getSelectedField().ifPresent(viewModel::showRemoveFieldNameConfirmationDialog);
}
@FXML
private void addNewKeyword() {
getSelectedField().ifPresent(viewModel::showInputKeywordDialog);
}
@FXML
private void removeKeyword() {
Optional<Field> fieldName = getSelectedField();
Optional<String> keywordToRemove = getSelectedKeyword();
if (fieldName.isPresent() && keywordToRemove.isPresent()) {
viewModel.showRemoveKeywordConfirmationDialog(fieldName.get(), keywordToRemove.get());
}
}
private <T> void initListView(ListView<T> listViewToInit, Supplier<ListProperty<T>> backingList) {
listViewToInit.itemsProperty().bind(backingList.get());
listViewToInit.getSelectionModel().selectFirst();
}
private Optional<Field> getSelectedField() {
return Optional.of(fieldsListView.getSelectionModel()).map(SelectionModel::getSelectedItem);
}
private Optional<String> getSelectedKeyword() {
return Optional.of(keywordsListView.getSelectionModel()).map(SelectionModel::getSelectedItem);
}
}
| 3,924
| 34.681818
| 110
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/libraryproperties/contentselectors/ContentSelectorViewModel.java
|
package org.jabref.gui.libraryproperties.contentselectors;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
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.DialogService;
import org.jabref.gui.libraryproperties.PropertiesTabViewModel;
import org.jabref.logic.l10n.Localization;
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.StandardField;
import org.jabref.model.metadata.ContentSelector;
import org.jabref.model.metadata.MetaData;
public class ContentSelectorViewModel implements PropertiesTabViewModel {
private static final List<Field> DEFAULT_FIELD_NAMES = Arrays.asList(StandardField.AUTHOR, StandardField.JOURNAL, StandardField.KEYWORDS, StandardField.PUBLISHER);
private final MetaData metaData;
private final DialogService dialogService;
private final Map<Field, List<String>> fieldKeywordsMap = new HashMap<>();
private final ListProperty<Field> fields = new SimpleListProperty<>(FXCollections.observableArrayList());
private final ListProperty<String> keywords = new SimpleListProperty<>(FXCollections.observableArrayList());
private final ObjectProperty<Field> selectedField = new SimpleObjectProperty<>();
private final StringProperty selectedKeyword = new SimpleStringProperty();
ContentSelectorViewModel(BibDatabaseContext databaseContext, DialogService dialogService) {
this.metaData = databaseContext.getMetaData();
this.dialogService = dialogService;
}
@Override
public void setValues() {
// Populate field names keyword map
metaData.getContentSelectors().getContentSelectors().forEach(
existingContentSelector -> fieldKeywordsMap.put(existingContentSelector.getField(), new ArrayList<>(existingContentSelector.getValues()))
);
// Populate Field names list
List<Field> existingFields = new ArrayList<>(fieldKeywordsMap.keySet());
fields.addAll(existingFields);
if (fields.isEmpty()) {
DEFAULT_FIELD_NAMES.forEach(this::addFieldIfUnique);
}
}
@Override
public void storeSettings() {
List<Field> metaDataFields = metaData.getContentSelectors().getFieldsWithSelectors();
fieldKeywordsMap.forEach((field, keywords) -> updateMetaDataContentSelector(metaDataFields, field, keywords));
List<Field> fieldNamesToRemove = filterFieldsToRemove();
fieldNamesToRemove.forEach(metaData::clearContentSelectors);
}
public ListProperty<Field> getFieldNamesBackingList() {
return fields;
}
public ObjectProperty<Field> selectedFieldProperty() {
return selectedField;
}
public BooleanBinding isFieldNameListEmpty() {
return Bindings.isEmpty(fields);
}
public BooleanBinding isNoFieldNameSelected() {
return Bindings.isEmpty(selectedField.asString());
}
public ListProperty<String> getKeywordsBackingList() {
return keywords;
}
StringProperty selectedKeywordProperty() {
return selectedKeyword;
}
BooleanBinding isNoKeywordSelected() {
return Bindings.isEmpty(selectedKeyword);
}
void showInputFieldNameDialog() {
dialogService.showInputDialogAndWait(Localization.lang("Add new field name"), Localization.lang("Field name"))
.map(FieldFactory::parseField)
.ifPresent(this::addFieldIfUnique);
}
private void addFieldIfUnique(Field fieldToAdd) {
boolean exists = fieldKeywordsMap.containsKey(fieldToAdd);
if (exists) {
dialogService.showErrorDialogAndWait(Localization.lang("Field name \"%0\" already exists", fieldToAdd.getDisplayName()));
return;
}
fieldKeywordsMap.put(fieldToAdd, new ArrayList<>());
fields.add(fieldToAdd);
}
void showRemoveFieldNameConfirmationDialog(Field fieldToRemove) {
if (fieldToRemove == null) {
dialogService.showErrorDialogAndWait(Localization.lang("No field name selected!"));
return;
}
boolean deleteConfirmed = dialogService.showConfirmationDialogAndWait(
Localization.lang("Remove field name"),
Localization.lang("Are you sure you want to remove field name: \"%0\"?", fieldToRemove.getDisplayName())
);
if (deleteConfirmed) {
removeFieldName(fieldToRemove);
}
}
private void removeFieldName(Field fieldToRemove) {
fieldKeywordsMap.remove(fieldToRemove);
fields.remove(fieldToRemove);
}
void populateKeywords(Field selectedField) {
keywords.clear();
if (selectedField != null) {
keywords.addAll(fieldKeywordsMap.get(selectedField));
}
}
void showInputKeywordDialog(Field selectedField) {
dialogService.showInputDialogAndWait(Localization.lang("Add new keyword"), Localization.lang("Keyword:"))
.ifPresent(newKeyword -> addKeywordIfUnique(selectedField, newKeyword));
}
private void addKeywordIfUnique(Field field, String keywordToAdd) {
boolean exists = fieldKeywordsMap.get(field).contains(keywordToAdd);
if (exists) {
dialogService.showErrorDialogAndWait(Localization.lang("Keyword \"%0\" already exists", keywordToAdd));
return;
}
List<String> existingKeywords = fieldKeywordsMap.getOrDefault(field, new ArrayList<>());
existingKeywords.add(keywordToAdd);
existingKeywords.sort(Comparator.naturalOrder());
fieldKeywordsMap.put(field, existingKeywords);
populateKeywords(field);
}
void showRemoveKeywordConfirmationDialog(Field field, String keywordToRemove) {
boolean deleteConfirmed = dialogService.showConfirmationDialogAndWait(Localization.lang("Remove keyword"), Localization.lang("Are you sure you want to remove keyword: \"%0\"?", keywordToRemove));
if (deleteConfirmed) {
removeKeyword(field, keywordToRemove);
}
}
private void removeKeyword(Field field, String keywordToRemove) {
fieldKeywordsMap.get(field).remove(keywordToRemove);
keywords.remove(keywordToRemove);
}
private List<Field> filterFieldsToRemove() {
Set<Field> newlyAddedKeywords = fieldKeywordsMap.keySet();
return metaData.getContentSelectors().getFieldsWithSelectors().stream()
.filter(field -> !newlyAddedKeywords.contains(field))
.collect(Collectors.toList());
}
private void updateMetaDataContentSelector(List<Field> existingFields, Field field, List<String> keywords) {
boolean fieldNameDoNotExists = !existingFields.contains(field);
if (fieldNameDoNotExists) {
metaData.addContentSelector(new ContentSelector(field, keywords));
}
if (keywordsHaveChanged(field, keywords)) {
metaData.clearContentSelectors(field);
metaData.addContentSelector(new ContentSelector(field, keywords));
}
}
private boolean keywordsHaveChanged(Field field, List<String> keywords) {
HashSet<String> keywordsSet = asHashSet(keywords);
List<String> existingKeywords = metaData.getContentSelectorValuesForField(field);
if (!keywordsSet.equals(asHashSet(existingKeywords))) {
return true;
}
return !keywordsSet.isEmpty() && existingKeywords.isEmpty();
}
private HashSet<String> asHashSet(List<String> listToConvert) {
return new HashSet<>(listToConvert);
}
}
| 8,254
| 37.938679
| 203
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/libraryproperties/general/GeneralPropertiesView.java
|
package org.jabref.gui.libraryproperties.general;
import java.nio.charset.Charset;
import javafx.fxml.FXML;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import org.jabref.gui.libraryproperties.AbstractPropertiesTabView;
import org.jabref.gui.util.ViewModelListCellFactory;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.database.BibDatabaseMode;
import org.jabref.preferences.PreferencesService;
import com.airhacks.afterburner.views.ViewLoader;
import jakarta.inject.Inject;
public class GeneralPropertiesView extends AbstractPropertiesTabView<GeneralPropertiesViewModel> {
@FXML private ComboBox<Charset> encoding;
@FXML private ComboBox<BibDatabaseMode> databaseMode;
@FXML private TextField generalFileDirectory;
@FXML private TextField userSpecificFileDirectory;
@FXML private TextField laTexFileDirectory;
@Inject private PreferencesService preferencesService;
public GeneralPropertiesView(BibDatabaseContext databaseContext) {
this.databaseContext = databaseContext;
ViewLoader.view(this)
.root(this)
.load();
}
@Override
public String getTabName() {
return Localization.lang("General");
}
public void initialize() {
this.viewModel = new GeneralPropertiesViewModel(databaseContext, dialogService, preferencesService);
new ViewModelListCellFactory<Charset>()
.withText(Charset::displayName)
.install(encoding);
encoding.disableProperty().bind(viewModel.encodingDisableProperty());
encoding.itemsProperty().bind(viewModel.encodingsProperty());
encoding.valueProperty().bindBidirectional(viewModel.selectedEncodingProperty());
new ViewModelListCellFactory<BibDatabaseMode>()
.withText(BibDatabaseMode::getFormattedName)
.install(databaseMode);
databaseMode.itemsProperty().bind(viewModel.databaseModesProperty());
databaseMode.valueProperty().bindBidirectional(viewModel.selectedDatabaseModeProperty());
generalFileDirectory.textProperty().bindBidirectional(viewModel.generalFileDirectoryPropertyProperty());
userSpecificFileDirectory.textProperty().bindBidirectional(viewModel.userSpecificFileDirectoryProperty());
laTexFileDirectory.textProperty().bindBidirectional(viewModel.laTexFileDirectoryProperty());
}
@FXML
public void browseGeneralFileDirectory() {
viewModel.browseGeneralDir();
}
@FXML
public void browseUserSpecificFileDirectory() {
viewModel.browseUserDir();
}
@FXML
void browseLatexFileDirectory() {
viewModel.browseLatexDir();
}
}
| 2,796
| 35.324675
| 114
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.