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/edit/automaticfiededitor/AutomaticFieldEditorDialog.java
|
package org.jabref.gui.edit.automaticfiededitor;
import java.util.ArrayList;
import java.util.List;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;
import javafx.fxml.FXML;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import org.jabref.gui.Globals;
import org.jabref.gui.StateManager;
import org.jabref.gui.util.BaseDialog;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;
import com.airhacks.afterburner.views.ViewLoader;
import com.tobiasdiez.easybind.EasyBind;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AutomaticFieldEditorDialog extends BaseDialog<String> {
private static final Logger LOGGER = LoggerFactory.getLogger(AutomaticFieldEditorDialog.class);
@FXML
private TabPane tabPane;
private final UndoManager undoManager;
private final BibDatabase database;
private final List<BibEntry> selectedEntries;
private final StateManager stateManager;
private AutomaticFieldEditorViewModel viewModel;
private List<NotificationPaneAdapter> notificationPanes = new ArrayList<>();
public AutomaticFieldEditorDialog(StateManager stateManager) {
this.selectedEntries = stateManager.getSelectedEntries();
this.database = stateManager.getActiveDatabase().orElseThrow().getDatabase();
this.stateManager = stateManager;
this.undoManager = Globals.undoManager;
this.setTitle(Localization.lang("Automatic field editor"));
ViewLoader.view(this)
.load()
.setAsDialogPane(this);
setResultConverter(buttonType -> {
if (buttonType != null && buttonType.getButtonData() == ButtonBar.ButtonData.OK_DONE) {
saveChanges();
} else {
cancelChanges();
}
return "";
});
// This will prevent all dialog buttons from having the same size
// Read more: https://stackoverflow.com/questions/45866249/javafx-8-alert-different-button-sizes
getDialogPane().getButtonTypes().stream()
.map(getDialogPane()::lookupButton)
.forEach(btn -> ButtonBar.setButtonUniformSize(btn, false));
}
@FXML
public void initialize() {
viewModel = new AutomaticFieldEditorViewModel(selectedEntries, database, undoManager, stateManager);
for (AutomaticFieldEditorTab tabModel : viewModel.getFieldEditorTabs()) {
NotificationPaneAdapter notificationPane = new NotificationPaneAdapter(tabModel.getContent());
notificationPanes.add(notificationPane);
tabPane.getTabs().add(new Tab(tabModel.getTabName(), notificationPane));
}
EasyBind.listen(stateManager.lastAutomaticFieldEditorEditProperty(), (obs, old, lastEdit) -> {
viewModel.getDialogEdits().addEdit(lastEdit.getEdit());
notificationPanes.get(lastEdit.getTabIndex())
.notify(lastEdit.getAffectedEntries(), selectedEntries.size());
});
}
private void saveChanges() {
viewModel.saveChanges();
}
private void cancelChanges() {
try {
viewModel.cancelChanges();
} catch (CannotUndoException e) {
LOGGER.info("Could not undo", e);
}
}
}
| 3,443
| 33.09901
| 108
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/edit/automaticfiededitor/AutomaticFieldEditorTab.java
|
package org.jabref.gui.edit.automaticfiededitor;
import javafx.scene.layout.Pane;
public interface AutomaticFieldEditorTab {
Pane getContent();
String getTabName();
}
| 178
| 16.9
| 48
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/edit/automaticfiededitor/AutomaticFieldEditorViewModel.java
|
package org.jabref.gui.edit.automaticfiededitor;
import java.util.List;
import javax.swing.undo.UndoManager;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.jabref.gui.AbstractViewModel;
import org.jabref.gui.StateManager;
import org.jabref.gui.edit.automaticfiededitor.copyormovecontent.CopyOrMoveFieldContentTabView;
import org.jabref.gui.edit.automaticfiededitor.editfieldcontent.EditFieldContentTabView;
import org.jabref.gui.edit.automaticfiededitor.renamefield.RenameFieldTabView;
import org.jabref.gui.undo.NamedCompound;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;
public class AutomaticFieldEditorViewModel extends AbstractViewModel {
public static final String NAMED_COMPOUND_EDITS = "EDIT_FIELDS";
private final ObservableList<AutomaticFieldEditorTab> fieldEditorTabs = FXCollections.observableArrayList();
private final NamedCompound dialogEdits = new NamedCompound(NAMED_COMPOUND_EDITS);
private final UndoManager undoManager;
public AutomaticFieldEditorViewModel(List<BibEntry> selectedEntries, BibDatabase database, UndoManager undoManager, StateManager stateManager) {
this.undoManager = undoManager;
fieldEditorTabs.addAll(
new EditFieldContentTabView(database, stateManager),
new CopyOrMoveFieldContentTabView(database, stateManager),
new RenameFieldTabView(database, stateManager)
);
}
public NamedCompound getDialogEdits() {
return dialogEdits;
}
public ObservableList<AutomaticFieldEditorTab> getFieldEditorTabs() {
return fieldEditorTabs;
}
public void saveChanges() {
dialogEdits.end();
undoManager.addEdit(dialogEdits);
}
public void cancelChanges() {
dialogEdits.end();
dialogEdits.undo();
}
}
| 1,894
| 34.754717
| 148
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/edit/automaticfiededitor/LastAutomaticFieldEditorEdit.java
|
package org.jabref.gui.edit.automaticfiededitor;
import javax.swing.undo.AbstractUndoableEdit;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import org.jabref.gui.undo.NamedCompound;
public class LastAutomaticFieldEditorEdit extends AbstractUndoableEdit {
private final Integer affectedEntries;
private final NamedCompound edit;
private final Integer tabIndex;
public LastAutomaticFieldEditorEdit(Integer affectedEntries, Integer tabIndex, NamedCompound edit) {
this.affectedEntries = affectedEntries;
this.edit = edit;
this.tabIndex = tabIndex;
}
public Integer getAffectedEntries() {
return affectedEntries;
}
public NamedCompound getEdit() {
return edit;
}
public Integer getTabIndex() {
return tabIndex;
}
@Override
public void undo() throws CannotUndoException {
super.undo();
edit.undo();
}
@Override
public void redo() throws CannotRedoException {
super.redo();
edit.redo();
}
}
| 1,088
| 23.2
| 104
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/edit/automaticfiededitor/MoveFieldValueAction.java
|
package org.jabref.gui.edit.automaticfiededitor;
import java.util.List;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.undo.NamedCompound;
import org.jabref.gui.undo.UndoableFieldChange;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.Field;
import org.jabref.model.strings.StringUtil;
public class MoveFieldValueAction extends SimpleCommand {
private final Field fromField;
private final Field toField;
private final List<BibEntry> entries;
private final NamedCompound edits;
private int affectedEntriesCount;
private final boolean overwriteToFieldContent;
public MoveFieldValueAction(Field fromField, Field toField, List<BibEntry> entries, NamedCompound edits, boolean overwriteToFieldContent) {
this.fromField = fromField;
this.toField = toField;
this.entries = entries;
this.edits = edits;
this.overwriteToFieldContent = overwriteToFieldContent;
}
public MoveFieldValueAction(Field fromField, Field toField, List<BibEntry> entries, NamedCompound edits) {
this(fromField, toField, entries, edits, true);
}
@Override
public void execute() {
affectedEntriesCount = 0;
for (BibEntry entry : entries) {
String fromFieldValue = entry.getField(fromField).orElse("");
String toFieldValue = entry.getField(toField).orElse("");
if (StringUtil.isNotBlank(fromFieldValue)) {
if (overwriteToFieldContent || toFieldValue.isEmpty()) {
entry.setField(toField, fromFieldValue);
entry.setField(fromField, "");
edits.addEdit(new UndoableFieldChange(entry, fromField, fromFieldValue, null));
edits.addEdit(new UndoableFieldChange(entry, toField, toFieldValue, fromFieldValue));
affectedEntriesCount++;
}
}
}
edits.end();
}
/**
* @return the number of affected entries
* */
public int executeAndGetAffectedEntriesCount() {
execute();
return affectedEntriesCount;
}
}
| 2,160
| 32.765625
| 143
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/edit/automaticfiededitor/NotificationPaneAdapter.java
|
package org.jabref.gui.edit.automaticfiededitor;
import java.util.Collections;
import javafx.scene.Node;
import javafx.util.Duration;
import org.jabref.gui.LibraryTab;
import org.jabref.gui.icon.IconTheme;
public class NotificationPaneAdapter extends LibraryTab.DatabaseNotification {
public NotificationPaneAdapter(Node content) {
super(content);
}
public void notify(int affectedEntries, int totalEntries) {
String notificationMessage = String.format("%d/%d affected entries", affectedEntries, totalEntries);
Node notificationGraphic = IconTheme.JabRefIcons.INTEGRITY_INFO.getGraphicNode();
notify(notificationGraphic, notificationMessage, Collections.emptyList(), Duration.seconds(2));
}
}
| 748
| 30.208333
| 108
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/edit/automaticfiededitor/copyormovecontent/CopyOrMoveFieldContentTabView.java
|
package org.jabref.gui.edit.automaticfiededitor.copyormovecontent;
import java.util.ArrayList;
import java.util.List;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import org.jabref.gui.StateManager;
import org.jabref.gui.edit.automaticfiededitor.AbstractAutomaticFieldEditorTabView;
import org.jabref.gui.edit.automaticfiededitor.AutomaticFieldEditorTab;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.Field;
import com.airhacks.afterburner.views.ViewLoader;
import com.tobiasdiez.easybind.EasyBind;
import de.saxsys.mvvmfx.utils.validation.visualization.ControlsFxVisualizer;
import static org.jabref.gui.util.FieldsUtil.FIELD_STRING_CONVERTER;
public class CopyOrMoveFieldContentTabView extends AbstractAutomaticFieldEditorTabView implements AutomaticFieldEditorTab {
public Button copyContentButton;
@FXML
private Button moveContentButton;
@FXML
private Button swapContentButton;
@FXML
private ComboBox<Field> fromFieldComboBox;
@FXML
private ComboBox<Field> toFieldComboBox;
@FXML
private CheckBox overwriteFieldContentCheckBox;
private CopyOrMoveFieldContentTabViewModel viewModel;
private final List<BibEntry> selectedEntries;
private final BibDatabase database;
private final StateManager stateManager;
private final ControlsFxVisualizer visualizer = new ControlsFxVisualizer();
public CopyOrMoveFieldContentTabView(BibDatabase database, StateManager stateManager) {
this.selectedEntries = new ArrayList<>(stateManager.getSelectedEntries());
this.database = database;
this.stateManager = stateManager;
ViewLoader.view(this)
.root(this)
.load();
}
public void initialize() {
viewModel = new CopyOrMoveFieldContentTabViewModel(selectedEntries, database, stateManager);
initializeFromAndToComboBox();
viewModel.overwriteFieldContentProperty().bindBidirectional(overwriteFieldContentCheckBox.selectedProperty());
moveContentButton.disableProperty().bind(viewModel.canMoveProperty().not());
swapContentButton.disableProperty().bind(viewModel.canSwapProperty().not());
copyContentButton.disableProperty().bind(viewModel.toFieldValidationStatus().validProperty().not());
overwriteFieldContentCheckBox.disableProperty().bind(viewModel.toFieldValidationStatus().validProperty().not());
Platform.runLater(() -> {
visualizer.initVisualization(viewModel.toFieldValidationStatus(), toFieldComboBox, true);
});
}
private void initializeFromAndToComboBox() {
fromFieldComboBox.getItems().setAll(viewModel.getAllFields());
toFieldComboBox.getItems().setAll(viewModel.getAllFields());
fromFieldComboBox.setConverter(FIELD_STRING_CONVERTER);
toFieldComboBox.setConverter(FIELD_STRING_CONVERTER);
fromFieldComboBox.valueProperty().bindBidirectional(viewModel.fromFieldProperty());
toFieldComboBox.valueProperty().bindBidirectional(viewModel.toFieldProperty());
EasyBind.listen(fromFieldComboBox.getEditor().textProperty(), observable -> fromFieldComboBox.commitValue());
EasyBind.listen(toFieldComboBox.getEditor().textProperty(), observable -> toFieldComboBox.commitValue());
}
@Override
public String getTabName() {
return Localization.lang("Copy or Move content");
}
@FXML
void copyContent() {
viewModel.copyValue();
}
@FXML
void moveContent() {
viewModel.moveValue();
}
@FXML
void swapContent() {
viewModel.swapValues();
}
}
| 3,873
| 34.218182
| 123
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/edit/automaticfiededitor/copyormovecontent/CopyOrMoveFieldContentTabViewModel.java
|
package org.jabref.gui.edit.automaticfiededitor.copyormovecontent;
import java.util.ArrayList;
import java.util.List;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;
import org.jabref.gui.StateManager;
import org.jabref.gui.edit.automaticfiededitor.AbstractAutomaticFieldEditorTabViewModel;
import org.jabref.gui.edit.automaticfiededitor.LastAutomaticFieldEditorEdit;
import org.jabref.gui.edit.automaticfiededitor.MoveFieldValueAction;
import org.jabref.gui.undo.NamedCompound;
import org.jabref.gui.undo.UndoableFieldChange;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.strings.StringUtil;
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 CopyOrMoveFieldContentTabViewModel extends AbstractAutomaticFieldEditorTabViewModel {
public static final int TAB_INDEX = 1;
private final ObjectProperty<Field> fromField = new SimpleObjectProperty<>(StandardField.ABSTRACT);
private final ObjectProperty<Field> toField = new SimpleObjectProperty<>(StandardField.AUTHOR);
private final BooleanProperty overwriteFieldContent = new SimpleBooleanProperty(Boolean.FALSE);
private final List<BibEntry> selectedEntries;
private final Validator toFieldValidator;
private final BooleanBinding canMove;
private final BooleanBinding canSwap;
public CopyOrMoveFieldContentTabViewModel(List<BibEntry> selectedEntries, BibDatabase bibDatabase, StateManager stateManager) {
super(bibDatabase, stateManager);
this.selectedEntries = new ArrayList<>(selectedEntries);
toFieldValidator = new FunctionBasedValidator<>(toField, field -> {
if (StringUtil.isBlank(field.getName())) {
return ValidationMessage.error("Field name cannot be empty");
} else if (StringUtil.containsWhitespace(field.getName())) {
return ValidationMessage.error("Field name cannot have whitespace characters");
}
return null;
});
canMove = BooleanBinding.booleanExpression(toFieldValidationStatus().validProperty())
.and(overwriteFieldContentProperty());
canSwap = BooleanBinding.booleanExpression(toFieldValidationStatus().validProperty())
.and(overwriteFieldContentProperty());
}
public ValidationStatus toFieldValidationStatus() {
return toFieldValidator.getValidationStatus();
}
public BooleanBinding canMoveProperty() {
return canMove;
}
public BooleanBinding canSwapProperty() {
return canSwap;
}
public Field getFromField() {
return fromField.get();
}
public ObjectProperty<Field> fromFieldProperty() {
return fromField;
}
public Field getToField() {
return toField.get();
}
public ObjectProperty<Field> toFieldProperty() {
return toField;
}
public boolean isOverwriteFieldContent() {
return overwriteFieldContent.get();
}
public BooleanProperty overwriteFieldContentProperty() {
return overwriteFieldContent;
}
public void copyValue() {
NamedCompound copyFieldValueEdit = new NamedCompound("COPY_FIELD_VALUE");
int affectedEntriesCount = 0;
for (BibEntry entry : selectedEntries) {
String fromFieldValue = entry.getField(fromField.get()).orElse("");
String toFieldValue = entry.getField(toField.get()).orElse("");
if (overwriteFieldContent.get() || StringUtil.isBlank(toFieldValue)) {
if (StringUtil.isNotBlank(fromFieldValue)) {
entry.setField(toField.get(), fromFieldValue);
copyFieldValueEdit.addEdit(new UndoableFieldChange(entry,
toField.get(),
toFieldValue,
fromFieldValue));
affectedEntriesCount++;
}
}
}
if (copyFieldValueEdit.hasEdits()) {
copyFieldValueEdit.end();
}
stateManager.setLastAutomaticFieldEditorEdit(new LastAutomaticFieldEditorEdit(
affectedEntriesCount, TAB_INDEX, copyFieldValueEdit
));
}
public void moveValue() {
NamedCompound moveEdit = new NamedCompound("MOVE_EDIT");
int affectedEntriesCount = 0;
if (overwriteFieldContent.get()) {
affectedEntriesCount = new MoveFieldValueAction(fromField.get(),
toField.get(),
selectedEntries,
moveEdit).executeAndGetAffectedEntriesCount();
if (moveEdit.hasEdits()) {
moveEdit.end();
}
}
stateManager.setLastAutomaticFieldEditorEdit(new LastAutomaticFieldEditorEdit(
affectedEntriesCount, TAB_INDEX, moveEdit
));
}
public void swapValues() {
NamedCompound swapFieldValuesEdit = new NamedCompound("SWAP_FIELD_VALUES");
int affectedEntriesCount = 0;
for (BibEntry entry : selectedEntries) {
String fromFieldValue = entry.getField(fromField.get()).orElse("");
String toFieldValue = entry.getField(toField.get()).orElse("");
if (overwriteFieldContent.get() && StringUtil.isNotBlank(fromFieldValue) && StringUtil.isNotBlank(toFieldValue)) {
entry.setField(toField.get(), fromFieldValue);
entry.setField(fromField.get(), toFieldValue);
swapFieldValuesEdit.addEdit(new UndoableFieldChange(
entry,
toField.get(),
toFieldValue,
fromFieldValue
));
swapFieldValuesEdit.addEdit(new UndoableFieldChange(
entry,
fromField.get(),
fromFieldValue,
toFieldValue
));
affectedEntriesCount++;
}
}
if (swapFieldValuesEdit.hasEdits()) {
swapFieldValuesEdit.end();
}
stateManager.setLastAutomaticFieldEditorEdit(new LastAutomaticFieldEditorEdit(
affectedEntriesCount, TAB_INDEX, swapFieldValuesEdit
));
}
public List<BibEntry> getSelectedEntries() {
return selectedEntries;
}
}
| 6,905
| 36.532609
| 131
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/edit/automaticfiededitor/editfieldcontent/EditFieldContentTabView.java
|
package org.jabref.gui.edit.automaticfiededitor.editfieldcontent;
import java.util.List;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import org.jabref.gui.StateManager;
import org.jabref.gui.edit.automaticfiededitor.AbstractAutomaticFieldEditorTabView;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.Field;
import com.airhacks.afterburner.views.ViewLoader;
import com.tobiasdiez.easybind.EasyBind;
import de.saxsys.mvvmfx.utils.validation.visualization.ControlsFxVisualizer;
import static org.jabref.gui.util.FieldsUtil.FIELD_STRING_CONVERTER;
public class EditFieldContentTabView extends AbstractAutomaticFieldEditorTabView {
public Button appendValueButton;
public Button clearFieldButton;
public Button setValueButton;
@FXML
private ComboBox<Field> fieldComboBox;
@FXML
private TextField fieldValueTextField;
@FXML
private CheckBox overwriteFieldContentCheckBox;
private final List<BibEntry> selectedEntries;
private final BibDatabase database;
private EditFieldContentViewModel viewModel;
private final StateManager stateManager;
private final ControlsFxVisualizer visualizer = new ControlsFxVisualizer();
public EditFieldContentTabView(BibDatabase database, StateManager stateManager) {
this.selectedEntries = stateManager.getSelectedEntries();
this.database = database;
this.stateManager = stateManager;
ViewLoader.view(this)
.root(this)
.load();
}
@FXML
public void initialize() {
viewModel = new EditFieldContentViewModel(database, selectedEntries, stateManager);
fieldComboBox.setConverter(FIELD_STRING_CONVERTER);
fieldComboBox.getItems().setAll(viewModel.getAllFields());
fieldComboBox.getSelectionModel().selectFirst();
fieldComboBox.valueProperty().bindBidirectional(viewModel.selectedFieldProperty());
EasyBind.listen(fieldComboBox.getEditor().textProperty(), observable -> fieldComboBox.commitValue());
fieldValueTextField.textProperty().bindBidirectional(viewModel.fieldValueProperty());
overwriteFieldContentCheckBox.selectedProperty().bindBidirectional(viewModel.overwriteFieldContentProperty());
appendValueButton.disableProperty().bind(viewModel.canAppendProperty().not());
setValueButton.disableProperty().bind(viewModel.fieldValidationStatus().validProperty().not());
clearFieldButton.disableProperty().bind(viewModel.fieldValidationStatus().validProperty().not());
overwriteFieldContentCheckBox.disableProperty().bind(viewModel.fieldValidationStatus().validProperty().not());
Platform.runLater(() -> visualizer.initVisualization(viewModel.fieldValidationStatus(), fieldComboBox, true));
}
@Override
public String getTabName() {
return Localization.lang("Edit content");
}
@FXML
void appendToFieldValue() {
viewModel.appendToFieldValue();
}
@FXML
void clearField() {
viewModel.clearSelectedField();
}
@FXML
void setFieldValue() {
viewModel.setFieldValue();
}
}
| 3,423
| 32.90099
| 118
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/edit/automaticfiededitor/editfieldcontent/EditFieldContentViewModel.java
|
package org.jabref.gui.edit.automaticfiededitor.editfieldcontent;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import org.jabref.gui.StateManager;
import org.jabref.gui.edit.automaticfiededitor.AbstractAutomaticFieldEditorTabViewModel;
import org.jabref.gui.edit.automaticfiededitor.LastAutomaticFieldEditorEdit;
import org.jabref.gui.undo.NamedCompound;
import org.jabref.gui.undo.UndoableFieldChange;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.strings.StringUtil;
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 EditFieldContentViewModel extends AbstractAutomaticFieldEditorTabViewModel {
public static final int TAB_INDEX = 0;
private final List<BibEntry> selectedEntries;
private final StringProperty fieldValue = new SimpleStringProperty("");
private final ObjectProperty<Field> selectedField = new SimpleObjectProperty<>(StandardField.AUTHOR);
private final BooleanProperty overwriteFieldContent = new SimpleBooleanProperty(Boolean.FALSE);
private final Validator fieldValidator;
private final BooleanBinding canAppend;
public EditFieldContentViewModel(BibDatabase database, List<BibEntry> selectedEntries, StateManager stateManager) {
super(database, stateManager);
this.selectedEntries = new ArrayList<>(selectedEntries);
fieldValidator = new FunctionBasedValidator<>(selectedField, field -> {
if (StringUtil.isBlank(field.getName())) {
return ValidationMessage.error("Field name cannot be empty");
} else if (StringUtil.containsWhitespace(field.getName())) {
return ValidationMessage.error("Field name cannot have whitespace characters");
}
return null;
});
canAppend = Bindings.and(overwriteFieldContentProperty(), fieldValidationStatus().validProperty());
}
public ValidationStatus fieldValidationStatus() {
return fieldValidator.getValidationStatus();
}
public BooleanBinding canAppendProperty() {
return canAppend;
}
public void clearSelectedField() {
NamedCompound clearFieldEdit = new NamedCompound("CLEAR_SELECTED_FIELD");
int affectedEntriesCount = 0;
for (BibEntry entry : selectedEntries) {
Optional<String> oldFieldValue = entry.getField(selectedField.get());
if (oldFieldValue.isPresent()) {
entry.clearField(selectedField.get())
.ifPresent(fieldChange -> clearFieldEdit.addEdit(new UndoableFieldChange(fieldChange)));
affectedEntriesCount++;
}
}
if (clearFieldEdit.hasEdits()) {
clearFieldEdit.end();
}
stateManager.setLastAutomaticFieldEditorEdit(new LastAutomaticFieldEditorEdit(
affectedEntriesCount,
TAB_INDEX,
clearFieldEdit
));
}
public void setFieldValue() {
NamedCompound setFieldEdit = new NamedCompound("CHANGE_SELECTED_FIELD");
String toSetFieldValue = fieldValue.getValue();
int affectedEntriesCount = 0;
for (BibEntry entry : selectedEntries) {
Optional<String> oldFieldValue = entry.getField(selectedField.get());
if (oldFieldValue.isEmpty() || overwriteFieldContent.get()) {
entry.setField(selectedField.get(), toSetFieldValue)
.ifPresent(fieldChange -> setFieldEdit.addEdit(new UndoableFieldChange(fieldChange)));
fieldValue.set("");
// TODO: increment affected entries only when UndoableFieldChange.isPresent()
affectedEntriesCount++;
}
}
if (setFieldEdit.hasEdits()) {
setFieldEdit.end();
}
stateManager.setLastAutomaticFieldEditorEdit(new LastAutomaticFieldEditorEdit(
affectedEntriesCount,
TAB_INDEX,
setFieldEdit
));
}
public void appendToFieldValue() {
NamedCompound appendToFieldEdit = new NamedCompound("APPEND_TO_SELECTED_FIELD");
String toAppendFieldValue = fieldValue.getValue();
int affectedEntriesCount = 0;
for (BibEntry entry : selectedEntries) {
Optional<String> oldFieldValue = entry.getField(selectedField.get());
// Append button should be disabled if 'overwriteNonEmptyFields' is false
if (overwriteFieldContent.get()) {
String newFieldValue = oldFieldValue.orElse("").concat(toAppendFieldValue);
entry.setField(selectedField.get(), newFieldValue)
.ifPresent(fieldChange -> appendToFieldEdit.addEdit(new UndoableFieldChange(fieldChange)));
fieldValue.set("");
affectedEntriesCount++;
}
}
if (appendToFieldEdit.hasEdits()) {
appendToFieldEdit.end();
}
stateManager.setLastAutomaticFieldEditorEdit(new LastAutomaticFieldEditorEdit(
affectedEntriesCount,
TAB_INDEX,
appendToFieldEdit
));
}
public ObjectProperty<Field> selectedFieldProperty() {
return selectedField;
}
public Field getSelectedField() {
return selectedFieldProperty().get();
}
public String getFieldValue() {
return fieldValue.get();
}
public StringProperty fieldValueProperty() {
return fieldValue;
}
public BooleanProperty overwriteFieldContentProperty() {
return overwriteFieldContent;
}
}
| 6,338
| 37.418182
| 119
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/edit/automaticfiededitor/renamefield/RenameFieldTabView.java
|
package org.jabref.gui.edit.automaticfiededitor.renamefield;
import java.util.List;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import org.jabref.gui.StateManager;
import org.jabref.gui.edit.automaticfiededitor.AbstractAutomaticFieldEditorTabView;
import org.jabref.gui.edit.automaticfiededitor.AutomaticFieldEditorTab;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.Field;
import com.airhacks.afterburner.views.ViewLoader;
import com.tobiasdiez.easybind.EasyBind;
import de.saxsys.mvvmfx.utils.validation.visualization.ControlsFxVisualizer;
import static org.jabref.gui.util.FieldsUtil.FIELD_STRING_CONVERTER;
public class RenameFieldTabView extends AbstractAutomaticFieldEditorTabView implements AutomaticFieldEditorTab {
@FXML
private Button renameButton;
@FXML
private ComboBox<Field> fieldComboBox;
@FXML
private TextField newFieldNameTextField;
private final List<BibEntry> selectedEntries;
private final BibDatabase database;
private final StateManager stateManager;
private RenameFieldViewModel viewModel;
private final ControlsFxVisualizer visualizer = new ControlsFxVisualizer();
public RenameFieldTabView(BibDatabase database, StateManager stateManager) {
this.selectedEntries = stateManager.getSelectedEntries();
this.database = database;
this.stateManager = stateManager;
ViewLoader.view(this)
.root(this)
.load();
}
@FXML
public void initialize() {
viewModel = new RenameFieldViewModel(selectedEntries, database, stateManager);
fieldComboBox.getItems().setAll(viewModel.getAllFields());
fieldComboBox.getSelectionModel().selectFirst();
fieldComboBox.setConverter(FIELD_STRING_CONVERTER);
fieldComboBox.valueProperty().bindBidirectional(viewModel.selectedFieldProperty());
EasyBind.listen(fieldComboBox.getEditor().textProperty(), observable -> fieldComboBox.commitValue());
renameButton.disableProperty().bind(viewModel.canRenameProperty().not());
newFieldNameTextField.textProperty().bindBidirectional(viewModel.newFieldNameProperty());
Platform.runLater(() -> {
visualizer.initVisualization(viewModel.fieldNameValidationStatus(), newFieldNameTextField, true);
});
}
@Override
public String getTabName() {
return Localization.lang("Rename field");
}
@FXML
void renameField() {
viewModel.renameField();
}
}
| 2,751
| 33.4
| 112
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/edit/automaticfiededitor/renamefield/RenameFieldViewModel.java
|
package org.jabref.gui.edit.automaticfiededitor.renamefield;
import java.util.List;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import org.jabref.gui.StateManager;
import org.jabref.gui.edit.automaticfiededitor.AbstractAutomaticFieldEditorTabViewModel;
import org.jabref.gui.edit.automaticfiededitor.LastAutomaticFieldEditorEdit;
import org.jabref.gui.edit.automaticfiededitor.MoveFieldValueAction;
import org.jabref.gui.undo.NamedCompound;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.FieldFactory;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.strings.StringUtil;
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 RenameFieldViewModel extends AbstractAutomaticFieldEditorTabViewModel {
public static final int TAB_INDEX = 2;
private final StringProperty newFieldName = new SimpleStringProperty("");
private final ObjectProperty<Field> selectedField = new SimpleObjectProperty<>(StandardField.AUTHOR);
private final List<BibEntry> selectedEntries;
private final Validator fieldValidator;
private final Validator fieldNameValidator;
private final BooleanBinding canRename;
public RenameFieldViewModel(List<BibEntry> selectedEntries, BibDatabase database, StateManager stateManager) {
super(database, stateManager);
this.selectedEntries = selectedEntries;
fieldValidator = new FunctionBasedValidator<>(selectedField, field -> StringUtil.isNotBlank(field.getName()),
ValidationMessage.error("Field cannot be empty"));
fieldNameValidator = new FunctionBasedValidator<>(newFieldName, fieldName -> {
if (StringUtil.isBlank(fieldName)) {
return ValidationMessage.error("Field name cannot be empty");
} else if (StringUtil.containsWhitespace(fieldName)) {
return ValidationMessage.error("Field name cannot have whitespace characters");
}
return null;
});
canRename = Bindings.and(fieldValidationStatus().validProperty(), fieldNameValidationStatus().validProperty());
}
public ValidationStatus fieldValidationStatus() {
return fieldValidator.getValidationStatus();
}
public ValidationStatus fieldNameValidationStatus() {
return fieldNameValidator.getValidationStatus();
}
public BooleanBinding canRenameProperty() {
return canRename;
}
public String getNewFieldName() {
return newFieldName.get();
}
public StringProperty newFieldNameProperty() {
return newFieldName;
}
public void setNewFieldName(String newName) {
newFieldNameProperty().set(newName);
}
public Field getSelectedField() {
return selectedField.get();
}
public ObjectProperty<Field> selectedFieldProperty() {
return selectedField;
}
public void selectField(Field field) {
selectedFieldProperty().set(field);
}
public void renameField() {
NamedCompound renameEdit = new NamedCompound("RENAME_EDIT");
int affectedEntriesCount = 0;
if (fieldNameValidationStatus().isValid()) {
affectedEntriesCount = new MoveFieldValueAction(selectedField.get(),
FieldFactory.parseField(newFieldName.get()),
selectedEntries,
renameEdit,
false).executeAndGetAffectedEntriesCount();
if (renameEdit.hasEdits()) {
renameEdit.end();
}
}
stateManager.setLastAutomaticFieldEditorEdit(new LastAutomaticFieldEditorEdit(
affectedEntriesCount, TAB_INDEX, renameEdit
));
}
}
| 4,228
| 35.773913
| 119
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/entryeditor/CommentsTab.java
|
package org.jabref.gui.entryeditor;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.swing.undo.UndoManager;
import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.autocompleter.SuggestionProviders;
import org.jabref.gui.fieldeditors.FieldEditorFX;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.theme.ThemeManager;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.pdf.search.indexing.IndexingTaskManager;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.field.UserSpecificCommentField;
import org.jabref.preferences.PreferencesService;
public class CommentsTab extends FieldsEditorTab {
public static final String NAME = "Comments";
private final String defaultOwner;
public CommentsTab(PreferencesService preferences,
BibDatabaseContext databaseContext,
SuggestionProviders suggestionProviders,
UndoManager undoManager,
DialogService dialogService,
StateManager stateManager,
ThemeManager themeManager,
IndexingTaskManager indexingTaskManager,
TaskExecutor taskExecutor,
JournalAbbreviationRepository journalAbbreviationRepository) {
super(
false,
databaseContext,
suggestionProviders,
undoManager,
dialogService,
preferences,
stateManager,
themeManager,
taskExecutor,
journalAbbreviationRepository,
indexingTaskManager
);
this.defaultOwner = preferences.getOwnerPreferences().getDefaultOwner();
setText(Localization.lang("Comments"));
setGraphic(IconTheme.JabRefIcons.COMMENT.getGraphicNode());
}
@Override
protected Set<Field> determineFieldsToShow(BibEntry entry) {
UserSpecificCommentField defaultCommentField = new UserSpecificCommentField(defaultOwner);
// As default: Show BibTeX comment field and the user-specific comment field of the default owner
Set<Field> comments = new LinkedHashSet<>(Set.of(defaultCommentField, StandardField.COMMENT));
comments.addAll(entry.getFields().stream()
.filter(field -> field instanceof UserSpecificCommentField ||
field.getName().toLowerCase().contains("comment"))
.collect(Collectors.toSet()));
return comments;
}
@Override
protected void setupPanel(BibEntry entry, boolean compressed) {
super.setupPanel(entry, compressed);
for (Map.Entry<Field, FieldEditorFX> fieldEditorEntry : editors.entrySet()) {
Field field = fieldEditorEntry.getKey();
FieldEditorFX editor = fieldEditorEntry.getValue();
if (field instanceof UserSpecificCommentField) {
if (field.getName().contains(defaultOwner)) {
editor.getNode().setDisable(false);
}
} else {
editor.getNode().setDisable(!field.getName().equals(StandardField.COMMENT.getName()));
}
}
}
}
| 3,662
| 38.815217
| 105
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/entryeditor/DeprecatedFieldsTab.java
|
package org.jabref.gui.entryeditor;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.swing.undo.UndoManager;
import javafx.scene.control.Tooltip;
import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.autocompleter.SuggestionProviders;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.theme.ThemeManager;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.pdf.search.indexing.IndexingTaskManager;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.database.BibDatabaseMode;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.BibEntryType;
import org.jabref.model.entry.BibEntryTypesManager;
import org.jabref.model.entry.field.Field;
import org.jabref.preferences.PreferencesService;
import com.tobiasdiez.easybind.EasyBind;
public class DeprecatedFieldsTab extends FieldsEditorTab {
public static final String NAME = "Deprecated fields";
private final BibEntryTypesManager entryTypesManager;
public DeprecatedFieldsTab(BibDatabaseContext databaseContext,
SuggestionProviders suggestionProviders,
UndoManager undoManager,
DialogService dialogService,
PreferencesService preferences,
StateManager stateManager,
ThemeManager themeManager,
IndexingTaskManager indexingTaskManager,
BibEntryTypesManager entryTypesManager,
TaskExecutor taskExecutor,
JournalAbbreviationRepository journalAbbreviationRepository) {
super(false, databaseContext, suggestionProviders, undoManager, dialogService, preferences, stateManager, themeManager, taskExecutor, journalAbbreviationRepository, indexingTaskManager);
this.entryTypesManager = entryTypesManager;
setText(Localization.lang("Deprecated fields"));
EasyBind.subscribe(preferences.getWorkspacePreferences().showAdvancedHintsProperty(), advancedHints -> {
if (advancedHints) {
setTooltip(new Tooltip(Localization.lang("Shows fields having a successor in biblatex.\nFor instance, the publication month should be part of the date field.\nUse the Cleanup Entries functionality to convert the entry to biblatex.")));
} else {
setTooltip(new Tooltip(Localization.lang("Shows fields having a successor in biblatex.")));
}
});
setGraphic(IconTheme.JabRefIcons.OPTIONAL.getGraphicNode());
}
@Override
protected Set<Field> determineFieldsToShow(BibEntry entry) {
BibDatabaseMode mode = databaseContext.getMode();
Optional<BibEntryType> entryType = entryTypesManager.enrich(entry.getType(), mode);
if (entryType.isPresent()) {
return entryType.get().getDeprecatedFields(mode).stream().filter(field -> !entry.getField(field).isEmpty()).collect(Collectors.toSet());
} else {
// Entry type unknown -> treat all fields as required
return Collections.emptySet();
}
}
}
| 3,427
| 45.958904
| 251
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/entryeditor/EntryEditor.java
|
package org.jabref.gui.entryeditor;
import java.io.File;
import java.nio.file.Path;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.SortedSet;
import java.util.stream.Collectors;
import javafx.fxml.FXML;
import javafx.geometry.Side;
import javafx.scene.control.Button;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.input.DataFormat;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.BorderPane;
import org.jabref.gui.DialogService;
import org.jabref.gui.LibraryTab;
import org.jabref.gui.StateManager;
import org.jabref.gui.citationkeypattern.GenerateCitationKeySingleAction;
import org.jabref.gui.cleanup.CleanupSingleAction;
import org.jabref.gui.entryeditor.fileannotationtab.FileAnnotationTab;
import org.jabref.gui.entryeditor.fileannotationtab.FulltextSearchResultsTab;
import org.jabref.gui.externalfiles.ExternalFilesEntryLinker;
import org.jabref.gui.help.HelpAction;
import org.jabref.gui.importer.GrobidOptInDialogHelper;
import org.jabref.gui.keyboard.KeyBinding;
import org.jabref.gui.keyboard.KeyBindingRepository;
import org.jabref.gui.menus.ChangeEntryTypeMenu;
import org.jabref.gui.mergeentries.FetchAndMergeEntry;
import org.jabref.gui.theme.ThemeManager;
import org.jabref.gui.undo.CountingUndoManager;
import org.jabref.gui.util.DefaultTaskExecutor;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.TypedBibEntry;
import org.jabref.logic.help.HelpFile;
import org.jabref.logic.importer.EntryBasedFetcher;
import org.jabref.logic.importer.WebFetchers;
import org.jabref.logic.importer.fileformat.PdfMergeMetadataImporter;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.BibEntryTypesManager;
import org.jabref.model.entry.field.Field;
import org.jabref.model.util.FileUpdateMonitor;
import org.jabref.preferences.PreferencesService;
import com.airhacks.afterburner.views.ViewLoader;
import com.tobiasdiez.easybind.EasyBind;
import com.tobiasdiez.easybind.Subscription;
import jakarta.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* GUI component that allows editing of the fields of a BibEntry (i.e. the one that shows up, when you double click on
* an entry in the table)
* <p>
* It hosts the tabs (required, general, optional) and the buttons to the left.
* <p>
* EntryEditor also registers itself to the event bus, receiving events whenever a field of the entry changes, enabling
* the text fields to update themselves if the change is made from somewhere else.
*/
public class EntryEditor extends BorderPane {
private static final Logger LOGGER = LoggerFactory.getLogger(EntryEditor.class);
private final LibraryTab libraryTab;
private final BibDatabaseContext databaseContext;
private final EntryEditorPreferences entryEditorPreferences;
private final ExternalFilesEntryLinker fileLinker;
/*
* Tabs which can apply filter, but seems non-sense
* */
private final List<EntryEditorTab> tabs;
private Subscription typeSubscription;
/*
* A reference to the entry this editor works on.
* */
private BibEntry entry;
private SourceTab sourceTab;
/*
* tabs to be showed in GUI
* */
@FXML private TabPane tabbed;
@FXML private Button typeChangeButton;
@FXML private Button fetcherButton;
@FXML private Label typeLabel;
@Inject private DialogService dialogService;
@Inject private TaskExecutor taskExecutor;
@Inject private PreferencesService preferencesService;
@Inject private StateManager stateManager;
@Inject private ThemeManager themeManager;
@Inject private FileUpdateMonitor fileMonitor;
@Inject private CountingUndoManager undoManager;
@Inject private BibEntryTypesManager bibEntryTypesManager;
@Inject private KeyBindingRepository keyBindingRepository;
@Inject private JournalAbbreviationRepository journalAbbreviationRepository;
private final List<EntryEditorTab> entryEditorTabs = new LinkedList<>();
public EntryEditor(LibraryTab libraryTab) {
this.libraryTab = libraryTab;
this.databaseContext = libraryTab.getBibDatabaseContext();
ViewLoader.view(this)
.root(this)
.load();
this.entryEditorPreferences = preferencesService.getEntryEditorPreferences();
this.fileLinker = new ExternalFilesEntryLinker(preferencesService.getFilePreferences(), databaseContext);
EasyBind.subscribe(tabbed.getSelectionModel().selectedItemProperty(), tab -> {
EntryEditorTab activeTab = (EntryEditorTab) tab;
if (activeTab != null) {
activeTab.notifyAboutFocus(entry);
}
});
setupKeyBindings();
this.tabs = createTabs();
this.setOnDragOver(event -> {
if (event.getDragboard().hasFiles()) {
event.acceptTransferModes(TransferMode.COPY, TransferMode.MOVE, TransferMode.LINK);
}
event.consume();
});
this.setOnDragDropped(event -> {
BibEntry entry = this.getEntry();
boolean success = false;
if (event.getDragboard().hasContent(DataFormat.FILES)) {
List<Path> files = event.getDragboard().getFiles().stream().map(File::toPath).collect(Collectors.toList());
switch (event.getTransferMode()) {
case COPY -> {
LOGGER.debug("Mode COPY");
fileLinker.copyFilesToFileDirAndAddToEntry(entry, files, libraryTab.getIndexingTaskManager());
}
case MOVE -> {
LOGGER.debug("Mode MOVE");
fileLinker.moveFilesToFileDirAndAddToEntry(entry, files, libraryTab.getIndexingTaskManager());
}
case LINK -> {
LOGGER.debug("Mode LINK");
fileLinker.addFilesToEntry(entry, files);
}
}
success = true;
}
event.setDropCompleted(success);
event.consume();
});
}
/**
* Set-up key bindings specific for the entry editor.
*/
private void setupKeyBindings() {
this.addEventHandler(KeyEvent.KEY_PRESSED, event -> {
Optional<KeyBinding> keyBinding = keyBindingRepository.mapToKeyBinding(event);
if (keyBinding.isPresent()) {
switch (keyBinding.get()) {
case ENTRY_EDITOR_NEXT_PANEL:
case ENTRY_EDITOR_NEXT_PANEL_2:
tabbed.getSelectionModel().selectNext();
event.consume();
break;
case ENTRY_EDITOR_PREVIOUS_PANEL:
case ENTRY_EDITOR_PREVIOUS_PANEL_2:
tabbed.getSelectionModel().selectPrevious();
event.consume();
break;
case ENTRY_EDITOR_NEXT_ENTRY:
libraryTab.selectNextEntry();
event.consume();
break;
case ENTRY_EDITOR_PREVIOUS_ENTRY:
libraryTab.selectPreviousEntry();
event.consume();
break;
case HELP:
new HelpAction(HelpFile.ENTRY_EDITOR, dialogService).execute();
event.consume();
break;
case CLOSE:
case EDIT_ENTRY:
close();
event.consume();
break;
default:
// Pass other keys to parent
}
}
});
}
@FXML
public void close() {
libraryTab.entryEditorClosing();
}
@FXML
private void deleteEntry() {
libraryTab.delete(entry);
}
@FXML
void generateCiteKeyButton() {
GenerateCitationKeySingleAction action = new GenerateCitationKeySingleAction(getEntry(), databaseContext,
dialogService, preferencesService, undoManager);
action.execute();
}
@FXML
void generateCleanupButton() {
CleanupSingleAction action = new CleanupSingleAction(getEntry(), preferencesService, dialogService, stateManager, undoManager);
action.execute();
}
@FXML
private void navigateToPreviousEntry() {
libraryTab.selectPreviousEntry();
}
@FXML
private void navigateToNextEntry() {
libraryTab.selectNextEntry();
}
private List<EntryEditorTab> createTabs() {
entryEditorTabs.add(new PreviewTab(databaseContext, dialogService, preferencesService, stateManager, themeManager, libraryTab.getIndexingTaskManager()));
// Required, optional, deprecated, and "other" fields
entryEditorTabs.add(new RequiredFieldsTab(databaseContext, libraryTab.getSuggestionProviders(), undoManager, dialogService, preferencesService, stateManager, themeManager, libraryTab.getIndexingTaskManager(), bibEntryTypesManager, taskExecutor, journalAbbreviationRepository));
entryEditorTabs.add(new OptionalFieldsTab(databaseContext, libraryTab.getSuggestionProviders(), undoManager, dialogService, preferencesService, stateManager, themeManager, libraryTab.getIndexingTaskManager(), bibEntryTypesManager, taskExecutor, journalAbbreviationRepository));
entryEditorTabs.add(new OptionalFields2Tab(databaseContext, libraryTab.getSuggestionProviders(), undoManager, dialogService, preferencesService, stateManager, themeManager, libraryTab.getIndexingTaskManager(), bibEntryTypesManager, taskExecutor, journalAbbreviationRepository));
entryEditorTabs.add(new DeprecatedFieldsTab(databaseContext, libraryTab.getSuggestionProviders(), undoManager, dialogService, preferencesService, stateManager, themeManager, libraryTab.getIndexingTaskManager(), bibEntryTypesManager, taskExecutor, journalAbbreviationRepository));
entryEditorTabs.add(new OtherFieldsTab(databaseContext, libraryTab.getSuggestionProviders(), undoManager, dialogService, preferencesService, stateManager, themeManager, libraryTab.getIndexingTaskManager(), bibEntryTypesManager, taskExecutor, journalAbbreviationRepository));
// Comment Tab: Tab for general and user-specific comments
entryEditorTabs.add(new CommentsTab(preferencesService, databaseContext, libraryTab.getSuggestionProviders(), undoManager, dialogService, stateManager, themeManager, libraryTab.getIndexingTaskManager(), taskExecutor, journalAbbreviationRepository));
// General fields from preferences
// First, remove all tabs that are already handled above or below; except for the source tab (which has different titles for BibTeX and BibLaTeX mode)
Map<String, Set<Field>> entryEditorTabList = new HashMap<>(entryEditorPreferences.getEntryEditorTabs());
entryEditorTabList.remove(PreviewTab.NAME);
entryEditorTabList.remove(RequiredFieldsTab.NAME);
entryEditorTabList.remove(OptionalFieldsTab.NAME);
entryEditorTabList.remove(OptionalFields2Tab.NAME);
entryEditorTabList.remove(DeprecatedFieldsTab.NAME);
entryEditorTabList.remove(CommentsTab.NAME);
entryEditorTabList.remove(MathSciNetTab.NAME);
entryEditorTabList.remove(FileAnnotationTab.NAME);
entryEditorTabList.remove(RelatedArticlesTab.NAME);
entryEditorTabList.remove(LatexCitationsTab.NAME);
entryEditorTabList.remove(FulltextSearchResultsTab.NAME);
entryEditorTabList.remove("Comments");
// Then show the remaining configured
for (Map.Entry<String, Set<Field>> tab : entryEditorTabList.entrySet()) {
entryEditorTabs.add(new UserDefinedFieldsTab(tab.getKey(), tab.getValue(), databaseContext, libraryTab.getSuggestionProviders(), undoManager, dialogService, preferencesService, stateManager, themeManager, libraryTab.getIndexingTaskManager(), taskExecutor, journalAbbreviationRepository));
}
// "Special" tabs
entryEditorTabs.add(new MathSciNetTab());
entryEditorTabs.add(new FileAnnotationTab(libraryTab.getAnnotationCache()));
entryEditorTabs.add(new RelatedArticlesTab(this, entryEditorPreferences, preferencesService, dialogService));
sourceTab = new SourceTab(
databaseContext,
undoManager,
preferencesService.getFieldPreferences(),
preferencesService.getImportFormatPreferences(),
fileMonitor,
dialogService,
stateManager,
keyBindingRepository);
entryEditorTabs.add(sourceTab);
entryEditorTabs.add(new LatexCitationsTab(databaseContext, preferencesService, taskExecutor, dialogService));
entryEditorTabs.add(new FulltextSearchResultsTab(stateManager, preferencesService, dialogService));
return entryEditorTabs;
}
private void recalculateVisibleTabs() {
List<Tab> visibleTabs = tabs.stream().filter(tab -> tab.shouldShow(entry)).collect(Collectors.toList());
// Start of ugly hack:
// We need to find out, which tabs will be shown and which not and remove and re-add the appropriate tabs
// to the editor. We don't want to simply remove all and re-add the complete list of visible tabs, because
// the tabs give an ugly animation the looks like all tabs are shifting in from the right.
// This hack is required since tabbed.getTabs().setAll(visibleTabs) changes the order of the tabs in the editor
// First, remove tabs that we do not want to show
List<EntryEditorTab> toBeRemoved = tabs.stream().filter(tab -> !tab.shouldShow(entry)).collect(Collectors.toList());
tabbed.getTabs().removeAll(toBeRemoved);
// Next add all the visible tabs (if not already present) at the right position
for (int i = 0; i < visibleTabs.size(); i++) {
Tab toBeAdded = visibleTabs.get(i);
Tab shown = null;
if (i < tabbed.getTabs().size()) {
shown = tabbed.getTabs().get(i);
}
if (!toBeAdded.equals(shown)) {
tabbed.getTabs().add(i, toBeAdded);
}
}
}
/**
* @return the currently edited entry
*/
public BibEntry getEntry() {
return entry;
}
/**
* Sets the entry to edit.
*/
public void setEntry(BibEntry entry) {
Objects.requireNonNull(entry);
// Remove subscription for old entry if existing
if (typeSubscription != null) {
typeSubscription.unsubscribe();
}
this.entry = entry;
recalculateVisibleTabs();
EasyBind.listen(preferencesService.getPreviewPreferences().showPreviewAsExtraTabProperty(),
(obs, oldValue, newValue) -> recalculateVisibleTabs());
if (entryEditorPreferences.showSourceTabByDefault()) {
tabbed.getSelectionModel().select(sourceTab);
}
// Notify current tab about new entry
getSelectedTab().notifyAboutFocus(entry);
setupToolBar();
// Subscribe to type changes for rebuilding the currently visible tab
typeSubscription = EasyBind.subscribe(this.entry.typeProperty(), type -> {
typeLabel.setText(new TypedBibEntry(entry, databaseContext.getMode()).getTypeForDisplay());
recalculateVisibleTabs();
getSelectedTab().notifyAboutFocus(entry);
});
}
private EntryEditorTab getSelectedTab() {
return (EntryEditorTab) tabbed.getSelectionModel().getSelectedItem();
}
private void setupToolBar() {
// Update type label
TypedBibEntry typedEntry = new TypedBibEntry(entry, databaseContext.getMode());
typeLabel.setText(typedEntry.getTypeForDisplay());
// Add type change menu
ContextMenu typeMenu = new ChangeEntryTypeMenu(Collections.singletonList(entry), databaseContext, undoManager, keyBindingRepository, bibEntryTypesManager).asContextMenu();
typeLabel.setOnMouseClicked(event -> typeMenu.show(typeLabel, Side.RIGHT, 0, 0));
typeChangeButton.setOnMouseClicked(event -> typeMenu.show(typeChangeButton, Side.RIGHT, 0, 0));
// Add menu for fetching bibliographic information
ContextMenu fetcherMenu = new ContextMenu();
SortedSet<EntryBasedFetcher> entryBasedFetchers = WebFetchers.getEntryBasedFetchers(
preferencesService.getImporterPreferences(),
preferencesService.getImportFormatPreferences(),
preferencesService.getFilePreferences(),
databaseContext);
for (EntryBasedFetcher fetcher : entryBasedFetchers) {
MenuItem fetcherMenuItem = new MenuItem(fetcher.getName());
if (fetcher instanceof PdfMergeMetadataImporter.EntryBasedFetcherWrapper) {
// Handle Grobid Opt-In in case of the PdfMergeMetadataImporter
fetcherMenuItem.setOnAction(event -> {
GrobidOptInDialogHelper.showAndWaitIfUserIsUndecided(dialogService, preferencesService.getGrobidPreferences());
PdfMergeMetadataImporter.EntryBasedFetcherWrapper pdfMergeMetadataImporter =
new PdfMergeMetadataImporter.EntryBasedFetcherWrapper(
preferencesService.getImportFormatPreferences(),
preferencesService.getFilePreferences(),
databaseContext);
fetchAndMerge(pdfMergeMetadataImporter);
});
} else {
fetcherMenuItem.setOnAction(event -> fetchAndMerge(fetcher));
}
fetcherMenu.getItems().add(fetcherMenuItem);
}
fetcherButton.setOnMouseClicked(event -> fetcherMenu.show(fetcherButton, Side.RIGHT, 0, 0));
}
private void fetchAndMerge(EntryBasedFetcher fetcher) {
new FetchAndMergeEntry(libraryTab, taskExecutor, preferencesService, dialogService).fetchAndMerge(entry, fetcher);
}
public void setFocusToField(Field field) {
DefaultTaskExecutor.runInJavaFXThread(() -> {
for (Tab tab : tabbed.getTabs()) {
if ((tab instanceof FieldsEditorTab fieldsEditorTab)
&& fieldsEditorTab.getShownFields().contains(field)) {
tabbed.getSelectionModel().select(tab);
fieldsEditorTab.requestFocus(field);
}
}
});
}
public void nextPreviewStyle() {
this.entryEditorTabs.forEach(EntryEditorTab::nextPreviewStyle);
}
public void previousPreviewStyle() {
this.entryEditorTabs.forEach(EntryEditorTab::previousPreviewStyle);
}
}
| 19,489
| 43.295455
| 300
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/entryeditor/EntryEditorPreferences.java
|
package org.jabref.gui.entryeditor;
import java.util.Map;
import java.util.Set;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.MapProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleMapProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableMap;
import org.jabref.model.entry.field.Field;
public class EntryEditorPreferences {
private final MapProperty<String, Set<Field>> entryEditorTabList;
private final MapProperty<String, Set<Field>> defaultEntryEditorTabList;
private final BooleanProperty shouldOpenOnNewEntry;
private final BooleanProperty shouldShowRecommendationsTab;
private final BooleanProperty isMrdlibAccepted;
private final BooleanProperty shouldShowLatexCitationsTab;
private final BooleanProperty showSourceTabByDefault;
private final BooleanProperty enableValidation;
private final BooleanProperty allowIntegerEditionBibtex;
private final DoubleProperty dividerPosition;
private final BooleanProperty autoLinkFiles;
public EntryEditorPreferences(Map<String, Set<Field>> entryEditorTabList,
Map<String, Set<Field>> defaultEntryEditorTabList,
boolean shouldOpenOnNewEntry,
boolean shouldShowRecommendationsTab,
boolean isMrdlibAccepted,
boolean shouldShowLatexCitationsTab,
boolean showSourceTabByDefault,
boolean enableValidation,
boolean allowIntegerEditionBibtex,
double dividerPosition,
boolean autolinkFilesEnabled) {
this.entryEditorTabList = new SimpleMapProperty<>(FXCollections.observableMap(entryEditorTabList));
this.defaultEntryEditorTabList = new SimpleMapProperty<>(FXCollections.observableMap(defaultEntryEditorTabList));
this.shouldOpenOnNewEntry = new SimpleBooleanProperty(shouldOpenOnNewEntry);
this.shouldShowRecommendationsTab = new SimpleBooleanProperty(shouldShowRecommendationsTab);
this.isMrdlibAccepted = new SimpleBooleanProperty(isMrdlibAccepted);
this.shouldShowLatexCitationsTab = new SimpleBooleanProperty(shouldShowLatexCitationsTab);
this.showSourceTabByDefault = new SimpleBooleanProperty(showSourceTabByDefault);
this.enableValidation = new SimpleBooleanProperty(enableValidation);
this.allowIntegerEditionBibtex = new SimpleBooleanProperty(allowIntegerEditionBibtex);
this.dividerPosition = new SimpleDoubleProperty(dividerPosition);
this.autoLinkFiles = new SimpleBooleanProperty(autolinkFilesEnabled);
}
public ObservableMap<String, Set<Field>> getEntryEditorTabs() {
return entryEditorTabList.get();
}
public MapProperty<String, Set<Field>> entryEditorTabs() {
return entryEditorTabList;
}
public void setEntryEditorTabList(Map<String, Set<Field>> entryEditorTabList) {
this.entryEditorTabList.set(FXCollections.observableMap(entryEditorTabList));
}
public ObservableMap<String, Set<Field>> getDefaultEntryEditorTabs() {
return defaultEntryEditorTabList.get();
}
public boolean shouldOpenOnNewEntry() {
return shouldOpenOnNewEntry.get();
}
public BooleanProperty shouldOpenOnNewEntryProperty() {
return shouldOpenOnNewEntry;
}
public void setShouldOpenOnNewEntry(boolean shouldOpenOnNewEntry) {
this.shouldOpenOnNewEntry.set(shouldOpenOnNewEntry);
}
public boolean shouldShowRecommendationsTab() {
return shouldShowRecommendationsTab.get();
}
public BooleanProperty shouldShowRecommendationsTabProperty() {
return shouldShowRecommendationsTab;
}
public void setShouldShowRecommendationsTab(boolean shouldShowRecommendationsTab) {
this.shouldShowRecommendationsTab.set(shouldShowRecommendationsTab);
}
public boolean isMrdlibAccepted() {
return isMrdlibAccepted.get();
}
public BooleanProperty isMrdlibAcceptedProperty() {
return isMrdlibAccepted;
}
public void setIsMrdlibAccepted(boolean isMrdlibAccepted) {
this.isMrdlibAccepted.set(isMrdlibAccepted);
}
public boolean shouldShowLatexCitationsTab() {
return shouldShowLatexCitationsTab.get();
}
public BooleanProperty shouldShowLatexCitationsTabProperty() {
return shouldShowLatexCitationsTab;
}
public void setShouldShowLatexCitationsTab(boolean shouldShowLatexCitationsTab) {
this.shouldShowLatexCitationsTab.set(shouldShowLatexCitationsTab);
}
public boolean showSourceTabByDefault() {
return showSourceTabByDefault.get();
}
public BooleanProperty showSourceTabByDefaultProperty() {
return showSourceTabByDefault;
}
public void setShowSourceTabByDefault(boolean showSourceTabByDefault) {
this.showSourceTabByDefault.set(showSourceTabByDefault);
}
public boolean shouldEnableValidation() {
return enableValidation.get();
}
public BooleanProperty enableValidationProperty() {
return enableValidation;
}
public void setEnableValidation(boolean enableValidation) {
this.enableValidation.set(enableValidation);
}
public boolean shouldAllowIntegerEditionBibtex() {
return allowIntegerEditionBibtex.get();
}
public BooleanProperty allowIntegerEditionBibtexProperty() {
return allowIntegerEditionBibtex;
}
public void setAllowIntegerEditionBibtex(boolean allowIntegerEditionBibtex) {
this.allowIntegerEditionBibtex.set(allowIntegerEditionBibtex);
}
public double getDividerPosition() {
return dividerPosition.get();
}
public DoubleProperty dividerPositionProperty() {
return dividerPosition;
}
public void setDividerPosition(double dividerPosition) {
this.dividerPosition.set(dividerPosition);
}
public boolean autoLinkFilesEnabled() {
return this.autoLinkFiles.getValue();
}
public BooleanProperty autoLinkEnabledProperty() {
return this.autoLinkFiles;
}
public void setAutoLinkFilesEnabled(boolean enabled) {
this.autoLinkFiles.setValue(enabled);
}
}
| 6,570
| 35.505556
| 121
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/entryeditor/EntryEditorTab.java
|
package org.jabref.gui.entryeditor;
import javafx.scene.control.Tab;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.types.EntryType;
public abstract class EntryEditorTab extends Tab {
protected BibEntry currentEntry;
/**
* Needed to track for which type of entry this tab was build and to rebuild it if the type changes
*/
private EntryType currentEntryType;
/**
* Decide whether to show this tab for the given entry.
*/
public abstract boolean shouldShow(BibEntry entry);
/**
* Updates the view with the contents of the given entry.
*/
protected abstract void bindToEntry(BibEntry entry);
/**
* The tab just got the focus. Override this method if you want to perform a special action on focus (like selecting
* the first field in the editor)
*/
protected void handleFocus() {
// Do nothing by default
}
/**
* Notifies the tab that it got focus and should display the given entry.
*/
public void notifyAboutFocus(BibEntry entry) {
if (!entry.equals(currentEntry) || !entry.getType().equals(currentEntryType)) {
currentEntry = entry;
currentEntryType = entry.getType();
bindToEntry(entry);
}
handleFocus();
}
/**
* Switch to next Preview style - should be overriden if a EntryEditorTab is actually showing a preview
*/
protected void nextPreviewStyle() {
// do nothing by default
}
/**
* Switch to previous Preview style - should be overriden if a EntryEditorTab is actually showing a preview
*/
protected void previousPreviewStyle() {
// do nothing by default
}
}
| 1,733
| 27.42623
| 120
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/entryeditor/FieldsEditorTab.java
|
package org.jabref.gui.entryeditor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Stream;
import javax.swing.undo.UndoManager;
import javafx.geometry.VPos;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.SplitPane;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.RowConstraints;
import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.autocompleter.SuggestionProviders;
import org.jabref.gui.fieldeditors.FieldEditorFX;
import org.jabref.gui.fieldeditors.FieldEditors;
import org.jabref.gui.fieldeditors.FieldNameLabel;
import org.jabref.gui.preview.PreviewPanel;
import org.jabref.gui.theme.ThemeManager;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.logic.pdf.search.indexing.IndexingTaskManager;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.Field;
import org.jabref.preferences.PreferencesService;
import com.tobiasdiez.easybind.EasyBind;
/**
* A single tab displayed in the EntryEditor holding several FieldEditors.
*/
abstract class FieldsEditorTab extends EntryEditorTab {
protected final BibDatabaseContext databaseContext;
protected final Map<Field, FieldEditorFX> editors = new LinkedHashMap<>();
private final boolean isCompressed;
private final SuggestionProviders suggestionProviders;
private final DialogService dialogService;
private final PreferencesService preferences;
private final ThemeManager themeManager;
private final TaskExecutor taskExecutor;
private final JournalAbbreviationRepository journalAbbreviationRepository;
private final StateManager stateManager;
private final IndexingTaskManager indexingTaskManager;
private PreviewPanel previewPanel;
private final UndoManager undoManager;
private Collection<Field> fields = new ArrayList<>();
private GridPane gridPane;
public FieldsEditorTab(boolean compressed,
BibDatabaseContext databaseContext,
SuggestionProviders suggestionProviders,
UndoManager undoManager,
DialogService dialogService,
PreferencesService preferences,
StateManager stateManager,
ThemeManager themeManager,
TaskExecutor taskExecutor,
JournalAbbreviationRepository journalAbbreviationRepository,
IndexingTaskManager indexingTaskManager) {
this.isCompressed = compressed;
this.databaseContext = Objects.requireNonNull(databaseContext);
this.suggestionProviders = Objects.requireNonNull(suggestionProviders);
this.undoManager = Objects.requireNonNull(undoManager);
this.dialogService = Objects.requireNonNull(dialogService);
this.preferences = Objects.requireNonNull(preferences);
this.themeManager = themeManager;
this.taskExecutor = Objects.requireNonNull(taskExecutor);
this.journalAbbreviationRepository = Objects.requireNonNull(journalAbbreviationRepository);
this.stateManager = stateManager;
this.indexingTaskManager = indexingTaskManager;
}
private static void addColumn(GridPane gridPane, int columnIndex, List<Label> nodes) {
gridPane.addColumn(columnIndex, nodes.toArray(new Node[0]));
}
private static void addColumn(GridPane gridPane, int columnIndex, Stream<Parent> nodes) {
gridPane.addColumn(columnIndex, nodes.toArray(Node[]::new));
}
protected void setupPanel(BibEntry entry, boolean compressed) {
// The preferences might be not initialized in tests -> return immediately
// TODO: Replace this ugly workaround by proper injection propagation
if (preferences == null) {
return;
}
editors.clear();
gridPane.getChildren().clear();
gridPane.getColumnConstraints().clear();
gridPane.getRowConstraints().clear();
fields = determineFieldsToShow(entry);
List<Label> labels = new ArrayList<>();
for (Field field : fields) {
FieldEditorFX fieldEditor = FieldEditors.getForField(
field,
taskExecutor,
dialogService,
journalAbbreviationRepository,
preferences,
databaseContext,
entry.getType(),
suggestionProviders,
undoManager);
fieldEditor.bindToEntry(entry);
editors.put(field, fieldEditor);
labels.add(new FieldNameLabel(field));
}
ColumnConstraints columnExpand = new ColumnConstraints();
columnExpand.setHgrow(Priority.ALWAYS);
ColumnConstraints columnDoNotContract = new ColumnConstraints();
columnDoNotContract.setMinWidth(Region.USE_PREF_SIZE);
int rows;
if (compressed) {
rows = (int) Math.ceil((double) fields.size() / 2);
addColumn(gridPane, 0, labels.subList(0, rows));
addColumn(gridPane, 3, labels.subList(rows, labels.size()));
addColumn(gridPane, 1, editors.values().stream().map(FieldEditorFX::getNode).limit(rows));
addColumn(gridPane, 4, editors.values().stream().map(FieldEditorFX::getNode).skip(rows));
columnExpand.setPercentWidth(40);
gridPane.getColumnConstraints().addAll(columnDoNotContract, columnExpand, new ColumnConstraints(10),
columnDoNotContract, columnExpand);
setCompressedRowLayout(gridPane, rows);
} else {
addColumn(gridPane, 0, labels);
addColumn(gridPane, 1, editors.values().stream().map(FieldEditorFX::getNode));
gridPane.getColumnConstraints().addAll(columnDoNotContract, columnExpand);
setRegularRowLayout(gridPane);
}
}
private void setRegularRowLayout(GridPane gridPane) {
double totalWeight = fields.stream()
.mapToDouble(field -> editors.get(field).getWeight())
.sum();
List<RowConstraints> constraints = new ArrayList<>();
for (Field field : fields) {
RowConstraints rowExpand = new RowConstraints();
rowExpand.setVgrow(Priority.ALWAYS);
rowExpand.setValignment(VPos.TOP);
rowExpand.setPercentHeight(100 * editors.get(field).getWeight() / totalWeight);
constraints.add(rowExpand);
}
gridPane.getRowConstraints().addAll(constraints);
}
private void setCompressedRowLayout(GridPane gridPane, int rows) {
RowConstraints rowExpand = new RowConstraints();
rowExpand.setVgrow(Priority.ALWAYS);
rowExpand.setValignment(VPos.TOP);
if (rows == 0) {
rowExpand.setPercentHeight(100);
} else {
rowExpand.setPercentHeight(100 / (double) rows);
}
for (int i = 0; i < rows; i++) {
gridPane.getRowConstraints().add(rowExpand);
}
}
public void requestFocus(Field fieldName) {
if (editors.containsKey(fieldName)) {
editors.get(fieldName).focus();
}
}
@Override
public boolean shouldShow(BibEntry entry) {
return !determineFieldsToShow(entry).isEmpty();
}
@Override
protected void bindToEntry(BibEntry entry) {
initPanel();
setupPanel(entry, isCompressed);
if (previewPanel != null) {
previewPanel.setEntry(entry);
}
}
@Override
protected void nextPreviewStyle() {
if (previewPanel != null) {
previewPanel.nextPreviewStyle();
}
}
@Override
protected void previousPreviewStyle() {
if (previewPanel != null) {
previewPanel.previousPreviewStyle();
}
}
protected abstract Set<Field> determineFieldsToShow(BibEntry entry);
public Collection<Field> getShownFields() {
return fields;
}
private void initPanel() {
if (gridPane == null) {
gridPane = new GridPane();
gridPane.getStyleClass().add("editorPane");
// Warp everything in a scroll-pane
ScrollPane scrollPane = new ScrollPane();
scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
scrollPane.setContent(gridPane);
scrollPane.setFitToWidth(true);
scrollPane.setFitToHeight(true);
SplitPane container = new SplitPane(scrollPane);
previewPanel = new PreviewPanel(databaseContext, dialogService, preferences.getKeyBindingRepository(), preferences, stateManager, themeManager, indexingTaskManager);
EasyBind.subscribe(preferences.getPreviewPreferences().showPreviewAsExtraTabProperty(), show -> {
if (show) {
container.getItems().remove(previewPanel);
} else {
container.getItems().add(1, previewPanel);
}
});
setContent(container);
}
}
}
| 9,785
| 37.679842
| 177
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/entryeditor/LatexCitationsTab.java
|
package org.jabref.gui.entryeditor;
import javafx.geometry.HPos;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.RowConstraints;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import org.jabref.gui.DialogService;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.texparser.CitationsDisplay;
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.preferences.PreferencesService;
import com.tobiasdiez.easybind.EasyBind;
public class LatexCitationsTab extends EntryEditorTab {
public static final String NAME = "LaTeX Citations";
private final LatexCitationsTabViewModel viewModel;
private final GridPane searchPane;
private final ProgressIndicator progressIndicator;
private final CitationsDisplay citationsDisplay;
public LatexCitationsTab(BibDatabaseContext databaseContext, PreferencesService preferencesService,
TaskExecutor taskExecutor, DialogService dialogService) {
this.viewModel = new LatexCitationsTabViewModel(databaseContext, preferencesService, taskExecutor, dialogService);
this.searchPane = new GridPane();
this.progressIndicator = new ProgressIndicator();
this.citationsDisplay = new CitationsDisplay();
setText(Localization.lang("LaTeX Citations"));
setTooltip(new Tooltip(Localization.lang("Search citations for this entry in LaTeX files")));
setGraphic(IconTheme.JabRefIcons.LATEX_CITATIONS.getGraphicNode());
setSearchPane();
}
private void setSearchPane() {
progressIndicator.setMaxSize(100, 100);
citationsDisplay.basePathProperty().bindBidirectional(viewModel.directoryProperty());
citationsDisplay.setItems(viewModel.getCitationList());
RowConstraints mainRow = new RowConstraints();
mainRow.setVgrow(Priority.ALWAYS);
RowConstraints bottomRow = new RowConstraints(40);
bottomRow.setVgrow(Priority.NEVER);
ColumnConstraints column = new ColumnConstraints();
column.setPercentWidth(100);
column.setHalignment(HPos.CENTER);
searchPane.getColumnConstraints().setAll(column);
searchPane.getRowConstraints().setAll(mainRow, bottomRow);
searchPane.setId("citationsPane");
setContent(searchPane);
EasyBind.subscribe(viewModel.statusProperty(), status -> {
searchPane.getChildren().clear();
switch (status) {
case IN_PROGRESS:
searchPane.add(progressIndicator, 0, 0);
break;
case CITATIONS_FOUND:
searchPane.add(getCitationsPane(), 0, 0);
break;
case NO_RESULTS:
searchPane.add(getNotFoundPane(), 0, 0);
break;
case ERROR:
searchPane.add(getErrorPane(), 0, 0);
break;
}
searchPane.add(getLatexDirectoryBox(), 0, 1);
});
}
private HBox getLatexDirectoryBox() {
Text latexDirectoryText = new Text(Localization.lang("Current search directory:"));
Text latexDirectoryPath = new Text(viewModel.directoryProperty().get().toString());
latexDirectoryPath.setStyle("-fx-font-family:monospace;-fx-font-weight: bold;");
Button latexDirectoryButton = new Button(Localization.lang("Set LaTeX file directory"));
latexDirectoryButton.setGraphic(IconTheme.JabRefIcons.LATEX_FILE_DIRECTORY.getGraphicNode());
latexDirectoryButton.setOnAction(event -> viewModel.setLatexDirectory());
HBox latexDirectoryBox = new HBox(10, latexDirectoryText, latexDirectoryPath, latexDirectoryButton);
latexDirectoryBox.setAlignment(Pos.CENTER);
return latexDirectoryBox;
}
private VBox getCitationsPane() {
VBox citationsBox = new VBox(30, citationsDisplay);
citationsBox.setStyle("-fx-padding: 0;");
return citationsBox;
}
private VBox getNotFoundPane() {
Label titleLabel = new Label(Localization.lang("No citations found"));
titleLabel.getStyleClass().add("heading");
Text notFoundText = new Text(Localization.lang("No LaTeX files containing this entry were found."));
notFoundText.getStyleClass().add("description");
VBox notFoundBox = new VBox(30, titleLabel, notFoundText);
notFoundBox.setStyle("-fx-padding: 30 0 0 30;");
return notFoundBox;
}
private VBox getErrorPane() {
Label titleLabel = new Label(Localization.lang("Error"));
titleLabel.setStyle("-fx-font-size: 1.5em;-fx-font-weight: bold;-fx-text-fill: -fx-accent;");
Text errorMessageText = new Text(viewModel.searchErrorProperty().get());
VBox errorMessageBox = new VBox(30, titleLabel, errorMessageText);
errorMessageBox.setStyle("-fx-padding: 30 0 0 30;");
return errorMessageBox;
}
@Override
protected void bindToEntry(BibEntry entry) {
viewModel.init(entry);
}
@Override
public boolean shouldShow(BibEntry entry) {
return viewModel.shouldShow();
}
}
| 5,607
| 39.637681
| 122
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/entryeditor/LatexCitationsTabViewModel.java
|
package org.jabref.gui.entryeditor;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ReadOnlyListWrapper;
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.util.BackgroundTask;
import org.jabref.gui.util.DirectoryDialogConfiguration;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.texparser.DefaultLatexParser;
import org.jabref.logic.util.io.FileUtil;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.texparser.Citation;
import org.jabref.model.texparser.LatexParserResult;
import org.jabref.preferences.PreferencesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LatexCitationsTabViewModel extends AbstractViewModel {
enum Status {
IN_PROGRESS,
CITATIONS_FOUND,
NO_RESULTS,
ERROR
}
private static final Logger LOGGER = LoggerFactory.getLogger(LatexCitationsTabViewModel.class);
private static final String TEX_EXT = ".tex";
private final BibDatabaseContext databaseContext;
private final PreferencesService preferencesService;
private final TaskExecutor taskExecutor;
private final DialogService dialogService;
private final ObjectProperty<Path> directory;
private final ObservableList<Citation> citationList;
private final ObjectProperty<Status> status;
private final StringProperty searchError;
private Future<?> searchTask;
private LatexParserResult latexParserResult;
private BibEntry currentEntry;
public LatexCitationsTabViewModel(BibDatabaseContext databaseContext,
PreferencesService preferencesService,
TaskExecutor taskExecutor,
DialogService dialogService) {
this.databaseContext = databaseContext;
this.preferencesService = preferencesService;
this.taskExecutor = taskExecutor;
this.dialogService = dialogService;
this.directory = new SimpleObjectProperty<>(databaseContext.getMetaData().getLatexFileDirectory(preferencesService.getFilePreferences().getUserAndHost())
.orElse(FileUtil.getInitialDirectory(databaseContext, preferencesService.getFilePreferences().getWorkingDirectory())));
this.citationList = FXCollections.observableArrayList();
this.status = new SimpleObjectProperty<>(Status.IN_PROGRESS);
this.searchError = new SimpleStringProperty("");
}
public void init(BibEntry entry) {
cancelSearch();
currentEntry = entry;
Optional<String> citeKey = entry.getCitationKey();
if (citeKey.isPresent()) {
startSearch(citeKey.get());
} else {
searchError.set(Localization.lang("Selected entry does not have an associated citation key."));
status.set(Status.ERROR);
}
}
public ObjectProperty<Path> directoryProperty() {
return directory;
}
public ObservableList<Citation> getCitationList() {
return new ReadOnlyListWrapper<>(citationList);
}
public ObjectProperty<Status> statusProperty() {
return status;
}
public StringProperty searchErrorProperty() {
return searchError;
}
private void startSearch(String citeKey) {
searchTask = BackgroundTask.wrap(() -> searchAndParse(citeKey))
.onRunning(() -> status.set(Status.IN_PROGRESS))
.onSuccess(result -> {
citationList.setAll(result);
status.set(citationList.isEmpty() ? Status.NO_RESULTS : Status.CITATIONS_FOUND);
})
.onFailure(error -> {
searchError.set(error.getMessage());
status.set(Status.ERROR);
})
.executeWith(taskExecutor);
}
private void cancelSearch() {
if (searchTask == null || searchTask.isCancelled() || searchTask.isDone()) {
return;
}
status.set(Status.IN_PROGRESS);
searchTask.cancel(true);
}
private Collection<Citation> searchAndParse(String citeKey) throws IOException {
// we need to check whether the user meanwhile set the LaTeX file directory or the database changed locations
Path newDirectory = databaseContext.getMetaData().getLatexFileDirectory(preferencesService.getFilePreferences().getUserAndHost())
.orElse(FileUtil.getInitialDirectory(databaseContext, preferencesService.getFilePreferences().getWorkingDirectory()));
if (latexParserResult == null || !newDirectory.equals(directory.get())) {
directory.set(newDirectory);
if (!newDirectory.toFile().exists()) {
throw new IOException(String.format("Current search directory does not exist: %s", newDirectory));
}
List<Path> texFiles = searchDirectory(newDirectory, new ArrayList<>());
latexParserResult = new DefaultLatexParser().parse(texFiles);
}
return latexParserResult.getCitationsByKey(citeKey);
}
private List<Path> searchDirectory(Path directory, List<Path> texFiles) {
Map<Boolean, List<Path>> fileListPartition;
try (Stream<Path> filesStream = Files.list(directory)) {
fileListPartition = filesStream.collect(Collectors.partitioningBy(path -> path.toFile().isDirectory()));
} catch (IOException e) {
LOGGER.error(String.format("%s while searching files: %s", e.getClass().getName(), e.getMessage()));
return texFiles;
}
List<Path> subDirectories = fileListPartition.get(true);
List<Path> files = fileListPartition.get(false)
.stream()
.filter(path -> path.toString().endsWith(TEX_EXT))
.collect(Collectors.toList());
texFiles.addAll(files);
subDirectories.forEach(subDirectory -> searchDirectory(subDirectory, texFiles));
return texFiles;
}
public void setLatexDirectory() {
DirectoryDialogConfiguration directoryDialogConfiguration = new DirectoryDialogConfiguration.Builder()
.withInitialDirectory(directory.get()).build();
dialogService.showDirectorySelectionDialog(directoryDialogConfiguration).ifPresent(selectedDirectory ->
databaseContext.getMetaData().setLatexFileDirectory(preferencesService.getFilePreferences().getUserAndHost(), selectedDirectory.toAbsolutePath()));
init(currentEntry);
}
public boolean shouldShow() {
return preferencesService.getEntryEditorPreferences().shouldShowLatexCitationsTab();
}
}
| 7,717
| 40.945652
| 186
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/entryeditor/MathSciNetTab.java
|
package org.jabref.gui.entryeditor;
import java.util.Optional;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebView;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.WebViewStore;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.identifier.MathSciNetId;
public class MathSciNetTab extends EntryEditorTab {
public static final String NAME = "MathSciNet Review";
public MathSciNetTab() {
setText(Localization.lang("MathSciNet Review"));
}
private Optional<MathSciNetId> getMathSciNetId(BibEntry entry) {
return entry.getField(StandardField.MR_NUMBER).flatMap(MathSciNetId::parse);
}
private StackPane getPane(BibEntry entry) {
StackPane root = new StackPane();
ProgressIndicator progress = new ProgressIndicator();
progress.setMaxSize(100, 100);
WebView browser = WebViewStore.get();
// Quick hack to disable navigating
browser.addEventFilter(javafx.scene.input.MouseEvent.ANY, javafx.scene.input.MouseEvent::consume);
browser.setContextMenuEnabled(false);
root.getChildren().addAll(browser, progress);
Optional<MathSciNetId> mathSciNetId = getMathSciNetId(entry);
mathSciNetId.flatMap(MathSciNetId::getExternalURI)
.ifPresent(url -> browser.getEngine().load(url.toASCIIString()));
// Hide progress indicator if finished (over 70% loaded)
browser.getEngine().getLoadWorker().progressProperty().addListener((observable, oldValue, newValue) -> {
if (newValue.doubleValue() >= 0.7) {
progress.setVisible(false);
}
});
return root;
}
@Override
public boolean shouldShow(BibEntry entry) {
return getMathSciNetId(entry).isPresent();
}
@Override
protected void bindToEntry(BibEntry entry) {
setContent(getPane(entry));
}
}
| 2,043
| 31.967742
| 112
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/entryeditor/OpenEntryEditorAction.java
|
package org.jabref.gui.entryeditor;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.ActionHelper;
import org.jabref.gui.actions.SimpleCommand;
public class OpenEntryEditorAction extends SimpleCommand {
private final JabRefFrame frame;
private final StateManager stateManager;
public OpenEntryEditorAction(JabRefFrame frame, StateManager stateManager) {
this.frame = frame;
this.stateManager = stateManager;
this.executable.bind(ActionHelper.needsEntriesSelected(stateManager));
}
public void execute() {
if (!stateManager.getSelectedEntries().isEmpty()) {
frame.getCurrentLibraryTab().showAndEdit(stateManager.getSelectedEntries().get(0));
}
}
}
| 781
| 29.076923
| 95
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/entryeditor/OptionalFields2Tab.java
|
package org.jabref.gui.entryeditor;
import javax.swing.undo.UndoManager;
import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.autocompleter.SuggestionProviders;
import org.jabref.gui.theme.ThemeManager;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.pdf.search.indexing.IndexingTaskManager;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntryTypesManager;
import org.jabref.preferences.PreferencesService;
public class OptionalFields2Tab extends OptionalFieldsTabBase {
public static final String NAME = "Optional fields 2";
public OptionalFields2Tab(BibDatabaseContext databaseContext,
SuggestionProviders suggestionProviders,
UndoManager undoManager,
DialogService dialogService,
PreferencesService preferences,
StateManager stateManager,
ThemeManager themeManager,
IndexingTaskManager indexingTaskManager,
BibEntryTypesManager entryTypesManager,
TaskExecutor taskExecutor,
JournalAbbreviationRepository journalAbbreviationRepository) {
super(
Localization.lang("Optional fields 2"),
false,
databaseContext,
suggestionProviders,
undoManager,
dialogService,
preferences,
stateManager,
themeManager,
indexingTaskManager,
entryTypesManager,
taskExecutor,
journalAbbreviationRepository
);
}
}
| 1,939
| 38.591837
| 92
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/entryeditor/OptionalFieldsTab.java
|
package org.jabref.gui.entryeditor;
import javax.swing.undo.UndoManager;
import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.autocompleter.SuggestionProviders;
import org.jabref.gui.theme.ThemeManager;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.pdf.search.indexing.IndexingTaskManager;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntryTypesManager;
import org.jabref.preferences.PreferencesService;
public class OptionalFieldsTab extends OptionalFieldsTabBase {
public static final String NAME = "Optional fields";
public OptionalFieldsTab(BibDatabaseContext databaseContext,
SuggestionProviders suggestionProviders,
UndoManager undoManager,
DialogService dialogService,
PreferencesService preferences,
StateManager stateManager,
ThemeManager themeManager,
IndexingTaskManager indexingTaskManager,
BibEntryTypesManager entryTypesManager,
TaskExecutor taskExecutor,
JournalAbbreviationRepository journalAbbreviationRepository) {
super(
Localization.lang("Optional fields"),
true,
databaseContext,
suggestionProviders,
undoManager,
dialogService,
preferences,
stateManager,
themeManager,
indexingTaskManager,
entryTypesManager,
taskExecutor,
journalAbbreviationRepository
);
}
}
| 1,922
| 38.244898
| 91
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/entryeditor/OptionalFieldsTabBase.java
|
package org.jabref.gui.entryeditor;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
import javax.swing.undo.UndoManager;
import javafx.scene.control.Tooltip;
import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.autocompleter.SuggestionProviders;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.theme.ThemeManager;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.pdf.search.indexing.IndexingTaskManager;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.database.BibDatabaseMode;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.BibEntryType;
import org.jabref.model.entry.BibEntryTypesManager;
import org.jabref.model.entry.field.Field;
import org.jabref.preferences.PreferencesService;
public class OptionalFieldsTabBase extends FieldsEditorTab {
private final BibEntryTypesManager entryTypesManager;
private final boolean isPrimaryOptionalFields;
public OptionalFieldsTabBase(String title,
boolean isPrimaryOptionalFields,
BibDatabaseContext databaseContext,
SuggestionProviders suggestionProviders,
UndoManager undoManager,
DialogService dialogService,
PreferencesService preferences,
StateManager stateManager,
ThemeManager themeManager,
IndexingTaskManager indexingTaskManager,
BibEntryTypesManager entryTypesManager,
TaskExecutor taskExecutor,
JournalAbbreviationRepository journalAbbreviationRepository) {
super(true,
databaseContext,
suggestionProviders,
undoManager,
dialogService,
preferences,
stateManager,
themeManager,
taskExecutor,
journalAbbreviationRepository,
indexingTaskManager);
this.entryTypesManager = entryTypesManager;
this.isPrimaryOptionalFields = isPrimaryOptionalFields;
setText(title);
setTooltip(new Tooltip(Localization.lang("Show optional fields")));
setGraphic(IconTheme.JabRefIcons.OPTIONAL.getGraphicNode());
}
@Override
protected Set<Field> determineFieldsToShow(BibEntry entry) {
BibDatabaseMode mode = databaseContext.getMode();
Optional<BibEntryType> entryType = entryTypesManager.enrich(entry.getType(), mode);
if (entryType.isPresent()) {
if (isPrimaryOptionalFields) {
return entryType.get().getPrimaryOptionalFields();
} else {
return entryType.get().getSecondaryOptionalNotDeprecatedFields(mode);
}
} else {
// Entry type unknown -> treat all fields as required
return Collections.emptySet();
}
}
}
| 3,271
| 40.417722
| 95
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/entryeditor/OtherFieldsTab.java
|
package org.jabref.gui.entryeditor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.swing.undo.UndoManager;
import javafx.scene.control.Tooltip;
import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.autocompleter.SuggestionProviders;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.theme.ThemeManager;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.pdf.search.indexing.IndexingTaskManager;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.database.BibDatabaseMode;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.BibEntryType;
import org.jabref.model.entry.BibEntryTypesManager;
import org.jabref.model.entry.field.BibField;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.InternalField;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.field.UserSpecificCommentField;
import org.jabref.preferences.PreferencesService;
public class OtherFieldsTab extends FieldsEditorTab {
public static final String NAME = "Other fields";
private final List<Field> customTabFieldNames;
private final BibEntryTypesManager entryTypesManager;
public OtherFieldsTab(BibDatabaseContext databaseContext,
SuggestionProviders suggestionProviders,
UndoManager undoManager,
DialogService dialogService,
PreferencesService preferences,
StateManager stateManager,
ThemeManager themeManager,
IndexingTaskManager indexingTaskManager,
BibEntryTypesManager entryTypesManager,
TaskExecutor taskExecutor,
JournalAbbreviationRepository journalAbbreviationRepository) {
super(false,
databaseContext,
suggestionProviders,
undoManager,
dialogService,
preferences,
stateManager,
themeManager,
taskExecutor,
journalAbbreviationRepository,
indexingTaskManager);
this.entryTypesManager = entryTypesManager;
this.customTabFieldNames = new ArrayList<>();
preferences.getEntryEditorPreferences().getDefaultEntryEditorTabs().values().forEach(customTabFieldNames::addAll);
setText(Localization.lang("Other fields"));
setTooltip(new Tooltip(Localization.lang("Show remaining fields")));
setGraphic(IconTheme.JabRefIcons.OPTIONAL.getGraphicNode());
}
@Override
protected Set<Field> determineFieldsToShow(BibEntry entry) {
BibDatabaseMode mode = databaseContext.getMode();
Optional<BibEntryType> entryType = entryTypesManager.enrich(entry.getType(), mode);
if (entryType.isPresent()) {
Set<Field> allKnownFields = entryType.get().getAllFields();
Set<Field> otherFields = entry.getFields().stream()
.filter(field -> !allKnownFields.contains(field) &&
!(field.equals(StandardField.COMMENT) || field instanceof UserSpecificCommentField))
.collect(Collectors.toCollection(LinkedHashSet::new));
otherFields.removeAll(entryType.get().getDeprecatedFields(mode));
otherFields.removeAll(entryType.get().getOptionalFields().stream().map(BibField::field).collect(Collectors.toSet()));
otherFields.remove(InternalField.KEY_FIELD);
customTabFieldNames.forEach(otherFields::remove);
return otherFields;
} else {
// Entry type unknown -> treat all fields as required
return Collections.emptySet();
}
}
}
| 4,193
| 43.147368
| 134
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/entryeditor/PreviewSwitchAction.java
|
package org.jabref.gui.entryeditor;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.SimpleCommand;
import static org.jabref.gui.actions.ActionHelper.needsDatabase;
public class PreviewSwitchAction extends SimpleCommand {
public enum Direction { PREVIOUS, NEXT }
private final JabRefFrame frame;
private final Direction direction;
public PreviewSwitchAction(Direction direction, JabRefFrame frame, StateManager stateManager) {
this.frame = frame;
this.direction = direction;
this.executable.bind(needsDatabase(stateManager));
}
@Override
public void execute() {
if (direction == Direction.NEXT) {
frame.getCurrentLibraryTab().getEntryEditor().nextPreviewStyle();
} else {
frame.getCurrentLibraryTab().getEntryEditor().previousPreviewStyle();
}
}
}
| 912
| 27.53125
| 99
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/entryeditor/PreviewTab.java
|
package org.jabref.gui.entryeditor;
import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.preview.PreviewPanel;
import org.jabref.gui.theme.ThemeManager;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.pdf.search.indexing.IndexingTaskManager;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.preferences.PreferencesService;
public class PreviewTab extends EntryEditorTab {
public static final String NAME = "Preview";
private final DialogService dialogService;
private final BibDatabaseContext databaseContext;
private final PreferencesService preferences;
private final StateManager stateManager;
private final ThemeManager themeManager;
private final IndexingTaskManager indexingTaskManager;
private PreviewPanel previewPanel;
public PreviewTab(BibDatabaseContext databaseContext,
DialogService dialogService,
PreferencesService preferences,
StateManager stateManager,
ThemeManager themeManager,
IndexingTaskManager indexingTaskManager) {
this.databaseContext = databaseContext;
this.dialogService = dialogService;
this.preferences = preferences;
this.stateManager = stateManager;
this.themeManager = themeManager;
this.indexingTaskManager = indexingTaskManager;
setGraphic(IconTheme.JabRefIcons.TOGGLE_ENTRY_PREVIEW.getGraphicNode());
setText(Localization.lang("Preview"));
}
@Override
protected void nextPreviewStyle() {
if (previewPanel != null) {
previewPanel.nextPreviewStyle();
}
}
@Override
protected void previousPreviewStyle() {
if (previewPanel != null) {
previewPanel.previousPreviewStyle();
}
}
@Override
public boolean shouldShow(BibEntry entry) {
return preferences.getPreviewPreferences().shouldShowPreviewAsExtraTab();
}
@Override
protected void bindToEntry(BibEntry entry) {
if (previewPanel == null) {
previewPanel = new PreviewPanel(databaseContext, dialogService, preferences.getKeyBindingRepository(), preferences, stateManager, themeManager, indexingTaskManager);
setContent(previewPanel);
}
previewPanel.setEntry(entry);
}
}
| 2,493
| 34.628571
| 177
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/entryeditor/RelatedArticlesTab.java
|
package org.jabref.gui.entryeditor;
import java.io.IOException;
import java.util.List;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.DoubleBinding;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.Text;
import org.jabref.gui.DialogService;
import org.jabref.gui.Globals;
import org.jabref.gui.desktop.JabRefDesktop;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.logic.importer.ImportCleanup;
import org.jabref.logic.importer.fetcher.MrDLibFetcher;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.database.BibDatabaseModeDetection;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.jabref.preferences.MrDlibPreferences;
import org.jabref.preferences.PreferencesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* GUI for tab displaying article recommendations based on the currently selected BibEntry
*/
public class RelatedArticlesTab extends EntryEditorTab {
public static final String NAME = "Related articles";
private static final Logger LOGGER = LoggerFactory.getLogger(RelatedArticlesTab.class);
private final EntryEditorPreferences preferences;
private final DialogService dialogService;
private final PreferencesService preferencesService;
public RelatedArticlesTab(EntryEditor entryEditor, EntryEditorPreferences preferences, PreferencesService preferencesService, DialogService dialogService) {
setText(Localization.lang("Related articles"));
setTooltip(new Tooltip(Localization.lang("Related articles")));
this.preferences = preferences;
this.dialogService = dialogService;
this.preferencesService = preferencesService;
}
/**
* Gets a StackPane of related article information to be displayed in the Related Articles tab
*
* @param entry The currently selected BibEntry on the JabRef UI.
* @return A StackPane with related article information to be displayed in the Related Articles tab.
*/
private StackPane getRelatedArticlesPane(BibEntry entry) {
StackPane root = new StackPane();
root.setId("related-articles-tab");
ProgressIndicator progress = new ProgressIndicator();
progress.setMaxSize(100, 100);
MrDLibFetcher fetcher = new MrDLibFetcher(preferencesService.getWorkspacePreferences().getLanguage().name(),
Globals.BUILD_INFO.version, preferencesService.getMrDlibPreferences());
BackgroundTask
.wrap(() -> fetcher.performSearch(entry))
.onRunning(() -> progress.setVisible(true))
.onSuccess(relatedArticles -> {
ImportCleanup cleanup = new ImportCleanup(BibDatabaseModeDetection.inferMode(new BibDatabase(List.of(entry))));
cleanup.doPostCleanup(relatedArticles);
progress.setVisible(false);
root.getChildren().add(getRelatedArticleInfo(relatedArticles, fetcher));
})
.onFailure(exception -> {
LOGGER.error("Error while fetching from Mr. DLib", exception);
progress.setVisible(false);
root.getChildren().add(getErrorInfo());
})
.executeWith(Globals.TASK_EXECUTOR);
root.getChildren().add(progress);
return root;
}
/**
* Creates a VBox of the related article information to be used in the StackPane displayed in the Related Articles tab
*
* @param list List of BibEntries of related articles
* @return VBox of related article descriptions to be displayed in the Related Articles tab
*/
private ScrollPane getRelatedArticleInfo(List<BibEntry> list, MrDLibFetcher fetcher) {
ScrollPane scrollPane = new ScrollPane();
VBox vBox = new VBox();
vBox.setSpacing(20.0);
String heading = fetcher.getHeading();
Text headingText = new Text(heading);
headingText.getStyleClass().add("heading");
String description = fetcher.getDescription();
Text descriptionText = new Text(description);
descriptionText.getStyleClass().add("description");
vBox.getChildren().add(headingText);
vBox.getChildren().add(descriptionText);
for (BibEntry entry : list) {
HBox hBox = new HBox();
hBox.setSpacing(5.0);
hBox.getStyleClass().add("recommendation-item");
String title = entry.getTitle().orElse("");
String journal = entry.getField(StandardField.JOURNAL).orElse("");
String authors = entry.getField(StandardField.AUTHOR).orElse("");
String year = entry.getField(StandardField.YEAR).orElse("");
Hyperlink titleLink = new Hyperlink(title);
Text journalText = new Text(journal);
journalText.setFont(Font.font(Font.getDefault().getFamily(), FontPosture.ITALIC, Font.getDefault().getSize()));
Text authorsText = new Text(authors);
Text yearText = new Text("(" + year + ")");
titleLink.setOnAction(event -> {
if (entry.getField(StandardField.URL).isPresent()) {
try {
JabRefDesktop.openBrowser(entry.getField(StandardField.URL).get());
} catch (IOException e) {
LOGGER.error("Error opening the browser to: " + entry.getField(StandardField.URL).get(), e);
dialogService.showErrorDialogAndWait(e);
}
}
});
hBox.getChildren().addAll(titleLink, journalText, authorsText, yearText);
vBox.getChildren().add(hBox);
}
scrollPane.setContent(vBox);
return scrollPane;
}
/**
* Gets a ScrollPane to display error info when recommendations fail.
*
* @return ScrollPane to display in place of recommendations
*/
private ScrollPane getErrorInfo() {
ScrollPane scrollPane = new ScrollPane();
VBox vBox = new VBox();
vBox.setSpacing(20.0);
Text descriptionText = new Text(Localization.lang("No recommendations received from Mr. DLib for this entry."));
descriptionText.getStyleClass().add("description");
vBox.getChildren().add(descriptionText);
scrollPane.setContent(vBox);
return scrollPane;
}
/**
* Returns a consent dialog used to ask permission to send data to Mr. DLib.
*
* @param entry Currently selected BibEntry. (required to allow reloading of pane if accepted)
* @return StackPane returned to be placed into Related Articles tab.
*/
private ScrollPane getPrivacyDialog(BibEntry entry) {
ScrollPane root = new ScrollPane();
root.setId("related-articles-tab");
VBox vbox = new VBox();
vbox.setId("gdpr-dialog");
vbox.setSpacing(20.0);
Text title = new Text(Localization.lang("Mr. DLib Privacy settings"));
title.getStyleClass().add("heading");
Button button = new Button(Localization.lang("I Agree"));
button.setDefaultButton(true);
DoubleBinding rootWidth = Bindings.subtract(root.widthProperty(), 88d);
Text line1 = new Text(Localization.lang("JabRef requests recommendations from Mr. DLib, which is an external service. To enable Mr. DLib to calculate recommendations, some of your data must be shared with Mr. DLib. Generally, the more data is shared the better recommendations can be calculated. However, we understand that some of your data in JabRef is sensitive, and you may not want to share it. Therefore, Mr. DLib offers a choice of which data you would like to share."));
line1.wrappingWidthProperty().bind(rootWidth);
Text line2 = new Text(Localization.lang("Whatever option you choose, Mr. DLib may share its data with research partners to further improve recommendation quality as part of a 'living lab'. Mr. DLib may also release public datasets that may contain anonymized information about you and the recommendations (sensitive information such as metadata of your articles will be anonymised through e.g. hashing). Research partners are obliged to adhere to the same strict data protection policy as Mr. DLib."));
line2.wrappingWidthProperty().bind(rootWidth);
Text line3 = new Text(Localization.lang("This setting may be changed in preferences at any time."));
line3.wrappingWidthProperty().bind(rootWidth);
Hyperlink mdlLink = new Hyperlink(Localization.lang("Further information about Mr. DLib for JabRef users."));
mdlLink.setOnAction(event -> {
try {
JabRefDesktop.openBrowser("http://mr-dlib.org/information-for-users/information-about-mr-dlib-for-jabref-users/");
} catch (IOException e) {
LOGGER.error("Error opening the browser to Mr. DLib information page.", e);
dialogService.showErrorDialogAndWait(e);
}
});
VBox vb = new VBox();
CheckBox cbTitle = new CheckBox(Localization.lang("Entry Title (Required to deliver recommendations.)"));
cbTitle.setSelected(true);
cbTitle.setDisable(true);
CheckBox cbVersion = new CheckBox(Localization.lang("JabRef Version (Required to ensure backwards compatibility with Mr. DLib's Web Service)"));
cbVersion.setSelected(true);
cbVersion.setDisable(true);
CheckBox cbLanguage = new CheckBox(Localization.lang("JabRef Language (Provides for better recommendations by giving an indication of user's preferred language.)"));
CheckBox cbOS = new CheckBox(Localization.lang("Operating System (Provides for better recommendations by giving an indication of user's system set-up.)"));
CheckBox cbTimezone = new CheckBox(Localization.lang("Timezone (Provides for better recommendations by indicating the time of day the request is being made.)"));
vb.getChildren().addAll(cbTitle, cbVersion, cbLanguage, cbOS, cbTimezone);
vb.setSpacing(10);
button.setOnAction(event -> {
preferences.setIsMrdlibAccepted(true);
MrDlibPreferences mrDlibPreferences = preferencesService.getMrDlibPreferences();
mrDlibPreferences.setSendLanguage(cbLanguage.isSelected());
mrDlibPreferences.setSendOs(cbOS.isSelected());
mrDlibPreferences.setSendTimezone(cbTimezone.isSelected());
dialogService.showWarningDialogAndWait(Localization.lang("Restart"), Localization.lang("Please restart JabRef for preferences to take effect."));
setContent(getRelatedArticlesPane(entry));
});
vbox.getChildren().addAll(title, line1, line2, mdlLink, line3, vb, button);
root.setContent(vbox);
return root;
}
@Override
public boolean shouldShow(BibEntry entry) {
return preferences.shouldShowRecommendationsTab();
}
@Override
protected void bindToEntry(BibEntry entry) {
// Ask for consent to send data to Mr. DLib on first time to tab
if (preferences.isMrdlibAccepted()) {
setContent(getRelatedArticlesPane(entry));
} else {
setContent(getPrivacyDialog(entry));
}
}
}
| 11,784
| 46.712551
| 510
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/entryeditor/RequiredFieldsTab.java
|
package org.jabref.gui.entryeditor;
import java.util.LinkedHashSet;
import java.util.Optional;
import java.util.Set;
import javax.swing.undo.UndoManager;
import javafx.scene.control.Tooltip;
import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.autocompleter.SuggestionProviders;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.theme.ThemeManager;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.pdf.search.indexing.IndexingTaskManager;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.BibEntryType;
import org.jabref.model.entry.BibEntryTypesManager;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.InternalField;
import org.jabref.model.entry.field.OrFields;
import org.jabref.preferences.PreferencesService;
public class RequiredFieldsTab extends FieldsEditorTab {
public static final String NAME = "Required fields";
private final BibEntryTypesManager entryTypesManager;
public RequiredFieldsTab(BibDatabaseContext databaseContext,
SuggestionProviders suggestionProviders,
UndoManager undoManager,
DialogService dialogService,
PreferencesService preferences,
StateManager stateManager,
ThemeManager themeManager,
IndexingTaskManager indexingTaskManager,
BibEntryTypesManager entryTypesManager,
TaskExecutor taskExecutor,
JournalAbbreviationRepository journalAbbreviationRepository) {
super(false, databaseContext, suggestionProviders, undoManager, dialogService,
preferences, stateManager, themeManager, taskExecutor, journalAbbreviationRepository, indexingTaskManager);
this.entryTypesManager = entryTypesManager;
setText(Localization.lang("Required fields"));
setTooltip(new Tooltip(Localization.lang("Show required fields")));
setGraphic(IconTheme.JabRefIcons.REQUIRED.getGraphicNode());
}
@Override
protected Set<Field> determineFieldsToShow(BibEntry entry) {
Optional<BibEntryType> entryType = entryTypesManager.enrich(entry.getType(), databaseContext.getMode());
Set<Field> fields = new LinkedHashSet<>();
if (entryType.isPresent()) {
for (OrFields orFields : entryType.get().getRequiredFields()) {
fields.addAll(orFields);
}
// Add the edit field for Bibtex-key.
fields.add(InternalField.KEY_FIELD);
} else {
// Entry type unknown -> treat all fields as required
fields.addAll(entry.getFields());
}
return fields;
}
}
| 3,029
| 42.285714
| 123
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/entryeditor/SourceTab.java
|
package org.jabref.gui.entryeditor;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.undo.UndoManager;
import javafx.beans.InvalidationListener;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.geometry.Point2D;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Tooltip;
import javafx.scene.input.InputMethodRequests;
import javafx.scene.input.KeyEvent;
import org.jabref.gui.DialogService;
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.icon.IconTheme;
import org.jabref.gui.keyboard.CodeAreaKeyBindings;
import org.jabref.gui.keyboard.KeyBindingRepository;
import org.jabref.gui.undo.CountingUndoManager;
import org.jabref.gui.undo.NamedCompound;
import org.jabref.gui.undo.UndoableChangeType;
import org.jabref.gui.undo.UndoableFieldChange;
import org.jabref.gui.util.DefaultTaskExecutor;
import org.jabref.logic.bibtex.BibEntryWriter;
import org.jabref.logic.bibtex.FieldPreferences;
import org.jabref.logic.bibtex.FieldWriter;
import org.jabref.logic.bibtex.InvalidFieldValueException;
import org.jabref.logic.exporter.BibWriter;
import org.jabref.logic.importer.ImportFormatPreferences;
import org.jabref.logic.importer.ParserResult;
import org.jabref.logic.importer.fileformat.BibtexParser;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.search.SearchQuery;
import org.jabref.logic.util.OS;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.database.BibDatabaseMode;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.Field;
import org.jabref.model.util.FileUpdateMonitor;
import de.saxsys.mvvmfx.utils.validation.ObservableRuleBasedValidator;
import de.saxsys.mvvmfx.utils.validation.ValidationMessage;
import de.saxsys.mvvmfx.utils.validation.ValidationStatus;
import org.fxmisc.flowless.VirtualizedScrollPane;
import org.fxmisc.richtext.CodeArea;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SourceTab extends EntryEditorTab {
private static final Logger LOGGER = LoggerFactory.getLogger(SourceTab.class);
private final FieldPreferences fieldPreferences;
private final BibDatabaseMode mode;
private final UndoManager undoManager;
private final ObjectProperty<ValidationMessage> sourceIsValid = new SimpleObjectProperty<>();
private final ObservableRuleBasedValidator sourceValidator = new ObservableRuleBasedValidator();
private final ImportFormatPreferences importFormatPreferences;
private final FileUpdateMonitor fileMonitor;
private final DialogService dialogService;
private final StateManager stateManager;
private Optional<Pattern> searchHighlightPattern = Optional.empty();
private final KeyBindingRepository keyBindingRepository;
private CodeArea codeArea;
private BibEntry previousEntry;
private class EditAction extends SimpleCommand {
private final StandardActions command;
public EditAction(StandardActions command) {
this.command = command;
}
@Override
public void execute() {
switch (command) {
case COPY -> codeArea.copy();
case CUT -> codeArea.cut();
case PASTE -> codeArea.paste();
case SELECT_ALL -> codeArea.selectAll();
}
codeArea.requestFocus();
}
}
public SourceTab(BibDatabaseContext bibDatabaseContext, CountingUndoManager undoManager, FieldPreferences fieldPreferences, ImportFormatPreferences importFormatPreferences, FileUpdateMonitor fileMonitor, DialogService dialogService, StateManager stateManager, KeyBindingRepository keyBindingRepository) {
this.mode = bibDatabaseContext.getMode();
this.setText(Localization.lang("%0 source", mode.getFormattedName()));
this.setTooltip(new Tooltip(Localization.lang("Show/edit %0 source", mode.getFormattedName())));
this.setGraphic(IconTheme.JabRefIcons.SOURCE.getGraphicNode());
this.undoManager = undoManager;
this.fieldPreferences = fieldPreferences;
this.importFormatPreferences = importFormatPreferences;
this.fileMonitor = fileMonitor;
this.dialogService = dialogService;
this.stateManager = stateManager;
this.keyBindingRepository = keyBindingRepository;
stateManager.activeSearchQueryProperty().addListener((observable, oldValue, newValue) -> {
searchHighlightPattern = newValue.flatMap(SearchQuery::getPatternForWords);
highlightSearchPattern();
});
}
private void highlightSearchPattern() {
if (searchHighlightPattern.isPresent() && (codeArea != null)) {
codeArea.setStyleClass(0, codeArea.getLength(), "text");
Matcher matcher = searchHighlightPattern.get().matcher(codeArea.getText());
while (matcher.find()) {
for (int i = 0; i <= matcher.groupCount(); i++) {
codeArea.setStyleClass(matcher.start(), matcher.end(), "search");
}
}
}
}
private String getSourceString(BibEntry entry, BibDatabaseMode type, FieldPreferences fieldPreferences) throws IOException {
StringWriter writer = new StringWriter();
BibWriter bibWriter = new BibWriter(writer, OS.NEWLINE);
FieldWriter fieldWriter = FieldWriter.buildIgnoreHashes(fieldPreferences);
new BibEntryWriter(fieldWriter, Globals.entryTypesManager).write(entry, bibWriter, type);
return writer.toString();
}
/* Work around for different input methods.
* https://github.com/FXMisc/RichTextFX/issues/146
*/
private static class InputMethodRequestsObject implements InputMethodRequests {
@Override
public String getSelectedText() {
return "";
}
@Override
public int getLocationOffset(int x, int y) {
return 0;
}
@Override
public void cancelLatestCommittedText() {
return;
}
@Override
public Point2D getTextLocation(int offset) {
return new Point2D(0, 0);
}
}
private void setupSourceEditor() {
codeArea = new CodeArea();
codeArea.setWrapText(true);
codeArea.setInputMethodRequests(new InputMethodRequestsObject());
codeArea.setOnInputMethodTextChanged(event -> {
String committed = event.getCommitted();
if (!committed.isEmpty()) {
codeArea.insertText(codeArea.getCaretPosition(), committed);
}
});
codeArea.setId("bibtexSourceCodeArea");
codeArea.addEventFilter(KeyEvent.KEY_PRESSED, event -> CodeAreaKeyBindings.call(codeArea, event, keyBindingRepository));
codeArea.addEventFilter(KeyEvent.KEY_PRESSED, this::listenForSaveKeybinding);
ActionFactory factory = new ActionFactory(keyBindingRepository);
ContextMenu contextMenu = new ContextMenu();
contextMenu.getItems().addAll(
factory.createMenuItem(StandardActions.CUT, new EditAction(StandardActions.CUT)),
factory.createMenuItem(StandardActions.COPY, new EditAction(StandardActions.COPY)),
factory.createMenuItem(StandardActions.PASTE, new EditAction(StandardActions.PASTE)),
factory.createMenuItem(StandardActions.SELECT_ALL, new EditAction(StandardActions.SELECT_ALL))
);
contextMenu.getStyleClass().add("context-menu");
codeArea.setContextMenu(contextMenu);
sourceValidator.addRule(sourceIsValid);
sourceValidator.getValidationStatus().getMessages().addListener((InvalidationListener) c -> {
ValidationStatus sourceValidationStatus = sourceValidator.getValidationStatus();
if (!sourceValidationStatus.isValid()) {
sourceValidationStatus.getHighestMessage().ifPresent(message -> {
String content = Localization.lang("User input via entry-editor in `{}bibtex source` tab led to failure.")
+ "\n" + Localization.lang("Please check your library file for wrong syntax.")
+ "\n\n" + message.getMessage();
dialogService.showWarningDialogAndWait(Localization.lang("SourceTab error"), content);
});
}
});
codeArea.focusedProperty().addListener((obs, oldValue, onFocus) -> {
if (!onFocus && (currentEntry != null)) {
storeSource(currentEntry, codeArea.textProperty().getValue());
}
});
VirtualizedScrollPane<CodeArea> scrollableCodeArea = new VirtualizedScrollPane<>(codeArea);
this.setContent(scrollableCodeArea);
}
@Override
public boolean shouldShow(BibEntry entry) {
return true;
}
private void updateCodeArea() {
DefaultTaskExecutor.runAndWaitInJavaFXThread(() -> {
if (codeArea == null) {
setupSourceEditor();
}
codeArea.clear();
try {
codeArea.appendText(getSourceString(currentEntry, mode, fieldPreferences));
codeArea.setEditable(true);
highlightSearchPattern();
} catch (IOException ex) {
codeArea.setEditable(false);
codeArea.appendText(ex.getMessage() + "\n\n" +
Localization.lang("Correct the entry, and reopen editor to display/edit source."));
LOGGER.debug("Incorrect entry", ex);
}
});
}
@Override
protected void bindToEntry(BibEntry entry) {
if ((previousEntry != null) && (codeArea != null)) {
storeSource(previousEntry, codeArea.textProperty().getValue());
}
this.previousEntry = entry;
updateCodeArea();
entry.typeProperty().addListener(listener -> updateCodeArea());
entry.getFieldsObservable().addListener((InvalidationListener) listener -> updateCodeArea());
}
private void storeSource(BibEntry outOfFocusEntry, String text) {
if ((outOfFocusEntry == null) || text.isEmpty()) {
return;
}
BibtexParser bibtexParser = new BibtexParser(importFormatPreferences, fileMonitor);
try {
ParserResult parserResult = bibtexParser.parse(new StringReader(text));
BibDatabase database = parserResult.getDatabase();
if (database.getEntryCount() > 1) {
throw new IllegalStateException("More than one entry found.");
}
if (!database.hasEntries()) {
if (parserResult.hasWarnings()) {
// put the warning into as exception text -> it will be displayed to the user
throw new IllegalStateException(parserResult.warnings().get(0));
} else {
throw new IllegalStateException("No entries found.");
}
}
if (parserResult.hasWarnings()) {
// put the warning into as exception text -> it will be displayed to the user
throw new IllegalStateException(parserResult.getErrorMessage());
}
NamedCompound compound = new NamedCompound(Localization.lang("source edit"));
BibEntry newEntry = database.getEntries().get(0);
String newKey = newEntry.getCitationKey().orElse(null);
if (newKey != null) {
outOfFocusEntry.setCitationKey(newKey);
} else {
outOfFocusEntry.clearCiteKey();
}
// First, remove fields that the user has removed.
for (Map.Entry<Field, String> field : outOfFocusEntry.getFieldMap().entrySet()) {
Field fieldName = field.getKey();
String fieldValue = field.getValue();
if (!newEntry.hasField(fieldName)) {
compound.addEdit(new UndoableFieldChange(outOfFocusEntry, fieldName, fieldValue, null));
outOfFocusEntry.clearField(fieldName);
}
}
// Then set all fields that have been set by the user.
for (Map.Entry<Field, String> field : newEntry.getFieldMap().entrySet()) {
Field fieldName = field.getKey();
String oldValue = outOfFocusEntry.getField(fieldName).orElse(null);
String newValue = field.getValue();
if (!Objects.equals(oldValue, newValue)) {
// Test if the field is legally set.
new FieldWriter(fieldPreferences).write(fieldName, newValue);
compound.addEdit(new UndoableFieldChange(outOfFocusEntry, fieldName, oldValue, newValue));
outOfFocusEntry.setField(fieldName, newValue);
}
}
// See if the user has changed the entry type:
if (!Objects.equals(newEntry.getType(), outOfFocusEntry.getType())) {
compound.addEdit(new UndoableChangeType(outOfFocusEntry, outOfFocusEntry.getType(), newEntry.getType()));
outOfFocusEntry.setType(newEntry.getType());
}
compound.end();
undoManager.addEdit(compound);
sourceIsValid.setValue(null);
} catch (InvalidFieldValueException | IllegalStateException | IOException ex) {
sourceIsValid.setValue(ValidationMessage.error(Localization.lang("Problem with parsing entry") + ": " + ex.getMessage()));
LOGGER.debug("Incorrect source", ex);
}
}
private void listenForSaveKeybinding(KeyEvent event) {
keyBindingRepository.mapToKeyBinding(event).ifPresent(binding -> {
switch (binding) {
case SAVE_DATABASE, SAVE_ALL, SAVE_DATABASE_AS -> {
storeSource(currentEntry, codeArea.textProperty().getValue());
}
}
});
}
}
| 14,487
| 41.239067
| 308
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/entryeditor/UserDefinedFieldsTab.java
|
package org.jabref.gui.entryeditor;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.swing.undo.UndoManager;
import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.autocompleter.SuggestionProviders;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.theme.ThemeManager;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.logic.pdf.search.indexing.IndexingTaskManager;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.Field;
import org.jabref.preferences.PreferencesService;
public class UserDefinedFieldsTab extends FieldsEditorTab {
private final LinkedHashSet<Field> fields;
public UserDefinedFieldsTab(String name,
Set<Field> fields,
BibDatabaseContext databaseContext,
SuggestionProviders suggestionProviders,
UndoManager undoManager,
DialogService dialogService,
PreferencesService preferences,
StateManager stateManager,
ThemeManager themeManager,
IndexingTaskManager indexingTaskManager,
TaskExecutor taskExecutor,
JournalAbbreviationRepository journalAbbreviationRepository) {
super(false, databaseContext, suggestionProviders, undoManager, dialogService, preferences, stateManager, themeManager, taskExecutor, journalAbbreviationRepository, indexingTaskManager);
this.fields = new LinkedHashSet<>(fields);
setText(name);
setGraphic(IconTheme.JabRefIcons.OPTIONAL.getGraphicNode());
}
@Override
protected Set<Field> determineFieldsToShow(BibEntry entry) {
return fields;
}
}
| 2,026
| 40.367347
| 194
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/entryeditor/fileannotationtab/FileAnnotationTab.java
|
package org.jabref.gui.entryeditor.fileannotationtab;
import javafx.scene.Parent;
import javafx.scene.control.Tooltip;
import org.jabref.gui.entryeditor.EntryEditorTab;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.pdf.FileAnnotationCache;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import com.airhacks.afterburner.views.ViewLoader;
public class FileAnnotationTab extends EntryEditorTab {
public static final String NAME = "File annotations";
private final FileAnnotationCache fileAnnotationCache;
public FileAnnotationTab(FileAnnotationCache cache) {
this.fileAnnotationCache = cache;
setText(Localization.lang("File annotations"));
setTooltip(new Tooltip(Localization.lang("Show file annotations")));
}
@Override
public boolean shouldShow(BibEntry entry) {
return entry.getField(StandardField.FILE).isPresent();
}
@Override
protected void bindToEntry(BibEntry entry) {
Parent content = ViewLoader.view(new FileAnnotationTabView(entry, fileAnnotationCache))
.load()
.getView();
setContent(content);
}
}
| 1,240
| 30.820513
| 95
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/entryeditor/fileannotationtab/FileAnnotationTabView.java
|
package org.jabref.gui.entryeditor.fileannotationtab;
import java.nio.file.Path;
import javafx.beans.binding.Bindings;
import javafx.collections.ListChangeListener;
import javafx.fxml.FXML;
import javafx.geometry.HPos;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TextArea;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.TextAlignment;
import org.jabref.gui.util.ViewModelListCellFactory;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.pdf.FileAnnotationCache;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.util.FileUpdateMonitor;
import com.tobiasdiez.easybind.EasyBind;
import jakarta.inject.Inject;
public class FileAnnotationTabView {
@FXML public ComboBox<Path> files;
@FXML public ListView<FileAnnotationViewModel> annotationList;
@FXML public Label author;
@FXML public Label page;
@FXML public Label date;
@FXML public TextArea content;
@FXML public TextArea marking;
@FXML public VBox details;
private final BibEntry entry;
private final FileAnnotationCache fileAnnotationCache;
private FileAnnotationTabViewModel viewModel;
@Inject
private FileUpdateMonitor fileMonitor;
public FileAnnotationTabView(BibEntry entry, FileAnnotationCache fileAnnotationCache) {
this.entry = entry;
this.fileAnnotationCache = fileAnnotationCache;
}
@FXML
public void initialize() {
viewModel = new FileAnnotationTabViewModel(fileAnnotationCache, entry, fileMonitor);
// Set-up files list
files.getItems().setAll(viewModel.filesProperty().get());
files.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> viewModel.notifyNewSelectedFile(newValue));
files.getSelectionModel().selectFirst();
// Set-up annotation list
annotationList.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
annotationList.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> viewModel.notifyNewSelectedAnnotation(newValue));
ViewModelListCellFactory<FileAnnotationViewModel> cellFactory = new ViewModelListCellFactory<FileAnnotationViewModel>()
.withGraphic(this::createFileAnnotationNode);
annotationList.setCellFactory(cellFactory);
annotationList.setPlaceholder(new Label(Localization.lang("File has no attached annotations")));
Bindings.bindContent(annotationList.itemsProperty().get(), viewModel.annotationsProperty());
annotationList.getSelectionModel().selectFirst();
annotationList.itemsProperty().get().addListener(
(ListChangeListener<? super FileAnnotationViewModel>) c -> annotationList.getSelectionModel().selectFirst());
// Set-up details pane
content.textProperty().bind(EasyBind.select(viewModel.currentAnnotationProperty()).selectObject(FileAnnotationViewModel::contentProperty));
marking.textProperty().bind(EasyBind.select(viewModel.currentAnnotationProperty()).selectObject(FileAnnotationViewModel::markingProperty));
details.disableProperty().bind(viewModel.isAnnotationsEmpty());
}
private Node createFileAnnotationNode(FileAnnotationViewModel annotation) {
GridPane node = new GridPane();
ColumnConstraints firstColumn = new ColumnConstraints();
ColumnConstraints secondColumn = new ColumnConstraints();
firstColumn.setPercentWidth(70);
secondColumn.setPercentWidth(30);
firstColumn.setHalignment(HPos.LEFT);
secondColumn.setHalignment(HPos.RIGHT);
node.getColumnConstraints().addAll(firstColumn, secondColumn);
Label marking = new Label(annotation.getMarking());
Label author = new Label(annotation.getAuthor());
Label date = new Label(annotation.getDate());
Label page = new Label(Localization.lang("Page") + ": " + annotation.getPage());
marking.setStyle("-fx-font-size: 0.75em; -fx-font-weight: bold");
marking.setMaxHeight(30);
Tooltip markingTooltip = new Tooltip(annotation.getMarking());
markingTooltip.setMaxWidth(800);
markingTooltip.setWrapText(true);
marking.setTooltip(markingTooltip);
// add alignment for text in the list
marking.setTextAlignment(TextAlignment.LEFT);
marking.setAlignment(Pos.TOP_LEFT);
marking.setMaxWidth(500);
marking.setWrapText(true);
author.setTextAlignment(TextAlignment.LEFT);
author.setAlignment(Pos.TOP_LEFT);
date.setTextAlignment(TextAlignment.RIGHT);
date.setAlignment(Pos.TOP_RIGHT);
page.setTextAlignment(TextAlignment.RIGHT);
page.setAlignment(Pos.TOP_RIGHT);
node.add(marking, 0, 0);
node.add(author, 0, 1);
node.add(date, 1, 0);
node.add(page, 1, 1);
return node;
}
public void copy() {
viewModel.copyCurrentAnnotation();
}
}
| 5,290
| 40.335938
| 163
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/entryeditor/fileannotationtab/FileAnnotationTabViewModel.java
|
package org.jabref.gui.entryeditor.fileannotationtab;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import java.util.stream.Collectors;
import javafx.beans.property.ListProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ReadOnlyBooleanProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import org.jabref.gui.AbstractViewModel;
import org.jabref.gui.Globals;
import org.jabref.gui.util.DefaultTaskExecutor;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.pdf.FileAnnotationCache;
import org.jabref.logic.util.OS;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.pdf.FileAnnotation;
import org.jabref.model.util.FileUpdateListener;
import org.jabref.model.util.FileUpdateMonitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FileAnnotationTabViewModel extends AbstractViewModel {
private static final Logger LOGGER = LoggerFactory.getLogger(FileAnnotationTabViewModel.class);
private final ListProperty<FileAnnotationViewModel> annotations = new SimpleListProperty<>(FXCollections.observableArrayList());
private final ListProperty<Path> files = new SimpleListProperty<>(FXCollections.observableArrayList());
private final ObjectProperty<FileAnnotationViewModel> currentAnnotation = new SimpleObjectProperty<>();
private final ReadOnlyBooleanProperty annotationEmpty = annotations.emptyProperty();
private final FileAnnotationCache cache;
private final BibEntry entry;
private Map<Path, List<FileAnnotation>> fileAnnotations;
private Path currentFile;
private final FileUpdateMonitor fileMonitor;
private final FileUpdateListener fileListener = this::reloadAnnotations;
public FileAnnotationTabViewModel(FileAnnotationCache cache, BibEntry entry, FileUpdateMonitor fileMonitor) {
this.cache = cache;
this.entry = entry;
this.fileMonitor = fileMonitor;
fileAnnotations = this.cache.getFromCache(this.entry);
files.setAll(fileAnnotations.keySet());
}
public ObjectProperty<FileAnnotationViewModel> currentAnnotationProperty() {
return currentAnnotation;
}
public ReadOnlyBooleanProperty isAnnotationsEmpty() {
return annotationEmpty;
}
public ListProperty<FileAnnotationViewModel> annotationsProperty() {
return annotations;
}
public ListProperty<Path> filesProperty() {
return files;
}
public void notifyNewSelectedAnnotation(FileAnnotationViewModel newAnnotation) {
currentAnnotation.set(newAnnotation);
}
public void notifyNewSelectedFile(Path newFile) {
fileMonitor.removeListener(currentFile, fileListener);
currentFile = newFile;
Comparator<FileAnnotation> byPage = Comparator.comparingInt(FileAnnotation::getPage);
List<FileAnnotationViewModel> newAnnotations = fileAnnotations
.getOrDefault(currentFile, new ArrayList<>())
.stream()
.filter(annotation -> (null != annotation.getContent()))
.sorted(byPage)
.map(FileAnnotationViewModel::new)
.collect(Collectors.toList());
annotations.setAll(newAnnotations);
try {
fileMonitor.addListenerForFile(currentFile, fileListener);
} catch (IOException e) {
LOGGER.error("Problem while watching file for changes " + currentFile, e);
}
}
private void reloadAnnotations() {
// Make sure to always run this in the JavaFX thread as the file monitor (and its notifications) live in a different thread
DefaultTaskExecutor.runInJavaFXThread(() -> {
// Remove annotations for the current entry and reinitialize annotation/cache
cache.remove(entry);
fileAnnotations = cache.getFromCache(entry);
files.setAll(fileAnnotations.keySet());
// Pretend that we just switched to the current file in order to refresh the display
notifyNewSelectedFile(currentFile);
});
}
/**
* Copies the meta and content information of the pdf annotation to the clipboard
*/
public void copyCurrentAnnotation() {
if (null == getCurrentAnnotation()) {
return;
}
StringJoiner sj = new StringJoiner("," + OS.NEWLINE);
sj.add(Localization.lang("Author") + ": " + getCurrentAnnotation().getAuthor());
sj.add(Localization.lang("Date") + ": " + getCurrentAnnotation().getDate());
sj.add(Localization.lang("Page") + ": " + getCurrentAnnotation().getPage());
sj.add(Localization.lang("Content") + ": " + getCurrentAnnotation().getContent());
sj.add(Localization.lang("Marking") + ": " + getCurrentAnnotation().markingProperty().get());
Globals.getClipboardManager().setContent(sj.toString());
}
private FileAnnotationViewModel getCurrentAnnotation() {
return currentAnnotation.get();
}
}
| 5,237
| 38.383459
| 132
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/entryeditor/fileannotationtab/FileAnnotationViewModel.java
|
package org.jabref.gui.entryeditor.fileannotationtab;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import org.jabref.logic.formatter.bibtexfields.RemoveHyphenatedNewlinesFormatter;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.pdf.FileAnnotation;
import org.jabref.model.pdf.FileAnnotationType;
public class FileAnnotationViewModel {
private static final String NEWLINE = String.format("%n");
private final FileAnnotation annotation;
private StringProperty author = new SimpleStringProperty();
private StringProperty page = new SimpleStringProperty();
private StringProperty date = new SimpleStringProperty();
private StringProperty content = new SimpleStringProperty();
private StringProperty marking = new SimpleStringProperty();
public FileAnnotationViewModel(FileAnnotation annotation) {
this.annotation = annotation;
author.set(annotation.getAuthor());
page.set(Integer.toString(annotation.getPage()));
date.set(annotation.getTimeModified().toString().replace('T', ' '));
setupContentProperties(annotation);
}
private void setupContentProperties(FileAnnotation annotation) {
if (annotation.hasLinkedAnnotation()) {
this.content.set(annotation.getLinkedFileAnnotation().getContent());
String annotationContent = annotation.getContent();
String illegibleTextMessage = Localization.lang("The marked area does not contain any legible text!");
String markingContent = annotationContent.isEmpty() ? illegibleTextMessage : annotationContent;
this.marking.set(removePunctuationMark(markingContent));
} else {
String content = annotation.getContent();
this.content.set(removePunctuationMark(content));
this.marking.set("");
}
}
public String removePunctuationMark(String content) {
// remove newlines && hyphens before linebreaks
content = content.replaceAll("-" + NEWLINE, "");
content = new RemoveHyphenatedNewlinesFormatter().format(content);
// remove new lines not preceded by '.' or ':'
content = content.replaceAll("(?<![.|:])" + NEWLINE, " ");
return content;
}
public String getAuthor() {
return author.get();
}
public String getPage() {
return page.get();
}
public String getDate() {
return date.get();
}
public String getContent() {
return content.get();
}
public StringProperty pageProperty() {
return page;
}
public StringProperty dateProperty() {
return date;
}
public StringProperty contentProperty() {
return content;
}
public StringProperty markingProperty() {
return marking;
}
public StringProperty authorProperty() {
return author;
}
@Override
public String toString() {
if (annotation.hasLinkedAnnotation() && this.getContent().isEmpty()) {
if (FileAnnotationType.UNDERLINE == annotation.getAnnotationType()) {
return Localization.lang("Empty Underline");
}
if (FileAnnotationType.HIGHLIGHT == annotation.getAnnotationType()) {
return Localization.lang("Empty Highlight");
}
return Localization.lang("Empty Marking");
}
if (FileAnnotationType.UNDERLINE == annotation.getAnnotationType()) {
return Localization.lang("Underline") + ": " + this.getContent();
}
if (FileAnnotationType.HIGHLIGHT == annotation.getAnnotationType()) {
return Localization.lang("Highlight") + ": " + this.getContent();
}
return super.toString();
}
public String getMarking() {
return marking.get();
}
}
| 3,891
| 33.140351
| 114
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/entryeditor/fileannotationtab/FulltextSearchResultsTab.java
|
package org.jabref.gui.entryeditor.fileannotationtab;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.Separator;
import javafx.scene.control.Tooltip;
import javafx.scene.input.MouseButton;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
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.desktop.JabRefDesktop;
import org.jabref.gui.documentviewer.DocumentViewerView;
import org.jabref.gui.entryeditor.EntryEditorTab;
import org.jabref.gui.maintable.OpenExternalFileAction;
import org.jabref.gui.maintable.OpenFolderAction;
import org.jabref.gui.util.TooltipTextUtil;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.LinkedFile;
import org.jabref.model.pdf.search.PdfSearchResults;
import org.jabref.model.pdf.search.SearchResult;
import org.jabref.model.search.rules.SearchRules;
import org.jabref.preferences.PreferencesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FulltextSearchResultsTab extends EntryEditorTab {
public static final String NAME = "Search results";
private static final Logger LOGGER = LoggerFactory.getLogger(FulltextSearchResultsTab.class);
private final StateManager stateManager;
private final PreferencesService preferencesService;
private final DialogService dialogService;
private final ActionFactory actionFactory;
private final TextFlow content;
private BibEntry entry;
private DocumentViewerView documentViewerView;
public FulltextSearchResultsTab(StateManager stateManager, PreferencesService preferencesService, DialogService dialogService) {
this.stateManager = stateManager;
this.preferencesService = preferencesService;
this.dialogService = dialogService;
this.actionFactory = new ActionFactory(preferencesService.getKeyBindingRepository());
content = new TextFlow();
ScrollPane scrollPane = new ScrollPane(content);
scrollPane.setFitToWidth(true);
content.setPadding(new Insets(10));
setContent(scrollPane);
setText(Localization.lang("Search results"));
this.stateManager.activeSearchQueryProperty().addListener((observable, oldValue, newValue) -> bindToEntry(entry));
}
@Override
public boolean shouldShow(BibEntry entry) {
return this.stateManager.activeSearchQueryProperty().isPresent().get() &&
this.stateManager.activeSearchQueryProperty().get().isPresent() &&
this.stateManager.activeSearchQueryProperty().get().get().getSearchFlags().contains(SearchRules.SearchFlags.FULLTEXT) &&
this.stateManager.activeSearchQueryProperty().get().get().getQuery().length() > 0;
}
@Override
protected void bindToEntry(BibEntry entry) {
if (entry == null || !shouldShow(entry)) {
return;
}
if (!entry.equals(this.entry)) {
documentViewerView = new DocumentViewerView();
}
this.entry = entry;
PdfSearchResults searchResults = stateManager.activeSearchQueryProperty().get().get().getRule().getFulltextResults(stateManager.activeSearchQueryProperty().get().get().getQuery(), entry);
content.getChildren().clear();
if (searchResults.numSearchResults() == 0) {
content.getChildren().add(new Text(Localization.lang("No search matches.")));
}
// Iterate through files with search hits
for (Map.Entry<String, List<SearchResult>> resultsForPath : searchResults.getSearchResultsByPath().entrySet()) {
content.getChildren().addAll(createFileLink(resultsForPath.getKey()), lineSeparator());
// Iterate through pages (within file) with search hits
for (SearchResult searchResult : resultsForPath.getValue()) {
for (String resultTextHtml : searchResult.getContentResultStringsHtml()) {
content.getChildren().addAll(TooltipTextUtil.createTextsFromHtml(resultTextHtml.replaceAll("</b> <b>", " ")));
content.getChildren().addAll(new Text(System.lineSeparator()), lineSeparator(0.8), createPageLink(searchResult.getPageNumber()));
}
if (!searchResult.getAnnotationsResultStringsHtml().isEmpty()) {
Text annotationsText = new Text(System.lineSeparator() + Localization.lang("Found matches in Annotations:") + System.lineSeparator() + System.lineSeparator());
annotationsText.setStyle("-fx-font-style: italic;");
content.getChildren().add(annotationsText);
}
for (String resultTextHtml : searchResult.getAnnotationsResultStringsHtml()) {
content.getChildren().addAll(TooltipTextUtil.createTextsFromHtml(resultTextHtml.replaceAll("</b> <b>", " ")));
content.getChildren().addAll(new Text(System.lineSeparator()), lineSeparator(0.8), createPageLink(searchResult.getPageNumber()));
}
}
}
}
private Text createFileLink(String pathToFile) {
LinkedFile linkedFile = new LinkedFile("", Path.of(pathToFile), "pdf");
Text fileLinkText = new Text(Localization.lang("Found match in %0", pathToFile) + System.lineSeparator() + System.lineSeparator());
fileLinkText.setStyle("-fx-font-weight: bold;");
ContextMenu fileContextMenu = getFileContextMenu(linkedFile);
Path resolvedPath = linkedFile.findIn(stateManager.getActiveDatabase().get(), preferencesService.getFilePreferences()).orElse(Path.of(pathToFile));
Tooltip fileLinkTooltip = new Tooltip(resolvedPath.toAbsolutePath().toString());
Tooltip.install(fileLinkText, fileLinkTooltip);
fileLinkText.setOnMouseClicked(event -> {
if (MouseButton.PRIMARY.equals(event.getButton())) {
try {
JabRefDesktop.openBrowser(resolvedPath.toUri());
} catch (IOException e) {
LOGGER.error("Cannot open {}.", resolvedPath.toString(), e);
}
} else {
fileContextMenu.show(fileLinkText, event.getScreenX(), event.getScreenY());
}
});
return fileLinkText;
}
private Text createPageLink(int pageNumber) {
Text pageLink = new Text(Localization.lang("On page %0", pageNumber) + System.lineSeparator() + System.lineSeparator());
pageLink.setStyle("-fx-font-style: italic; -fx-font-weight: bold;");
pageLink.setOnMouseClicked(event -> {
if (MouseButton.PRIMARY.equals(event.getButton())) {
documentViewerView.gotoPage(pageNumber);
documentViewerView.setLiveMode(false);
documentViewerView.show();
}
});
return pageLink;
}
private ContextMenu getFileContextMenu(LinkedFile file) {
ContextMenu fileContextMenu = new ContextMenu();
fileContextMenu.getItems().add(actionFactory.createMenuItem(StandardActions.OPEN_FOLDER, new OpenFolderAction(dialogService, stateManager, preferencesService, entry, file)));
fileContextMenu.getItems().add(actionFactory.createMenuItem(StandardActions.OPEN_EXTERNAL_FILE, new OpenExternalFileAction(dialogService, stateManager, preferencesService)));
return fileContextMenu;
}
private Separator lineSeparator() {
return lineSeparator(1.0);
}
private Separator lineSeparator(double widthMultiplier) {
Separator lineSeparator = new Separator(Orientation.HORIZONTAL);
lineSeparator.prefWidthProperty().bind(content.widthProperty().multiply(widthMultiplier));
lineSeparator.setPrefHeight(15);
return lineSeparator;
}
}
| 8,144
| 46.080925
| 195
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/errorconsole/ErrorConsoleView.java
|
package org.jabref.gui.errorconsole;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.util.Callback;
import org.jabref.gui.ClipBoardManager;
import org.jabref.gui.DialogService;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.keyboard.KeyBinding;
import org.jabref.gui.keyboard.KeyBindingRepository;
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.logic.util.BuildInfo;
import com.airhacks.afterburner.views.ViewLoader;
import jakarta.inject.Inject;
public class ErrorConsoleView extends BaseDialog<Void> {
private ErrorConsoleViewModel viewModel;
@FXML private ButtonType copyLogButton;
@FXML private ButtonType clearLogButton;
@FXML private ButtonType createIssueButton;
@FXML private ListView<LogEventViewModel> messagesListView;
@FXML private Label descriptionLabel;
@Inject private DialogService dialogService;
@Inject private ClipBoardManager clipBoardManager;
@Inject private BuildInfo buildInfo;
@Inject private KeyBindingRepository keyBindingRepository;
@Inject private ThemeManager themeManager;
public ErrorConsoleView() {
this.setTitle(Localization.lang("Event log"));
this.initModality(Modality.NONE);
ViewLoader.view(this)
.load()
.setAsDialogPane(this);
ControlHelper.setAction(copyLogButton, getDialogPane(), event -> copyLog());
ControlHelper.setAction(clearLogButton, getDialogPane(), event -> clearLog());
ControlHelper.setAction(createIssueButton, getDialogPane(), event -> createIssue());
themeManager.updateFontStyle(getDialogPane().getScene());
}
@FXML
private void initialize() {
viewModel = new ErrorConsoleViewModel(dialogService, clipBoardManager, buildInfo);
messagesListView.setCellFactory(createCellFactory());
messagesListView.itemsProperty().bind(viewModel.allMessagesDataProperty());
messagesListView.scrollTo(viewModel.allMessagesDataProperty().getSize() - 1);
messagesListView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
viewModel.allMessagesDataProperty().addListener((ListChangeListener<LogEventViewModel>) (change -> {
int size = viewModel.allMessagesDataProperty().size();
if (size > 0) {
messagesListView.scrollTo(size - 1);
}
}));
descriptionLabel.setGraphic(IconTheme.JabRefIcons.CONSOLE.getGraphicNode());
}
private Callback<ListView<LogEventViewModel>, ListCell<LogEventViewModel>> createCellFactory() {
return cell -> new ListCell<>() {
private HBox graphic;
private Node icon;
private VBox message;
private Label heading;
private Label stacktrace;
{
graphic = new HBox(10);
heading = new Label();
stacktrace = new Label();
message = new VBox();
message.getChildren().setAll(heading, stacktrace);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
}
@Override
public void updateItem(LogEventViewModel event, boolean empty) {
super.updateItem(event, empty);
if ((event == null) || empty) {
setGraphic(null);
} else {
icon = event.getIcon().getGraphicNode();
heading.setText(event.getDisplayText());
heading.getStyleClass().setAll(event.getStyleClass());
stacktrace.setText(event.getStackTrace().orElse(""));
graphic.getStyleClass().setAll(event.getStyleClass());
graphic.getChildren().setAll(icon, message);
setGraphic(graphic);
}
}
};
}
@FXML
private void copySelectedLogEntries(KeyEvent event) {
if (keyBindingRepository.checkKeyCombinationEquality(KeyBinding.COPY, event)) {
ObservableList<LogEventViewModel> selectedEntries = messagesListView.getSelectionModel().getSelectedItems();
viewModel.copyLog(selectedEntries);
}
}
@FXML
private void copyLog() {
viewModel.copyLog();
}
@FXML
private void clearLog() {
viewModel.clearLog();
}
@FXML
private void createIssue() {
viewModel.reportIssue();
}
}
| 5,050
| 35.338129
| 120
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/errorconsole/ErrorConsoleViewModel.java
|
package org.jabref.gui.errorconsole;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import javafx.beans.property.ListProperty;
import javafx.beans.property.ReadOnlyListWrapper;
import javafx.collections.ObservableList;
import org.jabref.gui.AbstractViewModel;
import org.jabref.gui.ClipBoardManager;
import org.jabref.gui.DialogService;
import org.jabref.gui.desktop.JabRefDesktop;
import org.jabref.gui.util.BindingsHelper;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.logging.LogMessages;
import org.jabref.logic.util.BuildInfo;
import org.jabref.logic.util.OS;
import com.tobiasdiez.easybind.EasyBind;
import org.apache.http.client.utils.URIBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ErrorConsoleViewModel extends AbstractViewModel {
private static final Logger LOGGER = LoggerFactory.getLogger(ErrorConsoleViewModel.class);
private final DialogService dialogService;
private final ClipBoardManager clipBoardManager;
private final BuildInfo buildInfo;
private final ListProperty<LogEventViewModel> allMessagesData;
public ErrorConsoleViewModel(DialogService dialogService, ClipBoardManager clipBoardManager, BuildInfo buildInfo) {
this.dialogService = Objects.requireNonNull(dialogService);
this.clipBoardManager = Objects.requireNonNull(clipBoardManager);
this.buildInfo = Objects.requireNonNull(buildInfo);
ObservableList<LogEventViewModel> eventViewModels = EasyBind.map(BindingsHelper.forUI(LogMessages.getInstance().getMessages()), LogEventViewModel::new);
allMessagesData = new ReadOnlyListWrapper<>(eventViewModels);
}
public ListProperty<LogEventViewModel> allMessagesDataProperty() {
return this.allMessagesData;
}
/**
* Concatenates the formatted message of the given {@link LogEvent}s by using the a new line separator.
*
* @return all messages as String
*/
private String getLogMessagesAsString(List<LogEventViewModel> messages) {
return messages.stream()
.map(LogEventViewModel::getDetailedText)
.collect(Collectors.joining(OS.NEWLINE));
}
/**
* Copies the whole log to the clipboard
*/
public void copyLog() {
copyLog(allMessagesData);
}
/**
* Copies the given list of {@link LogEvent}s to the clipboard.
*/
public void copyLog(List<LogEventViewModel> messages) {
if (messages.isEmpty()) {
return;
}
clipBoardManager.setContent(getLogMessagesAsString(messages));
dialogService.notify(Localization.lang("Log copied to clipboard."));
}
/**
* Clears the current log
*/
public void clearLog() {
LogMessages.getInstance().clear();
}
/**
* Opens a new issue on GitHub and copies log to clipboard.
*/
public void reportIssue() {
try {
// System info
String systemInfo = String.format("JabRef %s%n%s %s %s %nJava %s", buildInfo.version, BuildInfo.OS,
BuildInfo.OS_VERSION, BuildInfo.OS_ARCH, BuildInfo.JAVA_VERSION);
// Steps to reproduce
String howToReproduce = "Steps to reproduce:\n\n1. ...\n2. ...\n3. ...";
// Log messages
String issueDetails = "<details>\n" + "<summary>" + "Detail information:" + "</summary>\n\n```\n"
+ getLogMessagesAsString(allMessagesData) + "\n```\n\n</details>";
clipBoardManager.setContent(issueDetails);
// Bug report body
String issueBody = systemInfo + "\n\n" + howToReproduce + "\n\n" + "Paste your log details here.";
dialogService.notify(Localization.lang("Issue on GitHub successfully reported."));
dialogService.showInformationDialogAndWait(Localization.lang("Issue report successful"),
Localization.lang("Your issue was reported in your browser.") + "\n" +
Localization.lang("The log and exception information was copied to your clipboard.") + " " +
Localization.lang("Please paste this information (with Ctrl+V) in the issue description.") + "\n" +
Localization.lang("Please also add all steps to reproduce this issue, if possible."));
URIBuilder uriBuilder = new URIBuilder()
.setScheme("https").setHost("github.com")
.setPath("/JabRef/jabref/issues/new")
.setParameter("body", issueBody);
JabRefDesktop.openBrowser(uriBuilder.build().toString());
} catch (IOException | URISyntaxException e) {
LOGGER.error("Problem opening url", e);
}
}
}
| 4,882
| 40.033613
| 160
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/errorconsole/LogEventViewModel.java
|
package org.jabref.gui.errorconsole;
import java.util.Objects;
import java.util.Optional;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.icon.JabRefIcon;
import org.jabref.logic.util.OS;
import com.google.common.base.Throwables;
import org.tinylog.core.LogEntry;
public class LogEventViewModel {
private final LogEntry logEvent;
public LogEventViewModel(LogEntry logEvent) {
this.logEvent = Objects.requireNonNull(logEvent);
}
public String getDisplayText() {
return logEvent.getMessage();
}
public String getStyleClass() {
switch (logEvent.getLevel()) {
case ERROR:
return "exception";
case WARN:
return "output";
case INFO:
default:
return "log";
}
}
public JabRefIcon getIcon() {
switch (logEvent.getLevel()) {
case ERROR:
return IconTheme.JabRefIcons.INTEGRITY_FAIL;
case WARN:
return IconTheme.JabRefIcons.INTEGRITY_WARN;
case INFO:
default:
return IconTheme.JabRefIcons.INTEGRITY_INFO;
}
}
public Optional<String> getStackTrace() {
return Optional.ofNullable(logEvent.getException()).map(Throwables::getStackTraceAsString);
}
public String getDetailedText() {
return getDisplayText() + getStackTrace().map(stacktrace -> OS.NEWLINE + stacktrace).orElse("");
}
}
| 1,499
| 25.315789
| 104
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/exporter/CreateModifyExporterDialogView.java
|
package org.jabref.gui.exporter;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.ButtonType;
import javafx.scene.control.TextField;
import org.jabref.gui.DialogService;
import org.jabref.gui.util.BaseDialog;
import org.jabref.logic.l10n.Localization;
import org.jabref.preferences.PreferencesService;
import com.airhacks.afterburner.views.ViewLoader;
import jakarta.inject.Inject;
public class CreateModifyExporterDialogView extends BaseDialog<ExporterViewModel> {
private final ExporterViewModel exporter;
@FXML private TextField name;
@FXML private TextField fileName;
@FXML private TextField extension;
@FXML private ButtonType saveExporter;
@Inject private DialogService dialogService;
@Inject private PreferencesService preferences;
private CreateModifyExporterDialogViewModel viewModel;
public CreateModifyExporterDialogView(ExporterViewModel exporter) {
this.setTitle(Localization.lang("Customize Export Formats"));
this.exporter = exporter;
ViewLoader.view(this)
.load()
.setAsDialogPane(this);
this.setResultConverter(button -> {
if (button == saveExporter) {
return viewModel.saveExporter();
} else {
return null;
}
});
}
@FXML
private void initialize() {
viewModel = new CreateModifyExporterDialogViewModel(exporter, dialogService, preferences);
name.textProperty().bindBidirectional(viewModel.getName());
fileName.textProperty().bindBidirectional(viewModel.getLayoutFileName());
extension.textProperty().bindBidirectional(viewModel.getExtension());
}
@FXML
private void browse(ActionEvent event) {
viewModel.browse();
}
}
| 1,830
| 31.122807
| 98
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/exporter/CreateModifyExporterDialogViewModel.java
|
package org.jabref.gui.exporter;
import java.nio.file.Path;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import org.jabref.gui.AbstractViewModel;
import org.jabref.gui.DialogService;
import org.jabref.gui.util.FileDialogConfiguration;
import org.jabref.logic.exporter.TemplateExporter;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.StandardFileType;
import org.jabref.preferences.PreferencesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This view model can be used both for "add exporter" and "modify exporter" functionalities.
* It takes an optional exporter which is empty for "add exporter," and takes the selected exporter
* for "modify exporter." It returns an optional exporter which empty if an invalid or no exporter is
* created, and otherwise contains the exporter to be added or that is modified.
*/
public class CreateModifyExporterDialogViewModel extends AbstractViewModel {
private static final Logger LOGGER = LoggerFactory.getLogger(CreateModifyExporterDialogViewModel.class);
private final DialogService dialogService;
private final PreferencesService preferences;
private final StringProperty name = new SimpleStringProperty("");
private final StringProperty layoutFile = new SimpleStringProperty("");
private final StringProperty extension = new SimpleStringProperty("");
public CreateModifyExporterDialogViewModel(ExporterViewModel exporter,
DialogService dialogService,
PreferencesService preferences) {
this.dialogService = dialogService;
this.preferences = preferences;
// Set text of each of the boxes
if (exporter != null) {
name.setValue(exporter.name().get());
layoutFile.setValue(exporter.layoutFileName().get());
extension.setValue(exporter.extension().get());
}
}
public ExporterViewModel saveExporter() {
Path layoutFileDir = Path.of(layoutFile.get()).getParent();
if (layoutFileDir != null) {
preferences.getExportPreferences().setExportWorkingDirectory(layoutFileDir);
}
// Check that there are no empty strings.
if (layoutFile.get().isEmpty() || name.get().isEmpty() || extension.get().isEmpty()
|| !layoutFile.get().endsWith(".layout")) {
LOGGER.info("One of the fields is empty or invalid!");
return null;
}
// Create a new exporter to be returned to ExportCustomizationDialogViewModel, which requested it
TemplateExporter format = new TemplateExporter(
name.get(),
layoutFile.get(),
extension.get(),
preferences.getLayoutFormatterPreferences(),
preferences.getExportConfiguration());
format.setCustomExport(true);
return new ExporterViewModel(format);
}
public void browse() {
FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
.addExtensionFilter(Localization.lang("Custom layout file"), StandardFileType.LAYOUT)
.withDefaultExtension(Localization.lang("Custom layout file"), StandardFileType.LAYOUT)
.withInitialDirectory(preferences.getExportPreferences().getExportWorkingDirectory()).build();
dialogService.showFileOpenDialog(fileDialogConfiguration).ifPresent(f -> layoutFile.set(f.toAbsolutePath().toString()));
}
public StringProperty getName() {
return name;
}
public StringProperty getLayoutFileName() {
return layoutFile;
}
public StringProperty getExtension() {
return extension;
}
}
| 3,838
| 39.410526
| 128
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/exporter/ExportCommand.java
|
package org.jabref.gui.exporter;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import javafx.stage.FileChooser;
import javafx.util.Duration;
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.ActionHelper;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.desktop.JabRefDesktop;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.gui.util.FileDialogConfiguration;
import org.jabref.gui.util.FileFilterConverter;
import org.jabref.logic.exporter.Exporter;
import org.jabref.logic.exporter.ExporterFactory;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.io.FileUtil;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.preferences.PreferencesService;
import org.controlsfx.control.action.Action;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Performs an export action
*/
public class ExportCommand extends SimpleCommand {
public enum ExportMethod { EXPORT_ALL, EXPORT_SELECTED }
private static final Logger LOGGER = LoggerFactory.getLogger(ExportCommand.class);
private final ExportMethod exportMethod;
private final JabRefFrame frame;
private final StateManager stateManager;
private final PreferencesService preferences;
private final DialogService dialogService;
public ExportCommand(ExportMethod exportMethod,
JabRefFrame frame,
StateManager stateManager,
DialogService dialogService,
PreferencesService preferences) {
this.exportMethod = exportMethod;
this.frame = frame;
this.stateManager = stateManager;
this.preferences = preferences;
this.dialogService = dialogService;
this.executable.bind(exportMethod == ExportMethod.EXPORT_SELECTED
? ActionHelper.needsEntriesSelected(stateManager)
: ActionHelper.needsDatabase(stateManager));
}
@Override
public void execute() {
// Get list of exporters and sort before adding to file dialog
ExporterFactory exporterFactory = ExporterFactory.create(
preferences,
Globals.entryTypesManager);
List<Exporter> exporters = exporterFactory.getExporters().stream()
.sorted(Comparator.comparing(Exporter::getName))
.collect(Collectors.toList());
FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
.addExtensionFilter(FileFilterConverter.exporterToExtensionFilter(exporters))
.withDefaultExtension(preferences.getExportPreferences().getLastExportExtension())
.withInitialDirectory(preferences.getExportPreferences().getExportWorkingDirectory())
.build();
dialogService.showFileSaveDialog(fileDialogConfiguration)
.ifPresent(path -> export(path, fileDialogConfiguration.getSelectedExtensionFilter(), exporters));
}
private void export(Path file, FileChooser.ExtensionFilter selectedExtensionFilter, List<Exporter> exporters) {
String selectedExtension = selectedExtensionFilter.getExtensions().get(0).replace("*", "");
if (!file.endsWith(selectedExtension)) {
FileUtil.addExtension(file, selectedExtension);
}
final Exporter format = FileFilterConverter.getExporter(selectedExtensionFilter, exporters)
.orElseThrow(() -> new IllegalStateException("User didn't selected a file type for the extension"));
List<BibEntry> entries;
if (exportMethod == ExportMethod.EXPORT_SELECTED) {
// Selected entries
entries = stateManager.getSelectedEntries();
} else {
// All entries
entries = stateManager.getActiveDatabase()
.map(BibDatabaseContext::getEntries)
.orElse(Collections.emptyList());
}
List<Path> fileDirForDatabase = stateManager.getActiveDatabase()
.map(db -> db.getFileDirectories(preferences.getFilePreferences()))
.orElse(List.of(preferences.getFilePreferences().getWorkingDirectory()));
// Make sure we remember which filter was used, to set
// the default for next time:
preferences.getExportPreferences().setLastExportExtension(format.getName());
preferences.getExportPreferences().setExportWorkingDirectory(file.getParent());
final List<BibEntry> finEntries = entries;
BackgroundTask
.wrap(() -> {
format.export(stateManager.getActiveDatabase().get(),
file,
finEntries,
fileDirForDatabase,
Globals.journalAbbreviationRepository);
return null; // can not use BackgroundTask.wrap(Runnable) because Runnable.run() can't throw Exceptions
})
.onSuccess(save -> {
LibraryTab.DatabaseNotification notificationPane = frame.getCurrentLibraryTab().getNotificationPane();
notificationPane.notify(
IconTheme.JabRefIcons.FOLDER.getGraphicNode(),
Localization.lang("Export operation finished successfully."),
List.of(new Action(Localization.lang("Reveal in File Explorer"), event -> {
try {
JabRefDesktop.openFolderAndSelectFile(file, preferences, dialogService);
} catch (IOException e) {
LOGGER.error("Could not open export folder.", e);
}
notificationPane.hide();
})),
Duration.seconds(5));
})
.onFailure(this::handleError)
.executeWith(Globals.TASK_EXECUTOR);
}
private void handleError(Exception ex) {
LOGGER.warn("Problem exporting", ex);
dialogService.notify(Localization.lang("Could not save file."));
// Need to warn the user that saving failed!
dialogService.showErrorDialogAndWait(Localization.lang("Save library"), Localization.lang("Could not save file."), ex);
}
}
| 6,980
| 44.927632
| 151
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/exporter/ExportToClipboardAction.java
|
package org.jabref.gui.exporter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javafx.scene.input.ClipboardContent;
import org.jabref.gui.ClipBoardManager;
import org.jabref.gui.DialogService;
import org.jabref.gui.Globals;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.ActionHelper;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.exporter.Exporter;
import org.jabref.logic.exporter.ExporterFactory;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.FileType;
import org.jabref.logic.util.StandardFileType;
import org.jabref.model.entry.BibEntry;
import org.jabref.preferences.PreferencesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ExportToClipboardAction extends SimpleCommand {
private static final Logger LOGGER = LoggerFactory.getLogger(ExportToClipboardAction.class);
// Only text based exporters can be used
private static final Set<FileType> SUPPORTED_FILETYPES = Set.of(
StandardFileType.TXT,
StandardFileType.RTF,
StandardFileType.RDF,
StandardFileType.XML,
StandardFileType.HTML,
StandardFileType.CSV,
StandardFileType.RIS);
private final DialogService dialogService;
private final List<BibEntry> entries = new ArrayList<>();
private final ClipBoardManager clipBoardManager;
private final TaskExecutor taskExecutor;
private final PreferencesService preferences;
private final StateManager stateManager;
public ExportToClipboardAction(DialogService dialogService,
StateManager stateManager,
ClipBoardManager clipBoardManager,
TaskExecutor taskExecutor,
PreferencesService preferencesService) {
this.dialogService = dialogService;
this.clipBoardManager = clipBoardManager;
this.taskExecutor = taskExecutor;
this.preferences = preferencesService;
this.stateManager = stateManager;
this.executable.bind(ActionHelper.needsEntriesSelected(stateManager));
}
@Override
public void execute() {
if (stateManager.getSelectedEntries().isEmpty()) {
dialogService.notify(Localization.lang("This operation requires one or more entries to be selected."));
return;
}
ExporterFactory exporterFactory = ExporterFactory.create(
preferences,
Globals.entryTypesManager);
List<Exporter> exporters = exporterFactory.getExporters().stream()
.sorted(Comparator.comparing(Exporter::getName))
.filter(exporter -> SUPPORTED_FILETYPES.contains(exporter.getFileType()))
.collect(Collectors.toList());
// Find default choice, if any
Exporter defaultChoice = exporters.stream()
.filter(exporter -> exporter.getName().equals(preferences.getExportPreferences().getLastExportExtension()))
.findAny()
.orElse(null);
Optional<Exporter> selectedExporter = dialogService.showChoiceDialogAndWait(
Localization.lang("Export"), Localization.lang("Select export format"),
Localization.lang("Export"), defaultChoice, exporters);
selectedExporter.ifPresent(exporter -> BackgroundTask.wrap(() -> exportToClipboard(exporter))
.onSuccess(this::setContentToClipboard)
.onFailure(ex -> {
LOGGER.error("Error exporting to clipboard", ex);
dialogService.showErrorDialogAndWait("Error exporting to clipboard", ex);
})
.executeWith(taskExecutor));
}
private ExportResult exportToClipboard(Exporter exporter) throws Exception {
List<Path> fileDirForDatabase = stateManager.getActiveDatabase()
.map(db -> db.getFileDirectories(preferences.getFilePreferences()))
.orElse(List.of(preferences.getFilePreferences().getWorkingDirectory()));
// Add chosen export type to last used preference, to become default
preferences.getExportPreferences().setLastExportExtension(exporter.getName());
Path tmp = null;
try {
// To simplify the exporter API we simply do a normal export to a temporary
// file, and read the contents afterwards:
tmp = Files.createTempFile("jabrefCb", ".tmp");
entries.addAll(stateManager.getSelectedEntries());
// Write to file:
exporter.export(stateManager.getActiveDatabase().get(), tmp, entries, fileDirForDatabase, Globals.journalAbbreviationRepository);
// Read the file and put the contents on the clipboard:
return new ExportResult(Files.readString(tmp), exporter.getFileType());
} finally {
// Clean up:
if ((tmp != null) && Files.exists(tmp)) {
try {
Files.delete(tmp);
} catch (IOException e) {
LOGGER.info("Cannot delete temporary clipboard file", e);
}
}
}
}
private void setContentToClipboard(ExportResult result) {
ClipboardContent clipboardContent = new ClipboardContent();
List<String> extensions = result.fileType.getExtensions();
if (extensions.contains("html")) {
clipboardContent.putHtml(result.content);
} else if (extensions.contains("rtf")) {
clipboardContent.putRtf(result.content);
} else if (extensions.contains("rdf")) {
clipboardContent.putRtf(result.content);
}
clipboardContent.putString(result.content);
this.clipBoardManager.setContent(clipboardContent);
dialogService.notify(Localization.lang("Entries exported to clipboard") + ": " + entries.size());
}
private record ExportResult(String content, FileType fileType) {
}
}
| 6,881
| 43.4
| 149
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/exporter/ExporterViewModel.java
|
package org.jabref.gui.exporter;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import org.jabref.logic.exporter.TemplateExporter;
/**
* ExporterViewModel wraps a TemplateExporter from logic and is used in the exporter customization dialog view and ViewModel.
*/
public class ExporterViewModel {
private final TemplateExporter exporter;
private final StringProperty name = new SimpleStringProperty();
private final StringProperty layoutFileName = new SimpleStringProperty();
private final StringProperty extension = new SimpleStringProperty();
public ExporterViewModel(TemplateExporter exporter) {
this.exporter = exporter;
this.name.setValue(exporter.getName());
this.layoutFileName.setValue(exporter.getLayoutFileNameWithExtension());
// Only the first of the extensions gotten from FileType is saved into the class using get(0)
String extensionString = exporter.getFileType().getExtensions().get(0);
this.extension.setValue(extensionString);
}
public TemplateExporter getLogic() {
return this.exporter;
}
public StringProperty name() {
return this.name;
}
public StringProperty layoutFileName() {
return this.layoutFileName;
}
public StringProperty extension() {
return this.extension;
}
}
| 1,390
| 30.613636
| 125
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/exporter/SaveAction.java
|
package org.jabref.gui.exporter;
import org.jabref.gui.Globals;
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.preferences.PreferencesService;
/**
* This class is just a simple wrapper for the soon to be refactored SaveDatabaseAction.
*/
public class SaveAction extends SimpleCommand {
public enum SaveMethod { SAVE, SAVE_AS, SAVE_SELECTED }
private final SaveMethod saveMethod;
private final JabRefFrame frame;
private final PreferencesService preferencesService;
public SaveAction(SaveMethod saveMethod, JabRefFrame frame, PreferencesService preferencesService, StateManager stateManager) {
this.saveMethod = saveMethod;
this.frame = frame;
this.preferencesService = preferencesService;
if (saveMethod == SaveMethod.SAVE_SELECTED) {
this.executable.bind(ActionHelper.needsEntriesSelected(stateManager));
} else {
this.executable.bind(ActionHelper.needsDatabase(stateManager));
}
}
@Override
public void execute() {
SaveDatabaseAction saveDatabaseAction = new SaveDatabaseAction(
frame.getCurrentLibraryTab(),
preferencesService,
Globals.entryTypesManager);
switch (saveMethod) {
case SAVE -> saveDatabaseAction.save();
case SAVE_AS -> saveDatabaseAction.saveAs();
case SAVE_SELECTED -> saveDatabaseAction.saveSelectedAsPlain();
}
}
}
| 1,593
| 32.914894
| 131
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/exporter/SaveAllAction.java
|
package org.jabref.gui.exporter;
import org.jabref.gui.DialogService;
import org.jabref.gui.Globals;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.LibraryTab;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.logic.l10n.Localization;
import org.jabref.preferences.PreferencesService;
public class SaveAllAction extends SimpleCommand {
private final JabRefFrame frame;
private final DialogService dialogService;
private final PreferencesService preferencesService;
public SaveAllAction(JabRefFrame frame, PreferencesService preferencesService) {
this.frame = frame;
this.dialogService = frame.getDialogService();
this.preferencesService = preferencesService;
}
@Override
public void execute() {
dialogService.notify(Localization.lang("Saving all libraries..."));
for (LibraryTab libraryTab : frame.getLibraryTabs()) {
SaveDatabaseAction saveDatabaseAction = new SaveDatabaseAction(libraryTab, preferencesService, Globals.entryTypesManager);
boolean saveResult = saveDatabaseAction.save();
if (!saveResult) {
dialogService.notify(Localization.lang("Could not save file."));
}
}
dialogService.notify(Localization.lang("Save all finished."));
}
}
| 1,326
| 33.921053
| 134
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/exporter/SaveDatabaseAction.java
|
package org.jabref.gui.exporter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.charset.UnsupportedCharsetException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonType;
import javafx.scene.control.DialogPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import org.jabref.gui.DialogService;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.LibraryTab;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.gui.util.FileDialogConfiguration;
import org.jabref.logic.autosaveandbackup.AutosaveManager;
import org.jabref.logic.autosaveandbackup.BackupManager;
import org.jabref.logic.exporter.AtomicFileWriter;
import org.jabref.logic.exporter.BibDatabaseWriter;
import org.jabref.logic.exporter.BibWriter;
import org.jabref.logic.exporter.BibtexDatabaseWriter;
import org.jabref.logic.exporter.SaveConfiguration;
import org.jabref.logic.exporter.SaveException;
import org.jabref.logic.l10n.Encodings;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.shared.DatabaseLocation;
import org.jabref.logic.shared.prefs.SharedDatabasePreferences;
import org.jabref.logic.util.StandardFileType;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.database.event.ChangePropagation;
import org.jabref.model.entry.BibEntryTypesManager;
import org.jabref.preferences.PreferencesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Action for the "Save" and "Save as" operations called from BasePanel. This class is also used for save operations
* when closing a database or quitting the applications.
* <p>
* The save operation is loaded off of the GUI thread using {@link BackgroundTask}. Callers can query whether the
* operation was canceled, or whether it was successful.
*/
public class SaveDatabaseAction {
private static final Logger LOGGER = LoggerFactory.getLogger(SaveDatabaseAction.class);
private final LibraryTab libraryTab;
private final JabRefFrame frame;
private final DialogService dialogService;
private final PreferencesService preferences;
private final BibEntryTypesManager entryTypesManager;
public enum SaveDatabaseMode {
SILENT, NORMAL
}
public SaveDatabaseAction(LibraryTab libraryTab, PreferencesService preferences, BibEntryTypesManager entryTypesManager) {
this.libraryTab = libraryTab;
this.frame = libraryTab.frame();
this.dialogService = frame.getDialogService();
this.preferences = preferences;
this.entryTypesManager = entryTypesManager;
}
public boolean save() {
return save(libraryTab.getBibDatabaseContext(), SaveDatabaseMode.NORMAL);
}
public boolean save(SaveDatabaseMode mode) {
return save(libraryTab.getBibDatabaseContext(), mode);
}
/**
* Asks the user for the path and saves afterwards
*/
public void saveAs() {
askForSavePath().ifPresent(this::saveAs);
}
public boolean saveAs(Path file) {
return this.saveAs(file, SaveDatabaseMode.NORMAL);
}
public void saveSelectedAsPlain() {
askForSavePath().ifPresent(path -> {
try {
saveDatabase(path, true, StandardCharsets.UTF_8, BibDatabaseWriter.SaveType.PLAIN_BIBTEX);
frame.getFileHistory().newFile(path);
dialogService.notify(Localization.lang("Saved selected to '%0'.", path.toString()));
} catch (SaveException ex) {
LOGGER.error("A problem occurred when trying to save the file", ex);
dialogService.showErrorDialogAndWait(Localization.lang("Save library"), Localization.lang("Could not save file."), ex);
}
});
}
/**
* @param file the new file name to save the database to. This is stored in the database context of the panel upon
* successful save.
* @return true on successful save
*/
boolean saveAs(Path file, SaveDatabaseMode mode) {
BibDatabaseContext context = libraryTab.getBibDatabaseContext();
// Close AutosaveManager and BackupManager for original library
Optional<Path> databasePath = context.getDatabasePath();
if (databasePath.isPresent()) {
final Path oldFile = databasePath.get();
context.setDatabasePath(oldFile);
AutosaveManager.shutdown(context);
BackupManager.shutdown(context, this.preferences.getFilePreferences().getBackupDirectory(), preferences.getFilePreferences().shouldCreateBackup());
}
// Set new location
if (context.getLocation() == DatabaseLocation.SHARED) {
// Save all properties dependent on the ID. This makes it possible to restore them.
new SharedDatabasePreferences(context.getDatabase().generateSharedDatabaseID())
.putAllDBMSConnectionProperties(context.getDBMSSynchronizer().getConnectionProperties());
}
boolean saveResult = save(file, mode);
if (saveResult) {
// we managed to successfully save the file
// thus, we can store the path into the context
context.setDatabasePath(file);
libraryTab.updateTabTitle(false);
// Reset (here: uninstall and install again) AutosaveManager and BackupManager for the new file name
libraryTab.resetChangeMonitor();
libraryTab.installAutosaveManagerAndBackupManager();
frame.getFileHistory().newFile(file);
}
return saveResult;
}
/**
* Asks the user for the path to save to. Stores the directory to the preferences, which is used next time when
* opening the dialog.
*
* @return the path set by the user
*/
private Optional<Path> askForSavePath() {
FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
.addExtensionFilter(StandardFileType.BIBTEX_DB)
.withDefaultExtension(StandardFileType.BIBTEX_DB)
.withInitialDirectory(preferences.getFilePreferences().getWorkingDirectory())
.build();
Optional<Path> selectedPath = dialogService.showFileSaveDialog(fileDialogConfiguration);
selectedPath.ifPresent(path -> preferences.getFilePreferences().setWorkingDirectory(path.getParent()));
if (selectedPath.isPresent()) {
Path savePath = selectedPath.get();
// Workaround for linux systems not adding file extension
if (!(savePath.getFileName().toString().toLowerCase().endsWith(".bib"))) {
savePath = Path.of(savePath.toString() + ".bib");
if (!Files.notExists(savePath)) {
if (!dialogService.showConfirmationDialogAndWait(Localization.lang("Overwrite file"), Localization.lang("'%0' exists. Overwrite file?", savePath.getFileName()))) {
return Optional.empty();
}
}
selectedPath = Optional.of(savePath);
}
}
return selectedPath;
}
private boolean save(BibDatabaseContext bibDatabaseContext, SaveDatabaseMode mode) {
Optional<Path> databasePath = bibDatabaseContext.getDatabasePath();
if (databasePath.isEmpty()) {
Optional<Path> savePath = askForSavePath();
if (savePath.isEmpty()) {
return false;
}
return saveAs(savePath.get(), mode);
}
return save(databasePath.get(), mode);
}
private boolean save(Path targetPath, SaveDatabaseMode mode) {
if (mode == SaveDatabaseMode.NORMAL) {
dialogService.notify(String.format("%s...", Localization.lang("Saving library")));
}
synchronized (libraryTab) {
if (libraryTab.isSaving()) {
// if another thread is saving, we do not need to save
return true;
}
libraryTab.setSaving(true);
}
try {
Charset encoding = libraryTab.getBibDatabaseContext()
.getMetaData()
.getEncoding()
.orElse(StandardCharsets.UTF_8);
// Make sure to remember which encoding we used
libraryTab.getBibDatabaseContext().getMetaData().setEncoding(encoding, ChangePropagation.DO_NOT_POST_EVENT);
// Save the database
boolean success = saveDatabase(targetPath, false, encoding, BibDatabaseWriter.SaveType.ALL);
if (success) {
libraryTab.getUndoManager().markUnchanged();
libraryTab.resetChangedProperties();
}
dialogService.notify(Localization.lang("Library saved"));
return success;
} catch (SaveException ex) {
LOGGER.error(String.format("A problem occurred when trying to save the file %s", targetPath), ex);
dialogService.showErrorDialogAndWait(Localization.lang("Save library"), Localization.lang("Could not save file."), ex);
return false;
} finally {
// release panel from save status
libraryTab.setSaving(false);
}
}
private boolean saveDatabase(Path file, boolean selectedOnly, Charset encoding, BibDatabaseWriter.SaveType saveType) throws SaveException {
// if this code is adapted, please also adapt org.jabref.logic.autosaveandbackup.BackupManager.performBackup
SaveConfiguration saveConfiguration = new SaveConfiguration()
.withSaveType(saveType)
.withMetadataSaveOrder(true)
.withReformatOnSave(preferences.getLibraryPreferences().shouldAlwaysReformatOnSave());
BibDatabaseContext bibDatabaseContext = libraryTab.getBibDatabaseContext();
synchronized (bibDatabaseContext) {
try (AtomicFileWriter fileWriter = new AtomicFileWriter(file, encoding, saveConfiguration.shouldMakeBackup())) {
BibWriter bibWriter = new BibWriter(fileWriter, bibDatabaseContext.getDatabase().getNewLineSeparator());
BibtexDatabaseWriter databaseWriter = new BibtexDatabaseWriter(
bibWriter,
saveConfiguration,
preferences.getFieldPreferences(),
preferences.getCitationKeyPatternPreferences(),
entryTypesManager);
if (selectedOnly) {
databaseWriter.savePartOfDatabase(bibDatabaseContext, libraryTab.getSelectedEntries());
} else {
databaseWriter.saveDatabase(bibDatabaseContext);
}
libraryTab.registerUndoableChanges(databaseWriter.getSaveActionsFieldChanges());
if (fileWriter.hasEncodingProblems()) {
saveWithDifferentEncoding(file, selectedOnly, encoding, fileWriter.getEncodingProblems(), saveType);
}
} catch (UnsupportedCharsetException ex) {
throw new SaveException(Localization.lang("Character encoding '%0' is not supported.", encoding.displayName()), ex);
} catch (IOException ex) {
throw new SaveException("Problems saving: " + ex, ex);
}
return true;
}
}
private void saveWithDifferentEncoding(Path file, boolean selectedOnly, Charset encoding, Set<Character> encodingProblems, BibDatabaseWriter.SaveType saveType) throws SaveException {
DialogPane pane = new DialogPane();
VBox vbox = new VBox();
vbox.getChildren().addAll(
new Text(Localization.lang("The chosen encoding '%0' could not encode the following characters:", encoding.displayName())),
new Text(encodingProblems.stream().map(Object::toString).collect(Collectors.joining("."))),
new Text(Localization.lang("What do you want to do?"))
);
pane.setContent(vbox);
ButtonType tryDifferentEncoding = new ButtonType(Localization.lang("Try different encoding"), ButtonBar.ButtonData.OTHER);
ButtonType ignore = new ButtonType(Localization.lang("Ignore"), ButtonBar.ButtonData.APPLY);
boolean saveWithDifferentEncoding = dialogService
.showCustomDialogAndWait(Localization.lang("Save library"), pane, ignore, tryDifferentEncoding)
.filter(buttonType -> buttonType.equals(tryDifferentEncoding))
.isPresent();
if (saveWithDifferentEncoding) {
Optional<Charset> newEncoding = dialogService.showChoiceDialogAndWait(Localization.lang("Save library"), Localization.lang("Select new encoding"), Localization.lang("Save library"), encoding, Encodings.getCharsets());
if (newEncoding.isPresent()) {
// Make sure to remember which encoding we used.
libraryTab.getBibDatabaseContext().getMetaData().setEncoding(newEncoding.get(), ChangePropagation.DO_NOT_POST_EVENT);
saveDatabase(file, selectedOnly, newEncoding.get(), saveType);
}
}
}
}
| 13,455
| 44.459459
| 229
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/exporter/WriteMetadataToPdfAction.java
|
package org.jabref.gui.exporter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import org.jabref.gui.DialogService;
import org.jabref.gui.FXDialog;
import org.jabref.gui.Globals;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.bibtex.FieldPreferences;
import org.jabref.logic.exporter.EmbeddedBibFilePdfExporter;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.io.FileUtil;
import org.jabref.logic.xmp.XmpPreferences;
import org.jabref.logic.xmp.XmpUtilWriter;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.BibEntryTypesManager;
import org.jabref.preferences.FilePreferences;
import static org.jabref.gui.actions.ActionHelper.needsDatabase;
public class WriteMetadataToPdfAction extends SimpleCommand {
private final StateManager stateManager;
private final BibEntryTypesManager entryTypesManager;
private final FieldPreferences fieldPreferences;
private final DialogService dialogService;
private final TaskExecutor taskExecutor;
private final FilePreferences filePreferences;
private final XmpPreferences xmpPreferences;
private OptionsDialog optionsDialog;
private BibDatabase database;
private Collection<BibEntry> entries;
private boolean shouldContinue = true;
private int skipped;
private int entriesChanged;
private int errors;
public WriteMetadataToPdfAction(StateManager stateManager, BibEntryTypesManager entryTypesManager, FieldPreferences fieldPreferences, DialogService dialogService, TaskExecutor taskExecutor, FilePreferences filePreferences, XmpPreferences xmpPreferences) {
this.stateManager = stateManager;
this.entryTypesManager = entryTypesManager;
this.fieldPreferences = fieldPreferences;
this.dialogService = dialogService;
this.taskExecutor = taskExecutor;
this.filePreferences = filePreferences;
this.xmpPreferences = xmpPreferences;
this.executable.bind(needsDatabase(stateManager));
}
@Override
public void execute() {
init();
BackgroundTask.wrap(this::writeMetadata)
.executeWith(taskExecutor);
}
public void init() {
if (stateManager.getActiveDatabase().isEmpty()) {
return;
}
database = stateManager.getActiveDatabase().get().getDatabase();
// Get entries and check if it makes sense to perform this operation
entries = stateManager.getSelectedEntries();
if (entries.isEmpty()) {
entries = database.getEntries();
if (entries.isEmpty()) {
dialogService.showErrorDialogAndWait(
Localization.lang("Write metadata to PDF files"),
Localization.lang("This operation requires one or more entries to be selected."));
shouldContinue = false;
return;
} else {
boolean confirm = dialogService.showConfirmationDialogAndWait(
Localization.lang("Write metadata to PDF files"),
Localization.lang("Write metadata for all PDFs in current library?"));
if (confirm) {
shouldContinue = false;
return;
}
}
}
errors = entriesChanged = skipped = 0;
if (optionsDialog == null) {
optionsDialog = new OptionsDialog();
}
optionsDialog.open();
dialogService.notify(Localization.lang("Writing metadata..."));
}
private void writeMetadata() {
if (!shouldContinue || stateManager.getActiveDatabase().isEmpty()) {
return;
}
for (BibEntry entry : entries) {
// Make a list of all PDFs linked from this entry:
List<Path> files = entry.getFiles().stream()
.map(file -> file.findIn(stateManager.getActiveDatabase().get(), filePreferences))
.filter(Optional::isPresent)
.map(Optional::get)
.filter(FileUtil::isPDFFile)
.toList();
Platform.runLater(() -> optionsDialog.getProgressArea()
.appendText(entry.getCitationKey().orElse(Localization.lang("undefined")) + "\n"));
if (files.isEmpty()) {
skipped++;
Platform.runLater(() -> optionsDialog.getProgressArea()
.appendText(" " + Localization.lang("Skipped - No PDF linked") + ".\n"));
} else {
for (Path file : files) {
if (Files.exists(file)) {
try {
writeMetadataToFile(file, entry, stateManager.getActiveDatabase().get(), database);
Platform.runLater(() ->
optionsDialog.getProgressArea()
.appendText(" " + Localization.lang("OK") + ".\n"));
entriesChanged++;
} catch (Exception e) {
Platform.runLater(() -> {
optionsDialog.getProgressArea()
.appendText(" " + Localization.lang("Error while writing") + " '" + file + "':\n");
optionsDialog.getProgressArea().appendText(" " + e.getLocalizedMessage() + "\n");
});
errors++;
}
} else {
skipped++;
Platform.runLater(() -> {
optionsDialog.getProgressArea()
.appendText(" " + Localization.lang("Skipped - PDF does not exist") + ":\n");
optionsDialog.getProgressArea()
.appendText(" " + file + "\n");
});
}
}
}
if (optionsDialog.isCanceled()) {
Platform.runLater(() ->
optionsDialog.getProgressArea().appendText("\n" + Localization.lang("Operation canceled.") + "\n"));
break;
}
}
Platform.runLater(() -> {
optionsDialog.getProgressArea()
.appendText("\n"
+ Localization.lang("Finished writing metadata for %0 file (%1 skipped, %2 errors).",
String.valueOf(entriesChanged), String.valueOf(skipped), String.valueOf(errors)));
optionsDialog.done();
});
if (!shouldContinue) {
return;
}
dialogService.notify(Localization.lang("Finished writing metadata for %0 file (%1 skipped, %2 errors).",
String.valueOf(entriesChanged), String.valueOf(skipped), String.valueOf(errors)));
}
/**
* This writes both XMP data and embeds a corresponding .bib file
*/
synchronized private void writeMetadataToFile(Path file, BibEntry entry, BibDatabaseContext databaseContext, BibDatabase database) throws Exception {
new XmpUtilWriter(xmpPreferences).writeXmp(file, entry, database);
EmbeddedBibFilePdfExporter embeddedBibExporter = new EmbeddedBibFilePdfExporter(databaseContext.getMode(), entryTypesManager, fieldPreferences);
embeddedBibExporter.exportToFileByPath(databaseContext, database, filePreferences, file, Globals.journalAbbreviationRepository);
}
class OptionsDialog extends FXDialog {
private final Button okButton = new Button(Localization.lang("OK"));
private final Button cancelButton = new Button(Localization.lang("Cancel"));
private boolean isCancelled;
private final TextArea progressArea;
public OptionsDialog() {
super(AlertType.NONE, Localization.lang("Writing metadata for selected entries..."), false);
okButton.setDisable(true);
okButton.setOnAction(e -> dispose());
okButton.setPrefSize(100, 30);
cancelButton.setOnAction(e -> isCancelled = true);
cancelButton.setOnKeyPressed(e -> {
if (e.getCode() == KeyCode.ESCAPE) {
isCancelled = true;
}
});
cancelButton.setPrefSize(100, 30);
progressArea = new TextArea();
ScrollPane scrollPane = new ScrollPane(progressArea);
progressArea.setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY)));
progressArea.setEditable(false);
progressArea.setText("");
GridPane tmpPanel = new GridPane();
getDialogPane().setContent(tmpPanel);
tmpPanel.setHgap(450);
tmpPanel.setVgap(10);
tmpPanel.add(scrollPane, 0, 0, 2, 1);
tmpPanel.add(okButton, 0, 1);
tmpPanel.add(cancelButton, 1, 1);
tmpPanel.setGridLinesVisible(false);
this.setResizable(false);
}
private void dispose() {
((Stage) (getDialogPane().getScene().getWindow())).close();
}
public void done() {
okButton.setDisable(false);
cancelButton.setDisable(true);
}
public void open() {
progressArea.setText("");
isCancelled = false;
okButton.setDisable(true);
cancelButton.setDisable(false);
okButton.requestFocus();
optionsDialog.show();
}
public boolean isCanceled() {
return isCancelled;
}
public TextArea getProgressArea() {
return progressArea;
}
}
}
| 10,794
| 38.833948
| 259
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/externalfiles/AutoLinkFilesAction.java
|
package org.jabref.gui.externalfiles;
import java.util.List;
import javax.swing.undo.UndoManager;
import javafx.concurrent.Task;
import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.undo.NamedCompound;
import org.jabref.gui.util.BindingsHelper;
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.preferences.PreferencesService;
import static org.jabref.gui.actions.ActionHelper.needsDatabase;
import static org.jabref.gui.actions.ActionHelper.needsEntriesSelected;
/**
* This Action may only be used in a menu or button.
* Never in the entry editor. FileListEditor and EntryEditor have other ways to update the file links
*/
public class AutoLinkFilesAction extends SimpleCommand {
private final DialogService dialogService;
private final PreferencesService preferences;
private final StateManager stateManager;
private final UndoManager undoManager;
private final TaskExecutor taskExecutor;
public AutoLinkFilesAction(DialogService dialogService, PreferencesService preferences, StateManager stateManager, UndoManager undoManager, TaskExecutor taskExecutor) {
this.dialogService = dialogService;
this.preferences = preferences;
this.stateManager = stateManager;
this.undoManager = undoManager;
this.taskExecutor = taskExecutor;
this.executable.bind(needsDatabase(this.stateManager).and(needsEntriesSelected(stateManager)));
this.statusMessage.bind(BindingsHelper.ifThenElse(executable, "", Localization.lang("This operation requires one or more entries to be selected.")));
}
@Override
public void execute() {
final BibDatabaseContext database = stateManager.getActiveDatabase().orElseThrow(() -> new NullPointerException("Database null"));
final List<BibEntry> entries = stateManager.getSelectedEntries();
final AutoSetFileLinksUtil util = new AutoSetFileLinksUtil(
database,
preferences.getFilePreferences(),
preferences.getAutoLinkPreferences());
final NamedCompound nc = new NamedCompound(Localization.lang("Automatically set file links"));
Task<AutoSetFileLinksUtil.LinkFilesResult> linkFilesTask = new Task<>() {
@Override
protected AutoSetFileLinksUtil.LinkFilesResult call() {
return util.linkAssociatedFiles(entries, nc);
}
@Override
protected void succeeded() {
AutoSetFileLinksUtil.LinkFilesResult result = getValue();
if (!result.getFileExceptions().isEmpty()) {
dialogService.showWarningDialogAndWait(
Localization.lang("Automatically set file links"),
Localization.lang("Problem finding files. See error log for details."));
return;
}
if (result.getChangedEntries().isEmpty()) {
dialogService.showWarningDialogAndWait("Automatically set file links",
Localization.lang("Finished automatically setting external links.") + "\n"
+ Localization.lang("No files found."));
return;
}
if (nc.hasEdits()) {
nc.end();
undoManager.addEdit(nc);
}
dialogService.notify(Localization.lang("Finished automatically setting external links.") + " "
+ Localization.lang("Changed %0 entries.", String.valueOf(result.getChangedEntries().size())));
}
};
dialogService.showProgressDialog(
Localization.lang("Automatically setting file links"),
Localization.lang("Searching for files"),
linkFilesTask);
taskExecutor.execute(linkFilesTask);
}
}
| 4,120
| 41.484536
| 172
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/externalfiles/AutoSetFileLinksUtil.java
|
package org.jabref.gui.externalfiles;
import java.io.IOException;
import java.nio.file.Files;
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.externalfiletype.ExternalFileType;
import org.jabref.gui.externalfiletype.ExternalFileTypes;
import org.jabref.gui.externalfiletype.UnknownExternalFileType;
import org.jabref.gui.undo.NamedCompound;
import org.jabref.gui.undo.UndoableFieldChange;
import org.jabref.gui.util.DefaultTaskExecutor;
import org.jabref.logic.bibtex.FileFieldWriter;
import org.jabref.logic.util.io.AutoLinkPreferences;
import org.jabref.logic.util.io.FileFinder;
import org.jabref.logic.util.io.FileFinders;
import org.jabref.logic.util.io.FileUtil;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.LinkedFile;
import org.jabref.model.entry.field.StandardField;
import org.jabref.preferences.FilePreferences;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AutoSetFileLinksUtil {
public static class LinkFilesResult {
private final List<BibEntry> changedEntries = new ArrayList<>();
private final List<IOException> fileExceptions = new ArrayList<>();
protected void addBibEntry(BibEntry bibEntry) {
changedEntries.add(bibEntry);
}
protected void addFileException(IOException exception) {
fileExceptions.add(exception);
}
public List<BibEntry> getChangedEntries() {
return changedEntries;
}
public List<IOException> getFileExceptions() {
return fileExceptions;
}
}
private static final Logger LOGGER = LoggerFactory.getLogger(AutoSetFileLinksUtil.class);
private final List<Path> directories;
private final AutoLinkPreferences autoLinkPreferences;
private final FilePreferences filePreferences;
public AutoSetFileLinksUtil(BibDatabaseContext databaseContext, FilePreferences filePreferences, AutoLinkPreferences autoLinkPreferences) {
this(databaseContext.getFileDirectories(filePreferences), filePreferences, autoLinkPreferences);
}
private AutoSetFileLinksUtil(List<Path> directories, FilePreferences filePreferences, AutoLinkPreferences autoLinkPreferences) {
this.directories = directories;
this.autoLinkPreferences = autoLinkPreferences;
this.filePreferences = filePreferences;
}
public LinkFilesResult linkAssociatedFiles(List<BibEntry> entries, NamedCompound ce) {
LinkFilesResult result = new LinkFilesResult();
for (BibEntry entry : entries) {
List<LinkedFile> linkedFiles = new ArrayList<>();
try {
linkedFiles = findAssociatedNotLinkedFiles(entry);
} catch (IOException e) {
result.addFileException(e);
LOGGER.error("Problem finding files", e);
}
if (ce != null) {
boolean changed = false;
for (LinkedFile linkedFile : linkedFiles) {
// store undo information
String newVal = FileFieldWriter.getStringRepresentation(linkedFile);
String oldVal = entry.getField(StandardField.FILE).orElse(null);
UndoableFieldChange fieldChange = new UndoableFieldChange(entry, StandardField.FILE, oldVal, newVal);
ce.addEdit(fieldChange);
changed = true;
DefaultTaskExecutor.runInJavaFXThread(() -> {
entry.addFile(linkedFile);
});
}
if (changed) {
result.addBibEntry(entry);
}
}
}
return result;
}
public List<LinkedFile> findAssociatedNotLinkedFiles(BibEntry entry) throws IOException {
List<LinkedFile> linkedFiles = new ArrayList<>();
List<String> extensions = filePreferences.getExternalFileTypes().stream().map(ExternalFileType::getExtension).collect(Collectors.toList());
// Run the search operation
FileFinder fileFinder = FileFinders.constructFromConfiguration(autoLinkPreferences);
List<Path> result = fileFinder.findAssociatedFiles(entry, directories, extensions);
// Collect the found files that are not yet linked
for (Path foundFile : result) {
boolean fileAlreadyLinked = entry.getFiles().stream()
.map(file -> file.findIn(directories))
.anyMatch(file -> {
try {
return file.isPresent() && Files.isSameFile(file.get(), foundFile);
} catch (IOException e) {
LOGGER.error("Problem with isSameFile", e);
}
return false;
});
if (!fileAlreadyLinked) {
Optional<ExternalFileType> type = FileUtil.getFileExtension(foundFile)
.map(extension -> ExternalFileTypes.getExternalFileTypeByExt(extension, filePreferences))
.orElse(Optional.of(new UnknownExternalFileType("")));
String strType = type.isPresent() ? type.get().getName() : "";
Path relativeFilePath = FileUtil.relativize(foundFile, directories);
LinkedFile linkedFile = new LinkedFile("", relativeFilePath, strType);
linkedFiles.add(linkedFile);
}
}
return linkedFiles;
}
}
| 5,983
| 40.846154
| 149
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/externalfiles/ChainedFilters.java
|
package org.jabref.gui.externalfiles;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Path;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Chains the given filters - if ALL of them accept, the result is also accepted
*/
public class ChainedFilters implements DirectoryStream.Filter<Path> {
private static final Logger LOGGER = LoggerFactory.getLogger(ChainedFilters.class);
private DirectoryStream.Filter<Path>[] filters;
public ChainedFilters(DirectoryStream.Filter<Path>... filters) {
this.filters = filters;
}
@Override
public boolean accept(Path entry) throws IOException {
return Arrays.stream(filters).allMatch(filter -> {
try {
return filter.accept(entry);
} catch (IOException e) {
LOGGER.error("Could not apply filter", e);
return true;
}
});
}
}
| 981
| 26.277778
| 87
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/externalfiles/DateRange.java
|
package org.jabref.gui.externalfiles;
import org.jabref.logic.l10n.Localization;
public enum DateRange {
ALL_TIME(Localization.lang("All time")),
YEAR(Localization.lang("Last year")),
MONTH(Localization.lang("Last month")),
WEEK(Localization.lang("Last week")),
DAY(Localization.lang("Last day"));
private final String dateRange;
DateRange(String dateRange) {
this.dateRange = dateRange;
}
public String getDateRange() {
return dateRange;
}
}
| 506
| 22.045455
| 44
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/externalfiles/DownloadFullTextAction.java
|
package org.jabref.gui.externalfiles;
import java.net.URL;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import javafx.concurrent.Task;
import org.jabref.gui.DialogService;
import org.jabref.gui.Globals;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.ActionHelper;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.fieldeditors.LinkedFileViewModel;
import org.jabref.logic.importer.FulltextFetchers;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.LinkedFile;
import org.jabref.preferences.PreferencesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Try to download fulltext PDF for selected entry(ies) by following URL or DOI link.
*/
public class DownloadFullTextAction extends SimpleCommand {
private static final Logger LOGGER = LoggerFactory.getLogger(DownloadFullTextAction.class);
// The minimum number of selected entries to ask the user for confirmation
private static final int WARNING_LIMIT = 5;
private final DialogService dialogService;
private final StateManager stateManager;
private final PreferencesService preferences;
public DownloadFullTextAction(DialogService dialogService, StateManager stateManager, PreferencesService preferences) {
this.dialogService = dialogService;
this.stateManager = stateManager;
this.preferences = preferences;
this.executable.bind(ActionHelper.needsEntriesSelected(stateManager));
}
@Override
public void execute() {
if (stateManager.getActiveDatabase().isEmpty()) {
return;
}
List<BibEntry> entries = stateManager.getSelectedEntries();
if (entries.isEmpty()) {
LOGGER.debug("No entry selected for fulltext download.");
return;
}
dialogService.notify(Localization.lang("Looking for full text document..."));
if (entries.size() >= WARNING_LIMIT) {
boolean confirmDownload = dialogService.showConfirmationDialogAndWait(
Localization.lang("Download full text documents"),
Localization.lang(
"You are about to download full text documents for %0 entries.",
String.valueOf(stateManager.getSelectedEntries().size())) + "\n"
+ Localization.lang("JabRef will send at least one request per entry to a publisher.")
+ "\n"
+ Localization.lang("Do you still want to continue?"),
Localization.lang("Download full text documents"),
Localization.lang("Cancel"));
if (!confirmDownload) {
dialogService.notify(Localization.lang("Operation canceled."));
return;
}
}
Task<Map<BibEntry, Optional<URL>>> findFullTextsTask = new Task<>() {
@Override
protected Map<BibEntry, Optional<URL>> call() {
Map<BibEntry, Optional<URL>> downloads = new ConcurrentHashMap<>();
int count = 0;
for (BibEntry entry : entries) {
FulltextFetchers fetchers = new FulltextFetchers(
preferences.getImportFormatPreferences(),
preferences.getImporterPreferences());
downloads.put(entry, fetchers.findFullTextPDF(entry));
updateProgress(++count, entries.size());
}
return downloads;
}
};
findFullTextsTask.setOnSucceeded(value ->
downloadFullTexts(findFullTextsTask.getValue(), stateManager.getActiveDatabase().get()));
dialogService.showProgressDialog(
Localization.lang("Download full text documents"),
Localization.lang("Looking for full text document..."),
findFullTextsTask);
Globals.TASK_EXECUTOR.execute(findFullTextsTask);
}
private void downloadFullTexts(Map<BibEntry, Optional<URL>> downloads, BibDatabaseContext databaseContext) {
for (Map.Entry<BibEntry, Optional<URL>> download : downloads.entrySet()) {
BibEntry entry = download.getKey();
Optional<URL> result = download.getValue();
if (result.isPresent()) {
Optional<Path> dir = databaseContext.getFirstExistingFileDir(preferences.getFilePreferences());
if (dir.isEmpty()) {
dialogService.showErrorDialogAndWait(Localization.lang("Directory not found"),
Localization.lang("Main file directory not set. Check the preferences (\"Linked files\") or modify the library properties (\"Override default file directories\")."));
return;
}
// Download and link full text
addLinkedFileFromURL(databaseContext, result.get(), entry, dir.get());
} else {
dialogService.notify(Localization.lang("No full text document found for entry %0.",
entry.getCitationKey().orElse(Localization.lang("undefined"))));
}
}
}
/**
* This method attaches a linked file from a URL (if not already linked) to an entry using the key and value pair
* from the findFullTexts map and then downloads the file into the given targetDirectory
*
* @param databaseContext the active database
* @param url the url "key"
* @param entry the entry "value"
* @param targetDirectory the target directory for the downloaded file
*/
private void addLinkedFileFromURL(BibDatabaseContext databaseContext, URL url, BibEntry entry, Path targetDirectory) {
LinkedFile newLinkedFile = new LinkedFile(url, "");
if (!entry.getFiles().contains(newLinkedFile)) {
LinkedFileViewModel onlineFile = new LinkedFileViewModel(
newLinkedFile,
entry,
databaseContext,
Globals.TASK_EXECUTOR,
dialogService,
preferences);
onlineFile.download();
} else {
dialogService.notify(Localization.lang("Full text document for entry %0 already linked.",
entry.getCitationKey().orElse(Localization.lang("undefined"))));
}
}
}
| 6,670
| 41.490446
| 194
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/externalfiles/ExternalFileSorter.java
|
package org.jabref.gui.externalfiles;
import org.jabref.logic.l10n.Localization;
public enum ExternalFileSorter {
DEFAULT(Localization.lang("Default")),
DATE_ASCENDING(Localization.lang("Newest first")),
DATE_DESCENDING(Localization.lang("Oldest first"));
private final String sorter;
ExternalFileSorter(String sorter) {
this.sorter = sorter;
}
public String getSorter() {
return sorter;
}
}
| 445
| 21.3
| 55
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/externalfiles/ExternalFilesEntryLinker.java
|
package org.jabref.gui.externalfiles;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.jabref.gui.externalfiletype.ExternalFileType;
import org.jabref.gui.externalfiletype.ExternalFileTypes;
import org.jabref.gui.externalfiletype.UnknownExternalFileType;
import org.jabref.logic.cleanup.MoveFilesCleanup;
import org.jabref.logic.cleanup.RenamePdfCleanup;
import org.jabref.logic.pdf.search.indexing.IndexingTaskManager;
import org.jabref.logic.pdf.search.indexing.PdfIndexer;
import org.jabref.logic.util.io.FileUtil;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.LinkedFile;
import org.jabref.preferences.FilePreferences;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ExternalFilesEntryLinker {
private static final Logger LOGGER = LoggerFactory.getLogger(ExternalFilesEntryLinker.class);
private final FilePreferences filePreferences;
private final BibDatabaseContext bibDatabaseContext;
private final MoveFilesCleanup moveFilesCleanup;
private final RenamePdfCleanup renameFilesCleanup;
public ExternalFilesEntryLinker(FilePreferences filePreferences, BibDatabaseContext bibDatabaseContext) {
this.filePreferences = filePreferences;
this.bibDatabaseContext = bibDatabaseContext;
this.moveFilesCleanup = new MoveFilesCleanup(bibDatabaseContext, filePreferences);
this.renameFilesCleanup = new RenamePdfCleanup(false, bibDatabaseContext, filePreferences);
}
public Optional<Path> copyFileToFileDir(Path file) {
Optional<Path> firstExistingFileDir = bibDatabaseContext.getFirstExistingFileDir(filePreferences);
if (firstExistingFileDir.isPresent()) {
Path targetFile = firstExistingFileDir.get().resolve(file.getFileName());
if (FileUtil.copyFile(file, targetFile, false)) {
return Optional.of(targetFile);
}
}
return Optional.empty();
}
public void renameLinkedFilesToPattern(BibEntry entry) {
renameFilesCleanup.cleanup(entry);
}
public void moveLinkedFilesToFileDir(BibEntry entry) {
moveFilesCleanup.cleanup(entry);
}
public void addFilesToEntry(BibEntry entry, List<Path> files) {
for (Path file : files) {
FileUtil.getFileExtension(file).ifPresent(ext -> {
ExternalFileType type = ExternalFileTypes.getExternalFileTypeByExt(ext, filePreferences)
.orElse(new UnknownExternalFileType(ext));
Path relativePath = FileUtil.relativize(file, bibDatabaseContext.getFileDirectories(filePreferences));
LinkedFile linkedfile = new LinkedFile("", relativePath, type.getName());
entry.addFile(linkedfile);
});
}
}
public void moveFilesToFileDirAndAddToEntry(BibEntry entry, List<Path> files, IndexingTaskManager indexingTaskManager) {
try (AutoCloseable blocker = indexingTaskManager.blockNewTasks()) {
addFilesToEntry(entry, files);
moveLinkedFilesToFileDir(entry);
renameLinkedFilesToPattern(entry);
} catch (Exception e) {
LOGGER.error("Could not block IndexingTaskManager", e);
}
try {
indexingTaskManager.addToIndex(PdfIndexer.of(bibDatabaseContext, filePreferences), entry, bibDatabaseContext);
} catch (IOException e) {
LOGGER.error("Could not access Fulltext-Index", e);
}
}
public void copyFilesToFileDirAndAddToEntry(BibEntry entry, List<Path> files, IndexingTaskManager indexingTaskManager) {
try (AutoCloseable blocker = indexingTaskManager.blockNewTasks()) {
for (Path file : files) {
copyFileToFileDir(file)
.ifPresent(copiedFile -> addFilesToEntry(entry, Collections.singletonList(copiedFile)));
}
renameLinkedFilesToPattern(entry);
} catch (Exception e) {
LOGGER.error("Could not block IndexingTaskManager", e);
}
try {
indexingTaskManager.addToIndex(PdfIndexer.of(bibDatabaseContext, filePreferences), entry, bibDatabaseContext);
} catch (IOException e) {
LOGGER.error("Could not access Fulltext-Index", e);
}
}
}
| 4,486
| 41.330189
| 124
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/externalfiles/FileDownloadTask.java
|
package org.jabref.gui.externalfiles;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.logic.net.ProgressInputStream;
import org.jabref.logic.net.URLDownload;
import com.tobiasdiez.easybind.EasyBind;
public class FileDownloadTask extends BackgroundTask<Path> {
private final URL source;
private final Path destination;
public FileDownloadTask(URL source, Path destination) {
this.source = source;
this.destination = destination;
}
@Override
protected Path call() throws Exception {
URLDownload download = new URLDownload(source);
try (ProgressInputStream inputStream = download.asInputStream()) {
EasyBind.subscribe(
inputStream.totalNumBytesReadProperty(),
bytesRead -> updateProgress(bytesRead.longValue(), inputStream.getMaxNumBytes()));
// Make sure directory exists since otherwise copy fails
Files.createDirectories(destination.getParent());
Files.copy(inputStream, destination, StandardCopyOption.REPLACE_EXISTING);
}
return destination;
}
}
| 1,252
| 29.560976
| 102
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/externalfiles/FileExtensionViewModel.java
|
package org.jabref.gui.externalfiles;
import java.nio.file.DirectoryStream.Filter;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Collectors;
import org.jabref.gui.externalfiletype.ExternalFileType;
import org.jabref.gui.externalfiletype.ExternalFileTypes;
import org.jabref.gui.icon.JabRefIcon;
import org.jabref.gui.util.FileFilterConverter;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.FileType;
import org.jabref.preferences.FilePreferences;
public class FileExtensionViewModel {
private final String description;
private final List<String> extensions;
private final FilePreferences filePreferences;
FileExtensionViewModel(FileType fileType, FilePreferences filePreferences) {
this.description = Localization.lang("%0 file", fileType.getName());
this.extensions = fileType.getExtensionsWithAsteriskAndDot();
this.filePreferences = filePreferences;
}
public String getDescription() {
return this.description + extensions.stream().collect(Collectors.joining(", ", " (", ")"));
}
public JabRefIcon getIcon() {
return ExternalFileTypes.getExternalFileTypeByExt(extensions.get(0), filePreferences)
.map(ExternalFileType::getIcon)
.orElse(null);
}
public Filter<Path> dirFilter() {
return FileFilterConverter.toDirFilter(extensions);
}
}
| 1,454
| 33.642857
| 99
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/externalfiles/FileFilterUtils.java
|
package org.jabref.gui.externalfiles;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FileFilterUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(FileFilterUtils.class);
/* Returns the last edited time of a file as LocalDateTime. */
public static LocalDateTime getFileTime(Path path) {
FileTime lastEditedTime;
try {
lastEditedTime = Files.getLastModifiedTime(path);
} catch (IOException e) {
LOGGER.error("Could not retrieve file time", e);
return LocalDateTime.now();
}
LocalDateTime localDateTime = lastEditedTime
.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDateTime();
return localDateTime;
}
/* Returns true if a file with a specific path
* was edited during the last 24 hours. */
public boolean isDuringLastDay(LocalDateTime fileEditTime) {
LocalDateTime NOW = LocalDateTime.now(ZoneId.systemDefault());
return fileEditTime.isAfter(NOW.minusHours(24));
}
/* Returns true if a file with a specific path
* was edited during the last 7 days. */
public boolean isDuringLastWeek(LocalDateTime fileEditTime) {
LocalDateTime NOW = LocalDateTime.now(ZoneId.systemDefault());
return fileEditTime.isAfter(NOW.minusDays(7));
}
/* Returns true if a file with a specific path
* was edited during the last 30 days. */
public boolean isDuringLastMonth(LocalDateTime fileEditTime) {
LocalDateTime NOW = LocalDateTime.now(ZoneId.systemDefault());
return fileEditTime.isAfter(NOW.minusDays(30));
}
/* Returns true if a file with a specific path
* was edited during the last 365 days. */
public boolean isDuringLastYear(LocalDateTime fileEditTime) {
LocalDateTime NOW = LocalDateTime.now(ZoneId.systemDefault());
return fileEditTime.isAfter(NOW.minusDays(365));
}
/* Returns true if a file is edited in the time margin specified by the given filter. */
public static boolean filterByDate(Path path, DateRange filter) {
FileFilterUtils fileFilter = new FileFilterUtils();
LocalDateTime fileTime = FileFilterUtils.getFileTime(path);
boolean isInDateRange = switch (filter) {
case DAY -> fileFilter.isDuringLastDay(fileTime);
case WEEK -> fileFilter.isDuringLastWeek(fileTime);
case MONTH -> fileFilter.isDuringLastMonth(fileTime);
case YEAR -> fileFilter.isDuringLastYear(fileTime);
case ALL_TIME -> true;
};
return isInDateRange;
}
/**
* Sorts a list of Path objects according to the last edited date
* of their corresponding files, from newest to oldest.
*/
public List<Path> sortByDateAscending(List<Path> files) {
return files.stream()
.sorted(Comparator.comparingLong(file -> FileFilterUtils.getFileTime(file)
.atZone(ZoneId.systemDefault())
.toInstant()
.toEpochMilli()))
.collect(Collectors.toList());
}
/**
* Sorts a list of Path objects according to the last edited date
* of their corresponding files, from oldest to newest.
*/
public List<Path> sortByDateDescending(List<Path> files) {
return files.stream()
.sorted(Comparator.comparingLong(file -> -FileFilterUtils.getFileTime(file)
.atZone(ZoneId.systemDefault())
.toInstant()
.toEpochMilli()))
.collect(Collectors.toList());
}
/**
* Sorts a list of Path objects according to the last edited date
* the order depends on the specified sorter type.
*/
public static List<Path> sortByDate(List<Path> files, ExternalFileSorter sortType) {
FileFilterUtils fileFilter = new FileFilterUtils();
List<Path> sortedFiles = switch (sortType) {
case DEFAULT -> files;
case DATE_ASCENDING -> fileFilter.sortByDateDescending(files);
case DATE_DESCENDING -> fileFilter.sortByDateAscending(files);
};
return sortedFiles;
}
}
| 4,554
| 37.277311
| 92
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/externalfiles/FindUnlinkedFilesAction.java
|
package org.jabref.gui.externalfiles;
import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.SimpleCommand;
import static org.jabref.gui.actions.ActionHelper.needsDatabase;
public class FindUnlinkedFilesAction extends SimpleCommand {
private final DialogService dialogService;
private final StateManager stateManager;
public FindUnlinkedFilesAction(DialogService dialogService, StateManager stateManager) {
this.dialogService = dialogService;
this.stateManager = stateManager;
this.executable.bind(needsDatabase(this.stateManager));
}
@Override
public void execute() {
dialogService.showCustomDialogAndWait(new UnlinkedFilesDialogView());
}
}
| 758
| 28.192308
| 92
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/externalfiles/GitIgnoreFileFilter.java
|
package org.jabref.gui.externalfiles;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static java.util.function.Predicate.not;
public class GitIgnoreFileFilter implements DirectoryStream.Filter<Path> {
private static final Logger LOGGER = LoggerFactory.getLogger(GitIgnoreFileFilter.class);
private Set<PathMatcher> gitIgnorePatterns;
public GitIgnoreFileFilter(Path path) {
Path currentPath = path;
while ((currentPath != null) && !Files.exists(currentPath.resolve(".gitignore"))) {
currentPath = currentPath.getParent();
}
if (currentPath == null) {
// we did not find any gitignore, lets use the default
gitIgnorePatterns = Set.of(".git", ".DS_Store", "desktop.ini", "Thumbs.db").stream()
// duplicate code as below
.map(line -> "glob:" + line)
.map(matcherString -> FileSystems.getDefault().getPathMatcher(matcherString))
.collect(Collectors.toSet());
} else {
Path gitIgnore = currentPath.resolve(".gitignore");
try {
Set<PathMatcher> plainGitIgnorePatternsFromGitIgnoreFile = Files.readAllLines(gitIgnore).stream()
.map(String::trim)
.filter(not(String::isEmpty))
.filter(line -> !line.startsWith("#"))
// convert to Java syntax for Glob patterns
.map(line -> "glob:" + line)
.map(matcherString -> FileSystems.getDefault().getPathMatcher(matcherString))
.collect(Collectors.toSet());
gitIgnorePatterns = new HashSet<>(plainGitIgnorePatternsFromGitIgnoreFile);
// we want to ignore ".gitignore" itself
gitIgnorePatterns.add(FileSystems.getDefault().getPathMatcher("glob:.gitignore"));
} catch (IOException e) {
LOGGER.info("Could not read .gitignore from {}", gitIgnore, e);
gitIgnorePatterns = Set.of();
}
}
}
@Override
public boolean accept(Path path) throws IOException {
// We assume that git does not stop at a patern, but tries all. We implement that behavior
return gitIgnorePatterns.stream().noneMatch(filter ->
// we need this one for "*.png"
filter.matches(path.getFileName()) ||
// we need this one for "**/*.png"
filter.matches(path));
}
}
| 3,290
| 48.119403
| 157
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/externalfiles/ImportFilesResultItemViewModel.java
|
package org.jabref.gui.externalfiles;
import java.nio.file.Path;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.paint.Color;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.icon.JabRefIcon;
public class ImportFilesResultItemViewModel {
private final StringProperty file = new SimpleStringProperty("");
private final ObjectProperty<JabRefIcon> icon = new SimpleObjectProperty<>(IconTheme.JabRefIcons.WARNING);
private final StringProperty message = new SimpleStringProperty("");
public ImportFilesResultItemViewModel(Path file, boolean success, String message) {
this.file.setValue(file.toString());
this.message.setValue(message);
if (success) {
this.icon.setValue(IconTheme.JabRefIcons.CHECK.withColor(Color.GREEN));
} else {
this.icon.setValue(IconTheme.JabRefIcons.WARNING.withColor(Color.RED));
}
}
public ObjectProperty<JabRefIcon> icon() {
return this.icon;
}
public StringProperty file() {
return this.file;
}
public StringProperty message() {
return this.message;
}
@Override
public String toString() {
return "ImportFilesResultItemViewModel [file=" + file.get() + ", message=" + message.get() + "]";
}
}
| 1,452
| 29.914894
| 110
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/externalfiles/ImportHandler.java
|
package org.jabref.gui.externalfiles;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import javax.swing.undo.CompoundEdit;
import javax.swing.undo.UndoManager;
import org.jabref.gui.DialogService;
import org.jabref.gui.Globals;
import org.jabref.gui.StateManager;
import org.jabref.gui.duplicationFinder.DuplicateResolverDialog;
import org.jabref.gui.fieldeditors.LinkedFileViewModel;
import org.jabref.gui.undo.UndoableInsertEntries;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.gui.util.DefaultTaskExecutor;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.citationkeypattern.CitationKeyGenerator;
import org.jabref.logic.database.DuplicateCheck;
import org.jabref.logic.externalfiles.ExternalFilesContentImporter;
import org.jabref.logic.importer.FetcherException;
import org.jabref.logic.importer.ImportCleanup;
import org.jabref.logic.importer.ImportException;
import org.jabref.logic.importer.ImportFormatReader;
import org.jabref.logic.importer.ImportFormatReader.UnknownFormatImport;
import org.jabref.logic.importer.ParseException;
import org.jabref.logic.importer.fetcher.ArXivFetcher;
import org.jabref.logic.importer.fetcher.DoiFetcher;
import org.jabref.logic.importer.fetcher.isbntobibtex.IsbnFetcher;
import org.jabref.logic.importer.fileformat.BibtexParser;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.UpdateField;
import org.jabref.logic.util.io.FileUtil;
import org.jabref.model.FieldChange;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.LinkedFile;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.identifier.ArXivIdentifier;
import org.jabref.model.entry.identifier.DOI;
import org.jabref.model.entry.identifier.ISBN;
import org.jabref.model.groups.GroupEntryChanger;
import org.jabref.model.groups.GroupTreeNode;
import org.jabref.model.util.FileUpdateMonitor;
import org.jabref.model.util.OptionalUtil;
import org.jabref.preferences.PreferencesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ImportHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(ImportHandler.class);
private final BibDatabaseContext bibDatabaseContext;
private final PreferencesService preferencesService;
private final FileUpdateMonitor fileUpdateMonitor;
private final ExternalFilesEntryLinker linker;
private final ExternalFilesContentImporter contentImporter;
private final UndoManager undoManager;
private final StateManager stateManager;
private final DialogService dialogService;
private final TaskExecutor taskExecutor;
public ImportHandler(BibDatabaseContext database,
PreferencesService preferencesService,
FileUpdateMonitor fileupdateMonitor,
UndoManager undoManager,
StateManager stateManager,
DialogService dialogService,
TaskExecutor taskExecutor) {
this.bibDatabaseContext = database;
this.preferencesService = preferencesService;
this.fileUpdateMonitor = fileupdateMonitor;
this.stateManager = stateManager;
this.dialogService = dialogService;
this.taskExecutor = taskExecutor;
this.linker = new ExternalFilesEntryLinker(preferencesService.getFilePreferences(), database);
this.contentImporter = new ExternalFilesContentImporter(preferencesService.getImportFormatPreferences());
this.undoManager = undoManager;
}
public ExternalFilesEntryLinker getLinker() {
return linker;
}
public BackgroundTask<List<ImportFilesResultItemViewModel>> importFilesInBackground(final List<Path> files) {
return new BackgroundTask<>() {
private int counter;
private final List<ImportFilesResultItemViewModel> results = new ArrayList<>();
@Override
protected List<ImportFilesResultItemViewModel> call() {
counter = 1;
CompoundEdit ce = new CompoundEdit();
for (final Path file : files) {
final List<BibEntry> entriesToAdd = new ArrayList<>();
if (isCanceled()) {
break;
}
DefaultTaskExecutor.runInJavaFXThread(() -> {
updateMessage(Localization.lang("Processing file %0", file.getFileName()));
updateProgress(counter, files.size() - 1d);
});
try {
if (FileUtil.isPDFFile(file)) {
var pdfImporterResult = contentImporter.importPDFContent(file);
List<BibEntry> pdfEntriesInFile = pdfImporterResult.getDatabase().getEntries();
if (pdfImporterResult.hasWarnings()) {
addResultToList(file, false, Localization.lang("Error reading PDF content: %0", pdfImporterResult.getErrorMessage()));
}
if (!pdfEntriesInFile.isEmpty()) {
entriesToAdd.addAll(pdfEntriesInFile);
addResultToList(file, true, Localization.lang("File was successfully imported as a new entry"));
} else {
entriesToAdd.add(createEmptyEntryWithLink(file));
addResultToList(file, false, Localization.lang("No metadata was found. An empty entry was created with file link"));
}
} else if (FileUtil.isBibFile(file)) {
var bibtexParserResult = contentImporter.importFromBibFile(file, fileUpdateMonitor);
if (bibtexParserResult.hasWarnings()) {
addResultToList(file, false, bibtexParserResult.getErrorMessage());
}
entriesToAdd.addAll(bibtexParserResult.getDatabaseContext().getEntries());
addResultToList(file, true, Localization.lang("Bib entry was successfully imported"));
} else {
entriesToAdd.add(createEmptyEntryWithLink(file));
addResultToList(file, false, Localization.lang("No BibTeX data was found. An empty entry was created with file link"));
}
} catch (IOException ex) {
LOGGER.error("Error importing", ex);
addResultToList(file, false, Localization.lang("Error from import: %0", ex.getLocalizedMessage()));
DefaultTaskExecutor.runInJavaFXThread(() -> updateMessage(Localization.lang("Error")));
}
// We need to run the actual import on the FX Thread, otherwise we will get some deadlocks with the UIThreadList
DefaultTaskExecutor.runInJavaFXThread(() -> importEntries(entriesToAdd));
ce.addEdit(new UndoableInsertEntries(bibDatabaseContext.getDatabase(), entriesToAdd));
ce.end();
undoManager.addEdit(ce);
counter++;
}
return results;
}
private void addResultToList(Path newFile, boolean success, String logMessage) {
var result = new ImportFilesResultItemViewModel(newFile, success, logMessage);
results.add(result);
}
};
}
private BibEntry createEmptyEntryWithLink(Path file) {
BibEntry entry = new BibEntry();
entry.setField(StandardField.TITLE, file.getFileName().toString());
linker.addFilesToEntry(entry, Collections.singletonList(file));
return entry;
}
public void importEntries(List<BibEntry> entries) {
ImportCleanup cleanup = new ImportCleanup(bibDatabaseContext.getMode());
cleanup.doPostCleanup(entries);
bibDatabaseContext.getDatabase().insertEntries(entries);
// Set owner/timestamp
UpdateField.setAutomaticFields(entries,
preferencesService.getOwnerPreferences(),
preferencesService.getTimestampPreferences());
// Generate citation keys
if (preferencesService.getImporterPreferences().isGenerateNewKeyOnImport()) {
generateKeys(entries);
}
// Add to group
addToGroups(entries, stateManager.getSelectedGroup(bibDatabaseContext));
}
public void importEntryWithDuplicateCheck(BibDatabaseContext bibDatabaseContext, BibEntry entry) {
ImportCleanup cleanup = new ImportCleanup(bibDatabaseContext.getMode());
BibEntry cleanedEntry = cleanup.doPostCleanup(entry);
BibEntry entryToInsert = cleanedEntry;
Optional<BibEntry> existingDuplicateInLibrary = new DuplicateCheck(Globals.entryTypesManager).containsDuplicate(bibDatabaseContext.getDatabase(), entryToInsert, bibDatabaseContext.getMode());
if (existingDuplicateInLibrary.isPresent()) {
DuplicateResolverDialog dialog = new DuplicateResolverDialog(existingDuplicateInLibrary.get(), entryToInsert, DuplicateResolverDialog.DuplicateResolverType.IMPORT_CHECK, bibDatabaseContext, stateManager, dialogService, preferencesService);
switch (dialogService.showCustomDialogAndWait(dialog).orElse(DuplicateResolverDialog.DuplicateResolverResult.BREAK)) {
case KEEP_RIGHT:
bibDatabaseContext.getDatabase().removeEntry(existingDuplicateInLibrary.get());
break;
case KEEP_BOTH:
break;
case KEEP_MERGE:
bibDatabaseContext.getDatabase().removeEntry(existingDuplicateInLibrary.get());
entryToInsert = dialog.getMergedEntry();
break;
case KEEP_LEFT:
case AUTOREMOVE_EXACT:
case BREAK:
default:
return;
}
}
// Regenerate CiteKey of imported BibEntry
if (preferencesService.getImporterPreferences().isGenerateNewKeyOnImport()) {
generateKeys(List.of(entryToInsert));
}
bibDatabaseContext.getDatabase().insertEntry(entryToInsert);
// Set owner/timestamp
UpdateField.setAutomaticFields(List.of(entryToInsert),
preferencesService.getOwnerPreferences(),
preferencesService.getTimestampPreferences());
addToGroups(List.of(entry), stateManager.getSelectedGroup(this.bibDatabaseContext));
if (preferencesService.getFilePreferences().shouldDownloadLinkedFiles()) {
entry.getFiles().stream().filter(LinkedFile::isOnlineLink).forEach(linkedFile ->
new LinkedFileViewModel(
linkedFile,
entry,
bibDatabaseContext,
taskExecutor,
dialogService,
preferencesService).download());
}
}
private void addToGroups(List<BibEntry> entries, Collection<GroupTreeNode> groups) {
for (GroupTreeNode node : groups) {
if (node.getGroup() instanceof GroupEntryChanger entryChanger) {
List<FieldChange> undo = entryChanger.add(entries);
// TODO: Add undo
// if (!undo.isEmpty()) {
// ce.addEdit(UndoableChangeEntriesOfGroup.getUndoableEdit(new GroupTreeNodeViewModel(node),
// undo));
// }
}
}
}
/**
* Generate keys for given entries.
*
* @param entries entries to generate keys for
*/
private void generateKeys(List<BibEntry> entries) {
CitationKeyGenerator keyGenerator = new CitationKeyGenerator(
bibDatabaseContext.getMetaData().getCiteKeyPattern(preferencesService.getCitationKeyPatternPreferences()
.getKeyPattern()),
bibDatabaseContext.getDatabase(),
preferencesService.getCitationKeyPatternPreferences());
for (BibEntry entry : entries) {
keyGenerator.generateAndSetKey(entry);
}
}
public List<BibEntry> handleBibTeXData(String entries) {
BibtexParser parser = new BibtexParser(preferencesService.getImportFormatPreferences(), fileUpdateMonitor);
try {
return parser.parseEntries(new ByteArrayInputStream(entries.getBytes(StandardCharsets.UTF_8)));
} catch (ParseException ex) {
LOGGER.error("Could not paste", ex);
return Collections.emptyList();
}
}
public List<BibEntry> handleStringData(String data) throws FetcherException {
if ((data == null) || data.isEmpty()) {
return Collections.emptyList();
}
Optional<DOI> doi = DOI.findInText(data);
if (doi.isPresent()) {
return fetchByDOI(doi.get());
}
Optional<ArXivIdentifier> arXiv = ArXivIdentifier.parse(data);
if (arXiv.isPresent()) {
return fetchByArXiv(arXiv.get());
}
Optional<ISBN> isbn = ISBN.parse(data);
if (isbn.isPresent()) {
return fetchByISBN(isbn.get());
}
return tryImportFormats(data);
}
private List<BibEntry> tryImportFormats(String data) {
try {
ImportFormatReader importFormatReader = new ImportFormatReader(
preferencesService.getImporterPreferences(),
preferencesService.getImportFormatPreferences(),
fileUpdateMonitor);
UnknownFormatImport unknownFormatImport = importFormatReader.importUnknownFormat(data);
return unknownFormatImport.parserResult().getDatabase().getEntries();
} catch (ImportException ex) { // ex is already localized
dialogService.showErrorDialogAndWait(Localization.lang("Import error"), ex);
return Collections.emptyList();
}
}
private List<BibEntry> fetchByDOI(DOI doi) throws FetcherException {
LOGGER.info("Found DOI identifer in clipboard");
Optional<BibEntry> entry = new DoiFetcher(preferencesService.getImportFormatPreferences()).performSearchById(doi.getDOI());
return OptionalUtil.toList(entry);
}
private List<BibEntry> fetchByArXiv(ArXivIdentifier arXivIdentifier) throws FetcherException {
LOGGER.info("Found arxiv identifier in clipboard");
Optional<BibEntry> entry = new ArXivFetcher(preferencesService.getImportFormatPreferences()).performSearchById(arXivIdentifier.getNormalizedWithoutVersion());
return OptionalUtil.toList(entry);
}
private List<BibEntry> fetchByISBN(ISBN isbn) throws FetcherException {
LOGGER.info("Found ISBN identifier in clipboard");
Optional<BibEntry> entry = new IsbnFetcher(preferencesService.getImportFormatPreferences()).performSearchById(isbn.getNormalized());
return OptionalUtil.toList(entry);
}
}
| 15,763
| 45.228739
| 251
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/externalfiles/UnlinkedFilesCrawler.java
|
package org.jabref.gui.externalfiles;
import java.io.File;
import java.io.IOException;
import java.nio.file.DirectoryStream.Filter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import javafx.scene.control.CheckBoxTreeItem;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.gui.util.FileNodeViewModel;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.preferences.FilePreferences;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Util class for searching files on the file system which are not linked to a provided {@link BibDatabase}.
*/
public class UnlinkedFilesCrawler extends BackgroundTask<FileNodeViewModel> {
private static final Logger LOGGER = LoggerFactory.getLogger(UnlinkedFilesCrawler.class);
private final Path directory;
private final Filter<Path> fileFilter;
private final DateRange dateFilter;
private final ExternalFileSorter sorter;
private final BibDatabaseContext databaseContext;
private final FilePreferences filePreferences;
public UnlinkedFilesCrawler(Path directory, Filter<Path> fileFilter, DateRange dateFilter, ExternalFileSorter sorter, BibDatabaseContext databaseContext, FilePreferences filePreferences) {
this.directory = directory;
this.fileFilter = fileFilter;
this.dateFilter = dateFilter;
this.sorter = sorter;
this.databaseContext = databaseContext;
this.filePreferences = filePreferences;
}
@Override
protected FileNodeViewModel call() throws IOException {
UnlinkedPDFFileFilter unlinkedPDFFileFilter = new UnlinkedPDFFileFilter(fileFilter, databaseContext, filePreferences);
return searchDirectory(directory, unlinkedPDFFileFilter);
}
/**
* Searches recursively all files in the specified directory. <br>
* <br>
* All files matched by the given {@link UnlinkedPDFFileFilter} are taken into the resulting tree. <br>
* <br>
* The result will be a tree structure of nodes of the type {@link CheckBoxTreeItem}. <br>
* <br>
* The user objects that are attached to the nodes is the {@link FileNodeViewModel}, which wraps the {@link
* File}-Object. <br>
* <br>
* For ensuring the capability to cancel the work of this recursive method, the first position in the integer array
* 'state' must be set to 1, to keep the recursion running. When the states value changes, the method will resolve
* its recursion and return what it has saved so far.
* <br>
* The files are filtered according to the {@link DateRange} filter value
* and then sorted according to the {@link ExternalFileSorter} value.
*
* @param unlinkedPDFFileFilter contains a BibDatabaseContext which is used to determine whether the file is linked
*
* @return FileNodeViewModel containing the data of the current directory and all subdirectories
* @throws IOException if directory is not a directory or empty
*/
FileNodeViewModel searchDirectory(Path directory, UnlinkedPDFFileFilter unlinkedPDFFileFilter) throws IOException {
// Return null if the directory is not valid.
if ((directory == null) || !Files.isDirectory(directory)) {
throw new IOException(String.format("Invalid directory for searching: %s", directory));
}
FileNodeViewModel fileNodeViewModelForCurrentDirectory = new FileNodeViewModel(directory);
// Map from isDirectory (true/false) to full path
// Result: Contains only files not matching the filter (i.e., PDFs not linked and files not ignored)
// Filters:
// 1. UnlinkedPDFFileFilter
// 2. GitIgnoreFilter
ChainedFilters filters = new ChainedFilters(unlinkedPDFFileFilter, new GitIgnoreFileFilter(directory));
Map<Boolean, List<Path>> directoryAndFilePartition;
try (Stream<Path> filesStream = StreamSupport.stream(Files.newDirectoryStream(directory, filters).spliterator(), false)) {
directoryAndFilePartition = filesStream.collect(Collectors.partitioningBy(Files::isDirectory));
} catch (IOException e) {
LOGGER.error("Error while searching files", e);
return fileNodeViewModelForCurrentDirectory;
}
List<Path> subDirectories = directoryAndFilePartition.get(true);
List<Path> files = directoryAndFilePartition.get(false);
// at this point, only unlinked PDFs AND unignored files are contained
// initially, we find no files at all
int fileCountOfSubdirectories = 0;
// now we crawl into the found subdirectories first (!)
for (Path subDirectory : subDirectories) {
FileNodeViewModel subRoot = searchDirectory(subDirectory, unlinkedPDFFileFilter);
if (!subRoot.getChildren().isEmpty()) {
fileCountOfSubdirectories += subRoot.getFileCount();
fileNodeViewModelForCurrentDirectory.getChildren().add(subRoot);
}
}
// now we have the data of all subdirectories
// it is stored in fileNodeViewModelForCurrentDirectory.getChildren()
// now we handle the files in the current directory
// filter files according to last edited date.
// Note that we do not use the "StreamSupport.stream" filtering functionality, because refactoring the code to that would lead to more code
List<Path> resultingFiles = new ArrayList<>();
for (Path path : files) {
if (FileFilterUtils.filterByDate(path, dateFilter)) {
resultingFiles.add(path);
}
}
// sort files according to last edited date.
resultingFiles = FileFilterUtils.sortByDate(resultingFiles, sorter);
// the count of all files is the count of the found files in current directory plus the count of all files in the subdirectories
fileNodeViewModelForCurrentDirectory.setFileCount(resultingFiles.size() + fileCountOfSubdirectories);
// create and add FileNodeViewModel to the FileNodeViewModel for the current directory
fileNodeViewModelForCurrentDirectory.getChildren().addAll(resultingFiles.stream()
.map(FileNodeViewModel::new)
.collect(Collectors.toList()));
return fileNodeViewModelForCurrentDirectory;
}
}
| 6,585
| 45.380282
| 192
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/externalfiles/UnlinkedFilesDialogView.java
|
package org.jabref.gui.externalfiles;
import java.nio.file.Path;
import javax.swing.undo.UndoManager;
import javafx.application.Platform;
import javafx.beans.InvalidationListener;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.scene.control.Accordion;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.CheckBoxTreeItem;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Control;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.TitledPane;
import javafx.scene.control.TreeItem;
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.SimpleCommand;
import org.jabref.gui.actions.StandardActions;
import org.jabref.gui.icon.JabRefIcon;
import org.jabref.gui.theme.ThemeManager;
import org.jabref.gui.util.BaseDialog;
import org.jabref.gui.util.FileNodeViewModel;
import org.jabref.gui.util.IconValidationDecorator;
import org.jabref.gui.util.RecursiveTreeItem;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.gui.util.ValueTableCellFactory;
import org.jabref.gui.util.ViewModelListCellFactory;
import org.jabref.gui.util.ViewModelTreeCellFactory;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.util.FileUpdateMonitor;
import org.jabref.preferences.PreferencesService;
import com.airhacks.afterburner.views.ViewLoader;
import com.tobiasdiez.easybind.EasyBind;
import de.saxsys.mvvmfx.utils.validation.visualization.ControlsFxVisualizer;
import jakarta.inject.Inject;
import org.controlsfx.control.CheckTreeView;
public class UnlinkedFilesDialogView extends BaseDialog<Void> {
@FXML private TextField directoryPathField;
@FXML private ComboBox<FileExtensionViewModel> fileTypeCombo;
@FXML private ComboBox<DateRange> fileDateCombo;
@FXML private ComboBox<ExternalFileSorter> fileSortCombo;
@FXML private CheckTreeView<FileNodeViewModel> unlinkedFilesList;
@FXML private Button scanButton;
@FXML private Button exportButton;
@FXML private Button importButton;
@FXML private Label progressText;
@FXML private Accordion accordion;
@FXML private ProgressIndicator progressDisplay;
@FXML private VBox progressPane;
@FXML private TableView<ImportFilesResultItemViewModel> importResultTable;
@FXML private TableColumn<ImportFilesResultItemViewModel, JabRefIcon> colStatus;
@FXML private TableColumn<ImportFilesResultItemViewModel, String> colMessage;
@FXML private TableColumn<ImportFilesResultItemViewModel, String> colFile;
@FXML private TitledPane filePane;
@FXML private TitledPane resultPane;
@Inject private PreferencesService preferencesService;
@Inject private DialogService dialogService;
@Inject private StateManager stateManager;
@Inject private UndoManager undoManager;
@Inject private TaskExecutor taskExecutor;
@Inject private FileUpdateMonitor fileUpdateMonitor;
@Inject private ThemeManager themeManager;
private final ControlsFxVisualizer validationVisualizer;
private UnlinkedFilesDialogViewModel viewModel;
private BibDatabaseContext bibDatabaseContext;
public UnlinkedFilesDialogView() {
this.validationVisualizer = new ControlsFxVisualizer();
this.setTitle(Localization.lang("Search for unlinked local files"));
ViewLoader.view(this)
.load()
.setAsDialogPane(this);
setResultConverter(button -> {
if (button == ButtonType.CANCEL) {
viewModel.cancelTasks();
}
return null;
});
themeManager.updateFontStyle(getDialogPane().getScene());
}
@FXML
private void initialize() {
viewModel = new UnlinkedFilesDialogViewModel(
dialogService,
undoManager,
fileUpdateMonitor,
preferencesService,
stateManager,
taskExecutor);
this.bibDatabaseContext = stateManager.getActiveDatabase().orElseThrow(() -> new NullPointerException("No active library"));
progressDisplay.progressProperty().bind(viewModel.progressValueProperty());
progressText.textProperty().bind(viewModel.progressTextProperty());
progressPane.managedProperty().bind(viewModel.taskActiveProperty());
progressPane.visibleProperty().bind(viewModel.taskActiveProperty());
accordion.disableProperty().bind(viewModel.taskActiveProperty());
viewModel.treeRootProperty().addListener(observable -> {
scanButton.setDefaultButton(false);
importButton.setDefaultButton(true);
scanButton.setDefaultButton(false);
filePane.setExpanded(true);
resultPane.setExpanded(false);
});
viewModel.resultTableItems().addListener((InvalidationListener) observable -> {
filePane.setExpanded(false);
resultPane.setExpanded(true);
resultPane.setDisable(false);
});
initDirectorySelection();
initUnlinkedFilesList();
initResultTable();
initButtons();
}
private void initDirectorySelection() {
validationVisualizer.setDecoration(new IconValidationDecorator());
directoryPathField.textProperty().bindBidirectional(viewModel.directoryPathProperty());
Platform.runLater(() -> validationVisualizer.initVisualization(viewModel.directoryPathValidationStatus(), directoryPathField));
new ViewModelListCellFactory<FileExtensionViewModel>()
.withText(FileExtensionViewModel::getDescription)
.withIcon(FileExtensionViewModel::getIcon)
.install(fileTypeCombo);
fileTypeCombo.setItems(viewModel.getFileFilters());
fileTypeCombo.valueProperty().bindBidirectional(viewModel.selectedExtensionProperty());
fileTypeCombo.getSelectionModel().selectFirst();
new ViewModelListCellFactory<DateRange>()
.withText(DateRange::getDateRange)
.install(fileDateCombo);
fileDateCombo.setItems(viewModel.getDateFilters());
fileDateCombo.valueProperty().bindBidirectional(viewModel.selectedDateProperty());
fileDateCombo.getSelectionModel().selectFirst();
new ViewModelListCellFactory<ExternalFileSorter>()
.withText(ExternalFileSorter::getSorter)
.install(fileSortCombo);
fileSortCombo.setItems(viewModel.getSorters());
fileSortCombo.valueProperty().bindBidirectional(viewModel.selectedSortProperty());
fileSortCombo.getSelectionModel().selectFirst();
directoryPathField.setText(bibDatabaseContext.getFirstExistingFileDir(preferencesService.getFilePreferences()).map(Path::toString).orElse(""));
}
private void initUnlinkedFilesList() {
new ViewModelTreeCellFactory<FileNodeViewModel>()
.withText(FileNodeViewModel::getDisplayTextWithEditDate)
.install(unlinkedFilesList);
unlinkedFilesList.maxHeightProperty().bind(((Control) filePane.contentProperty().get()).heightProperty());
unlinkedFilesList.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
unlinkedFilesList.rootProperty().bind(EasyBind.map(viewModel.treeRootProperty(),
fileNode -> fileNode.map(fileNodeViewModel -> new RecursiveTreeItem<>(fileNodeViewModel, FileNodeViewModel::getChildren))
.orElse(null)));
unlinkedFilesList.setContextMenu(createSearchContextMenu());
EasyBind.subscribe(unlinkedFilesList.rootProperty(), root -> {
if (root != null) {
((CheckBoxTreeItem<FileNodeViewModel>) root).setSelected(true);
root.setExpanded(true);
EasyBind.bindContent(viewModel.checkedFileListProperty(), unlinkedFilesList.getCheckModel().getCheckedItems());
} else {
EasyBind.bindContent(viewModel.checkedFileListProperty(), FXCollections.observableArrayList());
}
});
}
private void initResultTable() {
colFile.setCellValueFactory(cellData -> cellData.getValue().file());
new ValueTableCellFactory<ImportFilesResultItemViewModel, String>()
.withText(item -> item).withTooltip(item -> item)
.install(colFile);
colMessage.setCellValueFactory(cellData -> cellData.getValue().message());
new ValueTableCellFactory<ImportFilesResultItemViewModel, String>()
.withText(item -> item).withTooltip(item -> item)
.install(colMessage);
colStatus.setCellValueFactory(cellData -> cellData.getValue().icon());
colStatus.setCellFactory(new ValueTableCellFactory<ImportFilesResultItemViewModel, JabRefIcon>().withGraphic(JabRefIcon::getGraphicNode));
importResultTable.setColumnResizePolicy(param -> true);
importResultTable.setItems(viewModel.resultTableItems());
}
private void initButtons() {
BooleanBinding noItemsChecked = Bindings.isNull(unlinkedFilesList.rootProperty())
.or(Bindings.isEmpty(viewModel.checkedFileListProperty()));
exportButton.disableProperty().bind(noItemsChecked);
importButton.disableProperty().bind(noItemsChecked);
scanButton.setDefaultButton(true);
scanButton.disableProperty().bind(viewModel.taskActiveProperty().or(viewModel.directoryPathValidationStatus().validProperty().not()));
}
@FXML
void browseFileDirectory() {
viewModel.browseFileDirectory();
}
@FXML
void scanFiles() {
viewModel.startSearch();
}
@FXML
void startImport() {
viewModel.startImport();
}
@FXML
void exportSelected() {
viewModel.startExport();
}
/**
* Expands or collapses the specified tree according to the <code>expand</code>-parameter.
*/
private void expandTree(TreeItem<?> item, boolean expand) {
if ((item != null) && !item.isLeaf()) {
item.setExpanded(expand);
for (TreeItem<?> child : item.getChildren()) {
expandTree(child, expand);
}
}
}
private ContextMenu createSearchContextMenu() {
ContextMenu contextMenu = new ContextMenu();
ActionFactory factory = new ActionFactory(preferencesService.getKeyBindingRepository());
contextMenu.getItems().add(factory.createMenuItem(StandardActions.SELECT_ALL, new SearchContextAction(StandardActions.SELECT_ALL)));
contextMenu.getItems().add(factory.createMenuItem(StandardActions.UNSELECT_ALL, new SearchContextAction(StandardActions.UNSELECT_ALL)));
contextMenu.getItems().add(factory.createMenuItem(StandardActions.EXPAND_ALL, new SearchContextAction(StandardActions.EXPAND_ALL)));
contextMenu.getItems().add(factory.createMenuItem(StandardActions.COLLAPSE_ALL, new SearchContextAction(StandardActions.COLLAPSE_ALL)));
return contextMenu;
}
private class SearchContextAction extends SimpleCommand {
private final StandardActions command;
public SearchContextAction(StandardActions command) {
this.command = command;
this.executable.bind(unlinkedFilesList.rootProperty().isNotNull());
}
@Override
public void execute() {
switch (command) {
case SELECT_ALL -> unlinkedFilesList.getCheckModel().checkAll();
case UNSELECT_ALL -> unlinkedFilesList.getCheckModel().clearChecks();
case EXPAND_ALL -> expandTree(unlinkedFilesList.getRoot(), true);
case COLLAPSE_ALL -> expandTree(unlinkedFilesList.getRoot(), false);
}
}
}
}
| 12,333
| 40.810169
| 151
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/externalfiles/UnlinkedFilesDialogViewModel.java
|
package org.jabref.gui.externalfiles;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream.Filter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.swing.undo.UndoManager;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.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.ProgressIndicator;
import javafx.scene.control.TreeItem;
import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.gui.util.DirectoryDialogConfiguration;
import org.jabref.gui.util.FileDialogConfiguration;
import org.jabref.gui.util.FileNodeViewModel;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.StandardFileType;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.util.FileUpdateMonitor;
import org.jabref.preferences.PreferencesService;
import de.saxsys.mvvmfx.utils.validation.FunctionBasedValidator;
import de.saxsys.mvvmfx.utils.validation.ValidationMessage;
import de.saxsys.mvvmfx.utils.validation.ValidationStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class UnlinkedFilesDialogViewModel {
private static final Logger LOGGER = LoggerFactory.getLogger(UnlinkedFilesDialogViewModel.class);
private final ImportHandler importHandler;
private final StringProperty directoryPath = new SimpleStringProperty("");
private final ObjectProperty<FileExtensionViewModel> selectedExtension = new SimpleObjectProperty<>();
private final ObjectProperty<DateRange> selectedDate = new SimpleObjectProperty<>();
private final ObjectProperty<ExternalFileSorter> selectedSort = new SimpleObjectProperty<>();
private final ObjectProperty<Optional<FileNodeViewModel>> treeRootProperty = new SimpleObjectProperty<>();
private final SimpleListProperty<TreeItem<FileNodeViewModel>> checkedFileListProperty = new SimpleListProperty<>(FXCollections.observableArrayList());
private final BooleanProperty taskActiveProperty = new SimpleBooleanProperty(false);
private final DoubleProperty progressValueProperty = new SimpleDoubleProperty(0);
private final StringProperty progressTextProperty = new SimpleStringProperty();
private final ObservableList<ImportFilesResultItemViewModel> resultList = FXCollections.observableArrayList();
private final ObservableList<FileExtensionViewModel> fileFilterList;
private final ObservableList<DateRange> dateFilterList;
private final ObservableList<ExternalFileSorter> fileSortList;
private final DialogService dialogService;
private final PreferencesService preferences;
private BackgroundTask<FileNodeViewModel> findUnlinkedFilesTask;
private BackgroundTask<List<ImportFilesResultItemViewModel>> importFilesBackgroundTask;
private final BibDatabaseContext bibDatabase;
private final TaskExecutor taskExecutor;
private final FunctionBasedValidator<String> scanDirectoryValidator;
public UnlinkedFilesDialogViewModel(DialogService dialogService,
UndoManager undoManager,
FileUpdateMonitor fileUpdateMonitor,
PreferencesService preferences,
StateManager stateManager,
TaskExecutor taskExecutor) {
this.preferences = preferences;
this.dialogService = dialogService;
this.taskExecutor = taskExecutor;
this.bibDatabase = stateManager.getActiveDatabase().orElseThrow(() -> new NullPointerException("Database null"));
importHandler = new ImportHandler(
bibDatabase,
preferences,
fileUpdateMonitor,
undoManager,
stateManager,
dialogService,
taskExecutor);
this.fileFilterList = FXCollections.observableArrayList(
new FileExtensionViewModel(StandardFileType.ANY_FILE, preferences.getFilePreferences()),
new FileExtensionViewModel(StandardFileType.HTML, preferences.getFilePreferences()),
new FileExtensionViewModel(StandardFileType.MARKDOWN, preferences.getFilePreferences()),
new FileExtensionViewModel(StandardFileType.PDF, preferences.getFilePreferences()));
this.dateFilterList = FXCollections.observableArrayList(DateRange.values());
this.fileSortList = FXCollections.observableArrayList(ExternalFileSorter.values());
Predicate<String> isDirectory = path -> Files.isDirectory(Path.of(path));
scanDirectoryValidator = new FunctionBasedValidator<>(directoryPath, isDirectory,
ValidationMessage.error(Localization.lang("Please enter a valid file path.")));
treeRootProperty.setValue(Optional.empty());
}
public void startSearch() {
Path directory = this.getSearchDirectory();
Filter<Path> selectedFileFilter = selectedExtension.getValue().dirFilter();
DateRange selectedDateFilter = selectedDate.getValue();
ExternalFileSorter selectedSortFilter = selectedSort.getValue();
progressValueProperty.unbind();
progressTextProperty.unbind();
findUnlinkedFilesTask = new UnlinkedFilesCrawler(directory, selectedFileFilter, selectedDateFilter, selectedSortFilter, bibDatabase, preferences.getFilePreferences())
.onRunning(() -> {
progressValueProperty.set(ProgressIndicator.INDETERMINATE_PROGRESS);
progressTextProperty.setValue(Localization.lang("Searching file system..."));
progressTextProperty.bind(findUnlinkedFilesTask.messageProperty());
taskActiveProperty.setValue(true);
treeRootProperty.setValue(Optional.empty());
})
.onFinished(() -> {
progressValueProperty.set(0);
taskActiveProperty.setValue(false);
})
.onSuccess(treeRoot -> treeRootProperty.setValue(Optional.of(treeRoot)));
findUnlinkedFilesTask.executeWith(taskExecutor);
}
public void startImport() {
List<Path> fileList = checkedFileListProperty.stream()
.map(item -> item.getValue().getPath())
.filter(path -> path.toFile().isFile())
.collect(Collectors.toList());
if (fileList.isEmpty()) {
LOGGER.warn("There are no valid files checked");
return;
}
resultList.clear();
importFilesBackgroundTask = importHandler.importFilesInBackground(fileList)
.onRunning(() -> {
progressValueProperty.bind(importFilesBackgroundTask.workDonePercentageProperty());
progressTextProperty.bind(importFilesBackgroundTask.messageProperty());
taskActiveProperty.setValue(true);
})
.onFinished(() -> {
progressValueProperty.unbind();
progressTextProperty.unbind();
taskActiveProperty.setValue(false);
})
.onSuccess(resultList::addAll);
importFilesBackgroundTask.executeWith(taskExecutor);
}
/**
* This starts the export of all files of all selected nodes in the file tree view.
*/
public void startExport() {
List<Path> fileList = checkedFileListProperty.stream()
.map(item -> item.getValue().getPath())
.filter(path -> path.toFile().isFile())
.toList();
if (fileList.isEmpty()) {
LOGGER.warn("There are no valid files checked");
return;
}
FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
.withInitialDirectory(preferences.getFilePreferences().getWorkingDirectory())
.addExtensionFilter(StandardFileType.TXT)
.withDefaultExtension(StandardFileType.TXT)
.build();
Optional<Path> exportPath = dialogService.showFileSaveDialog(fileDialogConfiguration);
if (exportPath.isEmpty()) {
return;
}
try (BufferedWriter writer = Files.newBufferedWriter(exportPath.get(), StandardCharsets.UTF_8,
StandardOpenOption.CREATE)) {
for (Path file : fileList) {
writer.write(file.toString() + "\n");
}
} catch (IOException e) {
LOGGER.error("Error exporting", e);
}
}
public ObservableList<FileExtensionViewModel> getFileFilters() {
return this.fileFilterList;
}
public ObservableList<DateRange> getDateFilters() {
return this.dateFilterList;
}
public ObservableList<ExternalFileSorter> getSorters() {
return this.fileSortList;
}
public void cancelTasks() {
if (findUnlinkedFilesTask != null) {
findUnlinkedFilesTask.cancel();
}
if (importFilesBackgroundTask != null) {
importFilesBackgroundTask.cancel();
}
}
public void browseFileDirectory() {
DirectoryDialogConfiguration directoryDialogConfiguration = new DirectoryDialogConfiguration.Builder()
.withInitialDirectory(preferences.getFilePreferences().getWorkingDirectory()).build();
dialogService.showDirectorySelectionDialog(directoryDialogConfiguration)
.ifPresent(selectedDirectory -> {
directoryPath.setValue(selectedDirectory.toAbsolutePath().toString());
preferences.getFilePreferences().setWorkingDirectory(selectedDirectory.toAbsolutePath());
});
}
private Path getSearchDirectory() {
Path directory = Path.of(directoryPath.getValue());
if (Files.notExists(directory)) {
directory = Path.of(System.getProperty("user.dir"));
directoryPath.setValue(directory.toAbsolutePath().toString());
}
if (!Files.isDirectory(directory)) {
directory = directory.getParent();
directoryPath.setValue(directory.toAbsolutePath().toString());
}
return directory;
}
public ObservableList<ImportFilesResultItemViewModel> resultTableItems() {
return this.resultList;
}
public ObjectProperty<Optional<FileNodeViewModel>> treeRootProperty() {
return this.treeRootProperty;
}
public ObjectProperty<FileExtensionViewModel> selectedExtensionProperty() {
return this.selectedExtension;
}
public ObjectProperty<DateRange> selectedDateProperty() {
return this.selectedDate;
}
public ObjectProperty<ExternalFileSorter> selectedSortProperty() {
return this.selectedSort;
}
public StringProperty directoryPathProperty() {
return this.directoryPath;
}
public ValidationStatus directoryPathValidationStatus() {
return this.scanDirectoryValidator.getValidationStatus();
}
public DoubleProperty progressValueProperty() {
return this.progressValueProperty;
}
public StringProperty progressTextProperty() {
return this.progressTextProperty;
}
public BooleanProperty taskActiveProperty() {
return this.taskActiveProperty;
}
public SimpleListProperty<TreeItem<FileNodeViewModel>> checkedFileListProperty() {
return checkedFileListProperty;
}
}
| 12,888
| 43.140411
| 174
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/externalfiles/UnlinkedPDFFileFilter.java
|
package org.jabref.gui.externalfiles;
import java.io.FileFilter;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.DirectoryStream.Filter;
import java.nio.file.Files;
import java.nio.file.Path;
import org.jabref.logic.util.io.DatabaseFileLookup;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.preferences.FilePreferences;
/**
* {@link FileFilter} implementation, that allows only files which are not linked in any of the {@link BibEntry}s of the
* specified {@link BibDatabase}.
* <p>
* This {@link FileFilter} sits on top of another {@link FileFilter} -implementation, which it first consults. Only if
* this major filefilter has accepted a file, this implementation will verify on that file.
*/
public class UnlinkedPDFFileFilter implements DirectoryStream.Filter<Path> {
private final DatabaseFileLookup lookup;
private final Filter<Path> fileFilter;
public UnlinkedPDFFileFilter(DirectoryStream.Filter<Path> fileFilter, BibDatabaseContext databaseContext, FilePreferences filePreferences) {
this.fileFilter = fileFilter;
this.lookup = new DatabaseFileLookup(databaseContext, filePreferences);
}
@Override
public boolean accept(Path pathname) throws IOException {
if (Files.isDirectory(pathname)) {
return true;
} else {
return fileFilter.accept(pathname) && !lookup.lookupDatabase(pathname) && !lookup.getPathOfDatabase().equals(pathname);
}
}
}
| 1,601
| 37.142857
| 144
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/externalfiletype/CustomExternalFileType.java
|
package org.jabref.gui.externalfiletype;
import java.util.Objects;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.icon.JabRefIcon;
/**
* This class defines a type of external files that can be linked to from JabRef.
* The class contains enough information to provide an icon, a standard extension
* and a link to which application handles files of this type.
*/
public class CustomExternalFileType implements ExternalFileType {
private String name;
private String extension;
private String openWith;
private String iconName;
private String mimeType;
private JabRefIcon icon;
public CustomExternalFileType(String name, String extension, String mimeType,
String openWith, String iconName, JabRefIcon icon) {
this.name = name;
this.extension = extension;
this.mimeType = mimeType;
this.openWith = openWith;
setIconName(iconName);
setIcon(icon);
}
public CustomExternalFileType(ExternalFileType type) {
this(type.getName(), type.getExtension(), type.getMimeType(), type.getOpenWithApplication(), "", type.getIcon());
}
/**
* Construct an ExternalFileType from a String array. This is used when
* reading file type definitions from Preferences, where the available data types are
* limited. We assume that the array contains the same values as the main constructor,
* in the same order.
*
* @param val arguments.
*/
public static ExternalFileType buildFromArgs(String[] val) {
if ((val == null) || (val.length < 4) || (val.length > 5)) {
throw new IllegalArgumentException("Cannot construct ExternalFileType without four elements in String[] argument.");
}
String name = val[0];
String extension = val[1];
String openWith;
String mimeType;
String iconName;
if (val.length == 4) {
// Up to version 2.4b the mime type is not included:
mimeType = "";
openWith = val[2];
iconName = val[3];
} else {
// When mime type is included, the array length should be 5:
mimeType = val[2];
openWith = val[3];
iconName = val[4];
}
// set icon to default first
JabRefIcon icon = IconTheme.JabRefIcons.FILE;
// check whether there is another icon defined for this file type
for (ExternalFileType fileType : ExternalFileTypes.getDefaultExternalFileTypes()) {
if (fileType.getName().equals(name)) {
icon = fileType.getIcon();
break;
}
}
return new CustomExternalFileType(name, extension, mimeType, openWith, iconName, icon);
}
@Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String getExtension() {
if (extension == null) {
return "";
}
return extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
@Override
public String getMimeType() {
if (mimeType == null) {
return "";
}
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
@Override
public String getOpenWithApplication() {
if (openWith == null) {
return "";
}
return openWith;
}
public void setOpenWith(String openWith) {
this.openWith = openWith;
}
/**
* Get the string associated with this file type's icon.
*
* @return The icon name.
*/
public String getIconName() {
return iconName;
}
/**
* Set the string associated with this file type's icon.
*
* @param name The icon name to use.
*/
public void setIconName(String name) {
this.iconName = name;
}
@Override
public JabRefIcon getIcon() {
return icon;
}
public void setIcon(JabRefIcon icon) {
Objects.requireNonNull(icon);
this.icon = icon;
}
@Override
public String toString() {
return getName();
}
public ExternalFileType copy() {
return new CustomExternalFileType(name, extension, mimeType, openWith, iconName, icon);
}
@Override
public int hashCode() {
return Objects.hash(name, extension, mimeType, openWith, iconName);
}
/**
* We define two file type objects as equal if their name, extension, openWith and
* iconName are equal.
*
* @param object The file type to compare with.
* @return true if the file types are equal.
*/
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object instanceof CustomExternalFileType other) {
return Objects.equals(name, other.name) && Objects.equals(extension, other.extension) &&
Objects.equals(mimeType, other.mimeType) && Objects.equals(openWith, other.openWith) && Objects.equals(iconName, other.iconName);
}
return false;
}
}
| 5,294
| 27.164894
| 149
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/externalfiletype/ExternalFileType.java
|
package org.jabref.gui.externalfiletype;
import org.jabref.gui.icon.JabRefIcon;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.FieldFactory;
public interface ExternalFileType {
String getName();
String getExtension();
String getMimeType();
String getOpenWithApplication();
JabRefIcon getIcon();
/**
* Get the bibtex field name used for this file type. Currently we assume that field name equals filename extension.
*
* @return The field name.
*/
default Field getField() {
return FieldFactory.parseField(getExtension());
}
/**
* Return a String array representing this file type. This is used for storage into
* Preferences, and the same array can be used to construct the file type later,
* using the String[] constructor.
*
* @return A String[] containing all information about this file type.
*/
default String[] toStringArray() {
return new String[]{getName(), getExtension(), getMimeType(), getOpenWithApplication(), getIcon().name()};
}
}
| 1,095
| 27.842105
| 120
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/externalfiletype/ExternalFileTypes.java
|
package org.jabref.gui.externalfiletype;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.Set;
import org.jabref.logic.bibtex.FileFieldWriter;
import org.jabref.logic.util.io.FileUtil;
import org.jabref.model.entry.LinkedFile;
import org.jabref.model.strings.StringUtil;
import org.jabref.preferences.FilePreferences;
// Do not make this class final, as it otherwise can't be mocked for tests
public class ExternalFileTypes {
// This String is used in the encoded list in prefs of external file type
// modifications, in order to indicate a removed default file type:
private static final String FILE_TYPE_REMOVED_FLAG = "REMOVED";
private static final ExternalFileType HTML_FALLBACK_TYPE = StandardExternalFileType.URL;
private ExternalFileTypes() {
}
public static List<ExternalFileType> getDefaultExternalFileTypes() {
return Arrays.asList(StandardExternalFileType.values());
}
/**
* Look up the external file type registered with this name, if any.
*
* @param name The file type name.
* @return The ExternalFileType registered, or null if none.
*/
public static Optional<ExternalFileType> getExternalFileTypeByName(String name, FilePreferences filePreferences) {
Optional<ExternalFileType> externalFileType = filePreferences.getExternalFileTypes().stream().filter(type -> type.getName().equals(name)).findFirst();
if (externalFileType.isPresent()) {
return externalFileType;
}
// Return an instance that signifies an unknown file type:
return Optional.of(new UnknownExternalFileType(name));
}
/**
* Look up the external file type registered for this extension, if any.
*
* @param extension The file extension.
* @return The ExternalFileType registered, or null if none.
*/
public static Optional<ExternalFileType> getExternalFileTypeByExt(String extension, FilePreferences filePreferences) {
String extensionCleaned = extension.replace(".", "").replace("*", "");
return filePreferences.getExternalFileTypes().stream().filter(type -> type.getExtension().equalsIgnoreCase(extensionCleaned)).findFirst();
}
/**
* Returns true if there is an external file type registered for this extension.
*
* @param extension The file extension.
* @return true if an ExternalFileType with the extension exists, false otherwise
*/
public static boolean isExternalFileTypeByExt(String extension, FilePreferences filePreferences) {
return filePreferences.getExternalFileTypes().stream().anyMatch(type -> type.getExtension().equalsIgnoreCase(extension));
}
/**
* Look up the external file type registered for this filename, if any.
*
* @param filename The name of the file whose type to look up.
* @return The ExternalFileType registered, or null if none.
*/
public static Optional<ExternalFileType> getExternalFileTypeForName(String filename, FilePreferences filePreferences) {
int longestFound = -1;
ExternalFileType foundType = null;
for (ExternalFileType type : filePreferences.getExternalFileTypes()) {
if (!type.getExtension().isEmpty() && filename.toLowerCase(Locale.ROOT).endsWith(type.getExtension().toLowerCase(Locale.ROOT))
&& (type.getExtension().length() > longestFound)) {
longestFound = type.getExtension().length();
foundType = type;
}
}
return Optional.ofNullable(foundType);
}
/**
* Look up the external file type registered for this MIME type, if any.
*
* @param mimeType The MIME type.
* @return The ExternalFileType registered, or null if none. For the mime type "text/html", a valid file type is
* guaranteed to be returned.
*/
public static Optional<ExternalFileType> getExternalFileTypeByMimeType(String mimeType, FilePreferences filePreferences) {
// Ignores parameters according to link: (https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types)
if (mimeType.indexOf(';') != -1) {
mimeType = mimeType.substring(0, mimeType.indexOf(';')).trim();
}
for (ExternalFileType type : filePreferences.getExternalFileTypes()) {
if (type.getMimeType().equalsIgnoreCase(mimeType)) {
return Optional.of(type);
}
}
if ("text/html".equalsIgnoreCase(mimeType)) {
return Optional.of(HTML_FALLBACK_TYPE);
} else {
return Optional.empty();
}
}
public static Optional<ExternalFileType> getExternalFileTypeByFile(Path file, FilePreferences filePreferences) {
final String filePath = file.toString();
final Optional<String> extension = FileUtil.getFileExtension(filePath);
return extension.flatMap(ext -> getExternalFileTypeByExt(ext, filePreferences));
}
public static Optional<ExternalFileType> getExternalFileTypeByLinkedFile(LinkedFile linkedFile, boolean deduceUnknownType, FilePreferences filePreferences) {
Optional<ExternalFileType> type = getExternalFileTypeByName(linkedFile.getFileType(), filePreferences);
boolean isUnknownType = type.isEmpty() || (type.get() instanceof UnknownExternalFileType);
if (isUnknownType && deduceUnknownType) {
// No file type was recognized. Try to find a usable file type based on mime type:
Optional<ExternalFileType> mimeType = getExternalFileTypeByMimeType(linkedFile.getFileType(), filePreferences);
if (mimeType.isPresent()) {
return mimeType;
}
// No type could be found from mime type. Try based on the extension:
return FileUtil.getFileExtension(linkedFile.getLink())
.flatMap(extension -> getExternalFileTypeByExt(extension, filePreferences));
} else {
return type;
}
}
/**
* @return A StringList of customized and removed file types compared to the default list of external file types for storing
*/
public static String toStringList(Collection<ExternalFileType> fileTypes) {
// First find a list of the default types:
List<ExternalFileType> defTypes = new ArrayList<>(getDefaultExternalFileTypes());
// Make a list of types that are unchanged:
List<ExternalFileType> unchanged = new ArrayList<>();
// Create a result list
List<ExternalFileType> results = new ArrayList<>();
for (ExternalFileType type : fileTypes) {
results.add(type);
// See if we can find a type with matching name in the default type list:
ExternalFileType found = null;
for (ExternalFileType defType : defTypes) {
if (defType.getName().equals(type.getName())) {
found = defType;
break;
}
}
if (found != null) {
// Found it! Check if it is an exact match, or if it has been customized:
if (found.equals(type)) {
unchanged.add(type);
} else {
// It was modified. Remove its entry from the defaults list, since
// the type hasn't been removed:
defTypes.remove(found);
}
}
}
// Go through unchanged types. Remove them from the ones that should be stored,
// and from the list of defaults, since we don't need to mention these in prefs:
for (ExternalFileType type : unchanged) {
defTypes.remove(type);
results.remove(type);
}
// Now set up the array to write to prefs, containing all new types, all modified
// types, and a flag denoting each default type that has been removed:
String[][] array = new String[results.size() + defTypes.size()][];
int i = 0;
for (ExternalFileType type : results) {
array[i] = type.toStringArray();
i++;
}
for (ExternalFileType type : defTypes) {
array[i] = new String[] {type.getName(), FILE_TYPE_REMOVED_FLAG};
i++;
}
return FileFieldWriter.encodeStringArray(array);
}
/**
* Set up the list of external file types, either from default values, or from values recorded in PreferencesService.
*/
public static Set<ExternalFileType> fromString(String storedFileTypes) {
// First get a list of the default file types as a starting point:
Set<ExternalFileType> types = new HashSet<>(getDefaultExternalFileTypes());
// If no changes have been stored, simply use the defaults:
if (StringUtil.isBlank(storedFileTypes)) {
return types;
}
// Read the prefs information for file types:
String[][] vals = StringUtil.decodeStringDoubleArray(storedFileTypes);
for (String[] val : vals) {
if ((val.length == 2) && val[1].equals(FILE_TYPE_REMOVED_FLAG)) {
// This entry indicates that a default entry type should be removed:
ExternalFileType toRemove = null;
for (ExternalFileType type : types) {
if (type.getName().equals(val[0])) {
toRemove = type;
break;
}
}
// If we found it, remove it from the type list:
if (toRemove != null) {
types.remove(toRemove);
}
} else {
// A new or modified entry type. Construct it from the string array:
ExternalFileType type = CustomExternalFileType.buildFromArgs(val);
// Check if there is a default type with the same name. If so, this is a
// modification of that type, so remove the default one:
ExternalFileType toRemove = null;
for (ExternalFileType defType : types) {
if (type.getName().equals(defType.getName())) {
toRemove = defType;
break;
}
}
// If we found it, remove it from the type list:
if (toRemove != null) {
types.remove(toRemove);
}
// Then add the new one:
types.add(type);
}
}
return types;
}
}
| 10,807
| 42.934959
| 161
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/externalfiletype/StandardExternalFileType.java
|
package org.jabref.gui.externalfiletype;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.icon.JabRefIcon;
import org.jabref.logic.l10n.Localization;
public enum StandardExternalFileType implements ExternalFileType {
PDF("PDF", "pdf", "application/pdf", "evince", "pdfSmall", IconTheme.JabRefIcons.PDF_FILE),
PostScript("PostScript", "ps", "application/postscript", "evince", "psSmall", IconTheme.JabRefIcons.FILE),
Word("Word", "doc", "application/msword", "oowriter", "openoffice", IconTheme.JabRefIcons.FILE_WORD),
Word_NEW("Word 2007+", "docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "oowriter", "openoffice", IconTheme.JabRefIcons.FILE_WORD),
OpenDocument_TEXT(Localization.lang("OpenDocument text"), "odt", "application/vnd.oasis.opendocument.text", "oowriter", "openoffice", IconTheme.JabRefIcons.FILE_OPENOFFICE),
Excel("Excel", "xls", "application/excel", "oocalc", "openoffice", IconTheme.JabRefIcons.FILE_EXCEL),
Excel_NEW("Excel 2007+", "xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "oocalc", "openoffice", IconTheme.JabRefIcons.FILE_EXCEL),
OpenDocumentSpreadsheet(Localization.lang("OpenDocument spreadsheet"), "ods", "application/vnd.oasis.opendocument.spreadsheet", "oocalc", "openoffice", IconTheme.JabRefIcons.FILE_OPENOFFICE),
PowerPoint("PowerPoint", "ppt", "application/vnd.ms-powerpoint", "ooimpress", "openoffice", IconTheme.JabRefIcons.FILE_POWERPOINT),
PowerPoint_NEW("PowerPoint 2007+", "pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", "ooimpress", "openoffice", IconTheme.JabRefIcons.FILE_POWERPOINT),
OpenDocumentPresentation(Localization.lang("OpenDocument presentation"), "odp", "application/vnd.oasis.opendocument.presentation", "ooimpress", "openoffice", IconTheme.JabRefIcons.FILE_OPENOFFICE),
RTF("Rich Text Format", "rtf", "application/rtf", "oowriter", "openoffice", IconTheme.JabRefIcons.FILE_TEXT),
PNG(Localization.lang("%0 image", "PNG"), "png", "image/png", "gimp", "picture", IconTheme.JabRefIcons.PICTURE),
GIF(Localization.lang("%0 image", "GIF"), "gif", "image/gif", "gimp", "picture", IconTheme.JabRefIcons.PICTURE),
JPG(Localization.lang("%0 image", "JPG"), "jpg", "image/jpeg", "gimp", "picture", IconTheme.JabRefIcons.PICTURE),
Djvu("Djvu", "djvu", "image/vnd.djvu", "evince", "psSmall", IconTheme.JabRefIcons.FILE),
TXT("Text", "txt", "text/plain", "emacs", "emacs", IconTheme.JabRefIcons.FILE_TEXT),
TEX("LaTeX", "tex", "application/x-latex", "emacs", "emacs", IconTheme.JabRefIcons.FILE_TEXT),
CHM("CHM", "chm", "application/mshelp", "gnochm", "www", IconTheme.JabRefIcons.WWW),
TIFF(Localization.lang("%0 image", "TIFF"), "tiff", "image/tiff", "gimp", "picture", IconTheme.JabRefIcons.PICTURE),
URL("URL", "html", "text/html", "firefox", "www", IconTheme.JabRefIcons.WWW),
MHT("MHT", "mht", "multipart/related", "firefox", "www", IconTheme.JabRefIcons.WWW),
ePUB("ePUB", "epub", "application/epub+zip", "firefox", "www", IconTheme.JabRefIcons.WWW),
MARKDOWN("Markdown", "md", "text/markdown", "emacs", "emacs", IconTheme.JabRefIcons.FILE_TEXT);
private final String name;
private final String extension;
private final String mimeType;
private final String openWith;
private final String iconName;
private final JabRefIcon icon;
StandardExternalFileType(String name, String extension, String mimeType,
String openWith, String iconName, JabRefIcon icon) {
this.name = name;
this.extension = extension;
this.mimeType = mimeType;
this.openWith = openWith;
this.iconName = iconName;
this.icon = icon;
}
@Override
public String getName() {
return name;
}
@Override
public String getExtension() {
return extension;
}
@Override
public String getMimeType() {
return mimeType;
}
@Override
public String getOpenWithApplication() {
// On all OSes there is a generic application available to handle file opening, so use this one
return "";
}
@Override
public JabRefIcon getIcon() {
return icon;
}
}
| 4,275
| 55.263158
| 201
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/externalfiletype/UnknownExternalFileType.java
|
package org.jabref.gui.externalfiletype;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.icon.JabRefIcon;
/**
* Unknown external file type.
* <p>
* This instance represents a file type unknown to JabRef.
* This can happen, for example, when a database is loaded which contains links to files of a type that has not been defined on this JabRef instance.
*/
public class UnknownExternalFileType implements ExternalFileType {
private final String name;
private final String extension;
public UnknownExternalFileType(String name) {
this(name, "");
}
public UnknownExternalFileType(String name, String extension) {
this.name = name;
this.extension = extension;
}
@Override
public String getName() {
return name;
}
@Override
public String getExtension() {
return extension;
}
@Override
public String getMimeType() {
return "";
}
@Override
public String getOpenWithApplication() {
return "";
}
@Override
public JabRefIcon getIcon() {
return IconTheme.JabRefIcons.FILE;
}
}
| 1,141
| 21.392157
| 149
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/AbstractEditorViewModel.java
|
package org.jabref.gui.fieldeditors;
import java.util.Collection;
import javax.swing.undo.UndoManager;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import org.jabref.gui.AbstractViewModel;
import org.jabref.gui.JabRefGUI;
import org.jabref.gui.autocompleter.SuggestionProvider;
import org.jabref.gui.undo.UndoableFieldChange;
import org.jabref.gui.util.BindingsHelper;
import org.jabref.logic.integrity.FieldCheckers;
import org.jabref.logic.integrity.ValueChecker;
import org.jabref.logic.util.OS;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.Field;
import com.tobiasdiez.easybind.EasyObservableValue;
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.Validator;
import org.controlsfx.control.textfield.AutoCompletionBinding;
public class AbstractEditorViewModel extends AbstractViewModel {
protected final Field field;
protected StringProperty text = new SimpleStringProperty("");
protected BibEntry entry;
private final SuggestionProvider<?> suggestionProvider;
private final CompositeValidator fieldValidator;
private EasyObservableValue<String> fieldBinding;
public AbstractEditorViewModel(Field field, SuggestionProvider<?> suggestionProvider, FieldCheckers fieldCheckers) {
this.field = field;
this.suggestionProvider = suggestionProvider;
this.fieldValidator = new CompositeValidator();
for (ValueChecker checker : fieldCheckers.getForField(field)) {
FunctionBasedValidator<String> validator = new FunctionBasedValidator<>(text, value ->
checker.checkValue(value).map(ValidationMessage::warning).orElse(null));
fieldValidator.addValidators(validator);
}
}
public Validator getFieldValidator() {
return fieldValidator;
}
public StringProperty textProperty() {
return text;
}
public void bindToEntry(BibEntry entry) {
this.entry = entry;
// We need to keep a reference to the binding since it otherwise gets discarded
fieldBinding = entry.getFieldBinding(field).asOrdinary();
BindingsHelper.bindBidirectional(
this.textProperty(),
fieldBinding,
newValue -> {
if (newValue != null) {
// Controlsfx uses hardcoded \n for multiline fields, but JabRef stores them in OS Newlines format
String oldValue = entry.getField(field).map(value -> value.replace(OS.NEWLINE, "\n").trim()).orElse(null);
// Autosave and save action trigger the entry editor to reload the fields, so we have to
// check for changes here, otherwise the cursor position is annoyingly reset every few seconds
if (!(newValue.trim()).equals(oldValue)) {
entry.setField(field, newValue);
UndoManager undoManager = JabRefGUI.getMainFrame().getUndoManager();
undoManager.addEdit(new UndoableFieldChange(entry, field, oldValue, newValue));
}
}
});
}
public Collection<?> complete(AutoCompletionBinding.ISuggestionRequest request) {
return suggestionProvider.provideSuggestions(request);
}
}
| 3,564
| 41.440476
| 130
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/CitationKeyEditor.java
|
package org.jabref.gui.fieldeditors;
import java.util.Collections;
import javax.swing.undo.UndoManager;
import javafx.fxml.FXML;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import org.jabref.gui.DialogService;
import org.jabref.gui.actions.ActionFactory;
import org.jabref.gui.actions.StandardActions;
import org.jabref.gui.autocompleter.SuggestionProvider;
import org.jabref.logic.integrity.FieldCheckers;
import org.jabref.model.database.BibDatabaseContext;
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 CitationKeyEditor extends HBox implements FieldEditorFX {
private final PreferencesService preferences;
@FXML private final CitationKeyEditorViewModel viewModel;
@FXML private Button generateCitationKeyButton;
@FXML private EditorTextField textField;
public CitationKeyEditor(Field field,
PreferencesService preferences,
SuggestionProvider<?> suggestionProvider,
FieldCheckers fieldCheckers,
BibDatabaseContext databaseContext,
UndoManager undoManager,
DialogService dialogService) {
this.preferences = preferences;
this.viewModel = new CitationKeyEditorViewModel(
field,
suggestionProvider,
fieldCheckers,
preferences,
databaseContext,
undoManager,
dialogService);
ViewLoader.view(this)
.root(this)
.load();
textField.textProperty().bindBidirectional(viewModel.textProperty());
textField.initContextMenu(Collections::emptyList);
new EditorValidator(preferences).configureValidation(viewModel.getFieldValidator().getValidationStatus(), textField);
}
public CitationKeyEditorViewModel getViewModel() {
return viewModel;
}
@Override
public void bindToEntry(BibEntry entry) {
viewModel.bindToEntry(entry);
// Configure button to generate citation key
new ActionFactory(preferences.getKeyBindingRepository())
.configureIconButton(
StandardActions.GENERATE_CITE_KEY,
viewModel.getGenerateCiteKeyCommand(),
generateCitationKeyButton);
}
@Override
public Parent getNode() {
return this;
}
}
| 2,664
| 31.901235
| 125
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/CitationKeyEditorViewModel.java
|
package org.jabref.gui.fieldeditors;
import javax.swing.undo.UndoManager;
import org.jabref.gui.DialogService;
import org.jabref.gui.autocompleter.SuggestionProvider;
import org.jabref.gui.citationkeypattern.GenerateCitationKeySingleAction;
import org.jabref.logic.integrity.FieldCheckers;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.field.Field;
import org.jabref.preferences.PreferencesService;
import de.saxsys.mvvmfx.utils.commands.Command;
public class CitationKeyEditorViewModel extends AbstractEditorViewModel {
private final PreferencesService preferencesService;
private final BibDatabaseContext databaseContext;
private final UndoManager undoManager;
private final DialogService dialogService;
public CitationKeyEditorViewModel(Field field, SuggestionProvider<?> suggestionProvider, FieldCheckers fieldCheckers, PreferencesService preferencesService, BibDatabaseContext databaseContext, UndoManager undoManager, DialogService dialogService) {
super(field, suggestionProvider, fieldCheckers);
this.preferencesService = preferencesService;
this.databaseContext = databaseContext;
this.undoManager = undoManager;
this.dialogService = dialogService;
}
public Command getGenerateCiteKeyCommand() {
return new GenerateCitationKeySingleAction(entry, databaseContext, dialogService, preferencesService, undoManager);
}
}
| 1,448
| 42.909091
| 252
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/ContextMenuAddable.java
|
package org.jabref.gui.fieldeditors;
import java.util.List;
import java.util.function.Supplier;
import javafx.scene.control.MenuItem;
public interface ContextMenuAddable {
/**
* Adds the given list of menu items to the context menu. The usage of {@link Supplier} prevents that the menus need
* to be instantiated at this point. They are populated when the user needs them which prevents many unnecessary
* allocations when the main table is just scrolled with the entry editor open.
*/
void initContextMenu(final Supplier<List<MenuItem>> items);
}
| 579
| 35.25
| 120
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/DateEditor.java
|
package org.jabref.gui.fieldeditors;
import java.time.format.DateTimeFormatter;
import javafx.fxml.FXML;
import javafx.scene.Parent;
import javafx.scene.layout.HBox;
import org.jabref.gui.autocompleter.SuggestionProvider;
import org.jabref.gui.util.component.TemporalAccessorPicker;
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 DateEditor extends HBox implements FieldEditorFX {
@FXML private DateEditorViewModel viewModel;
@FXML private TemporalAccessorPicker datePicker;
public DateEditor(Field field, DateTimeFormatter dateFormatter, SuggestionProvider<?> suggestionProvider, FieldCheckers fieldCheckers, PreferencesService preferences) {
this.viewModel = new DateEditorViewModel(field, suggestionProvider, dateFormatter, fieldCheckers);
ViewLoader.view(this)
.root(this)
.load();
datePicker.setStringConverter(viewModel.getDateToStringConverter());
datePicker.getEditor().textProperty().bindBidirectional(viewModel.textProperty());
new EditorValidator(preferences).configureValidation(viewModel.getFieldValidator().getValidationStatus(), datePicker.getEditor());
}
public DateEditorViewModel getViewModel() {
return viewModel;
}
@Override
public void bindToEntry(BibEntry entry) {
viewModel.bindToEntry(entry);
}
@Override
public Parent getNode() {
return this;
}
}
| 1,631
| 31.64
| 172
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/DateEditorViewModel.java
|
package org.jabref.gui.fieldeditors;
import java.time.DateTimeException;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.TemporalAccessor;
import javafx.util.StringConverter;
import org.jabref.gui.autocompleter.SuggestionProvider;
import org.jabref.logic.integrity.FieldCheckers;
import org.jabref.model.entry.Date;
import org.jabref.model.entry.field.Field;
import org.jabref.model.strings.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DateEditorViewModel extends AbstractEditorViewModel {
private static final Logger LOGGER = LoggerFactory.getLogger(DateEditorViewModel.class);
private final DateTimeFormatter dateFormatter;
public DateEditorViewModel(Field field, SuggestionProvider<?> suggestionProvider, DateTimeFormatter dateFormatter, FieldCheckers fieldCheckers) {
super(field, suggestionProvider, fieldCheckers);
this.dateFormatter = dateFormatter;
}
public StringConverter<TemporalAccessor> getDateToStringConverter() {
return new StringConverter<>() {
@Override
public String toString(TemporalAccessor date) {
if (date != null) {
try {
return dateFormatter.format(date);
} catch (DateTimeException ex) {
LOGGER.error("Could not format date", ex);
return "";
}
} else {
return "";
}
}
@Override
public TemporalAccessor fromString(String string) {
if (StringUtil.isNotBlank(string)) {
try {
return dateFormatter.parse(string);
} catch (DateTimeParseException exception) {
// We accept all kinds of dates (not just in the format specified)
return Date.parse(string).map(Date::toTemporalAccessor).orElse(null);
}
} else {
return null;
}
}
};
}
}
| 2,195
| 35
| 149
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/EditorTextArea.java
|
package org.jabref.gui.fieldeditors;
import java.net.URL;
import java.util.List;
import java.util.Objects;
import java.util.ResourceBundle;
import java.util.function.Supplier;
import javafx.fxml.Initializable;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import org.jabref.gui.ClipBoardManager;
import org.jabref.gui.Globals;
import org.jabref.gui.fieldeditors.contextmenu.EditorContextAction;
public class EditorTextArea extends javafx.scene.control.TextArea implements Initializable, ContextMenuAddable {
private final ContextMenu contextMenu = new ContextMenu();
/**
* Variable that contains user-defined behavior for paste action.
*/
private PasteActionHandler pasteActionHandler = () -> {
// Set empty paste behavior by default
};
public EditorTextArea() {
this("");
}
public EditorTextArea(final String text) {
super(text);
// Hide horizontal scrollbar and always wrap text
setWrapText(true);
ClipBoardManager.addX11Support(this);
}
@Override
public void initContextMenu(final Supplier<List<MenuItem>> items) {
setOnContextMenuRequested(event -> {
contextMenu.getItems().setAll(EditorContextAction.getDefaultContextMenuItems(this, Globals.getKeyPrefs()));
contextMenu.getItems().addAll(0, items.get());
TextInputControlBehavior.showContextMenu(this, contextMenu, event);
});
}
@Override
public void initialize(URL location, ResourceBundle resources) {
// not needed
}
/**
* Set pasteActionHandler variable to passed handler
*
* @param handler an instance of PasteActionHandler that describes paste behavior
*/
public void setPasteActionHandler(PasteActionHandler handler) {
Objects.requireNonNull(handler);
this.pasteActionHandler = handler;
}
/**
* Override javafx TextArea method applying TextArea.paste() and pasteActionHandler after
*/
@Override
public void paste() {
super.paste();
pasteActionHandler.handle();
}
/**
* Interface presents user-described paste behaviour applying to paste method
*/
@FunctionalInterface
public interface PasteActionHandler {
void handle();
}
}
| 2,333
| 27.463415
| 119
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/EditorTextField.java
|
package org.jabref.gui.fieldeditors;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import java.util.function.Supplier;
import javafx.fxml.Initializable;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import org.jabref.gui.ClipBoardManager;
import org.jabref.gui.Globals;
import org.jabref.gui.fieldeditors.contextmenu.EditorContextAction;
public class EditorTextField extends javafx.scene.control.TextField implements Initializable, ContextMenuAddable {
private final ContextMenu contextMenu = new ContextMenu();
public EditorTextField() {
this("");
}
public EditorTextField(final String text) {
super(text);
// Always fill out all the available space
setPrefHeight(Double.POSITIVE_INFINITY);
HBox.setHgrow(this, Priority.ALWAYS);
ClipBoardManager.addX11Support(this);
}
@Override
public void initContextMenu(final Supplier<List<MenuItem>> items) {
setOnContextMenuRequested(event -> {
contextMenu.getItems().setAll(EditorContextAction.getDefaultContextMenuItems(this, Globals.getKeyPrefs()));
contextMenu.getItems().addAll(0, items.get());
TextInputControlBehavior.showContextMenu(this, contextMenu, event);
});
}
@Override
public void initialize(URL location, ResourceBundle resources) {
// not needed
}
}
| 1,505
| 28.529412
| 119
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/EditorTypeEditorViewModel.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 EditorTypeEditorViewModel extends MapBasedEditorViewModel<String> {
private BiMap<String, String> itemMap = HashBiMap.create(7);
public EditorTypeEditorViewModel(Field field, SuggestionProvider<?> suggestionProvider, FieldCheckers fieldCheckers) {
super(field, suggestionProvider, fieldCheckers);
itemMap.put("editor", Localization.lang("Editor"));
itemMap.put("compiler", Localization.lang("Compiler"));
itemMap.put("founder", Localization.lang("Founder"));
itemMap.put("continuator", Localization.lang("Continuator"));
itemMap.put("redactor", Localization.lang("Redactor"));
itemMap.put("reviser", Localization.lang("Reviser"));
itemMap.put("collaborator", Localization.lang("Collaborator"));
}
@Override
protected BiMap<String, String> getItemMap() {
return itemMap;
}
@Override
public String convertToDisplayText(String object) {
return object;
}
}
| 1,302
| 34.216216
| 122
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/EditorValidator.java
|
package org.jabref.gui.fieldeditors;
import javafx.scene.control.TextInputControl;
import org.jabref.gui.util.IconValidationDecorator;
import org.jabref.preferences.PreferencesService;
import de.saxsys.mvvmfx.utils.validation.ValidationStatus;
import de.saxsys.mvvmfx.utils.validation.visualization.ControlsFxVisualizer;
public class EditorValidator {
private final PreferencesService preferences;
public EditorValidator(PreferencesService preferences) {
this.preferences = preferences;
}
public void configureValidation(final ValidationStatus status, final TextInputControl textInput) {
if (preferences.getEntryEditorPreferences().shouldEnableValidation()) {
ControlsFxVisualizer validationVisualizer = new ControlsFxVisualizer();
validationVisualizer.setDecoration(new IconValidationDecorator());
validationVisualizer.initVisualization(status, textInput);
}
}
}
| 951
| 34.259259
| 102
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/FieldEditorFX.java
|
package org.jabref.gui.fieldeditors;
import javafx.scene.Parent;
import org.jabref.gui.util.ControlHelper;
import org.jabref.model.entry.BibEntry;
public interface FieldEditorFX {
void bindToEntry(BibEntry entry);
Parent getNode();
default void focus() {
getNode().getChildrenUnmodifiable()
.stream()
.findFirst()
.orElse(getNode())
.requestFocus();
}
default boolean childIsFocused() {
return ControlHelper.childIsFocused(getNode());
}
/**
* Returns relative size of the field editor in terms of display space.
* <p>
* A value of 1 means that the editor gets exactly as much space as all other regular editors.
* <p>
* A value of 2 means that the editor gets twice as much space as regular editors.
*
* @return the relative weight of the editor in terms of display space
*/
default double getWeight() {
return 1;
}
}
| 994
| 24.512821
| 98
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/FieldEditors.java
|
package org.jabref.gui.fieldeditors;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Set;
import javax.swing.undo.UndoManager;
import org.jabref.gui.DialogService;
import org.jabref.gui.autocompleter.ContentSelectorSuggestionProvider;
import org.jabref.gui.autocompleter.SuggestionProvider;
import org.jabref.gui.autocompleter.SuggestionProviders;
import org.jabref.gui.fieldeditors.identifier.IdentifierEditor;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.integrity.FieldCheckers;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.FieldFactory;
import org.jabref.model.entry.field.FieldProperty;
import org.jabref.model.entry.field.InternalField;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.entry.types.EntryType;
import org.jabref.model.entry.types.IEEETranEntryType;
import org.jabref.model.metadata.MetaData;
import org.jabref.preferences.PreferencesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings("unchecked")
public class FieldEditors {
private static final Logger LOGGER = LoggerFactory.getLogger(FieldEditors.class);
public static FieldEditorFX getForField(final Field field,
final TaskExecutor taskExecutor,
final DialogService dialogService,
final JournalAbbreviationRepository journalAbbreviationRepository,
final PreferencesService preferences,
final BibDatabaseContext databaseContext,
final EntryType entryType,
final SuggestionProviders suggestionProviders,
final UndoManager undoManager) {
final Set<FieldProperty> fieldProperties = field.getProperties();
final SuggestionProvider<?> suggestionProvider = getSuggestionProvider(field, suggestionProviders, databaseContext.getMetaData());
final FieldCheckers fieldCheckers = new FieldCheckers(
databaseContext,
preferences.getFilePreferences(),
journalAbbreviationRepository,
preferences.getEntryEditorPreferences().shouldAllowIntegerEditionBibtex());
boolean isMultiLine = FieldFactory.isMultiLineField(field, preferences.getFieldPreferences().getNonWrappableFields());
if (preferences.getTimestampPreferences().getTimestampField().equals(field)) {
return new DateEditor(field, DateTimeFormatter.ofPattern(preferences.getTimestampPreferences().getTimestampFormat()), suggestionProvider, fieldCheckers, preferences);
} else if (fieldProperties.contains(FieldProperty.DATE)) {
return new DateEditor(field, DateTimeFormatter.ofPattern("[uuuu][-MM][-dd]"), suggestionProvider, fieldCheckers, preferences);
} else if (fieldProperties.contains(FieldProperty.EXTERNAL)) {
return new UrlEditor(field, dialogService, suggestionProvider, fieldCheckers, preferences);
} else if (fieldProperties.contains(FieldProperty.JOURNAL_NAME)) {
return new JournalEditor(field, journalAbbreviationRepository, preferences, suggestionProvider, fieldCheckers);
} else if (fieldProperties.contains(FieldProperty.DOI) || fieldProperties.contains(FieldProperty.EPRINT) || fieldProperties.contains(FieldProperty.ISBN)) {
return new IdentifierEditor(field, taskExecutor, dialogService, suggestionProvider, fieldCheckers, preferences);
} else if (field == StandardField.OWNER) {
return new OwnerEditor(field, preferences, suggestionProvider, fieldCheckers);
} else if (field == StandardField.GROUPS) {
return new GroupEditor(field, suggestionProvider, fieldCheckers, preferences, isMultiLine);
} else if (fieldProperties.contains(FieldProperty.FILE_EDITOR)) {
return new LinkedFilesEditor(field, databaseContext, suggestionProvider, fieldCheckers);
} else if (fieldProperties.contains(FieldProperty.YES_NO)) {
return new OptionEditor<>(new YesNoEditorViewModel(field, suggestionProvider, fieldCheckers));
} else if (fieldProperties.contains(FieldProperty.MONTH)) {
return new OptionEditor<>(new MonthEditorViewModel(field, suggestionProvider, databaseContext.getMode(), fieldCheckers));
} else if (fieldProperties.contains(FieldProperty.GENDER)) {
return new OptionEditor<>(new GenderEditorViewModel(field, suggestionProvider, fieldCheckers));
} else if (fieldProperties.contains(FieldProperty.EDITOR_TYPE)) {
return new OptionEditor<>(new EditorTypeEditorViewModel(field, suggestionProvider, fieldCheckers));
} else if (fieldProperties.contains(FieldProperty.PAGINATION)) {
return new OptionEditor<>(new PaginationEditorViewModel(field, suggestionProvider, fieldCheckers));
} else if (fieldProperties.contains(FieldProperty.TYPE)) {
if (entryType.equals(IEEETranEntryType.Patent)) {
return new OptionEditor<>(new PatentTypeEditorViewModel(field, suggestionProvider, fieldCheckers));
} else {
return new OptionEditor<>(new TypeEditorViewModel(field, suggestionProvider, fieldCheckers));
}
} else if (fieldProperties.contains(FieldProperty.SINGLE_ENTRY_LINK)) {
return new LinkedEntriesEditor(field, databaseContext, (SuggestionProvider<BibEntry>) suggestionProvider, fieldCheckers);
} else if (fieldProperties.contains(FieldProperty.MULTIPLE_ENTRY_LINK)) {
return new LinkedEntriesEditor(field, databaseContext, (SuggestionProvider<BibEntry>) suggestionProvider, fieldCheckers);
} else if (fieldProperties.contains(FieldProperty.PERSON_NAMES)) {
return new PersonsEditor(field, suggestionProvider, preferences, fieldCheckers, isMultiLine);
} else if (StandardField.KEYWORDS == field) {
return new KeywordsEditor(field, suggestionProvider, fieldCheckers, preferences);
} else if (field == InternalField.KEY_FIELD) {
return new CitationKeyEditor(field, preferences, suggestionProvider, fieldCheckers, databaseContext, undoManager, dialogService);
} else {
// default
return new SimpleEditor(field, suggestionProvider, fieldCheckers, preferences, isMultiLine);
}
}
private static SuggestionProvider<?> getSuggestionProvider(Field field, SuggestionProviders suggestionProviders, MetaData metaData) {
SuggestionProvider<?> suggestionProvider = suggestionProviders.getForField(field);
List<String> contentSelectorValues = metaData.getContentSelectorValuesForField(field);
if (!contentSelectorValues.isEmpty()) {
// Enrich auto completion by content selector values
try {
return new ContentSelectorSuggestionProvider((SuggestionProvider<String>) suggestionProvider, contentSelectorValues);
} catch (ClassCastException exception) {
LOGGER.error("Content selectors are only supported for normal fields with string-based auto completion.");
return suggestionProvider;
}
} else {
return suggestionProvider;
}
}
}
| 7,649
| 61.195122
| 178
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/FieldNameLabel.java
|
package org.jabref.gui.fieldeditors;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.stage.Screen;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.InternalField;
import org.jabref.model.entry.field.SpecialField;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.strings.StringUtil;
public class FieldNameLabel extends Label {
public FieldNameLabel(Field field) {
super(field.getDisplayName());
setPadding(new Insets(4, 0, 0, 0));
setAlignment(Pos.CENTER);
setPrefHeight(Double.POSITIVE_INFINITY);
String description = getDescription(field);
if (StringUtil.isNotBlank(description)) {
Screen currentScreen = Screen.getPrimary();
double maxWidth = currentScreen.getBounds().getWidth();
Tooltip tooltip = new Tooltip(description);
tooltip.setMaxWidth(maxWidth * 2 / 3);
tooltip.setWrapText(true);
this.setTooltip(tooltip);
}
}
public String getDescription(Field field) {
if (field.isStandardField()) {
StandardField standardField = (StandardField) field;
switch (standardField) {
case ABSTRACT:
return Localization.lang("This field is intended for recording abstracts, to be printed by a special bibliography style.");
case ADDENDUM:
return Localization.lang("Miscellaneous bibliographic data usually printed at the end of the entry.");
case AFTERWORD:
return Localization.lang("Author(s) of an afterword to the work.");
case ANNOTATION:
case ANNOTE:
return Localization.lang("This field may be useful when implementing a style for annotated bibliographies.");
case ANNOTATOR:
return Localization.lang("Author(s) of annotations to the work.");
case AUTHOR:
return Localization.lang("Author(s) of the work.");
case BOOKSUBTITLE:
return Localization.lang("Subtitle related to the \"Booktitle\".");
case BOOKTITLE:
return Localization.lang("Title of the main publication this work is part of.");
case BOOKTITLEADDON:
return Localization.lang("Annex to the \"Booktitle\", to be printed in a different font.");
case CHAPTER:
return Localization.lang("Chapter or section or any other unit of a work.");
case COMMENT:
return Localization.lang("Comment to this entry.");
case COMMENTATOR:
return Localization.lang("Author(s) of a commentary to the work.") + "\n" +
Localization.lang("Note that this field is intended for commented editions which have a commentator in addition to the author. If the work is a stand-alone commentary, the commentator should be given in the author field.");
case DATE:
return Localization.lang("Publication date of the work.");
case DOI:
return Localization.lang("Digital Object Identifier of the work.");
case EDITION:
return Localization.lang("Edition of a printed publication.");
case EDITOR:
return Localization.lang("Editor(s) of the work or the main publication, depending on the type of the entry.");
case EDITORA:
return Localization.lang("Secondary editor performing a different editorial role, such as compiling, redacting, etc.");
case EDITORB:
return Localization.lang("Another secondary editor performing a different role.");
case EDITORC:
return Localization.lang("Another secondary editor performing a different role.");
case EDITORTYPE:
return Localization.lang("Type of editorial role performed by the \"Editor\".");
case EDITORATYPE:
return Localization.lang("Type of editorial role performed by the \"Editora\".");
case EDITORBTYPE:
return Localization.lang("Type of editorial role performed by the \"Editorb\".");
case EDITORCTYPE:
return Localization.lang("Type of editorial role performed by the \"Editorc\".");
case EID:
return Localization.lang("Electronic identifier of a work.") + "\n" +
Localization.lang("This field may replace the pages field for journals deviating from the classic pagination scheme of printed journals by only enumerating articles or papers and not pages.");
case EPRINT:
return Localization.lang("Electronic identifier of an online publication.") + "\n" +
Localization.lang("This is roughly comparable to a DOI but specific to a certain archive, repository, service, or system.");
case EPRINTCLASS:
case PRIMARYCLASS:
return Localization.lang("Additional information related to the resource indicated by the eprint field.") + "\n" +
Localization.lang("This could be a section of an archive, a path indicating a service, a classification of some sort.");
case EPRINTTYPE:
case ARCHIVEPREFIX:
return Localization.lang("Type of the eprint identifier, e. g., the name of the archive, repository, service, or system the eprint field refers to.");
case EVENTDATE:
return Localization.lang("Date of a conference, a symposium, or some other event.");
case EVENTTITLE:
return Localization.lang("Title of a conference, a symposium, or some other event.") + "\n"
+ Localization.lang("Note that this field holds the plain title of the event. Things like \"Proceedings of the Fifth XYZ Conference\" go into the titleaddon or booktitleaddon field.");
case EVENTTITLEADDON:
return Localization.lang("Annex to the eventtitle field.") + "\n" +
Localization.lang("Can be used for known event acronyms.");
case FILE:
case PDF:
return Localization.lang("Link(s) to a local PDF or other document of the work.");
case FOREWORD:
return Localization.lang("Author(s) of a foreword to the work.");
case HOWPUBLISHED:
return Localization.lang("Publication notice for unusual publications which do not fit into any of the common categories.");
case INSTITUTION:
case SCHOOL:
return Localization.lang("Name of a university or some other institution.");
case INTRODUCTION:
return Localization.lang("Author(s) of an introduction to the work.");
case ISBN:
return Localization.lang("International Standard Book Number of a book.");
case ISRN:
return Localization.lang("International Standard Technical Report Number of a technical report.");
case ISSN:
return Localization.lang("International Standard Serial Number of a periodical.");
case ISSUE:
return Localization.lang("Issue of a journal.") + "\n" +
Localization.lang("This field is intended for journals whose individual issues are identified by a designation such as \"Spring\" or \"Summer\" rather than the month or a number. Integer ranges and short designators are better written to the number field.");
case ISSUESUBTITLE:
return Localization.lang("Subtitle of a specific issue of a journal or other periodical.");
case ISSUETITLE:
return Localization.lang("Title of a specific issue of a journal or other periodical.");
case JOURNALSUBTITLE:
return Localization.lang("Subtitle of a journal, a newspaper, or some other periodical.");
case JOURNALTITLE:
case JOURNAL:
return Localization.lang("Name of a journal, a newspaper, or some other periodical.");
case LABEL:
return Localization.lang("Designation to be used by the citation style as a substitute for the regular label if any data required to generate the regular label is missing.");
case LANGUAGE:
return Localization.lang("Language(s) of the work. Languages may be specified literally or as localisation keys.");
case LIBRARY:
return Localization.lang("Information such as a library name and a call number.");
case LOCATION:
case ADDRESS:
return Localization.lang("Place(s) of publication, i. e., the location of the publisher or institution, depending on the entry type.");
case MAINSUBTITLE:
return Localization.lang("Subtitle related to the \"Maintitle\".");
case MAINTITLE:
return Localization.lang("Main title of a multi-volume book, such as \"Collected Works\".");
case MAINTITLEADDON:
return Localization.lang("Annex to the \"Maintitle\", to be printed in a different font.");
case MONTH:
return Localization.lang("Publication month.");
case NAMEADDON:
return Localization.lang("Addon to be printed immediately after the author name in the bibliography.");
case NOTE:
return Localization.lang("Miscellaneous bibliographic data which does not fit into any other field.");
case NUMBER:
return Localization.lang("Number of a journal or the volume/number of a book in a series.");
case ORGANIZATION:
return Localization.lang("Organization(s) that published a manual or an online resource, or sponsored a conference.");
case ORIGDATE:
return Localization.lang("If the work is a translation, a reprint, or something similar, the publication date of the original edition.");
case ORIGLANGUAGE:
return Localization.lang("If the work is a translation, the language(s) of the original work.");
case PAGES:
return Localization.lang("One or more page numbers or page ranges.") + "\n" +
Localization.lang("If the work is published as part of another one, such as an article in a journal or a collection, this field holds the relevant page range in that other work. It may also be used to limit the reference to a specific part of a work (a chapter in a book, for example). For papers in electronic journals with anon-classical pagination setup the eid field may be more suitable.");
case PAGETOTAL:
return Localization.lang("Total number of pages of the work.");
case PAGINATION:
return Localization.lang("Pagination of the work. The key should be given in the singular form.");
case PART:
return Localization.lang("Number of a partial volume. This field applies to books only, not to journals. It may be used when a logical volume consists of two or more physical ones.");
case PUBLISHER:
return Localization.lang("Name(s) of the publisher(s).");
case PUBSTATE:
return Localization.lang("Publication state of the work, e. g., \"in press\".");
case SERIES:
return Localization.lang("Name of a publication series, such as \"Studies in...\", or the number of a journal series.");
case SHORTTITLE:
return Localization.lang("Title in an abridged form.");
case SUBTITLE:
return Localization.lang("Subtitle of the work.");
case TITLE:
return Localization.lang("Title of the work.");
case TITLEADDON:
return Localization.lang("Annex to the \"Title\", to be printed in a different font.");
case TRANSLATOR:
return Localization.lang("Translator(s) of the \"Title\" or \"Booktitle\", depending on the entry type. If the translator is identical to the \"Editor\", the standard styles will automatically concatenate these fields in the bibliography.");
case TYPE:
return Localization.lang("Type of a \"Manual\", \"Patent\", \"Report\", or \"Thesis\".");
case URL:
return Localization.lang("URL of an online publication.");
case URLDATE:
return Localization.lang("Access date of the address specified in the url field.");
case VENUE:
return Localization.lang("Location of a conference, a symposium, or some other event.");
case VERSION:
return Localization.lang("Revision number of a piece of software, a manual, etc.");
case VOLUME:
return Localization.lang("Volume of a multi-volume book or a periodical.");
case VOLUMES:
return Localization.lang("Total number of volumes of a multi-volume work.");
case YEAR:
return Localization.lang("Year of publication.");
case CROSSREF:
return Localization.lang("This field holds an entry key for the cross-referencing feature. Child entries with a \"Crossref\" field inherit data from the parent entry specified in the \"Crossref\" field.");
case GENDER:
return Localization.lang("Gender of the author or gender of the editor, if there is no author.");
case KEYWORDS:
return Localization.lang("Separated list of keywords.");
case RELATED:
return Localization.lang("Citation keys of other entries which have a relationship to this entry.");
case XREF:
return Localization.lang("This field is an alternative cross-referencing mechanism. It differs from \"Crossref\" in that the child entry will not inherit any data from the parent entry specified in the \"Xref\" field.");
case GROUPS:
return Localization.lang("Name(s) of the (manual) groups the entry belongs to.");
case OWNER:
return Localization.lang("Owner/creator of this entry.");
case TIMESTAMP:
return Localization.lang("Timestamp of this entry, when it has been created or last modified.");
}
} else if (field instanceof InternalField internalField) {
switch (internalField) {
case KEY_FIELD:
return Localization.lang("Key by which the work may be cited.");
}
} else if (field instanceof SpecialField specialField) {
switch (specialField) {
case PRINTED:
return Localization.lang("User-specific printed flag, in case the entry has been printed.");
case PRIORITY:
return Localization.lang("User-specific priority.");
case QUALITY:
return Localization.lang("User-specific quality flag, in case its quality is assured.");
case RANKING:
return Localization.lang("User-specific ranking.");
case READ_STATUS:
return Localization.lang("User-specific read status.");
case RELEVANCE:
return Localization.lang("User-specific relevance flag, in case the entry is relevant.");
}
}
return "";
}
}
| 16,640
| 65.564
| 423
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/GenderEditorViewModel.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 GenderEditorViewModel extends MapBasedEditorViewModel<String> {
private final BiMap<String, String> itemMap = HashBiMap.create(7);
public GenderEditorViewModel(Field field, SuggestionProvider<?> suggestionProvider, FieldCheckers fieldCheckers) {
super(field, suggestionProvider, fieldCheckers);
itemMap.put("sf", Localization.lang("Female name"));
itemMap.put("sm", Localization.lang("Male name"));
itemMap.put("sn", Localization.lang("Neuter name"));
itemMap.put("pf", Localization.lang("Female names"));
itemMap.put("pm", Localization.lang("Male names"));
itemMap.put("pn", Localization.lang("Neuter names"));
itemMap.put("pp", Localization.lang("Mixed names"));
}
@Override
protected BiMap<String, String> getItemMap() {
return itemMap;
}
@Override
public String convertToDisplayText(String object) {
return object;
}
}
| 1,272
| 33.405405
| 118
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/GroupEditor.java
|
package org.jabref.gui.fieldeditors;
import java.util.List;
import java.util.Optional;
import javafx.scene.input.TransferMode;
import org.jabref.gui.DragAndDropDataFormats;
import org.jabref.gui.autocompleter.SuggestionProvider;
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.preferences.PreferencesService;
public class GroupEditor extends SimpleEditor {
private Optional<BibEntry> bibEntry;
public GroupEditor(final Field field,
final SuggestionProvider<?> suggestionProvider,
final FieldCheckers fieldCheckers,
final PreferencesService preferences,
final boolean isMultiLine) {
super(field, suggestionProvider, fieldCheckers, preferences, isMultiLine);
this.setOnDragOver(event -> {
if (event.getDragboard().hasContent(DragAndDropDataFormats.GROUP)) {
event.acceptTransferModes(TransferMode.MOVE);
}
event.consume();
});
this.setOnDragDropped(event -> {
boolean success = false;
if (event.getDragboard().hasContent(DragAndDropDataFormats.GROUP)) {
List<String> draggedGroups = (List<String>) event.getDragboard().getContent(DragAndDropDataFormats.GROUP);
if (bibEntry.isPresent() && draggedGroups.get(0) != null) {
String newGroup = bibEntry.map(entry -> entry.getField(StandardField.GROUPS)
.map(oldGroups -> oldGroups + (preferences.getBibEntryPreferences().getKeywordSeparator()) + (draggedGroups.get(0)))
.orElse(draggedGroups.get(0)))
.orElse(null);
bibEntry.map(entry -> entry.setField(StandardField.GROUPS, newGroup));
success = true;
}
}
event.setDropCompleted(success);
event.consume();
});
}
@Override
public void bindToEntry(BibEntry entry) {
super.bindToEntry(entry);
this.bibEntry = Optional.of(entry);
}
}
| 2,366
| 39.810345
| 185
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/JournalEditor.java
|
package org.jabref.gui.fieldeditors;
import javafx.fxml.FXML;
import javafx.scene.Parent;
import javafx.scene.layout.HBox;
import org.jabref.gui.autocompleter.AutoCompletionTextInputBinding;
import org.jabref.gui.autocompleter.SuggestionProvider;
import org.jabref.gui.fieldeditors.contextmenu.DefaultMenu;
import org.jabref.logic.integrity.FieldCheckers;
import org.jabref.logic.journals.JournalAbbreviationRepository;
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 JournalEditor extends HBox implements FieldEditorFX {
@FXML private JournalEditorViewModel viewModel;
@FXML private EditorTextField textField;
public JournalEditor(Field field,
JournalAbbreviationRepository journalAbbreviationRepository,
PreferencesService preferences,
SuggestionProvider<?> suggestionProvider,
FieldCheckers fieldCheckers) {
this.viewModel = new JournalEditorViewModel(field, suggestionProvider, journalAbbreviationRepository, fieldCheckers);
ViewLoader.view(this)
.root(this)
.load();
textField.textProperty().bindBidirectional(viewModel.textProperty());
textField.initContextMenu(new DefaultMenu(textField));
AutoCompletionTextInputBinding.autoComplete(textField, viewModel::complete);
new EditorValidator(preferences).configureValidation(viewModel.getFieldValidator().getValidationStatus(), textField);
}
public JournalEditorViewModel getViewModel() {
return viewModel;
}
@Override
public void bindToEntry(BibEntry entry) {
viewModel.bindToEntry(entry);
}
@Override
public Parent getNode() {
return this;
}
@FXML
private void toggleAbbreviation() {
viewModel.toggleAbbreviation();
}
}
| 2,012
| 32
| 125
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/JournalEditorViewModel.java
|
package org.jabref.gui.fieldeditors;
import org.jabref.gui.autocompleter.SuggestionProvider;
import org.jabref.logic.integrity.FieldCheckers;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.model.entry.field.Field;
import org.jabref.model.strings.StringUtil;
public class JournalEditorViewModel extends AbstractEditorViewModel {
private final JournalAbbreviationRepository journalAbbreviationRepository;
public JournalEditorViewModel(Field field, SuggestionProvider<?> suggestionProvider, JournalAbbreviationRepository journalAbbreviationRepository, FieldCheckers fieldCheckers) {
super(field, suggestionProvider, fieldCheckers);
this.journalAbbreviationRepository = journalAbbreviationRepository;
}
public void toggleAbbreviation() {
if (StringUtil.isBlank(text.get())) {
return;
}
// Ignore brackets when matching abbreviations.
final String name = StringUtil.ignoreCurlyBracket(text.get());
journalAbbreviationRepository.getNextAbbreviation(name).ifPresent(nextAbbreviation -> {
text.set(nextAbbreviation);
// TODO: Add undo
// panel.getUndoManager().addEdit(new UndoableFieldChange(entry, editor.getName(), text, nextAbbreviation));
});
}
}
| 1,317
| 40.1875
| 180
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/KeywordsEditor.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 KeywordsEditor extends SimpleEditor implements FieldEditorFX {
public KeywordsEditor(Field field,
SuggestionProvider<?> suggestionProvider,
FieldCheckers fieldCheckers,
PreferencesService preferences) {
super(field, suggestionProvider, fieldCheckers, preferences);
}
@Override
public double getWeight() {
return 2;
}
}
| 685
| 30.181818
| 75
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/LinkedEntriesEditor.java
|
package org.jabref.gui.fieldeditors;
import java.util.Comparator;
import java.util.stream.Collectors;
import javafx.beans.binding.Bindings;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.HBox;
import org.jabref.gui.ClipBoardManager;
import org.jabref.gui.DialogService;
import org.jabref.gui.JabRefDialogService;
import org.jabref.gui.actions.ActionFactory;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.actions.StandardActions;
import org.jabref.gui.autocompleter.SuggestionProvider;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.keyboard.KeyBindingRepository;
import org.jabref.gui.util.ViewModelListCellFactory;
import org.jabref.logic.integrity.FieldCheckers;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.ParsedEntryLink;
import org.jabref.model.entry.field.Field;
import com.airhacks.afterburner.views.ViewLoader;
import com.dlsc.gemsfx.TagsField;
import jakarta.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LinkedEntriesEditor extends HBox implements FieldEditorFX {
private static final Logger LOGGER = LoggerFactory.getLogger(LinkedEntriesEditor.class);
@FXML public TagsField<ParsedEntryLink> entryLinkField;
@Inject private DialogService dialogService;
@Inject private ClipBoardManager clipBoardManager;
@Inject private KeyBindingRepository keyBindingRepository;
private final LinkedEntriesEditorViewModel viewModel;
public LinkedEntriesEditor(Field field, BibDatabaseContext databaseContext, SuggestionProvider<BibEntry> suggestionProvider, FieldCheckers fieldCheckers) {
ViewLoader.view(this)
.root(this)
.load();
this.viewModel = new LinkedEntriesEditorViewModel(field, suggestionProvider, databaseContext, fieldCheckers);
entryLinkField.setCellFactory(new ViewModelListCellFactory<ParsedEntryLink>().withText(ParsedEntryLink::getKey));
// Mind the .collect(Collectors.toList()) as the list needs to be mutable
entryLinkField.setSuggestionProvider(request ->
suggestionProvider.getPossibleSuggestions().stream()
.filter(suggestion -> suggestion.getCitationKey().orElse("").toLowerCase()
.contains(request.getUserText().toLowerCase()))
.map(ParsedEntryLink::new)
.collect(Collectors.toList()));
entryLinkField.setTagViewFactory(this::createTag);
entryLinkField.setConverter(viewModel.getStringConverter());
entryLinkField.setNewItemProducer(searchText -> viewModel.getStringConverter().fromString(searchText));
entryLinkField.setMatcher((entryLink, searchText) -> entryLink.getKey().toLowerCase().startsWith(searchText.toLowerCase()));
entryLinkField.setComparator(Comparator.comparing(ParsedEntryLink::getKey));
entryLinkField.setShowSearchIcon(false);
entryLinkField.getEditor().getStyleClass().clear();
entryLinkField.getEditor().getStyleClass().add("tags-field-editor");
Bindings.bindContentBidirectional(entryLinkField.getTags(), viewModel.linkedEntriesProperty());
}
private Node createTag(ParsedEntryLink entryLink) {
Label tagLabel = new Label();
tagLabel.setText(entryLinkField.getConverter().toString(entryLink));
tagLabel.setGraphic(IconTheme.JabRefIcons.REMOVE_TAGS.getGraphicNode());
tagLabel.getGraphic().setOnMouseClicked(event -> entryLinkField.removeTags(entryLink));
tagLabel.setContentDisplay(ContentDisplay.RIGHT);
tagLabel.setOnMouseClicked(event -> {
if (event.getClickCount() == 2 && event.getButton().equals(MouseButton.PRIMARY)) {
viewModel.jumpToEntry(entryLink);
}
});
ContextMenu contextMenu = new ContextMenu();
ActionFactory factory = new ActionFactory(keyBindingRepository);
contextMenu.getItems().addAll(
factory.createMenuItem(StandardActions.COPY, new TagContextAction(StandardActions.COPY, entryLink)),
factory.createMenuItem(StandardActions.CUT, new TagContextAction(StandardActions.CUT, entryLink)),
factory.createMenuItem(StandardActions.DELETE, new TagContextAction(StandardActions.DELETE, entryLink))
);
tagLabel.setContextMenu(contextMenu);
return tagLabel;
}
public LinkedEntriesEditorViewModel getViewModel() {
return viewModel;
}
@Override
public void bindToEntry(BibEntry entry) {
viewModel.bindToEntry(entry);
}
@Override
public Parent getNode() {
return this;
}
private class TagContextAction extends SimpleCommand {
private final StandardActions command;
private final ParsedEntryLink entryLink;
public TagContextAction(StandardActions command, ParsedEntryLink entryLink) {
this.command = command;
this.entryLink = entryLink;
}
@Override
public void execute() {
switch (command) {
case COPY -> {
clipBoardManager.setContent(entryLink.getKey());
dialogService.notify(Localization.lang("Copied '%0' to clipboard.",
JabRefDialogService.shortenDialogMessage(entryLink.getKey())));
}
case CUT -> {
clipBoardManager.setContent(entryLink.getKey());
dialogService.notify(Localization.lang("Copied '%0' to clipboard.",
JabRefDialogService.shortenDialogMessage(entryLink.getKey())));
entryLinkField.removeTags(entryLink);
}
case DELETE ->
entryLinkField.removeTags(entryLink);
default ->
LOGGER.info("Action {} not defined", command.getText());
}
}
}
}
| 6,370
| 42.636986
| 159
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/LinkedEntriesEditorViewModel.java
|
package org.jabref.gui.fieldeditors;
import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.FXCollections;
import javafx.util.StringConverter;
import org.jabref.gui.autocompleter.SuggestionProvider;
import org.jabref.gui.util.BindingsHelper;
import org.jabref.logic.integrity.FieldCheckers;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.EntryLinkList;
import org.jabref.model.entry.ParsedEntryLink;
import org.jabref.model.entry.field.Field;
public class LinkedEntriesEditorViewModel extends AbstractEditorViewModel {
private final BibDatabaseContext databaseContext;
private final ListProperty<ParsedEntryLink> linkedEntries;
public LinkedEntriesEditorViewModel(Field field, SuggestionProvider<?> suggestionProvider, BibDatabaseContext databaseContext, FieldCheckers fieldCheckers) {
super(field, suggestionProvider, fieldCheckers);
this.databaseContext = databaseContext;
linkedEntries = new SimpleListProperty<>(FXCollections.observableArrayList());
BindingsHelper.bindContentBidirectional(
linkedEntries,
text,
EntryLinkList::serialize,
newText -> EntryLinkList.parse(newText, databaseContext.getDatabase()));
}
public ListProperty<ParsedEntryLink> linkedEntriesProperty() {
return linkedEntries;
}
public StringConverter<ParsedEntryLink> getStringConverter() {
return new StringConverter<>() {
@Override
public String toString(ParsedEntryLink linkedEntry) {
if (linkedEntry == null) {
return "";
}
return linkedEntry.getKey();
}
@Override
public ParsedEntryLink fromString(String key) {
return new ParsedEntryLink(key, databaseContext.getDatabase());
}
};
}
public void jumpToEntry(ParsedEntryLink parsedEntryLink) {
// TODO: Implement jump to entry
// TODO: Add toolitp for tag: Localization.lang("Jump to entry")
// This feature was removed while converting the linked entries editor to JavaFX
// Right now there is no nice way to re-implement it as we have no good interface to control the focus of the main table
// (except directly using the JabRefFrame class as below)
// parsedEntryLink.getLinkedEntry().ifPresent(
// e -> frame.getCurrentBasePanel().highlightEntry(e)
// );
}
}
| 2,588
| 38.830769
| 161
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/LinkedFileViewModel.java
|
package org.jabref.gui.fieldeditors;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.BiPredicate;
import java.util.function.Supplier;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;
import javafx.beans.Observable;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.ObjectBinding;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.Node;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.ButtonType;
import org.jabref.gui.AbstractViewModel;
import org.jabref.gui.DialogService;
import org.jabref.gui.desktop.JabRefDesktop;
import org.jabref.gui.externalfiles.FileDownloadTask;
import org.jabref.gui.externalfiletype.ExternalFileType;
import org.jabref.gui.externalfiletype.ExternalFileTypes;
import org.jabref.gui.externalfiletype.StandardExternalFileType;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.icon.JabRefIcon;
import org.jabref.gui.linkedfile.LinkedFileEditDialogView;
import org.jabref.gui.mergeentries.MultiMergeEntriesView;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.gui.util.ControlHelper;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.externalfiles.LinkedFileHandler;
import org.jabref.logic.importer.Importer;
import org.jabref.logic.importer.ParserResult;
import org.jabref.logic.importer.fileformat.PdfContentImporter;
import org.jabref.logic.importer.fileformat.PdfEmbeddedBibFileImporter;
import org.jabref.logic.importer.fileformat.PdfGrobidImporter;
import org.jabref.logic.importer.fileformat.PdfVerbatimBibTextImporter;
import org.jabref.logic.importer.fileformat.PdfXmpImporter;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.net.URLDownload;
import org.jabref.logic.util.io.FileNameUniqueness;
import org.jabref.logic.util.io.FileUtil;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.LinkedFile;
import org.jabref.model.strings.StringUtil;
import org.jabref.model.util.OptionalUtil;
import org.jabref.preferences.FilePreferences;
import org.jabref.preferences.PreferencesService;
import de.saxsys.mvvmfx.utils.validation.FunctionBasedValidator;
import de.saxsys.mvvmfx.utils.validation.ValidationMessage;
import de.saxsys.mvvmfx.utils.validation.ValidationStatus;
import de.saxsys.mvvmfx.utils.validation.Validator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LinkedFileViewModel extends AbstractViewModel {
private static final Logger LOGGER = LoggerFactory.getLogger(LinkedFileViewModel.class);
private final LinkedFile linkedFile;
private final BibDatabaseContext databaseContext;
private final DoubleProperty downloadProgress = new SimpleDoubleProperty(-1);
private final BooleanProperty downloadOngoing = new SimpleBooleanProperty(false);
private final BooleanProperty isAutomaticallyFound = new SimpleBooleanProperty(false);
private final BooleanProperty isOfflinePdf = new SimpleBooleanProperty(false);
private final DialogService dialogService;
private final BibEntry entry;
private final TaskExecutor taskExecutor;
private final PreferencesService preferences;
private final LinkedFileHandler linkedFileHandler;
private ObjectBinding<Node> linkedFileIconBinding;
private final Validator fileExistsValidator;
public LinkedFileViewModel(LinkedFile linkedFile,
BibEntry entry,
BibDatabaseContext databaseContext,
TaskExecutor taskExecutor,
DialogService dialogService,
PreferencesService preferences) {
this.linkedFile = linkedFile;
this.preferences = preferences;
this.linkedFileHandler = new LinkedFileHandler(linkedFile, entry, databaseContext, preferences.getFilePreferences());
this.databaseContext = databaseContext;
this.entry = entry;
this.dialogService = dialogService;
this.taskExecutor = taskExecutor;
fileExistsValidator = new FunctionBasedValidator<>(
linkedFile.linkProperty(),
link -> {
if (linkedFile.isOnlineLink()) {
return true;
} else {
Optional<Path> path = FileUtil.find(databaseContext, link, preferences.getFilePreferences());
return path.isPresent() && Files.exists(path.get());
}
},
ValidationMessage.warning(Localization.lang("Could not find file '%0'.", linkedFile.getLink())));
downloadOngoing.bind(downloadProgress.greaterThanOrEqualTo(0).and(downloadProgress.lessThan(1)));
isOfflinePdf.setValue(!linkedFile.isOnlineLink() && "pdf".equalsIgnoreCase(linkedFile.getFileType()));
}
public BooleanProperty isOfflinePdfProperty() {
return isOfflinePdf;
}
public boolean isAutomaticallyFound() {
return isAutomaticallyFound.get();
}
public BooleanProperty isAutomaticallyFoundProperty() {
return isAutomaticallyFound;
}
public BooleanProperty downloadOngoingProperty() {
return downloadOngoing;
}
public DoubleProperty downloadProgressProperty() {
return downloadProgress;
}
public StringProperty linkProperty() {
return linkedFile.linkProperty();
}
public StringProperty descriptionProperty() {
return linkedFile.descriptionProperty();
}
public String getDescription() {
return linkedFile.getDescription();
}
public String getDescriptionAndLink() {
if (StringUtil.isBlank(linkedFile.getDescription())) {
return linkedFile.getLink();
} else {
return linkedFile.getDescription() + " (" + linkedFile.getLink() + ")";
}
}
public String getTruncatedDescriptionAndLink() {
if (StringUtil.isBlank(linkedFile.getDescription())) {
return ControlHelper.truncateString(linkedFile.getLink(), -1, "...",
ControlHelper.EllipsisPosition.CENTER);
} else {
return ControlHelper.truncateString(linkedFile.getDescription(), -1, "...",
ControlHelper.EllipsisPosition.CENTER) + " (" +
ControlHelper.truncateString(linkedFile.getLink(), -1, "...",
ControlHelper.EllipsisPosition.CENTER) + ")";
}
}
public Optional<Path> findIn(List<Path> directories) {
return linkedFile.findIn(directories);
}
public JabRefIcon getTypeIcon() {
return ExternalFileTypes.getExternalFileTypeByLinkedFile(linkedFile, false, preferences.getFilePreferences())
.map(ExternalFileType::getIcon)
.orElse(IconTheme.JabRefIcons.FILE);
}
public ObjectBinding<Node> typeIconProperty() {
if (linkedFileIconBinding == null) {
linkedFileIconBinding = Bindings.createObjectBinding(() -> this.getTypeIcon().getGraphicNode(), linkedFile.fileTypeProperty());
}
return linkedFileIconBinding;
}
public void markAsAutomaticallyFound() {
isAutomaticallyFound.setValue(true);
}
public void acceptAsLinked() {
isAutomaticallyFound.setValue(false);
}
public Observable[] getObservables() {
List<Observable> observables = new ArrayList<>(Arrays.asList(linkedFile.getObservables()));
observables.add(downloadOngoing);
observables.add(downloadProgress);
observables.add(isAutomaticallyFound);
return observables.toArray(new Observable[0]);
}
public void open() {
try {
Optional<ExternalFileType> type = ExternalFileTypes.getExternalFileTypeByLinkedFile(linkedFile, true, preferences.getFilePreferences());
boolean successful = JabRefDesktop.openExternalFileAnyFormat(databaseContext, preferences, linkedFile.getLink(), type);
if (!successful) {
dialogService.showErrorDialogAndWait(Localization.lang("File not found"), Localization.lang("Could not find file '%0'.", linkedFile.getLink()));
}
} catch (IOException e) {
dialogService.showErrorDialogAndWait(Localization.lang("Error opening file '%0'.", linkedFile.getLink()), e);
}
}
public void openFolder() {
try {
if (!linkedFile.isOnlineLink()) {
Optional<Path> resolvedPath = FileUtil.find(
databaseContext,
linkedFile.getLink(),
preferences.getFilePreferences());
if (resolvedPath.isPresent()) {
JabRefDesktop.openFolderAndSelectFile(resolvedPath.get(), preferences, dialogService);
} else {
dialogService.showErrorDialogAndWait(Localization.lang("File not found"));
}
} else {
dialogService.showErrorDialogAndWait(Localization.lang("Cannot open folder as the file is an online link."));
}
} catch (IOException ex) {
LOGGER.debug("Cannot open folder", ex);
}
}
public void renameToSuggestion() {
renameFileToName(linkedFileHandler.getSuggestedFileName());
}
public void askForNameAndRename() {
String oldFile = this.linkedFile.getLink();
Path oldFilePath = Path.of(oldFile);
Optional<String> askedFileName = dialogService.showInputDialogWithDefaultAndWait(
Localization.lang("Rename file"),
Localization.lang("New Filename"),
oldFilePath.getFileName().toString());
askedFileName.ifPresent(this::renameFileToName);
}
public void renameFileToName(String targetFileName) {
if (linkedFile.isOnlineLink()) {
// Cannot rename remote links
return;
}
Optional<Path> file = linkedFile.findIn(databaseContext, preferences.getFilePreferences());
if (file.isPresent()) {
performRenameWithConflictCheck(targetFileName);
} else {
dialogService.showErrorDialogAndWait(Localization.lang("File not found"), Localization.lang("Could not find file '%0'.", linkedFile.getLink()));
}
}
private void performRenameWithConflictCheck(String targetFileName) {
Optional<Path> existingFile = linkedFileHandler.findExistingFile(linkedFile, entry, targetFileName);
boolean overwriteFile = false;
if (existingFile.isPresent()) {
overwriteFile = dialogService.showConfirmationDialogAndWait(
Localization.lang("File exists"),
Localization.lang("'%0' exists. Overwrite file?", targetFileName),
Localization.lang("Overwrite"));
if (!overwriteFile) {
return;
}
}
try {
linkedFileHandler.renameToName(targetFileName, overwriteFile);
} catch (IOException e) {
dialogService.showErrorDialogAndWait(Localization.lang("Rename failed"), Localization.lang("JabRef cannot access the file because it is being used by another process."));
}
}
public void moveToDefaultDirectory() {
if (linkedFile.isOnlineLink()) {
// Cannot move remote links
return;
}
// Get target folder
Optional<Path> fileDir = databaseContext.getFirstExistingFileDir(preferences.getFilePreferences());
if (fileDir.isEmpty()) {
dialogService.showErrorDialogAndWait(Localization.lang("Move file"), Localization.lang("File directory is not set or does not exist!"));
return;
}
Optional<Path> file = linkedFile.findIn(databaseContext, preferences.getFilePreferences());
if (file.isPresent()) {
// Found the linked file, so move it
try {
linkedFileHandler.moveToDefaultDirectory();
} catch (IOException exception) {
dialogService.showErrorDialogAndWait(
Localization.lang("Move file"),
Localization.lang("Could not move file '%0'.", file.get().toString()),
exception);
}
} else {
// File doesn't exist, so we can't move it.
dialogService.showErrorDialogAndWait(Localization.lang("File not found"), Localization.lang("Could not find file '%0'.", linkedFile.getLink()));
}
}
/**
* Gets the filename for the current linked file and compares it to the new suggested filename.
*
* @return true if the suggested filename is same as current filename.
*/
public boolean isGeneratedNameSameAsOriginal() {
Path file = Path.of(this.linkedFile.getLink());
String currentFileName = file.getFileName().toString();
String suggestedFileName = this.linkedFileHandler.getSuggestedFileName();
return currentFileName.equals(suggestedFileName);
}
/**
* Compares suggested directory of current linkedFile with existing filepath directory.
*
* @return true if suggested filepath is same as existing filepath.
*/
public boolean isGeneratedPathSameAsOriginal() {
FilePreferences filePreferences = preferences.getFilePreferences();
Optional<Path> baseDir = databaseContext.getFirstExistingFileDir(filePreferences);
if (baseDir.isEmpty()) {
// could not find default path
return false;
}
// append File directory pattern if exits
String targetDirectoryName = FileUtil.createDirNameFromPattern(
databaseContext.getDatabase(),
entry,
filePreferences.getFileDirectoryPattern());
Optional<Path> targetDir = baseDir.map(dir -> dir.resolve(targetDirectoryName));
Optional<Path> currentDir = linkedFile.findIn(databaseContext, preferences.getFilePreferences()).map(Path::getParent);
if (currentDir.isEmpty()) {
// Could not find file
return false;
}
BiPredicate<Path, Path> equality = (fileA, fileB) -> {
try {
return Files.isSameFile(fileA, fileB);
} catch (IOException e) {
return false;
}
};
return OptionalUtil.equals(targetDir, currentDir, equality);
}
public void moveToDefaultDirectoryAndRename() {
moveToDefaultDirectory();
renameToSuggestion();
}
/**
* Asks the user for confirmation that he really wants to the delete the file from disk (or just remove the link).
*
* @return true if the linked file should be removed afterwards from the entry (i.e because it was deleted
* successfully, does not exist in the first place or the user choose to remove it)
*/
public boolean delete() {
Optional<Path> file = linkedFile.findIn(databaseContext, preferences.getFilePreferences());
if (file.isEmpty()) {
LOGGER.warn("Could not find file {}", linkedFile.getLink());
return true;
}
ButtonType removeFromEntry = new ButtonType(Localization.lang("Remove from entry"), ButtonData.YES);
ButtonType deleteFromEntry = new ButtonType(Localization.lang("Delete from disk"));
Optional<ButtonType> buttonType = dialogService.showCustomButtonDialogAndWait(AlertType.INFORMATION,
Localization.lang("Delete '%0'", file.get().getFileName().toString()),
Localization.lang("Delete '%0' permanently from disk, or just remove the file from the entry? Pressing Delete will delete the file permanently from disk.", file.get().toString()),
removeFromEntry, deleteFromEntry, ButtonType.CANCEL);
if (buttonType.isPresent()) {
if (buttonType.get().equals(removeFromEntry)) {
return true;
}
if (buttonType.get().equals(deleteFromEntry)) {
try {
Files.delete(file.get());
return true;
} catch (IOException ex) {
dialogService.showErrorDialogAndWait(Localization.lang("Cannot delete file"), Localization.lang("File permission error"));
LOGGER.warn("File permission error while deleting: {}", linkedFile, ex);
}
}
}
return false;
}
public void edit() {
Optional<LinkedFile> editedFile = dialogService.showCustomDialogAndWait(new LinkedFileEditDialogView(this.linkedFile));
editedFile.ifPresent(file -> {
this.linkedFile.setLink(file.getLink());
this.linkedFile.setDescription(file.getDescription());
this.linkedFile.setFileType(file.getFileType());
});
}
public WriteMetadataToPdfCommand createWriteMetadataToPdfCommand() {
return new WriteMetadataToPdfCommand(linkedFile, databaseContext, preferences, dialogService, entry, LOGGER, taskExecutor);
}
public void download() {
if (!linkedFile.isOnlineLink()) {
throw new UnsupportedOperationException("In order to download the file it has to be an online link");
}
try {
Optional<Path> targetDirectory = databaseContext.getFirstExistingFileDir(preferences.getFilePreferences());
if (targetDirectory.isEmpty()) {
dialogService.showErrorDialogAndWait(Localization.lang("Download file"), Localization.lang("File directory is not set or does not exist!"));
return;
}
URLDownload urlDownload = new URLDownload(linkedFile.getLink());
if (!checkSSLHandshake(urlDownload)) {
return;
}
BackgroundTask<Path> downloadTask = prepareDownloadTask(targetDirectory.get(), urlDownload);
downloadTask.onSuccess(destination -> {
boolean isDuplicate;
try {
isDuplicate = FileNameUniqueness.isDuplicatedFile(targetDirectory.get(), destination.getFileName(), dialogService);
} catch (IOException e) {
LOGGER.error("FileNameUniqueness.isDuplicatedFile failed", e);
return;
}
if (!isDuplicate) {
// we need to call LinkedFileViewModel#fromFile, because we need to make the path relative to the configured directories
LinkedFile newLinkedFile = LinkedFilesEditorViewModel.fromFile(
destination,
databaseContext.getFileDirectories(preferences.getFilePreferences()),
preferences.getFilePreferences());
entry.replaceDownloadedFile(linkedFile.getLink(), newLinkedFile);
// Notify in bar when the file type is HTML.
if (newLinkedFile.getFileType().equals(StandardExternalFileType.URL.getName())) {
dialogService.notify(Localization.lang("Downloaded website as an HTML file."));
LOGGER.debug("Downloaded website {} as an HTML file at {}", linkedFile.getLink(), destination);
}
}
});
downloadProgress.bind(downloadTask.workDonePercentageProperty());
downloadTask.titleProperty().set(Localization.lang("Downloading"));
downloadTask.messageProperty().set(
Localization.lang("Fulltext for") + ": " + entry.getCitationKey().orElse(Localization.lang("New entry")));
downloadTask.showToUser(true);
downloadTask.onFailure(ex -> {
LOGGER.error("Error downloading", ex);
dialogService.showErrorDialogAndWait(Localization.lang("Error downloading"), ex);
});
taskExecutor.execute(downloadTask);
} catch (MalformedURLException exception) {
dialogService.showErrorDialogAndWait(Localization.lang("Invalid URL"), exception);
}
}
public boolean checkSSLHandshake(URLDownload urlDownload) {
try {
urlDownload.canBeReached();
} catch (kong.unirest.UnirestException ex) {
if (ex.getCause() instanceof javax.net.ssl.SSLHandshakeException) {
if (dialogService.showConfirmationDialogAndWait(Localization.lang("Download file"),
Localization.lang("Unable to find valid certification path to requested target(%0), download anyway?",
urlDownload.getSource().toString()))) {
return true;
} else {
dialogService.notify(Localization.lang("Download operation canceled."));
return false;
}
} else {
LOGGER.error("Error while checking if the file can be downloaded", ex);
dialogService.notify(Localization.lang("Error downloading"));
return false;
}
}
return true;
}
public BackgroundTask<Path> prepareDownloadTask(Path targetDirectory, URLDownload urlDownload) {
SSLSocketFactory defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
HostnameVerifier defaultHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
BackgroundTask<Path> downloadTask = BackgroundTask
.wrap(() -> {
Optional<ExternalFileType> suggestedType = inferFileType(urlDownload);
ExternalFileType externalFileType = suggestedType.orElse(StandardExternalFileType.PDF);
String suggestedName = linkedFileHandler.getSuggestedFileName(externalFileType.getExtension());
String fulltextDir = FileUtil.createDirNameFromPattern(databaseContext.getDatabase(), entry, preferences.getFilePreferences().getFileDirectoryPattern());
suggestedName = FileNameUniqueness.getNonOverWritingFileName(targetDirectory.resolve(fulltextDir), suggestedName);
return targetDirectory.resolve(fulltextDir).resolve(suggestedName);
})
.then(destination -> new FileDownloadTask(urlDownload.getSource(), destination))
.onFinished(() -> URLDownload.setSSLVerification(defaultSSLSocketFactory, defaultHostnameVerifier));
return downloadTask;
}
private Optional<ExternalFileType> inferFileType(URLDownload urlDownload) {
Optional<ExternalFileType> suggestedType = inferFileTypeFromMimeType(urlDownload);
// If we did not find a file type from the MIME type, try based on extension:
if (suggestedType.isEmpty()) {
suggestedType = inferFileTypeFromURL(urlDownload.getSource().toExternalForm());
}
return suggestedType;
}
private Optional<ExternalFileType> inferFileTypeFromMimeType(URLDownload urlDownload) {
String mimeType = urlDownload.getMimeType();
if (mimeType != null) {
LOGGER.debug("MIME Type suggested: " + mimeType);
return ExternalFileTypes.getExternalFileTypeByMimeType(mimeType, preferences.getFilePreferences());
} else {
return Optional.empty();
}
}
private Optional<ExternalFileType> inferFileTypeFromURL(String url) {
return URLUtil.getSuffix(url, preferences.getFilePreferences())
.flatMap(extension -> ExternalFileTypes.getExternalFileTypeByExt(extension, preferences.getFilePreferences()));
}
public LinkedFile getFile() {
return linkedFile;
}
public ValidationStatus fileExistsValidationStatus() {
return fileExistsValidator.getValidationStatus();
}
public void parsePdfMetadataAndShowMergeDialog() {
linkedFile.findIn(databaseContext, preferences.getFilePreferences()).ifPresent(filePath -> {
MultiMergeEntriesView dialog = new MultiMergeEntriesView(preferences, taskExecutor);
dialog.setTitle(Localization.lang("Merge PDF metadata"));
dialog.addSource(Localization.lang("Entry"), entry);
dialog.addSource(Localization.lang("Verbatim"), wrapImporterToSupplier(new PdfVerbatimBibTextImporter(preferences.getImportFormatPreferences()), filePath));
dialog.addSource(Localization.lang("Embedded"), wrapImporterToSupplier(new PdfEmbeddedBibFileImporter(preferences.getImportFormatPreferences()), filePath));
if (preferences.getGrobidPreferences().isGrobidEnabled()) {
dialog.addSource("Grobid", wrapImporterToSupplier(new PdfGrobidImporter(preferences.getImportFormatPreferences()), filePath));
}
dialog.addSource(Localization.lang("XMP metadata"), wrapImporterToSupplier(new PdfXmpImporter(preferences.getXmpPreferences()), filePath));
dialog.addSource(Localization.lang("Content"), wrapImporterToSupplier(new PdfContentImporter(preferences.getImportFormatPreferences()), filePath));
dialogService.showCustomDialogAndWait(dialog).ifPresent(newEntry -> {
databaseContext.getDatabase().removeEntry(entry);
databaseContext.getDatabase().insertEntry(newEntry);
});
});
}
private Supplier<BibEntry> wrapImporterToSupplier(Importer importer, Path filePath) {
return () -> {
try {
ParserResult parserResult = importer.importDatabase(filePath);
if (parserResult.isInvalid() || parserResult.isEmpty() || !parserResult.getDatabase().hasEntries()) {
return null;
}
return parserResult.getDatabase().getEntries().get(0);
} catch (IOException e) {
return null;
}
};
}
}
| 26,604
| 44.01692
| 195
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/LinkedFilesEditor.java
|
package org.jabref.gui.fieldeditors;
import java.util.Optional;
import javafx.beans.binding.Bindings;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.ObservableList;
import javafx.css.PseudoClass;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.OverrunStyle;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.Tooltip;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.text.Text;
import org.jabref.gui.DialogService;
import org.jabref.gui.DragAndDropDataFormats;
import org.jabref.gui.Globals;
import org.jabref.gui.actions.ActionFactory;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.actions.StandardActions;
import org.jabref.gui.autocompleter.SuggestionProvider;
import org.jabref.gui.copyfiles.CopySingleFileAction;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.icon.JabRefIconView;
import org.jabref.gui.importer.GrobidOptInDialogHelper;
import org.jabref.gui.keyboard.KeyBinding;
import org.jabref.gui.linkedfile.DeleteFileAction;
import org.jabref.gui.util.BindingsHelper;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.gui.util.ViewModelListCellFactory;
import org.jabref.gui.util.uithreadaware.UiThreadObservableList;
import org.jabref.logic.integrity.FieldCheckers;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.LinkedFile;
import org.jabref.model.entry.field.Field;
import org.jabref.preferences.PreferencesService;
import com.airhacks.afterburner.views.ViewLoader;
import com.tobiasdiez.easybind.EasyBind;
import com.tobiasdiez.easybind.optional.ObservableOptionalValue;
import jakarta.inject.Inject;
public class LinkedFilesEditor extends HBox implements FieldEditorFX {
@FXML private ListView<LinkedFileViewModel> listView;
@FXML private JabRefIconView fulltextFetcher;
private final Field field;
private final BibDatabaseContext databaseContext;
private final SuggestionProvider<?> suggestionProvider;
private final FieldCheckers fieldCheckers;
@Inject private DialogService dialogService;
@Inject private PreferencesService preferencesService;
@Inject private TaskExecutor taskExecutor;
private LinkedFilesEditorViewModel viewModel;
private ObservableOptionalValue<BibEntry> bibEntry = EasyBind.wrapNullable(new SimpleObjectProperty<>());
private final UiThreadObservableList<LinkedFileViewModel> decoratedModelList;
public LinkedFilesEditor(Field field,
BibDatabaseContext databaseContext,
SuggestionProvider<?> suggestionProvider,
FieldCheckers fieldCheckers) {
this.field = field;
this.databaseContext = databaseContext;
this.suggestionProvider = suggestionProvider;
this.fieldCheckers = fieldCheckers;
ViewLoader.view(this)
.root(this)
.load();
decoratedModelList = new UiThreadObservableList<>(viewModel.filesProperty());
Bindings.bindContentBidirectional(listView.itemsProperty().get(), decoratedModelList);
}
@FXML
private void initialize() {
this.viewModel = new LinkedFilesEditorViewModel(field, suggestionProvider, dialogService, databaseContext, taskExecutor, fieldCheckers, preferencesService);
new ViewModelListCellFactory<LinkedFileViewModel>()
.withStringTooltip(LinkedFileViewModel::getDescriptionAndLink)
.withGraphic(this::createFileDisplay)
.withContextMenu(this::createContextMenuForFile)
.withOnMouseClickedEvent(this::handleItemMouseClick)
.setOnDragDetected(this::handleOnDragDetected)
.setOnDragDropped(this::handleOnDragDropped)
.setOnDragOver(this::handleOnDragOver)
.withValidation(LinkedFileViewModel::fileExistsValidationStatus)
.install(listView);
listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
fulltextFetcher.visibleProperty().bind(viewModel.fulltextLookupInProgressProperty().not());
setUpKeyBindings();
}
private void handleOnDragOver(LinkedFileViewModel originalItem, DragEvent event) {
if ((event.getGestureSource() != originalItem) && event.getDragboard().hasContent(DragAndDropDataFormats.LINKED_FILE)) {
event.acceptTransferModes(TransferMode.MOVE);
}
}
private void handleOnDragDetected(@SuppressWarnings("unused") LinkedFileViewModel linkedFile, MouseEvent event) {
LinkedFile selectedItem = listView.getSelectionModel().getSelectedItem().getFile();
if (selectedItem != null) {
ClipboardContent content = new ClipboardContent();
Dragboard dragboard = listView.startDragAndDrop(TransferMode.MOVE);
// We have to use the model class here, as the content of the dragboard must be serializable
content.put(DragAndDropDataFormats.LINKED_FILE, selectedItem);
dragboard.setContent(content);
}
event.consume();
}
private void handleOnDragDropped(LinkedFileViewModel originalItem, DragEvent event) {
Dragboard dragboard = event.getDragboard();
boolean success = false;
ObservableList<LinkedFileViewModel> items = listView.itemsProperty().get();
if (dragboard.hasContent(DragAndDropDataFormats.LINKED_FILE)) {
LinkedFile linkedFile = (LinkedFile) dragboard.getContent(DragAndDropDataFormats.LINKED_FILE);
LinkedFileViewModel transferredItem = null;
int draggedIdx = 0;
for (int i = 0; i < items.size(); i++) {
if (items.get(i).getFile().equals(linkedFile)) {
draggedIdx = i;
transferredItem = items.get(i);
break;
}
}
int thisIdx = items.indexOf(originalItem);
items.set(draggedIdx, originalItem);
items.set(thisIdx, transferredItem);
success = true;
}
event.setDropCompleted(success);
event.consume();
}
private Node createFileDisplay(LinkedFileViewModel linkedFile) {
PseudoClass opacity = PseudoClass.getPseudoClass("opacity");
Node icon = linkedFile.getTypeIcon().getGraphicNode();
icon.setOnMouseClicked(event -> linkedFile.open());
Text link = new Text();
link.textProperty().bind(linkedFile.linkProperty());
link.getStyleClass().setAll("file-row-text");
EasyBind.subscribe(linkedFile.isAutomaticallyFoundProperty(), found -> link.pseudoClassStateChanged(opacity, found));
Text desc = new Text();
desc.textProperty().bind(linkedFile.descriptionProperty());
desc.getStyleClass().setAll("file-row-text");
ProgressBar progressIndicator = new ProgressBar();
progressIndicator.progressProperty().bind(linkedFile.downloadProgressProperty());
progressIndicator.visibleProperty().bind(linkedFile.downloadOngoingProperty());
Label label = new Label();
label.graphicProperty().bind(linkedFile.typeIconProperty());
label.textProperty().bind(linkedFile.linkProperty());
label.getStyleClass().setAll("file-row-text");
label.textOverrunProperty().setValue(OverrunStyle.LEADING_ELLIPSIS);
EasyBind.subscribe(linkedFile.isAutomaticallyFoundProperty(), found -> label.pseudoClassStateChanged(opacity, found));
HBox info = new HBox(8);
HBox.setHgrow(info, Priority.ALWAYS);
info.setStyle("-fx-padding: 0.5em 0 0.5em 0;"); // To align with buttons below which also have 0.5em padding
info.getChildren().setAll(label, progressIndicator);
Button acceptAutoLinkedFile = IconTheme.JabRefIcons.AUTO_LINKED_FILE.asButton();
acceptAutoLinkedFile.setTooltip(new Tooltip(Localization.lang("This file was found automatically. Do you want to link it to this entry?")));
acceptAutoLinkedFile.visibleProperty().bind(linkedFile.isAutomaticallyFoundProperty());
acceptAutoLinkedFile.managedProperty().bind(linkedFile.isAutomaticallyFoundProperty());
acceptAutoLinkedFile.setOnAction(event -> linkedFile.acceptAsLinked());
acceptAutoLinkedFile.getStyleClass().setAll("icon-button");
Button writeMetadataToPdf = IconTheme.JabRefIcons.PDF_METADATA_WRITE.asButton();
writeMetadataToPdf.setTooltip(new Tooltip(Localization.lang("Write BibTeXEntry metadata to PDF.")));
writeMetadataToPdf.visibleProperty().bind(linkedFile.isOfflinePdfProperty());
writeMetadataToPdf.getStyleClass().setAll("icon-button");
WriteMetadataToPdfCommand writeMetadataToPdfCommand = linkedFile.createWriteMetadataToPdfCommand();
writeMetadataToPdf.disableProperty().bind(writeMetadataToPdfCommand.executableProperty().not());
writeMetadataToPdf.setOnAction(event -> writeMetadataToPdfCommand.execute());
Button parsePdfMetadata = IconTheme.JabRefIcons.PDF_METADATA_READ.asButton();
parsePdfMetadata.setTooltip(new Tooltip(Localization.lang("Parse Metadata from PDF.")));
parsePdfMetadata.visibleProperty().bind(linkedFile.isOfflinePdfProperty());
parsePdfMetadata.setOnAction(event -> {
GrobidOptInDialogHelper.showAndWaitIfUserIsUndecided(dialogService, preferencesService.getGrobidPreferences());
linkedFile.parsePdfMetadataAndShowMergeDialog();
});
parsePdfMetadata.getStyleClass().setAll("icon-button");
HBox container = new HBox(2);
container.setPrefHeight(Double.NEGATIVE_INFINITY);
container.maxWidthProperty().bind(listView.widthProperty().subtract(20d));
container.getChildren().addAll(acceptAutoLinkedFile, info, writeMetadataToPdf, parsePdfMetadata);
return container;
}
private void setUpKeyBindings() {
listView.addEventFilter(KeyEvent.KEY_PRESSED, event -> {
Optional<KeyBinding> keyBinding = Globals.getKeyPrefs().mapToKeyBinding(event);
if (keyBinding.isPresent()) {
switch (keyBinding.get()) {
case DELETE_ENTRY:
new DeleteFileAction(dialogService, preferencesService, databaseContext,
viewModel, listView).execute();
event.consume();
break;
default:
// Pass other keys to children
}
}
});
}
public LinkedFilesEditorViewModel getViewModel() {
return viewModel;
}
@Override
public void bindToEntry(BibEntry entry) {
bibEntry = EasyBind.wrapNullable(new SimpleObjectProperty<>(entry));
viewModel.bindToEntry(entry);
}
@Override
public Parent getNode() {
return this;
}
@FXML
private void addNewFile() {
viewModel.addNewFile();
}
@FXML
private void fetchFulltext() {
viewModel.fetchFulltext();
}
@FXML
private void addFromURL() {
viewModel.addFromURL();
}
private void handleItemMouseClick(LinkedFileViewModel linkedFile, MouseEvent event) {
if (event.getButton().equals(MouseButton.PRIMARY) && (event.getClickCount() == 2)) {
// Double click -> open
linkedFile.open();
}
}
@Override
public double getWeight() {
return 3;
}
private ContextMenu createContextMenuForFile(LinkedFileViewModel linkedFile) {
ContextMenu menu = new ContextMenu();
ActionFactory factory = new ActionFactory(Globals.getKeyPrefs());
menu.getItems().addAll(
factory.createMenuItem(StandardActions.EDIT_FILE_LINK, new ContextAction(StandardActions.EDIT_FILE_LINK, linkedFile, preferencesService)),
new SeparatorMenuItem(),
factory.createMenuItem(StandardActions.OPEN_FILE, new ContextAction(StandardActions.OPEN_FILE, linkedFile, preferencesService)),
factory.createMenuItem(StandardActions.OPEN_FOLDER, new ContextAction(StandardActions.OPEN_FOLDER, linkedFile, preferencesService)),
new SeparatorMenuItem(),
factory.createMenuItem(StandardActions.DOWNLOAD_FILE, new ContextAction(StandardActions.DOWNLOAD_FILE, linkedFile, preferencesService)),
factory.createMenuItem(StandardActions.RENAME_FILE_TO_PATTERN, new ContextAction(StandardActions.RENAME_FILE_TO_PATTERN, linkedFile, preferencesService)),
factory.createMenuItem(StandardActions.RENAME_FILE_TO_NAME, new ContextAction(StandardActions.RENAME_FILE_TO_NAME, linkedFile, preferencesService)),
factory.createMenuItem(StandardActions.MOVE_FILE_TO_FOLDER, new ContextAction(StandardActions.MOVE_FILE_TO_FOLDER, linkedFile, preferencesService)),
factory.createMenuItem(StandardActions.MOVE_FILE_TO_FOLDER_AND_RENAME, new ContextAction(StandardActions.MOVE_FILE_TO_FOLDER_AND_RENAME, linkedFile, preferencesService)),
factory.createMenuItem(StandardActions.COPY_FILE_TO_FOLDER, new CopySingleFileAction(linkedFile.getFile(), dialogService, databaseContext, preferencesService.getFilePreferences())),
factory.createMenuItem(StandardActions.REMOVE_LINK, new ContextAction(StandardActions.REMOVE_LINK, linkedFile, preferencesService)),
factory.createMenuItem(StandardActions.DELETE_FILE, new ContextAction(StandardActions.DELETE_FILE, linkedFile, preferencesService))
);
return menu;
}
private class ContextAction extends SimpleCommand {
private final StandardActions command;
private final LinkedFileViewModel linkedFile;
public ContextAction(StandardActions command, LinkedFileViewModel linkedFile, PreferencesService preferencesService) {
this.command = command;
this.linkedFile = linkedFile;
this.executable.bind(
switch (command) {
case RENAME_FILE_TO_PATTERN -> Bindings.createBooleanBinding(
() -> !linkedFile.getFile().isOnlineLink()
&& linkedFile.getFile().findIn(databaseContext, preferencesService.getFilePreferences()).isPresent()
&& !linkedFile.isGeneratedNameSameAsOriginal(),
linkedFile.getFile().linkProperty(), bibEntry.getValue().map(BibEntry::getFieldsObservable).orElse(null));
case MOVE_FILE_TO_FOLDER, MOVE_FILE_TO_FOLDER_AND_RENAME -> Bindings.createBooleanBinding(
() -> !linkedFile.getFile().isOnlineLink()
&& linkedFile.getFile().findIn(databaseContext, preferencesService.getFilePreferences()).isPresent()
&& !linkedFile.isGeneratedPathSameAsOriginal(),
linkedFile.getFile().linkProperty(), bibEntry.getValue().map(BibEntry::getFieldsObservable).orElse(null));
case DOWNLOAD_FILE -> Bindings.createBooleanBinding(
() -> linkedFile.getFile().isOnlineLink(),
linkedFile.getFile().linkProperty(), bibEntry.getValue().map(BibEntry::getFieldsObservable).orElse(null));
case OPEN_FILE, OPEN_FOLDER, RENAME_FILE_TO_NAME, DELETE_FILE -> Bindings.createBooleanBinding(
() -> !linkedFile.getFile().isOnlineLink()
&& linkedFile.getFile().findIn(databaseContext, preferencesService.getFilePreferences()).isPresent(),
linkedFile.getFile().linkProperty(), bibEntry.getValue().map(BibEntry::getFieldsObservable).orElse(null));
default -> BindingsHelper.constantOf(true);
});
}
@Override
public void execute() {
switch (command) {
case EDIT_FILE_LINK -> linkedFile.edit();
case OPEN_FILE -> linkedFile.open();
case OPEN_FOLDER -> linkedFile.openFolder();
case DOWNLOAD_FILE -> linkedFile.download();
case RENAME_FILE_TO_PATTERN -> linkedFile.renameToSuggestion();
case RENAME_FILE_TO_NAME -> linkedFile.askForNameAndRename();
case MOVE_FILE_TO_FOLDER -> linkedFile.moveToDefaultDirectory();
case MOVE_FILE_TO_FOLDER_AND_RENAME -> linkedFile.moveToDefaultDirectoryAndRename();
case DELETE_FILE -> viewModel.deleteFile(linkedFile);
case REMOVE_LINK -> viewModel.removeFileLink(linkedFile);
}
}
}
}
| 17,581
| 47.97493
| 197
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/LinkedFilesEditorViewModel.java
|
package org.jabref.gui.fieldeditors;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ListProperty;
import javafx.beans.property.ReadOnlyBooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.jabref.gui.DialogService;
import org.jabref.gui.autocompleter.SuggestionProvider;
import org.jabref.gui.externalfiles.AutoSetFileLinksUtil;
import org.jabref.gui.externalfiletype.CustomExternalFileType;
import org.jabref.gui.externalfiletype.ExternalFileType;
import org.jabref.gui.externalfiletype.ExternalFileTypes;
import org.jabref.gui.externalfiletype.UnknownExternalFileType;
import org.jabref.gui.linkedfile.AttachFileFromURLAction;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.gui.util.BindingsHelper;
import org.jabref.gui.util.FileDialogConfiguration;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.bibtex.FileFieldWriter;
import org.jabref.logic.importer.FulltextFetchers;
import org.jabref.logic.importer.util.FileFieldParser;
import org.jabref.logic.integrity.FieldCheckers;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.io.FileUtil;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.LinkedFile;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.StandardField;
import org.jabref.preferences.FilePreferences;
import org.jabref.preferences.PreferencesService;
public class LinkedFilesEditorViewModel extends AbstractEditorViewModel {
private final ListProperty<LinkedFileViewModel> files = new SimpleListProperty<>(FXCollections.observableArrayList(LinkedFileViewModel::getObservables));
private final BooleanProperty fulltextLookupInProgress = new SimpleBooleanProperty(false);
private final DialogService dialogService;
private final BibDatabaseContext databaseContext;
private final TaskExecutor taskExecutor;
private final PreferencesService preferences;
public LinkedFilesEditorViewModel(Field field, SuggestionProvider<?> suggestionProvider,
DialogService dialogService,
BibDatabaseContext databaseContext,
TaskExecutor taskExecutor,
FieldCheckers fieldCheckers,
PreferencesService preferences) {
super(field, suggestionProvider, fieldCheckers);
this.dialogService = dialogService;
this.databaseContext = databaseContext;
this.taskExecutor = taskExecutor;
this.preferences = preferences;
BindingsHelper.bindContentBidirectional(
files,
text,
LinkedFilesEditorViewModel::getStringRepresentation,
this::parseToFileViewModel);
}
private static String getStringRepresentation(List<LinkedFileViewModel> files) {
// Only serialize linked files, not the ones that are automatically found
List<LinkedFile> filesToSerialize = files.stream()
.filter(file -> !file.isAutomaticallyFound())
.map(LinkedFileViewModel::getFile)
.collect(Collectors.toList());
return FileFieldWriter.getStringRepresentation(filesToSerialize);
}
/**
* Creates an instance of {@link LinkedFile} based on the given file.
* We try to guess the file type and relativize the path against the given file directories.
*
* TODO: Move this method to {@link LinkedFile} as soon as {@link CustomExternalFileType} lives in model.
*/
public static LinkedFile fromFile(Path file, List<Path> fileDirectories, FilePreferences filePreferences) {
String fileExtension = FileUtil.getFileExtension(file).orElse("");
ExternalFileType suggestedFileType = ExternalFileTypes.getExternalFileTypeByExt(fileExtension, filePreferences)
.orElse(new UnknownExternalFileType(fileExtension));
Path relativePath = FileUtil.relativize(file, fileDirectories);
return new LinkedFile("", relativePath, suggestedFileType.getName());
}
public LinkedFileViewModel fromFile(Path file, FilePreferences filePreferences) {
List<Path> fileDirectories = databaseContext.getFileDirectories(preferences.getFilePreferences());
LinkedFile linkedFile = fromFile(file, fileDirectories, filePreferences);
return new LinkedFileViewModel(
linkedFile,
entry,
databaseContext,
taskExecutor,
dialogService,
preferences);
}
private List<LinkedFileViewModel> parseToFileViewModel(String stringValue) {
return FileFieldParser.parse(stringValue).stream()
.map(linkedFile -> new LinkedFileViewModel(
linkedFile,
entry,
databaseContext,
taskExecutor,
dialogService,
preferences))
.collect(Collectors.toList());
}
public ObservableList<LinkedFileViewModel> getFiles() {
return files.get();
}
public ListProperty<LinkedFileViewModel> filesProperty() {
return files;
}
public void addNewFile() {
Path workingDirectory = databaseContext.getFirstExistingFileDir(preferences.getFilePreferences())
.orElse(preferences.getFilePreferences().getWorkingDirectory());
FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
.withInitialDirectory(workingDirectory)
.build();
List<Path> fileDirectories = databaseContext.getFileDirectories(preferences.getFilePreferences());
dialogService.showFileOpenDialogAndGetMultipleFiles(fileDialogConfiguration).forEach(newFile -> {
LinkedFile newLinkedFile = fromFile(newFile, fileDirectories, preferences.getFilePreferences());
files.add(new LinkedFileViewModel(
newLinkedFile,
entry,
databaseContext,
taskExecutor,
dialogService,
preferences));
});
}
@Override
public void bindToEntry(BibEntry entry) {
super.bindToEntry(entry);
if ((entry != null) && preferences.getEntryEditorPreferences().autoLinkFilesEnabled()) {
BackgroundTask<List<LinkedFileViewModel>> findAssociatedNotLinkedFiles = BackgroundTask
.wrap(() -> findAssociatedNotLinkedFiles(entry))
.onSuccess(files::addAll);
taskExecutor.execute(findAssociatedNotLinkedFiles);
}
}
/**
* Find files that are probably associated to the given entry but not yet linked.
*/
private List<LinkedFileViewModel> findAssociatedNotLinkedFiles(BibEntry entry) {
List<LinkedFileViewModel> result = new ArrayList<>();
AutoSetFileLinksUtil util = new AutoSetFileLinksUtil(
databaseContext,
preferences.getFilePreferences(),
preferences.getAutoLinkPreferences());
try {
List<LinkedFile> linkedFiles = util.findAssociatedNotLinkedFiles(entry);
for (LinkedFile linkedFile : linkedFiles) {
LinkedFileViewModel newLinkedFile = new LinkedFileViewModel(
linkedFile,
entry,
databaseContext,
taskExecutor,
dialogService,
preferences);
newLinkedFile.markAsAutomaticallyFound();
result.add(newLinkedFile);
}
} catch (IOException e) {
dialogService.showErrorDialogAndWait("Error accessing the file system", e);
}
return result;
}
public boolean downloadFile(String urlText) {
try {
URL url = new URL(urlText);
addFromURLAndDownload(url);
return true;
} catch (MalformedURLException exception) {
dialogService.showErrorDialogAndWait(
Localization.lang("Invalid URL"),
exception);
return false;
}
}
public void fetchFulltext() {
FulltextFetchers fetcher = new FulltextFetchers(
preferences.getImportFormatPreferences(),
preferences.getImporterPreferences());
Optional<String> urlField = entry.getField(StandardField.URL);
boolean download_success = false;
if (urlField.isPresent()) {
download_success = downloadFile(urlField.get());
}
if (urlField.isEmpty() || !download_success) {
BackgroundTask
.wrap(() -> fetcher.findFullTextPDF(entry))
.onRunning(() -> fulltextLookupInProgress.setValue(true))
.onFinished(() -> fulltextLookupInProgress.setValue(false))
.onSuccess(url -> {
if (url.isPresent()) {
addFromURLAndDownload(url.get());
} else {
dialogService.notify(Localization.lang("No full text document found"));
}
})
.executeWith(taskExecutor);
}
}
public void addFromURL() {
AttachFileFromURLAction.getUrlForDownloadFromClipBoardOrEntry(dialogService, entry)
.ifPresent(this::downloadFile);
}
private void addFromURLAndDownload(URL url) {
LinkedFileViewModel onlineFile = new LinkedFileViewModel(
new LinkedFile(url, ""),
entry,
databaseContext,
taskExecutor,
dialogService,
preferences);
files.add(onlineFile);
onlineFile.download();
}
public void deleteFile(LinkedFileViewModel file) {
if (file.getFile().isOnlineLink()) {
removeFileLink(file);
} else {
boolean deleteSuccessful = file.delete();
if (deleteSuccessful) {
files.remove(file);
}
}
}
public void removeFileLink(LinkedFileViewModel file) {
files.remove(file);
}
public ReadOnlyBooleanProperty fulltextLookupInProgressProperty() {
return fulltextLookupInProgress;
}
}
| 11,239
| 40.62963
| 157
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/MapBasedEditorViewModel.java
|
package org.jabref.gui.fieldeditors;
import java.util.ArrayList;
import java.util.List;
import javafx.util.StringConverter;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* View model for a field editor that shows various options backed by a map.
*/
public abstract class MapBasedEditorViewModel<T> extends OptionEditorViewModel<T> {
private static final Logger LOGGER = LoggerFactory.getLogger(MapBasedEditorViewModel.class);
public MapBasedEditorViewModel(Field field, SuggestionProvider<?> suggestionProvider, FieldCheckers fieldCheckers) {
super(field, suggestionProvider, fieldCheckers);
}
protected abstract BiMap<String, T> getItemMap();
@Override
public StringConverter<T> getStringConverter() {
return new StringConverter<T>() {
@Override
public String toString(T object) {
if (object == null) {
return null;
} else {
return getItemMap().inverse().getOrDefault(object, object.toString()); // if the object is not found we simply return itself as string
}
}
@Override
public T fromString(String string) {
if (string == null) {
return null;
} else {
return getItemMap().getOrDefault(string, getValueFromString(string));
}
}
};
}
/**
* Converts a String value to the Type T. If the type cannot be directly casted to T, this method must be overriden in a subclass
*
* @param string The input value to convert
* @return The value or null if the value could not be casted
*/
@SuppressWarnings("unchecked")
protected T getValueFromString(String string) {
try {
return (T) string;
} catch (ClassCastException ex) {
LOGGER.error(String.format("Could not cast string to type %1$s. Try overriding the method in a subclass and provide a conversion from string to the concrete type %1$s", string.getClass()), ex);
}
return null;
}
@Override
public List<T> getItems() {
return new ArrayList<>(getItemMap().values());
}
}
| 2,449
| 32.561644
| 205
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/MonthEditorViewModel.java
|
package org.jabref.gui.fieldeditors;
import java.util.Arrays;
import java.util.List;
import javafx.util.StringConverter;
import org.jabref.gui.autocompleter.SuggestionProvider;
import org.jabref.logic.integrity.FieldCheckers;
import org.jabref.model.database.BibDatabaseMode;
import org.jabref.model.entry.Month;
import org.jabref.model.entry.field.Field;
import org.jabref.model.strings.StringUtil;
public class MonthEditorViewModel extends OptionEditorViewModel<Month> {
private BibDatabaseMode databaseMode;
public MonthEditorViewModel(Field field, SuggestionProvider<?> suggestionProvider, BibDatabaseMode databaseMode, FieldCheckers fieldCheckers) {
super(field, suggestionProvider, fieldCheckers);
this.databaseMode = databaseMode;
}
@Override
public StringConverter<Month> getStringConverter() {
return new StringConverter<Month>() {
@Override
public String toString(Month object) {
if (object == null) {
return null;
} else {
if (databaseMode == BibDatabaseMode.BIBLATEX) {
return String.valueOf(object.getNumber());
} else {
return object.getJabRefFormat();
}
}
}
@Override
public Month fromString(String string) {
if (StringUtil.isNotBlank(string)) {
return Month.parse(string).orElse(null);
} else {
return null;
}
}
};
}
@Override
public List<Month> getItems() {
return Arrays.asList(Month.values());
}
@Override
public String convertToDisplayText(Month object) {
return object.getFullName();
}
}
| 1,850
| 29.85
| 147
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/OptionEditor.java
|
package org.jabref.gui.fieldeditors;
import javafx.fxml.FXML;
import javafx.scene.Parent;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ContextMenu;
import javafx.scene.layout.HBox;
import org.jabref.gui.Globals;
import org.jabref.gui.fieldeditors.contextmenu.EditorContextAction;
import org.jabref.gui.util.ViewModelListCellFactory;
import org.jabref.model.entry.BibEntry;
import com.airhacks.afterburner.views.ViewLoader;
/**
* Field editor that provides various pre-defined options as a drop-down combobox.
*/
public class OptionEditor<T> extends HBox implements FieldEditorFX {
@FXML private final OptionEditorViewModel<T> viewModel;
@FXML private ComboBox<T> comboBox;
public OptionEditor(OptionEditorViewModel<T> viewModel) {
this.viewModel = viewModel;
ViewLoader.view(this)
.root(this)
.load();
comboBox.setConverter(viewModel.getStringConverter());
comboBox.setCellFactory(new ViewModelListCellFactory<T>().withText(viewModel::convertToDisplayText));
comboBox.getItems().setAll(viewModel.getItems());
comboBox.getEditor().textProperty().bindBidirectional(viewModel.textProperty());
comboBox.getEditor().setOnContextMenuRequested(event -> {
ContextMenu contextMenu = new ContextMenu();
contextMenu.getItems().setAll(EditorContextAction.getDefaultContextMenuItems(comboBox.getEditor(), Globals.getKeyPrefs()));
TextInputControlBehavior.showContextMenu(comboBox.getEditor(), contextMenu, event);
});
}
public OptionEditorViewModel<T> getViewModel() {
return viewModel;
}
@Override
public void bindToEntry(BibEntry entry) {
viewModel.bindToEntry(entry);
}
@Override
public Parent getNode() {
return this;
}
}
| 1,856
| 31.578947
| 135
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/OptionEditorViewModel.java
|
package org.jabref.gui.fieldeditors;
import java.util.List;
import javafx.util.StringConverter;
import org.jabref.gui.autocompleter.SuggestionProvider;
import org.jabref.logic.integrity.FieldCheckers;
import org.jabref.model.entry.field.Field;
public abstract class OptionEditorViewModel<T> extends AbstractEditorViewModel {
public OptionEditorViewModel(Field field, SuggestionProvider<?> suggestionProvider, FieldCheckers fieldCheckers) {
super(field, suggestionProvider, fieldCheckers);
}
public abstract StringConverter<T> getStringConverter();
public abstract List<T> getItems();
public abstract String convertToDisplayText(T object);
}
| 677
| 28.478261
| 118
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/fieldeditors/OwnerEditor.java
|
package org.jabref.gui.fieldeditors;
import javafx.fxml.FXML;
import javafx.scene.Parent;
import javafx.scene.layout.HBox;
import org.jabref.gui.autocompleter.SuggestionProvider;
import org.jabref.gui.fieldeditors.contextmenu.EditorMenus;
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 OwnerEditor extends HBox implements FieldEditorFX {
@FXML private OwnerEditorViewModel viewModel;
@FXML private EditorTextArea textArea;
public OwnerEditor(Field field,
PreferencesService preferences,
SuggestionProvider<?> suggestionProvider,
FieldCheckers fieldCheckers) {
this.viewModel = new OwnerEditorViewModel(field, suggestionProvider, preferences, fieldCheckers);
ViewLoader.view(this)
.root(this)
.load();
textArea.textProperty().bindBidirectional(viewModel.textProperty());
textArea.initContextMenu(EditorMenus.getNameMenu(textArea));
new EditorValidator(preferences).configureValidation(viewModel.getFieldValidator().getValidationStatus(), textArea);
}
public OwnerEditorViewModel getViewModel() {
return viewModel;
}
@Override
public void bindToEntry(BibEntry entry) {
viewModel.bindToEntry(entry);
}
@Override
public Parent getNode() {
return this;
}
@FXML
private void setOwner() {
viewModel.setOwner();
}
}
| 1,657
| 28.087719
| 124
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.