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/preferences/PreferencesDialogView.java
|
package org.jabref.gui.preferences;
import java.util.Locale;
import javafx.fxml.FXML;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ListView;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ToggleButton;
import javafx.scene.input.KeyCode;
import org.jabref.gui.DialogService;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.keyboard.KeyBinding;
import org.jabref.gui.theme.ThemeManager;
import org.jabref.gui.util.BaseDialog;
import org.jabref.gui.util.ControlHelper;
import org.jabref.gui.util.ViewModelListCellFactory;
import org.jabref.logic.l10n.Localization;
import org.jabref.preferences.PreferencesService;
import com.airhacks.afterburner.views.ViewLoader;
import com.tobiasdiez.easybind.EasyBind;
import jakarta.inject.Inject;
import org.controlsfx.control.textfield.CustomTextField;
/**
* Preferences dialog. Contains a TabbedPane, and tabs will be defined in separate classes. Tabs MUST implement the
* PreferencesTab interface, since this dialog will call the storeSettings() method of all tabs when the user presses
* ok.
*/
public class PreferencesDialogView extends BaseDialog<PreferencesDialogViewModel> {
@FXML private CustomTextField searchBox;
@FXML private ListView<PreferencesTab> preferenceTabList;
@FXML private ScrollPane preferencesContainer;
@FXML private ButtonType saveButton;
@FXML private ToggleButton memoryStickMode;
@Inject private DialogService dialogService;
@Inject private PreferencesService preferencesService;
@Inject private ThemeManager themeManager;
private final JabRefFrame frame;
private PreferencesDialogViewModel viewModel;
public PreferencesDialogView(JabRefFrame frame) {
this.frame = frame;
this.setTitle(Localization.lang("JabRef preferences"));
ViewLoader.view(this)
.load()
.setAsDialogPane(this);
ControlHelper.setAction(saveButton, getDialogPane(), event -> savePreferencesAndCloseDialog());
// Stop the default button from firing when the user hits enter within the search box
searchBox.setOnKeyPressed(event -> {
if (event.getCode() == KeyCode.ENTER) {
event.consume();
}
});
themeManager.updateFontStyle(getDialogPane().getScene());
}
public PreferencesDialogViewModel getViewModel() {
return viewModel;
}
@FXML
private void initialize() {
viewModel = new PreferencesDialogViewModel(dialogService, preferencesService, frame);
preferenceTabList.itemsProperty().setValue(viewModel.getPreferenceTabs());
// The list view does not respect the listener for the dialog and needs its own
preferenceTabList.setOnKeyReleased(key -> {
if (preferencesService.getKeyBindingRepository().checkKeyCombinationEquality(KeyBinding.CLOSE, key)) {
this.closeDialog();
}
});
PreferencesSearchHandler searchHandler = new PreferencesSearchHandler(viewModel.getPreferenceTabs());
preferenceTabList.itemsProperty().bindBidirectional(searchHandler.filteredPreferenceTabsProperty());
searchBox.textProperty().addListener((observable, previousText, newText) -> {
searchHandler.filterTabs(newText.toLowerCase(Locale.ROOT));
preferenceTabList.getSelectionModel().clearSelection();
preferenceTabList.getSelectionModel().selectFirst();
});
searchBox.setPromptText(Localization.lang("Search") + "...");
searchBox.setLeft(IconTheme.JabRefIcons.SEARCH.getGraphicNode());
EasyBind.subscribe(preferenceTabList.getSelectionModel().selectedItemProperty(), tab -> {
if (tab instanceof AbstractPreferenceTabView<?> preferencesTab) {
preferencesContainer.setContent(preferencesTab.getBuilder());
preferencesTab.prefWidthProperty().bind(preferencesContainer.widthProperty().subtract(10d));
preferencesTab.getStyleClass().add("preferencesTab");
} else {
preferencesContainer.setContent(null);
}
});
preferenceTabList.getSelectionModel().selectFirst();
new ViewModelListCellFactory<PreferencesTab>()
.withText(PreferencesTab::getTabName)
.install(preferenceTabList);
memoryStickMode.selectedProperty().bindBidirectional(viewModel.getMemoryStickProperty());
viewModel.setValues();
}
@FXML
private void closeDialog() {
close();
}
@FXML
private void savePreferencesAndCloseDialog() {
if (viewModel.validSettings()) {
viewModel.storeAllSettings();
closeDialog();
}
}
@FXML
void exportPreferences() {
viewModel.exportPreferences();
}
@FXML
void importPreferences() {
viewModel.importPreferences();
}
@FXML
void showAllPreferences() {
viewModel.showPreferences();
}
@FXML
void resetPreferences() {
viewModel.resetPreferences();
}
}
| 5,171
| 33.945946
| 117
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/PreferencesDialogViewModel.java
|
package org.jabref.gui.preferences;
import java.util.ArrayList;
import java.util.List;
import java.util.prefs.BackingStoreException;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ReadOnlyListWrapper;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.jabref.gui.AbstractViewModel;
import org.jabref.gui.DialogService;
import org.jabref.gui.Globals;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.preferences.autocompletion.AutoCompletionTab;
import org.jabref.gui.preferences.citationkeypattern.CitationKeyPatternTab;
import org.jabref.gui.preferences.customentrytypes.CustomEntryTypesTab;
import org.jabref.gui.preferences.customexporter.CustomExporterTab;
import org.jabref.gui.preferences.customimporter.CustomImporterTab;
import org.jabref.gui.preferences.entry.EntryTab;
import org.jabref.gui.preferences.entryeditor.EntryEditorTab;
import org.jabref.gui.preferences.export.ExportTab;
import org.jabref.gui.preferences.external.ExternalTab;
import org.jabref.gui.preferences.externalfiletypes.ExternalFileTypesTab;
import org.jabref.gui.preferences.general.GeneralTab;
import org.jabref.gui.preferences.groups.GroupsTab;
import org.jabref.gui.preferences.journals.JournalAbbreviationsTab;
import org.jabref.gui.preferences.keybindings.KeyBindingsTab;
import org.jabref.gui.preferences.linkedfiles.LinkedFilesTab;
import org.jabref.gui.preferences.nameformatter.NameFormatterTab;
import org.jabref.gui.preferences.network.NetworkTab;
import org.jabref.gui.preferences.preview.PreviewTab;
import org.jabref.gui.preferences.protectedterms.ProtectedTermsTab;
import org.jabref.gui.preferences.table.TableTab;
import org.jabref.gui.preferences.websearch.WebSearchTab;
import org.jabref.gui.preferences.xmp.XmpPrivacyTab;
import org.jabref.gui.util.FileDialogConfiguration;
import org.jabref.logic.JabRefException;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.StandardFileType;
import org.jabref.preferences.PreferencesFilter;
import org.jabref.preferences.PreferencesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PreferencesDialogViewModel extends AbstractViewModel {
private static final Logger LOGGER = LoggerFactory.getLogger(PreferencesDialogViewModel.class);
private final SimpleBooleanProperty memoryStickProperty = new SimpleBooleanProperty();
private final DialogService dialogService;
private final PreferencesService preferences;
private final ObservableList<PreferencesTab> preferenceTabs;
private final JabRefFrame frame;
public PreferencesDialogViewModel(DialogService dialogService, PreferencesService preferences, JabRefFrame frame) {
this.dialogService = dialogService;
this.preferences = preferences;
this.frame = frame;
preferenceTabs = FXCollections.observableArrayList(
new GeneralTab(),
new KeyBindingsTab(),
new GroupsTab(),
new WebSearchTab(),
new EntryTab(),
new TableTab(),
new PreviewTab(),
new EntryEditorTab(),
new CustomEntryTypesTab(),
new CitationKeyPatternTab(),
new LinkedFilesTab(),
new ExportTab(),
new AutoCompletionTab(),
new ProtectedTermsTab(),
new ExternalTab(),
new ExternalFileTypesTab(),
new JournalAbbreviationsTab(),
new NameFormatterTab(),
new XmpPrivacyTab(),
new CustomImporterTab(),
new CustomExporterTab(),
new NetworkTab()
);
}
public ObservableList<PreferencesTab> getPreferenceTabs() {
return new ReadOnlyListWrapper<>(preferenceTabs);
}
public void importPreferences() {
FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
.addExtensionFilter(StandardFileType.XML)
.withDefaultExtension(StandardFileType.XML)
.withInitialDirectory(preferences.getInternalPreferences().getLastPreferencesExportPath()).build();
dialogService.showFileOpenDialog(fileDialogConfiguration)
.ifPresent(file -> {
try {
preferences.importPreferences(file);
updateAfterPreferenceChanges();
dialogService.showWarningDialogAndWait(Localization.lang("Import preferences"),
Localization.lang("You must restart JabRef for this to come into effect."));
} catch (JabRefException ex) {
LOGGER.error("Error while importing preferences", ex);
dialogService.showErrorDialogAndWait(Localization.lang("Import preferences"), ex);
}
});
}
public void exportPreferences() {
FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
.addExtensionFilter(StandardFileType.XML)
.withDefaultExtension(StandardFileType.XML)
.withInitialDirectory(preferences.getInternalPreferences().getLastPreferencesExportPath())
.build();
dialogService.showFileSaveDialog(fileDialogConfiguration)
.ifPresent(exportFile -> {
try {
storeAllSettings();
preferences.exportPreferences(exportFile);
preferences.getInternalPreferences().setLastPreferencesExportPath(exportFile);
} catch (JabRefException ex) {
LOGGER.warn(ex.getMessage(), ex);
dialogService.showErrorDialogAndWait(Localization.lang("Export preferences"), ex);
}
});
}
public void showPreferences() {
dialogService.showCustomDialogAndWait(new PreferencesFilterDialog(new PreferencesFilter(preferences)));
}
public void resetPreferences() {
boolean resetPreferencesConfirmed = dialogService.showConfirmationDialogAndWait(
Localization.lang("Reset preferences"),
Localization.lang("Are you sure you want to reset all settings to default values?"),
Localization.lang("Reset preferences"),
Localization.lang("Cancel"));
if (resetPreferencesConfirmed) {
try {
preferences.clear();
dialogService.showWarningDialogAndWait(Localization.lang("Reset preferences"),
Localization.lang("You must restart JabRef for this to come into effect."));
} catch (BackingStoreException ex) {
LOGGER.error("Error while resetting preferences", ex);
dialogService.showErrorDialogAndWait(Localization.lang("Reset preferences"), ex);
}
updateAfterPreferenceChanges();
}
}
/**
* Reloads the preferences into the UI
*/
private void updateAfterPreferenceChanges() {
setValues();
frame.getLibraryTabs().forEach(panel -> panel.getMainTable().getTableModel().refresh());
}
/**
* Checks if all tabs are valid
*/
public boolean validSettings() {
for (PreferencesTab tab : preferenceTabs) {
if (!tab.validateSettings()) {
return false;
}
}
return true;
}
public void storeAllSettings() {
List<String> restartWarnings = new ArrayList<>();
// Run validation checks
if (!validSettings()) {
return;
}
// Store settings
preferences.getInternalPreferences().setMemoryStickMode(memoryStickProperty.get());
for (PreferencesTab tab : preferenceTabs) {
tab.storeSettings();
restartWarnings.addAll(tab.getRestartWarnings());
}
preferences.flush();
if (!restartWarnings.isEmpty()) {
dialogService.showWarningDialogAndWait(Localization.lang("Restart required"),
String.join(",\n", restartWarnings)
+ "\n\n"
+ Localization.lang("You must restart JabRef for this to come into effect."));
}
frame.setupAllTables();
frame.getGlobalSearchBar().updateHintVisibility();
Globals.entryTypesManager = preferences.getCustomEntryTypesRepository();
dialogService.notify(Localization.lang("Preferences recorded."));
updateAfterPreferenceChanges();
}
/**
* Inserts the preference values into the Properties of the ViewModel
*/
public void setValues() {
memoryStickProperty.setValue(preferences.getInternalPreferences().isMemoryStickMode());
for (PreferencesTab preferencesTab : preferenceTabs) {
preferencesTab.setValues();
}
}
public BooleanProperty getMemoryStickProperty() {
return memoryStickProperty;
}
}
| 9,355
| 39.855895
| 119
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/PreferencesFilterDialog.java
|
package org.jabref.gui.preferences;
import java.util.Locale;
import java.util.Objects;
import javafx.beans.binding.Bindings;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.fxml.FXML;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import org.jabref.gui.util.BaseDialog;
import org.jabref.logic.l10n.Localization;
import org.jabref.preferences.PreferencesFilter;
import com.airhacks.afterburner.views.ViewLoader;
import com.tobiasdiez.easybind.EasyBind;
public class PreferencesFilterDialog extends BaseDialog<Void> {
private final PreferencesFilter preferencesFilter;
private final ObservableList<PreferencesFilter.PreferenceOption> preferenceOptions;
private final FilteredList<PreferencesFilter.PreferenceOption> filteredOptions;
@FXML private TableView<PreferencesFilter.PreferenceOption> table;
@FXML private TableColumn<PreferencesFilter.PreferenceOption, PreferencesFilter.PreferenceType> columnType;
@FXML private TableColumn<PreferencesFilter.PreferenceOption, String> columnKey;
@FXML private TableColumn<PreferencesFilter.PreferenceOption, Object> columnValue;
@FXML private TableColumn<PreferencesFilter.PreferenceOption, Object> columnDefaultValue;
@FXML private CheckBox showOnlyDeviatingPreferenceOptions;
@FXML private Label count;
@FXML private TextField searchField;
public PreferencesFilterDialog(PreferencesFilter preferencesFilter) {
this.preferencesFilter = Objects.requireNonNull(preferencesFilter);
this.preferenceOptions = FXCollections.observableArrayList();
this.filteredOptions = new FilteredList<>(this.preferenceOptions);
ViewLoader.view(this)
.load()
.setAsDialogPane(this);
this.setTitle(Localization.lang("Preferences"));
}
@FXML
private void initialize() {
showOnlyDeviatingPreferenceOptions.setOnAction(event -> updateModel());
filteredOptions.predicateProperty().bind(EasyBind.map(searchField.textProperty(), searchText -> {
if ((searchText == null) || searchText.isEmpty()) {
return null;
}
String lowerCaseSearchText = searchText.toLowerCase(Locale.ROOT);
return option -> option.getKey().toLowerCase(Locale.ROOT).contains(lowerCaseSearchText);
}));
columnType.setCellValueFactory(data -> new ReadOnlyObjectWrapper<>(data.getValue().getType()));
columnKey.setCellValueFactory(data -> new ReadOnlyStringWrapper(data.getValue().getKey()));
columnValue.setCellValueFactory(data -> new ReadOnlyObjectWrapper<>(data.getValue().getValue()));
columnDefaultValue.setCellValueFactory(data -> new ReadOnlyObjectWrapper<>(data.getValue().getDefaultValue().orElse("")));
table.setItems(filteredOptions);
count.textProperty().bind(Bindings.size(table.getItems()).asString("(%d)"));
updateModel();
}
private void updateModel() {
if (showOnlyDeviatingPreferenceOptions.isSelected()) {
preferenceOptions.setAll(preferencesFilter.getDeviatingPreferences());
} else {
preferenceOptions.setAll(preferencesFilter.getPreferenceOptions());
}
}
}
| 3,566
| 43.5875
| 130
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/PreferencesSearchHandler.java
|
package org.jabref.gui.preferences;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.FXCollections;
import javafx.css.PseudoClass;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.Labeled;
import com.google.common.collect.ArrayListMultimap;
class PreferencesSearchHandler {
private static PseudoClass labelHighlight = PseudoClass.getPseudoClass("search-highlight");
private final List<PreferencesTab> preferenceTabs;
private final ListProperty<PreferencesTab> filteredPreferenceTabs;
private final ArrayListMultimap<PreferencesTab, Labeled> preferenceTabsLabelNames;
private final ArrayList<Labeled> highlightedLabels = new ArrayList<>();
PreferencesSearchHandler(List<PreferencesTab> preferenceTabs) {
this.preferenceTabs = preferenceTabs;
this.preferenceTabsLabelNames = getPrefsTabLabelMap();
this.filteredPreferenceTabs = new SimpleListProperty<>(FXCollections.observableArrayList(preferenceTabs));
}
public void filterTabs(String text) {
clearHighlights();
if (text.isEmpty()) {
clearSearch();
return;
}
filteredPreferenceTabs.clear();
for (PreferencesTab tab : preferenceTabsLabelNames.keySet()) {
boolean tabContainsLabel = false;
for (Labeled labeled : preferenceTabsLabelNames.get(tab)) {
if (labelContainsText(labeled, text)) {
tabContainsLabel = true;
highlightLabel(labeled);
}
}
boolean tabNameIsMatchedByQuery = tab.getTabName().toLowerCase(Locale.ROOT).contains(text);
if (tabContainsLabel || tabNameIsMatchedByQuery) {
filteredPreferenceTabs.add(tab);
}
}
}
private boolean labelContainsText(Labeled labeled, String text) {
return labeled.getText().toLowerCase(Locale.ROOT).contains(text);
}
private void highlightLabel(Labeled labeled) {
labeled.pseudoClassStateChanged(labelHighlight, true);
highlightedLabels.add(labeled);
}
private void clearHighlights() {
highlightedLabels.forEach(labeled -> labeled.pseudoClassStateChanged(labelHighlight, false));
}
private void clearSearch() {
filteredPreferenceTabs.setAll(preferenceTabs);
}
/*
* Traverse all nodes of a PreferencesTab and return a
* mapping from PreferencesTab to all its Labeled type nodes.
*/
private ArrayListMultimap<PreferencesTab, Labeled> getPrefsTabLabelMap() {
ArrayListMultimap<PreferencesTab, Labeled> prefsTabLabelMap = ArrayListMultimap.create();
for (PreferencesTab preferencesTab : preferenceTabs) {
Node builder = preferencesTab.getBuilder();
if (builder instanceof Parent) {
Parent parentBuilder = (Parent) builder;
scanLabeledControls(parentBuilder, prefsTabLabelMap, preferencesTab);
}
}
return prefsTabLabelMap;
}
protected ListProperty<PreferencesTab> filteredPreferenceTabsProperty() {
return filteredPreferenceTabs;
}
private static void scanLabeledControls(Parent parent, ArrayListMultimap<PreferencesTab, Labeled> prefsTabLabelMap, PreferencesTab preferencesTab) {
for (Node child : parent.getChildrenUnmodifiable()) {
if (!(child instanceof Labeled)) {
scanLabeledControls((Parent) child, prefsTabLabelMap, preferencesTab);
} else {
Labeled labeled = (Labeled) child;
if (!labeled.getText().isEmpty()) {
prefsTabLabelMap.put(preferencesTab, labeled);
}
}
}
}
}
| 3,908
| 36.586538
| 152
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/PreferencesTab.java
|
package org.jabref.gui.preferences;
import java.util.List;
import javafx.scene.Node;
/**
* A prefsTab is a component displayed in the PreferenceDialog.
* <p>
* It needs to extend from Component.
*/
public interface PreferencesTab {
Node getBuilder();
/**
* Should return the localized identifier to use for the tab.
*
* @return Identifier for the tab (for instance "General", "Appearance" or "External Files").
*/
String getTabName();
/**
* This method is called when the dialog is opened, or if it is made
* visible after being hidden. This calls the appropriate method in the
* ViewModel.
*/
void setValues();
/**
* This method is called when the user presses OK in the Preferences
* dialog. This calls the appropriate method in the ViewModel.
*/
void storeSettings();
/**
* This method is called before the {@link #storeSettings()} method,
* to check if there are illegal settings in the tab, or if is ready
* to be closed. This calls the appropriate method in the ViewModel.
*/
boolean validateSettings();
/**
* This method should be called after storing the preferences, This
* calls the appropriate method in the ViewModel.
*
* @return The messages for the changed properties (e. g. "Changed language: English")
*/
List<String> getRestartWarnings();
}
| 1,415
| 26.764706
| 97
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/ShowPreferencesAction.java
|
package org.jabref.gui.preferences;
import org.jabref.gui.DialogService;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.util.TaskExecutor;
import com.airhacks.afterburner.injection.Injector;
public class ShowPreferencesAction extends SimpleCommand {
private final JabRefFrame jabRefFrame;
private final TaskExecutor taskExecutor;
public ShowPreferencesAction(JabRefFrame jabRefFrame, TaskExecutor taskExecutor) {
this.jabRefFrame = jabRefFrame;
this.taskExecutor = taskExecutor;
}
@Override
public void execute() {
DialogService dialogService = Injector.instantiateModelOrService(DialogService.class);
dialogService.showCustomDialog(new PreferencesDialogView(jabRefFrame));
}
}
| 799
| 29.769231
| 94
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/autocompletion/AutoCompletionTab.java
|
package org.jabref.gui.preferences.autocompletion;
import javafx.fxml.FXML;
import javafx.scene.control.CheckBox;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import org.jabref.gui.preferences.AbstractPreferenceTabView;
import org.jabref.gui.preferences.PreferencesTab;
import org.jabref.logic.l10n.Localization;
import com.airhacks.afterburner.views.ViewLoader;
public class AutoCompletionTab extends AbstractPreferenceTabView<AutoCompletionTabViewModel> implements PreferencesTab {
@FXML private CheckBox enableAutoComplete;
@FXML private TextField autoCompleteFields;
@FXML private RadioButton autoCompleteFirstLast;
@FXML private RadioButton autoCompleteLastFirst;
@FXML private RadioButton autoCompleteBoth;
@FXML private RadioButton firstNameModeAbbreviated;
@FXML private RadioButton firstNameModeFull;
@FXML private RadioButton firstNameModeBoth;
public AutoCompletionTab() {
ViewLoader.view(this)
.root(this)
.load();
}
@Override
public String getTabName() {
return Localization.lang("Autocompletion");
}
public void initialize() {
viewModel = new AutoCompletionTabViewModel(preferencesService.getAutoCompletePreferences());
enableAutoComplete.selectedProperty().bindBidirectional(viewModel.enableAutoCompleteProperty());
autoCompleteFields.textProperty().bindBidirectional(viewModel.autoCompleteFieldsProperty());
autoCompleteFirstLast.selectedProperty().bindBidirectional(viewModel.autoCompleteFirstLastProperty());
autoCompleteLastFirst.selectedProperty().bindBidirectional(viewModel.autoCompleteLastFirstProperty());
autoCompleteBoth.selectedProperty().bindBidirectional(viewModel.autoCompleteBothProperty());
firstNameModeAbbreviated.selectedProperty().bindBidirectional(viewModel.firstNameModeAbbreviatedProperty());
firstNameModeFull.selectedProperty().bindBidirectional(viewModel.firstNameModeFullProperty());
firstNameModeBoth.selectedProperty().bindBidirectional(viewModel.firstNameModeBothProperty());
}
}
| 2,154
| 42.979592
| 120
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/autocompletion/AutoCompletionTabViewModel.java
|
package org.jabref.gui.preferences.autocompletion;
import java.util.ArrayList;
import java.util.List;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import org.jabref.gui.autocompleter.AutoCompleteFirstNameMode;
import org.jabref.gui.autocompleter.AutoCompletePreferences;
import org.jabref.gui.preferences.PreferenceTabViewModel;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.entry.field.FieldFactory;
public class AutoCompletionTabViewModel implements PreferenceTabViewModel {
private final BooleanProperty enableAutoCompleteProperty = new SimpleBooleanProperty();
private final StringProperty autoCompleteFieldsProperty = new SimpleStringProperty();
private final BooleanProperty autoCompleteFirstLastProperty = new SimpleBooleanProperty();
private final BooleanProperty autoCompleteLastFirstProperty = new SimpleBooleanProperty();
private final BooleanProperty autoCompleteBothProperty = new SimpleBooleanProperty();
private final BooleanProperty firstNameModeAbbreviatedProperty = new SimpleBooleanProperty();
private final BooleanProperty firstNameModeFullProperty = new SimpleBooleanProperty();
private final BooleanProperty firstNameModeBothProperty = new SimpleBooleanProperty();
private final AutoCompletePreferences autoCompletePreferences;
private final List<String> restartWarnings = new ArrayList<>();
public AutoCompletionTabViewModel(AutoCompletePreferences autoCompletePreferences) {
this.autoCompletePreferences = autoCompletePreferences;
}
@Override
public void setValues() {
enableAutoCompleteProperty.setValue(autoCompletePreferences.shouldAutoComplete());
autoCompleteFieldsProperty.setValue(autoCompletePreferences.getCompleteNamesAsString());
if (autoCompletePreferences.getNameFormat() == AutoCompletePreferences.NameFormat.FIRST_LAST) {
autoCompleteFirstLastProperty.setValue(true);
} else if (autoCompletePreferences.getNameFormat() == AutoCompletePreferences.NameFormat.LAST_FIRST) {
autoCompleteLastFirstProperty.setValue(true);
} else {
autoCompleteBothProperty.setValue(true);
}
switch (autoCompletePreferences.getFirstNameMode()) {
case ONLY_ABBREVIATED -> firstNameModeAbbreviatedProperty.setValue(true);
case ONLY_FULL -> firstNameModeFullProperty.setValue(true);
default -> firstNameModeBothProperty.setValue(true);
}
}
@Override
public void storeSettings() {
autoCompletePreferences.setAutoComplete(enableAutoCompleteProperty.getValue());
if (autoCompleteBothProperty.getValue()) {
autoCompletePreferences.setNameFormat(AutoCompletePreferences.NameFormat.BOTH);
} else if (autoCompleteFirstLastProperty.getValue()) {
autoCompletePreferences.setNameFormat(AutoCompletePreferences.NameFormat.FIRST_LAST);
} else if (autoCompleteLastFirstProperty.getValue()) {
autoCompletePreferences.setNameFormat(AutoCompletePreferences.NameFormat.LAST_FIRST);
}
if (firstNameModeBothProperty.getValue()) {
autoCompletePreferences.setFirstNameMode(AutoCompleteFirstNameMode.BOTH);
} else if (firstNameModeAbbreviatedProperty.getValue()) {
autoCompletePreferences.setFirstNameMode(AutoCompleteFirstNameMode.ONLY_ABBREVIATED);
} else if (firstNameModeFullProperty.getValue()) {
autoCompletePreferences.setFirstNameMode(AutoCompleteFirstNameMode.ONLY_FULL);
}
if (autoCompletePreferences.shouldAutoComplete() != enableAutoCompleteProperty.getValue()) {
if (enableAutoCompleteProperty.getValue()) {
restartWarnings.add(Localization.lang("Auto complete enabled."));
} else {
restartWarnings.add(Localization.lang("Auto complete disabled."));
}
}
autoCompletePreferences.getCompleteFields().clear();
autoCompletePreferences.getCompleteFields().addAll(FieldFactory.parseFieldList(autoCompleteFieldsProperty.getValue()));
}
@Override
public List<String> getRestartWarnings() {
return restartWarnings;
}
public BooleanProperty enableAutoCompleteProperty() {
return enableAutoCompleteProperty;
}
public StringProperty autoCompleteFieldsProperty() {
return autoCompleteFieldsProperty;
}
public BooleanProperty autoCompleteFirstLastProperty() {
return autoCompleteFirstLastProperty;
}
public BooleanProperty autoCompleteLastFirstProperty() {
return autoCompleteLastFirstProperty;
}
public BooleanProperty autoCompleteBothProperty() {
return autoCompleteBothProperty;
}
public BooleanProperty firstNameModeAbbreviatedProperty() {
return firstNameModeAbbreviatedProperty;
}
public BooleanProperty firstNameModeFullProperty() {
return firstNameModeFullProperty;
}
public BooleanProperty firstNameModeBothProperty() {
return firstNameModeBothProperty;
}
}
| 5,260
| 41.088
| 127
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/citationkeypattern/CitationKeyPatternTab.java
|
package org.jabref.gui.preferences.citationkeypattern;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import org.jabref.gui.Globals;
import org.jabref.gui.actions.ActionFactory;
import org.jabref.gui.actions.StandardActions;
import org.jabref.gui.commonfxcontrols.CitationKeyPatternPanel;
import org.jabref.gui.help.HelpAction;
import org.jabref.gui.preferences.AbstractPreferenceTabView;
import org.jabref.gui.preferences.PreferencesTab;
import org.jabref.logic.help.HelpFile;
import org.jabref.logic.l10n.Localization;
import com.airhacks.afterburner.views.ViewLoader;
public class CitationKeyPatternTab extends AbstractPreferenceTabView<CitationKeyPatternTabViewModel> implements PreferencesTab {
@FXML private CheckBox overwriteAllow;
@FXML private CheckBox overwriteWarning;
@FXML private CheckBox generateOnSave;
@FXML private RadioButton letterStartA;
@FXML private RadioButton letterStartB;
@FXML private RadioButton letterAlwaysAdd;
@FXML private TextField keyPatternRegex;
@FXML private TextField keyPatternReplacement;
@FXML private TextField unwantedCharacters;
@FXML private Button keyPatternHelp;
@FXML private CitationKeyPatternPanel bibtexKeyPatternTable;
public CitationKeyPatternTab() {
ViewLoader.view(this)
.root(this)
.load();
}
@Override
public String getTabName() {
return Localization.lang("Citation key generator");
}
public void initialize() {
this.viewModel = new CitationKeyPatternTabViewModel(preferencesService.getCitationKeyPatternPreferences());
overwriteAllow.selectedProperty().bindBidirectional(viewModel.overwriteAllowProperty());
overwriteWarning.selectedProperty().bindBidirectional(viewModel.overwriteWarningProperty());
generateOnSave.selectedProperty().bindBidirectional(viewModel.generateOnSaveProperty());
letterStartA.selectedProperty().bindBidirectional(viewModel.letterStartAProperty());
letterStartB.selectedProperty().bindBidirectional(viewModel.letterStartBProperty());
letterAlwaysAdd.selectedProperty().bindBidirectional(viewModel.letterAlwaysAddProperty());
keyPatternRegex.textProperty().bindBidirectional(viewModel.keyPatternRegexProperty());
keyPatternReplacement.textProperty().bindBidirectional(viewModel.keyPatternReplacementProperty());
unwantedCharacters.textProperty().bindBidirectional(viewModel.unwantedCharactersProperty());
bibtexKeyPatternTable.patternListProperty().bindBidirectional(viewModel.patternListProperty());
bibtexKeyPatternTable.defaultKeyPatternProperty().bindBidirectional(viewModel.defaultKeyPatternProperty());
ActionFactory actionFactory = new ActionFactory(Globals.getKeyPrefs());
actionFactory.configureIconButton(StandardActions.HELP_KEY_PATTERNS, new HelpAction(HelpFile.CITATION_KEY_PATTERN, dialogService), keyPatternHelp);
}
@Override
public void setValues() {
viewModel.setValues();
bibtexKeyPatternTable.setValues(
Globals.entryTypesManager.getAllTypes(preferencesService.getLibraryPreferences().getDefaultBibDatabaseMode()),
preferencesService.getCitationKeyPatternPreferences().getKeyPattern());
}
@Override
public void storeSettings() {
viewModel.storeSettings();
}
@FXML
public void resetAllKeyPatterns() {
bibtexKeyPatternTable.resetAll();
}
}
| 3,623
| 42.142857
| 155
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/citationkeypattern/CitationKeyPatternTabViewModel.java
|
package org.jabref.gui.preferences.citationkeypattern;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ListProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import org.jabref.gui.commonfxcontrols.CitationKeyPatternPanelItemModel;
import org.jabref.gui.commonfxcontrols.CitationKeyPatternPanelViewModel;
import org.jabref.gui.preferences.PreferenceTabViewModel;
import org.jabref.logic.citationkeypattern.CitationKeyPatternPreferences;
import org.jabref.logic.citationkeypattern.GlobalCitationKeyPattern;
public class CitationKeyPatternTabViewModel implements PreferenceTabViewModel {
private final BooleanProperty overwriteAllowProperty = new SimpleBooleanProperty();
private final BooleanProperty overwriteWarningProperty = new SimpleBooleanProperty();
private final BooleanProperty generateOnSaveProperty = new SimpleBooleanProperty();
private final BooleanProperty letterStartAProperty = new SimpleBooleanProperty();
private final BooleanProperty letterStartBProperty = new SimpleBooleanProperty();
private final BooleanProperty letterAlwaysAddProperty = new SimpleBooleanProperty();
private final StringProperty keyPatternRegexProperty = new SimpleStringProperty();
private final StringProperty keyPatternReplacementProperty = new SimpleStringProperty();
private final StringProperty unwantedCharactersProperty = new SimpleStringProperty();
// The list and the default properties are being overwritten by the bound properties of the tableView, but to
// prevent an NPE on storing the preferences before lazy-loading of the setValues, they need to be initialized.
private final ListProperty<CitationKeyPatternPanelItemModel> patternListProperty = new SimpleListProperty<>(FXCollections.observableArrayList());
private final ObjectProperty<CitationKeyPatternPanelItemModel> defaultKeyPatternProperty = new SimpleObjectProperty<>(
new CitationKeyPatternPanelItemModel(new CitationKeyPatternPanelViewModel.DefaultEntryType(), ""));
private final CitationKeyPatternPreferences keyPatternPreferences;
public CitationKeyPatternTabViewModel(CitationKeyPatternPreferences keyPatternPreferences) {
this.keyPatternPreferences = keyPatternPreferences;
}
@Override
public void setValues() {
overwriteAllowProperty.setValue(!keyPatternPreferences.shouldAvoidOverwriteCiteKey());
overwriteWarningProperty.setValue(keyPatternPreferences.shouldWarnBeforeOverwriteCiteKey());
generateOnSaveProperty.setValue(keyPatternPreferences.shouldGenerateCiteKeysBeforeSaving());
if (keyPatternPreferences.getKeySuffix()
== CitationKeyPatternPreferences.KeySuffix.ALWAYS) {
letterAlwaysAddProperty.setValue(true);
letterStartAProperty.setValue(false);
letterStartBProperty.setValue(false);
} else if (keyPatternPreferences.getKeySuffix()
== CitationKeyPatternPreferences.KeySuffix.SECOND_WITH_A) {
letterAlwaysAddProperty.setValue(false);
letterStartAProperty.setValue(true);
letterStartBProperty.setValue(false);
} else {
letterAlwaysAddProperty.setValue(false);
letterStartAProperty.setValue(false);
letterStartBProperty.setValue(true);
}
keyPatternRegexProperty.setValue(keyPatternPreferences.getKeyPatternRegex());
keyPatternReplacementProperty.setValue(keyPatternPreferences.getKeyPatternReplacement());
unwantedCharactersProperty.setValue(keyPatternPreferences.getUnwantedCharacters());
}
@Override
public void storeSettings() {
GlobalCitationKeyPattern newKeyPattern =
new GlobalCitationKeyPattern(keyPatternPreferences.getKeyPattern().getDefaultValue());
patternListProperty.forEach(item -> {
String patternString = item.getPattern();
if (!item.getEntryType().getName().equals("default")) {
if (!patternString.trim().isEmpty()) {
newKeyPattern.addCitationKeyPattern(item.getEntryType(), patternString);
}
}
});
if (!defaultKeyPatternProperty.getValue().getPattern().trim().isEmpty()) {
// we do not trim the value at the assignment to enable users to have spaces at the beginning and
// at the end of the pattern
newKeyPattern.setDefaultValue(defaultKeyPatternProperty.getValue().getPattern());
}
CitationKeyPatternPreferences.KeySuffix keySuffix = CitationKeyPatternPreferences.KeySuffix.ALWAYS;
if (letterStartAProperty.getValue()) {
keySuffix = CitationKeyPatternPreferences.KeySuffix.SECOND_WITH_A;
} else if (letterStartBProperty.getValue()) {
keySuffix = CitationKeyPatternPreferences.KeySuffix.SECOND_WITH_B;
}
keyPatternPreferences.setAvoidOverwriteCiteKey(!overwriteAllowProperty.getValue());
keyPatternPreferences.setWarnBeforeOverwriteCiteKey(overwriteWarningProperty.getValue());
keyPatternPreferences.setGenerateCiteKeysBeforeSaving(generateOnSaveProperty.getValue());
keyPatternPreferences.setKeySuffix(keySuffix);
keyPatternPreferences.setKeyPatternRegex(keyPatternRegexProperty.getValue());
keyPatternPreferences.setKeyPatternReplacement(keyPatternReplacementProperty.getValue());
keyPatternPreferences.setUnwantedCharacters(unwantedCharactersProperty.getValue());
keyPatternPreferences.setKeyPattern(newKeyPattern);
}
public BooleanProperty overwriteAllowProperty() {
return overwriteAllowProperty;
}
public BooleanProperty overwriteWarningProperty() {
return overwriteWarningProperty;
}
public BooleanProperty generateOnSaveProperty() {
return generateOnSaveProperty;
}
public BooleanProperty letterStartAProperty() {
return letterStartAProperty;
}
public BooleanProperty letterStartBProperty() {
return letterStartBProperty;
}
public BooleanProperty letterAlwaysAddProperty() {
return letterAlwaysAddProperty;
}
public StringProperty keyPatternRegexProperty() {
return keyPatternRegexProperty;
}
public StringProperty keyPatternReplacementProperty() {
return keyPatternReplacementProperty;
}
public ListProperty<CitationKeyPatternPanelItemModel> patternListProperty() {
return patternListProperty;
}
public ObjectProperty<CitationKeyPatternPanelItemModel> defaultKeyPatternProperty() {
return defaultKeyPatternProperty;
}
public StringProperty unwantedCharactersProperty() {
return unwantedCharactersProperty;
}
}
| 7,067
| 45.807947
| 149
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/customentrytypes/CustomEntryTypeViewModel.java
|
package org.jabref.gui.preferences.customentrytypes;
import java.util.function.Predicate;
import org.jabref.model.entry.BibEntryType;
import org.jabref.model.entry.field.Field;
public class CustomEntryTypeViewModel extends EntryTypeViewModel {
public CustomEntryTypeViewModel(BibEntryType entryType, Predicate<Field> isMultiline) {
super(entryType, isMultiline);
}
}
| 387
| 26.714286
| 91
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/customentrytypes/CustomEntryTypesTab.java
|
package org.jabref.gui.preferences.customentrytypes;
import javafx.application.Platform;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.Group;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;
import org.jabref.gui.DragAndDropDataFormats;
import org.jabref.gui.StateManager;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.preferences.AbstractPreferenceTabView;
import org.jabref.gui.preferences.PreferencesTab;
import org.jabref.gui.util.ControlHelper;
import org.jabref.gui.util.CustomLocalDragboard;
import org.jabref.gui.util.FieldsUtil;
import org.jabref.gui.util.ValueTableCellFactory;
import org.jabref.gui.util.ViewModelTableRowFactory;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.database.BibDatabaseMode;
import org.jabref.model.entry.BibEntryTypesManager;
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 jakarta.inject.Inject;
public class CustomEntryTypesTab extends AbstractPreferenceTabView<CustomEntryTypesTabViewModel> implements PreferencesTab {
@FXML private TableView<EntryTypeViewModel> entryTypesTable;
@FXML private TableColumn<EntryTypeViewModel, String> entryTypColumn;
@FXML private TableColumn<EntryTypeViewModel, String> entryTypeActionsColumn;
@FXML private TextField addNewEntryType;
@FXML private TableView<FieldViewModel> fields;
@FXML private TableColumn<FieldViewModel, String> fieldNameColumn;
@FXML private TableColumn<FieldViewModel, Boolean> fieldTypeColumn;
@FXML private TableColumn<FieldViewModel, String> fieldTypeActionColumn;
@FXML private TableColumn<FieldViewModel, Boolean> fieldTypeMultilineColumn;
@FXML private ComboBox<Field> addNewField;
@FXML private Button addNewEntryTypeButton;
@FXML private Button addNewFieldButton;
@Inject private StateManager stateManager;
private final ControlsFxVisualizer visualizer = new ControlsFxVisualizer();
private CustomLocalDragboard localDragboard;
public CustomEntryTypesTab() {
ViewLoader.view(this)
.root(this)
.load();
}
@Override
public String getTabName() {
return Localization.lang("Entry types");
}
public void initialize() {
BibDatabaseMode mode = stateManager.getActiveDatabase().map(BibDatabaseContext::getMode)
.orElse(preferencesService.getLibraryPreferences().getDefaultBibDatabaseMode());
BibEntryTypesManager entryTypesRepository = preferencesService.getCustomEntryTypesRepository();
this.viewModel = new CustomEntryTypesTabViewModel(mode, entryTypesRepository, dialogService, preferencesService);
// As the state manager gets injected it's not available in the constructor
this.localDragboard = stateManager.getLocalDragboard();
setupEntryTypesTable();
setupFieldsTable();
addNewEntryTypeButton.disableProperty().bind(viewModel.entryTypeValidationStatus().validProperty().not());
addNewFieldButton.disableProperty().bind(viewModel.fieldValidationStatus().validProperty().not());
Platform.runLater(() -> {
visualizer.initVisualization(viewModel.entryTypeValidationStatus(), addNewEntryType, true);
visualizer.initVisualization(viewModel.fieldValidationStatus(), addNewField, true);
});
}
private void setupEntryTypesTable() {
// Table View must be editable, otherwise the change of the Radiobuttons does not propagate the commit event
fields.setEditable(true);
entryTypColumn.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().entryType().get().getType().getDisplayName()));
entryTypesTable.setItems(viewModel.entryTypes());
entryTypesTable.getSelectionModel().selectFirst();
entryTypeActionsColumn.setSortable(false);
entryTypeActionsColumn.setReorderable(false);
entryTypeActionsColumn.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().entryType().get().getType().getDisplayName()));
new ValueTableCellFactory<EntryTypeViewModel, String>()
.withGraphic((type, name) -> {
if (type instanceof CustomEntryTypeViewModel) {
return IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode();
} else {
return null;
}
})
.withTooltip((type, name) -> {
if (type instanceof CustomEntryTypeViewModel) {
return Localization.lang("Remove entry type") + " " + name;
} else {
return null;
}
})
.withOnMouseClickedEvent((type, name) -> {
if (type instanceof CustomEntryTypeViewModel) {
return evt -> viewModel.removeEntryType(entryTypesTable.getSelectionModel().getSelectedItem());
} else {
return evt -> {
};
}
})
.install(entryTypeActionsColumn);
viewModel.selectedEntryTypeProperty().bind(entryTypesTable.getSelectionModel().selectedItemProperty());
viewModel.entryTypeToAddProperty().bindBidirectional(addNewEntryType.textProperty());
EasyBind.subscribe(viewModel.selectedEntryTypeProperty(), type -> {
if (type != null) {
var items = type.fields();
fields.setItems(items);
} else {
fields.setItems(null);
}
});
}
private void setupFieldsTable() {
fieldNameColumn.setCellValueFactory(item -> item.getValue().displayNameProperty());
fieldNameColumn.setCellFactory(TextFieldTableCell.forTableColumn());
fieldNameColumn.setEditable(true);
fieldNameColumn.setOnEditCommit((TableColumn.CellEditEvent<FieldViewModel, String> event) -> {
String newDisplayName = event.getNewValue();
if (newDisplayName.isBlank()) {
dialogService.notify(Localization.lang("Name cannot be empty"));
event.getTableView().edit(-1, null);
event.getTableView().refresh();
return;
}
FieldViewModel fieldViewModel = event.getRowValue();
String currentDisplayName = fieldViewModel.displayNameProperty().getValue();
EntryTypeViewModel selectedEntryType = viewModel.selectedEntryTypeProperty().get();
ObservableList<FieldViewModel> entryFields = selectedEntryType.fields();
// The first predicate will check if the user input the original field name or doesn't edit anything after double click
boolean fieldExists = !newDisplayName.equals(currentDisplayName) && viewModel.displayNameExists(newDisplayName);
if (fieldExists) {
dialogService.notify(Localization.lang("Unable to change field name. \"%0\" already in use.", newDisplayName));
event.getTableView().edit(-1, null);
} else {
fieldViewModel.displayNameProperty().setValue(newDisplayName);
}
event.getTableView().refresh();
});
fieldTypeColumn.setCellFactory(CheckBoxTableCell.forTableColumn(fieldTypeColumn));
fieldTypeColumn.setCellValueFactory(item -> item.getValue().requiredProperty());
makeRotatedColumnHeader(fieldTypeColumn, Localization.lang("Required"));
fieldTypeMultilineColumn.setCellFactory(CheckBoxTableCell.forTableColumn(fieldTypeMultilineColumn));
fieldTypeMultilineColumn.setCellValueFactory(item -> item.getValue().multilineProperty());
makeRotatedColumnHeader(fieldTypeMultilineColumn, Localization.lang("Multiline"));
fieldTypeActionColumn.setSortable(false);
fieldTypeActionColumn.setReorderable(false);
fieldTypeActionColumn.setEditable(false);
fieldTypeActionColumn.setCellValueFactory(cellData -> cellData.getValue().displayNameProperty());
new ValueTableCellFactory<FieldViewModel, String>()
.withGraphic(item -> IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode())
.withTooltip(name -> Localization.lang("Remove field %0 from currently selected entry type", name))
.withOnMouseClickedEvent(item -> evt -> viewModel.removeField(fields.getSelectionModel().getSelectedItem()))
.install(fieldTypeActionColumn);
new ViewModelTableRowFactory<FieldViewModel>()
.setOnDragDetected(this::handleOnDragDetected)
.setOnDragDropped(this::handleOnDragDropped)
.setOnDragOver(this::handleOnDragOver)
.setOnDragExited(this::handleOnDragExited)
.install(fields);
addNewField.setItems(viewModel.fieldsForAdding());
addNewField.setConverter(FieldsUtil.FIELD_STRING_CONVERTER);
viewModel.newFieldToAddProperty().bindBidirectional(addNewField.valueProperty());
// The valueProperty() of addNewField ComboBox needs to be updated by typing text in the ComboBox textfield,
// since the enabled/disabled state of addNewFieldButton won't update otherwise
EasyBind.subscribe(addNewField.getEditor().textProperty(), text -> addNewField.setValue(FieldsUtil.FIELD_STRING_CONVERTER.fromString(text)));
}
private void makeRotatedColumnHeader(TableColumn<?, ?> column, String text) {
Label label = new Label();
label.setText(text);
label.setRotate(-90);
label.setMinWidth(80);
column.setGraphic(new Group(label));
column.getStyleClass().add("rotated");
}
private void handleOnDragOver(TableRow<FieldViewModel> row, FieldViewModel originalItem, DragEvent
event) {
if ((event.getGestureSource() != originalItem) && event.getDragboard().hasContent(DragAndDropDataFormats.FIELD)) {
event.acceptTransferModes(TransferMode.MOVE);
ControlHelper.setDroppingPseudoClasses(row, event);
}
}
private void handleOnDragDetected(TableRow<FieldViewModel> row, FieldViewModel fieldViewModel, MouseEvent
event) {
row.startFullDrag();
FieldViewModel field = fields.getSelectionModel().getSelectedItem();
ClipboardContent content = new ClipboardContent();
Dragboard dragboard = fields.startDragAndDrop(TransferMode.MOVE);
content.put(DragAndDropDataFormats.FIELD, "");
localDragboard.putValue(FieldViewModel.class, field);
dragboard.setContent(content);
event.consume();
}
private void handleOnDragDropped(TableRow<FieldViewModel> row, FieldViewModel originalItem, DragEvent event) {
if (localDragboard.hasType(FieldViewModel.class)) {
FieldViewModel field = localDragboard.getValue(FieldViewModel.class);
fields.getItems().remove(field);
if (row.isEmpty()) {
fields.getItems().add(field);
} else {
// decide based on drop position whether to add the element before or after
int offset = event.getY() > (row.getHeight() / 2) ? 1 : 0;
fields.getItems().add(row.getIndex() + offset, field);
}
}
event.setDropCompleted(true);
event.consume();
}
private void handleOnDragExited(TableRow<FieldViewModel> row, FieldViewModel fieldViewModel, DragEvent dragEvent) {
ControlHelper.removeDroppingPseudoClasses(row);
}
@FXML
void addEntryType() {
EntryTypeViewModel newlyAdded = viewModel.addNewCustomEntryType();
this.entryTypesTable.getSelectionModel().select(newlyAdded);
this.entryTypesTable.scrollTo(newlyAdded);
}
@FXML
void addNewField() {
viewModel.addNewField();
}
@FXML
void resetEntryTypes() {
boolean reset = dialogService.showConfirmationDialogAndWait(
Localization.lang("Reset entry types and fields to defaults"),
Localization.lang("This will reset all entry types to their default values and remove all custom entry types"),
Localization.lang("Reset to default"));
if (reset) {
viewModel.resetAllCustomEntryTypes();
fields.getSelectionModel().clearSelection();
entryTypesTable.getSelectionModel().clearSelection();
viewModel.setValues();
entryTypesTable.refresh();
}
}
}
| 13,456
| 45.888502
| 156
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/customentrytypes/CustomEntryTypesTabViewModel.java
|
package org.jabref.gui.preferences.customentrytypes;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javafx.beans.Observable;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.jabref.gui.DialogService;
import org.jabref.gui.preferences.PreferenceTabViewModel;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabaseMode;
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.FieldFactory;
import org.jabref.model.entry.field.FieldPriority;
import org.jabref.model.entry.field.FieldProperty;
import org.jabref.model.entry.field.OrFields;
import org.jabref.model.entry.types.EntryType;
import org.jabref.model.entry.types.UnknownEntryType;
import org.jabref.model.strings.StringUtil;
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;
public class CustomEntryTypesTabViewModel implements PreferenceTabViewModel {
private final ObservableList<Field> fieldsForAdding = FXCollections.observableArrayList(FieldFactory.getStandardFieldsWithCitationKey());
private final ObjectProperty<EntryTypeViewModel> selectedEntryType = new SimpleObjectProperty<>();
private final StringProperty entryTypeToAdd = new SimpleStringProperty("");
private final ObjectProperty<Field> newFieldToAdd = new SimpleObjectProperty<>();
private final ObservableList<EntryTypeViewModel> entryTypesWithFields = FXCollections.observableArrayList(extractor -> new Observable[]{extractor.entryType(), extractor.fields()});
private final List<BibEntryType> entryTypesToDelete = new ArrayList<>();
private final PreferencesService preferencesService;
private final BibEntryTypesManager entryTypesManager;
private final DialogService dialogService;
private final BibDatabaseMode bibDatabaseMode;
private final Validator entryTypeValidator;
private final Validator fieldValidator;
private final Set<Field> multiLineFields = new HashSet<>();
Predicate<Field> isMultiline = field -> this.multiLineFields.contains(field) || field.getProperties().contains(FieldProperty.MULTILINE_TEXT);
public CustomEntryTypesTabViewModel(BibDatabaseMode mode,
BibEntryTypesManager entryTypesManager,
DialogService dialogService,
PreferencesService preferencesService) {
this.preferencesService = preferencesService;
this.entryTypesManager = entryTypesManager;
this.dialogService = dialogService;
this.bibDatabaseMode = mode;
this.multiLineFields.addAll(preferencesService.getFieldPreferences().getNonWrappableFields());
entryTypeValidator = new FunctionBasedValidator<>(
entryTypeToAdd,
StringUtil::isNotBlank,
ValidationMessage.error(Localization.lang("Entry type cannot be empty. Please enter a name.")));
fieldValidator = new FunctionBasedValidator<>(
newFieldToAdd,
input -> (input != null) && StringUtil.isNotBlank(input.getDisplayName()),
ValidationMessage.error(Localization.lang("Field cannot be empty. Please enter a name.")));
}
@Override
public void setValues() {
if (!this.entryTypesWithFields.isEmpty()) {
this.entryTypesWithFields.clear();
}
Collection<BibEntryType> allTypes = entryTypesManager.getAllTypes(bibDatabaseMode);
for (BibEntryType entryType : allTypes) {
EntryTypeViewModel viewModel;
if (entryTypesManager.isCustomType(entryType.getType(), bibDatabaseMode)) {
viewModel = new CustomEntryTypeViewModel(entryType, isMultiline);
} else {
viewModel = new EntryTypeViewModel(entryType, isMultiline);
}
this.entryTypesWithFields.add(viewModel);
}
}
@Override
public void storeSettings() {
Set<Field> multilineFields = new HashSet<>();
for (EntryTypeViewModel typeViewModel : entryTypesWithFields) {
BibEntryType type = typeViewModel.entryType().getValue();
List<FieldViewModel> allFields = typeViewModel.fields();
multilineFields.addAll(allFields.stream()
.filter(FieldViewModel::isMultiline)
.map(FieldViewModel::toField)
.toList());
List<OrFields> required = allFields.stream()
.filter(FieldViewModel::isRequired)
.map(FieldViewModel::toField)
.map(OrFields::new)
.collect(Collectors.toList());
List<BibField> fields = allFields.stream().map(FieldViewModel::toBibField).collect(Collectors.toList());
BibEntryType newType = new BibEntryType(type.getType(), fields, required);
entryTypesManager.addCustomOrModifiedType(newType, bibDatabaseMode);
}
for (var entryType : entryTypesToDelete) {
entryTypesManager.removeCustomOrModifiedEntryType(entryType, bibDatabaseMode);
}
preferencesService.getFieldPreferences().setNonWrappableFields(multilineFields);
preferencesService.storeCustomEntryTypesRepository(entryTypesManager);
}
public EntryTypeViewModel addNewCustomEntryType() {
EntryType newentryType = new UnknownEntryType(entryTypeToAdd.getValue());
BibEntryType type = new BibEntryType(newentryType, new ArrayList<>(), Collections.emptyList());
EntryTypeViewModel viewModel = new CustomEntryTypeViewModel(type, isMultiline);
this.entryTypesWithFields.add(viewModel);
this.entryTypeToAdd.setValue("");
return viewModel;
}
public void removeEntryType(EntryTypeViewModel focusedItem) {
entryTypesWithFields.remove(focusedItem);
entryTypesToDelete.add(focusedItem.entryType().getValue());
}
public void addNewField() {
Field field = newFieldToAdd.getValue();
boolean fieldExists = displayNameExists(field.getDisplayName());
if (fieldExists) {
dialogService.showWarningDialogAndWait(
Localization.lang("Duplicate fields"),
Localization.lang("Warning: You added field \"%0\" twice. Only one will be kept.", field.getDisplayName()));
} else {
this.selectedEntryType.getValue().addField(new FieldViewModel(
field,
FieldViewModel.Mandatory.REQUIRED,
FieldPriority.IMPORTANT,
false));
}
newFieldToAddProperty().setValue(null);
}
public boolean displayNameExists(String displayName) {
ObservableList<FieldViewModel> entryFields = this.selectedEntryType.getValue().fields();
return entryFields.stream().anyMatch(fieldViewModel ->
fieldViewModel.displayNameProperty().getValue().equals(displayName));
}
public void removeField(FieldViewModel focusedItem) {
selectedEntryType.getValue().removeField(focusedItem);
}
public void resetAllCustomEntryTypes() {
entryTypesManager.clearAllCustomEntryTypes(bibDatabaseMode);
preferencesService.storeCustomEntryTypesRepository(entryTypesManager);
}
public ObjectProperty<EntryTypeViewModel> selectedEntryTypeProperty() {
return this.selectedEntryType;
}
public StringProperty entryTypeToAddProperty() {
return this.entryTypeToAdd;
}
public ObjectProperty<Field> newFieldToAddProperty() {
return this.newFieldToAdd;
}
public ObservableList<EntryTypeViewModel> entryTypes() {
return this.entryTypesWithFields;
}
public ObservableList<Field> fieldsForAdding() {
return this.fieldsForAdding;
}
public ValidationStatus entryTypeValidationStatus() {
return entryTypeValidator.getValidationStatus();
}
public ValidationStatus fieldValidationStatus() {
return fieldValidator.getValidationStatus();
}
}
| 9,030
| 42.418269
| 184
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/customentrytypes/EntryTypeViewModel.java
|
package org.jabref.gui.preferences.customentrytypes;
import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.jabref.model.entry.BibEntryType;
import org.jabref.model.entry.field.Field;
import static org.jabref.gui.preferences.customentrytypes.FieldViewModel.Mandatory;
public class EntryTypeViewModel {
private final ObjectProperty<BibEntryType> entryType = new SimpleObjectProperty<>();
private final ObservableList<FieldViewModel> fields;
public EntryTypeViewModel(BibEntryType entryType, Predicate<Field> isMultiline) {
this.entryType.set(entryType);
List<FieldViewModel> allFieldsForType = entryType.getAllBibFields()
.stream().map(bibField -> new FieldViewModel(bibField.field(),
entryType.isRequired(bibField.field()) ? Mandatory.REQUIRED : Mandatory.OPTIONAL,
bibField.priority(),
isMultiline.test(bibField.field())))
.collect(Collectors.toList());
fields = FXCollections.observableArrayList(allFieldsForType);
}
@Override
public int hashCode() {
return Objects.hash(entryType, fields);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof EntryTypeViewModel)) {
return false;
}
EntryTypeViewModel other = (EntryTypeViewModel) obj;
return Objects.equals(entryType, other.entryType) && Objects.equals(fields, other.fields);
}
public void addField(FieldViewModel field) {
this.fields.add(field);
}
public ObservableList<FieldViewModel> fields() {
return this.fields;
}
public ObjectProperty<BibEntryType> entryType() {
return this.entryType;
}
public void removeField(FieldViewModel focusedItem) {
this.fields.remove(focusedItem);
}
@Override
public String toString() {
return "CustomEntryTypeViewModel [entryType=" + entryType + ", fields=" + fields + "]";
}
}
| 2,392
| 32.236111
| 116
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/customentrytypes/FieldViewModel.java
|
package org.jabref.gui.preferences.customentrytypes;
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.logic.l10n.Localization;
import org.jabref.model.entry.field.BibField;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.FieldFactory;
import org.jabref.model.entry.field.FieldPriority;
import org.jabref.model.entry.field.FieldProperty;
public class FieldViewModel {
private final StringProperty displayName = new SimpleStringProperty("");
private final BooleanProperty required = new SimpleBooleanProperty();
private final BooleanProperty multiline = new SimpleBooleanProperty();
private final ObjectProperty<FieldPriority> priorityProperty = new SimpleObjectProperty<>();
public FieldViewModel(Field field,
Mandatory required,
FieldPriority priorityProperty,
boolean multiline) {
this.displayName.setValue(field.getDisplayName());
this.required.setValue(required == Mandatory.REQUIRED);
this.priorityProperty.setValue(priorityProperty);
this.multiline.setValue(multiline);
}
public StringProperty displayNameProperty() {
return displayName;
}
public BooleanProperty requiredProperty() {
return required;
}
public boolean isRequired() {
return required.getValue();
}
public BooleanProperty multilineProperty() {
return multiline;
}
public boolean isMultiline() {
return multiline.getValue();
}
public FieldPriority getPriority() {
return priorityProperty.getValue();
}
public Field toField() {
// If the field name is known by JabRef, JabRef's casing will win.
// If the field is not known by JabRef (UnknownField), the new casing will be taken.
Field field = FieldFactory.parseField(displayName.getValue());
if (multiline.getValue()) {
field.getProperties().add(FieldProperty.MULTILINE_TEXT);
}
return field;
}
public BibField toBibField() {
return new BibField(toField(), priorityProperty.getValue());
}
@Override
public String toString() {
return displayName.getValue();
}
public enum Mandatory {
REQUIRED(Localization.lang("Required")),
OPTIONAL(Localization.lang("Optional"));
private final String name;
Mandatory(String name) {
this.name = name;
}
public String getDisplayName() {
return name;
}
}
}
| 2,837
| 29.847826
| 96
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/customexporter/CustomExporterTab.java
|
package org.jabref.gui.preferences.customexporter;
import javafx.fxml.FXML;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import org.jabref.gui.exporter.ExporterViewModel;
import org.jabref.gui.preferences.AbstractPreferenceTabView;
import org.jabref.gui.preferences.PreferencesTab;
import org.jabref.logic.l10n.Localization;
import com.airhacks.afterburner.views.ViewLoader;
import com.tobiasdiez.easybind.EasyBind;
public class CustomExporterTab extends AbstractPreferenceTabView<CustomExporterTabViewModel> implements PreferencesTab {
@FXML private TableView<ExporterViewModel> exporterTable;
@FXML private TableColumn<ExporterViewModel, String> nameColumn;
@FXML private TableColumn<ExporterViewModel, String> layoutColumn;
@FXML private TableColumn<ExporterViewModel, String> extensionColumn;
public CustomExporterTab() {
ViewLoader.view(this)
.root(this)
.load();
}
@Override
public String getTabName() {
return Localization.lang("Custom export formats");
}
@FXML
private void initialize() {
viewModel = new CustomExporterTabViewModel(preferencesService, dialogService);
exporterTable.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
exporterTable.itemsProperty().bind(viewModel.exportersProperty());
EasyBind.bindContent(viewModel.selectedExportersProperty(), exporterTable.getSelectionModel().getSelectedItems());
nameColumn.setCellValueFactory(cellData -> cellData.getValue().name());
layoutColumn.setCellValueFactory(cellData -> cellData.getValue().layoutFileName());
extensionColumn.setCellValueFactory(cellData -> cellData.getValue().extension());
}
@FXML
private void add() {
viewModel.addExporter();
}
@FXML
private void modify() {
viewModel.modifyExporter();
}
@FXML
private void remove() {
viewModel.removeExporters();
}
}
| 2,057
| 32.737705
| 122
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/customexporter/CustomExporterTabViewModel.java
|
package org.jabref.gui.preferences.customexporter;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.FXCollections;
import org.jabref.gui.DialogService;
import org.jabref.gui.exporter.CreateModifyExporterDialogView;
import org.jabref.gui.exporter.ExporterViewModel;
import org.jabref.gui.preferences.PreferenceTabViewModel;
import org.jabref.logic.exporter.TemplateExporter;
import org.jabref.preferences.PreferencesService;
public class CustomExporterTabViewModel implements PreferenceTabViewModel {
private final ListProperty<ExporterViewModel> exporters = new SimpleListProperty<>(FXCollections.observableArrayList());
private final ListProperty<ExporterViewModel> selectedExporters = new SimpleListProperty<>(FXCollections.observableArrayList());
private final PreferencesService preferences;
private final DialogService dialogService;
public CustomExporterTabViewModel(PreferencesService preferences, DialogService dialogService) {
this.preferences = preferences;
this.dialogService = dialogService;
}
@Override
public void setValues() {
List<TemplateExporter> exportersLogic = preferences.getExportPreferences().getCustomExporters();
for (TemplateExporter exporter : exportersLogic) {
exporters.add(new ExporterViewModel(exporter));
}
}
@Override
public void storeSettings() {
List<TemplateExporter> exportersLogic = exporters.stream()
.map(ExporterViewModel::getLogic)
.collect(Collectors.toList());
preferences.getExportPreferences().setCustomExporters(exportersLogic);
}
public void addExporter() {
CreateModifyExporterDialogView dialog = new CreateModifyExporterDialogView(null);
Optional<ExporterViewModel> exporter = dialogService.showCustomDialogAndWait(dialog);
if ((exporter != null) && exporter.isPresent()) {
exporters.add(exporter.get());
}
}
public void modifyExporter() {
if (selectedExporters.isEmpty()) {
return;
}
ExporterViewModel exporterToModify = selectedExporters.get(0);
CreateModifyExporterDialogView dialog = new CreateModifyExporterDialogView(exporterToModify);
Optional<ExporterViewModel> exporter = dialogService.showCustomDialogAndWait(dialog);
if ((exporter != null) && exporter.isPresent()) {
exporters.remove(exporterToModify);
exporters.add(exporter.get());
}
}
public void removeExporters() {
exporters.removeAll(selectedExporters);
}
public ListProperty<ExporterViewModel> selectedExportersProperty() {
return selectedExporters;
}
public ListProperty<ExporterViewModel> exportersProperty() {
return exporters;
}
}
| 3,054
| 36.716049
| 132
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/customimporter/CustomImporterTab.java
|
package org.jabref.gui.preferences.customimporter;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.Tooltip;
import org.jabref.gui.importer.ImporterViewModel;
import org.jabref.gui.preferences.AbstractPreferenceTabView;
import org.jabref.gui.preferences.PreferencesTab;
import org.jabref.gui.util.ViewModelTableRowFactory;
import org.jabref.logic.l10n.Localization;
import com.airhacks.afterburner.views.ViewLoader;
import com.tobiasdiez.easybind.EasyBind;
public class CustomImporterTab extends AbstractPreferenceTabView<CustomImporterTabViewModel> implements PreferencesTab {
@FXML private TableView<ImporterViewModel> importerTable;
@FXML private TableColumn<ImporterViewModel, String> nameColumn;
@FXML private TableColumn<ImporterViewModel, String> classColumn;
@FXML private TableColumn<ImporterViewModel, String> basePathColumn;
@FXML private Button addButton;
public CustomImporterTab() {
ViewLoader.view(this)
.root(this)
.load();
}
@Override
public String getTabName() {
return Localization.lang("Custom import formats");
}
@FXML
private void initialize() {
viewModel = new CustomImporterTabViewModel(preferencesService, dialogService);
importerTable.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
importerTable.itemsProperty().bind(viewModel.importersProperty());
EasyBind.bindContent(viewModel.selectedImportersProperty(), importerTable.getSelectionModel().getSelectedItems());
nameColumn.setCellValueFactory(cellData -> cellData.getValue().name());
classColumn.setCellValueFactory(cellData -> cellData.getValue().className());
basePathColumn.setCellValueFactory(cellData -> cellData.getValue().basePath());
new ViewModelTableRowFactory<ImporterViewModel>()
.withTooltip(importer -> importer.getLogic().getDescription())
.install(importerTable);
addButton.setTooltip(new Tooltip(
Localization.lang("Add a (compiled) custom Importer class from a class path.")
+ "\n" + Localization.lang("The path need not be on the classpath of JabRef.")));
}
@FXML
private void add() {
viewModel.addImporter();
}
@FXML
private void remove() {
viewModel.removeSelectedImporter();
}
}
| 2,557
| 37.179104
| 122
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/customimporter/CustomImporterTabViewModel.java
|
package org.jabref.gui.preferences.customimporter;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.FXCollections;
import org.jabref.gui.DialogService;
import org.jabref.gui.importer.ImporterViewModel;
import org.jabref.gui.preferences.PreferenceTabViewModel;
import org.jabref.gui.util.FileDialogConfiguration;
import org.jabref.logic.importer.ImportException;
import org.jabref.logic.importer.fileformat.CustomImporter;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.StandardFileType;
import org.jabref.logic.util.io.FileUtil;
import org.jabref.preferences.PreferencesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CustomImporterTabViewModel implements PreferenceTabViewModel {
private static final Logger LOGGER = LoggerFactory.getLogger(CustomImporterTabViewModel.class);
private final ListProperty<ImporterViewModel> importers = new SimpleListProperty<>(FXCollections.observableArrayList());
private final ListProperty<ImporterViewModel> selectedImporters = new SimpleListProperty<>(FXCollections.observableArrayList());
private final PreferencesService preferences;
private final DialogService dialogService;
public CustomImporterTabViewModel(PreferencesService preferences, DialogService dialogService) {
this.preferences = preferences;
this.dialogService = dialogService;
}
@Override
public void setValues() {
Set<CustomImporter> importersLogic = preferences.getImporterPreferences().getCustomImporters();
for (CustomImporter importer : importersLogic) {
importers.add(new ImporterViewModel(importer));
}
}
@Override
public void storeSettings() {
preferences.getImporterPreferences().setCustomImporters(importers.stream()
.map(ImporterViewModel::getLogic)
.collect(Collectors.toSet()));
}
/**
* Converts a path relative to a base-path into a class name.
*
* @param basePath base path
* @param path path that includes base-path as a prefix
* @return class name
*/
private static String pathToClass(String basePath, Path path) {
String className = FileUtil.relativize(path, Collections.singletonList(Path.of(basePath))).toString();
if (className != null) {
int lastDot = className.lastIndexOf('.');
if (lastDot < 0) {
return className;
}
className = className.substring(0, lastDot);
}
return className;
}
public void addImporter() {
FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
.addExtensionFilter(StandardFileType.CLASS, StandardFileType.JAR, StandardFileType.ZIP)
.withDefaultExtension(StandardFileType.CLASS)
.withInitialDirectory(preferences.getFilePreferences().getWorkingDirectory())
.build();
Optional<Path> selectedFile = dialogService.showFileOpenDialog(fileDialogConfiguration);
if (selectedFile.isPresent() && (selectedFile.get().getParent() != null)) {
boolean isArchive = FileUtil.getFileExtension(selectedFile.get())
.filter(extension -> "jar".equalsIgnoreCase(extension) || "zip".equalsIgnoreCase(extension))
.isPresent();
if (isArchive) {
try {
Optional<Path> selectedFileInArchive = dialogService.showFileOpenFromArchiveDialog(selectedFile.get());
if (selectedFileInArchive.isPresent()) {
String className = selectedFileInArchive.get().toString().substring(0, selectedFileInArchive.get().toString().lastIndexOf('.')).replace(
"/", ".");
CustomImporter importer = new CustomImporter(selectedFile.get().toAbsolutePath().toString(), className);
importers.add(new ImporterViewModel(importer));
}
} catch (IOException exc) {
LOGGER.error("Could not open ZIP-archive.", exc);
dialogService.showErrorDialogAndWait(
Localization.lang("Could not open %0", selectedFile.get().toString()) + "\n"
+ Localization.lang("Have you chosen the correct package path?"),
exc);
} catch (ImportException exc) {
LOGGER.error("Could not instantiate importer", exc);
dialogService.showErrorDialogAndWait(
Localization.lang("Could not instantiate %0 %1", "importer"),
exc);
}
} else {
try {
String basePath = selectedFile.get().getParent().toString();
String className = pathToClass(basePath, selectedFile.get());
CustomImporter importer = new CustomImporter(basePath, className);
importers.add(new ImporterViewModel(importer));
} catch (Exception exc) {
LOGGER.error("Could not instantiate importer", exc);
dialogService.showErrorDialogAndWait(Localization.lang("Could not instantiate %0", selectedFile.get().toString()), exc);
} catch (NoClassDefFoundError exc) {
LOGGER.error("Could not find class while instantiating importer", exc);
dialogService.showErrorDialogAndWait(
Localization.lang("Could not instantiate %0. Have you chosen the correct package path?", selectedFile.get().toString()),
exc);
}
}
}
}
public void removeSelectedImporter() {
importers.removeAll(selectedImporters);
}
public ListProperty<ImporterViewModel> selectedImportersProperty() {
return selectedImporters;
}
public ListProperty<ImporterViewModel> importersProperty() {
return importers;
}
}
| 6,544
| 44.451389
| 160
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/entry/EntryTab.java
|
package org.jabref.gui.preferences.entry;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TextField;
import org.jabref.gui.actions.ActionFactory;
import org.jabref.gui.actions.StandardActions;
import org.jabref.gui.help.HelpAction;
import org.jabref.gui.keyboard.KeyBindingRepository;
import org.jabref.gui.preferences.AbstractPreferenceTabView;
import org.jabref.gui.preferences.PreferencesTab;
import org.jabref.logic.help.HelpFile;
import org.jabref.logic.l10n.Localization;
import com.airhacks.afterburner.views.ViewLoader;
import jakarta.inject.Inject;
public class EntryTab extends AbstractPreferenceTabView<EntryTabViewModel> implements PreferencesTab {
@FXML private TextField keywordSeparator;
@FXML private CheckBox resolveStrings;
@FXML private TextField resolveStringsForFields;
@FXML private TextField nonWrappableFields;
@FXML private CheckBox markOwner;
@FXML private TextField markOwnerName;
@FXML private CheckBox markOwnerOverwrite;
@FXML private Button markOwnerHelp;
@FXML private CheckBox addCreationDate;
@FXML private CheckBox addModificationDate;
@Inject private KeyBindingRepository keyBindingRepository;
public EntryTab() {
ViewLoader.view(this)
.root(this)
.load();
}
public void initialize() {
this.viewModel = new EntryTabViewModel(preferencesService);
keywordSeparator.textProperty().bindBidirectional(viewModel.keywordSeparatorProperty());
resolveStrings.selectedProperty().bindBidirectional(viewModel.resolveStringsProperty());
resolveStringsForFields.textProperty().bindBidirectional(viewModel.resolveStringsForFieldsProperty());
nonWrappableFields.textProperty().bindBidirectional(viewModel.nonWrappableFieldsProperty());
markOwner.selectedProperty().bindBidirectional(viewModel.markOwnerProperty());
markOwnerName.textProperty().bindBidirectional(viewModel.markOwnerNameProperty());
markOwnerName.disableProperty().bind(markOwner.selectedProperty().not());
markOwnerOverwrite.selectedProperty().bindBidirectional(viewModel.markOwnerOverwriteProperty());
markOwnerOverwrite.disableProperty().bind(markOwner.selectedProperty().not());
addCreationDate.selectedProperty().bindBidirectional(viewModel.addCreationDateProperty());
addModificationDate.selectedProperty().bindBidirectional(viewModel.addModificationDateProperty());
ActionFactory actionFactory = new ActionFactory(keyBindingRepository);
actionFactory.configureIconButton(StandardActions.HELP, new HelpAction(HelpFile.OWNER, dialogService), markOwnerHelp);
}
@Override
public String getTabName() {
return Localization.lang("Entry");
}
}
| 2,862
| 38.219178
| 126
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/entry/EntryTabViewModel.java
|
package org.jabref.gui.preferences.entry;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import org.jabref.gui.preferences.PreferenceTabViewModel;
import org.jabref.logic.bibtex.FieldPreferences;
import org.jabref.logic.preferences.OwnerPreferences;
import org.jabref.logic.preferences.TimestampPreferences;
import org.jabref.model.entry.field.FieldFactory;
import org.jabref.preferences.BibEntryPreferences;
import org.jabref.preferences.PreferencesService;
public class EntryTabViewModel implements PreferenceTabViewModel {
private final StringProperty keywordSeparatorProperty = new SimpleStringProperty("");
private final BooleanProperty resolveStringsProperty = new SimpleBooleanProperty();
private final StringProperty resolveStringsForFieldsProperty = new SimpleStringProperty("");
private final StringProperty nonWrappableFieldsProperty = new SimpleStringProperty("");
private final BooleanProperty markOwnerProperty = new SimpleBooleanProperty();
private final StringProperty markOwnerNameProperty = new SimpleStringProperty("");
private final BooleanProperty markOwnerOverwriteProperty = new SimpleBooleanProperty();
private final BooleanProperty addCreationDateProperty = new SimpleBooleanProperty();
private final BooleanProperty addModificationDateProperty = new SimpleBooleanProperty();
private final FieldPreferences fieldPreferences;
private final BibEntryPreferences bibEntryPreferences;
private final OwnerPreferences ownerPreferences;
private final TimestampPreferences timestampPreferences;
public EntryTabViewModel(PreferencesService preferencesService) {
this.bibEntryPreferences = preferencesService.getBibEntryPreferences();
this.fieldPreferences = preferencesService.getFieldPreferences();
this.ownerPreferences = preferencesService.getOwnerPreferences();
this.timestampPreferences = preferencesService.getTimestampPreferences();
}
@Override
public void setValues() {
keywordSeparatorProperty.setValue(bibEntryPreferences.getKeywordSeparator().toString());
resolveStringsProperty.setValue(fieldPreferences.shouldResolveStrings());
resolveStringsForFieldsProperty.setValue(FieldFactory.serializeFieldsList(fieldPreferences.getResolvableFields()));
nonWrappableFieldsProperty.setValue(FieldFactory.serializeFieldsList(fieldPreferences.getNonWrappableFields()));
markOwnerProperty.setValue(ownerPreferences.isUseOwner());
markOwnerNameProperty.setValue(ownerPreferences.getDefaultOwner());
markOwnerOverwriteProperty.setValue(ownerPreferences.isOverwriteOwner());
addCreationDateProperty.setValue(timestampPreferences.shouldAddCreationDate());
addModificationDateProperty.setValue(timestampPreferences.shouldAddModificationDate());
}
@Override
public void storeSettings() {
bibEntryPreferences.keywordSeparatorProperty().setValue(keywordSeparatorProperty.getValue().charAt(0));
fieldPreferences.setResolveStrings(resolveStringsProperty.getValue());
fieldPreferences.setResolvableFields(FieldFactory.parseFieldList(resolveStringsForFieldsProperty.getValue().trim()));
fieldPreferences.setNonWrappableFields(FieldFactory.parseFieldList(nonWrappableFieldsProperty.getValue().trim()));
ownerPreferences.setUseOwner(markOwnerProperty.getValue());
ownerPreferences.setDefaultOwner(markOwnerNameProperty.getValue());
ownerPreferences.setOverwriteOwner(markOwnerOverwriteProperty.getValue());
timestampPreferences.setAddCreationDate(addCreationDateProperty.getValue());
timestampPreferences.setAddModificationDate(addModificationDateProperty.getValue());
}
public StringProperty keywordSeparatorProperty() {
return keywordSeparatorProperty;
}
public BooleanProperty resolveStringsProperty() {
return resolveStringsProperty;
}
public StringProperty resolveStringsForFieldsProperty() {
return resolveStringsForFieldsProperty;
}
public StringProperty nonWrappableFieldsProperty() {
return nonWrappableFieldsProperty;
}
// Entry owner
public BooleanProperty markOwnerProperty() {
return this.markOwnerProperty;
}
public StringProperty markOwnerNameProperty() {
return this.markOwnerNameProperty;
}
public BooleanProperty markOwnerOverwriteProperty() {
return this.markOwnerOverwriteProperty;
}
// Time stamp
public BooleanProperty addCreationDateProperty() {
return addCreationDateProperty;
}
public BooleanProperty addModificationDateProperty() {
return addModificationDateProperty;
}
}
| 4,884
| 41.850877
| 125
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/entryeditor/EntryEditorTab.java
|
package org.jabref.gui.preferences.entryeditor;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TextArea;
import org.jabref.gui.actions.ActionFactory;
import org.jabref.gui.actions.StandardActions;
import org.jabref.gui.help.HelpAction;
import org.jabref.gui.keyboard.KeyBindingRepository;
import org.jabref.gui.preferences.AbstractPreferenceTabView;
import org.jabref.gui.preferences.PreferencesTab;
import org.jabref.logic.help.HelpFile;
import org.jabref.logic.l10n.Localization;
import com.airhacks.afterburner.views.ViewLoader;
import jakarta.inject.Inject;
public class EntryEditorTab extends AbstractPreferenceTabView<EntryEditorTabViewModel> implements PreferencesTab {
@FXML private CheckBox openOnNewEntry;
@FXML private CheckBox defaultSource;
@FXML private CheckBox enableRelatedArticlesTab;
@FXML private CheckBox acceptRecommendations;
@FXML private CheckBox enableLatexCitationsTab;
@FXML private CheckBox enableValidation;
@FXML private CheckBox allowIntegerEdition;
@FXML private CheckBox autoLinkFilesEnabled;
@FXML private Button generalFieldsHelp;
@FXML private TextArea fieldsTextArea;
@Inject private KeyBindingRepository keyBindingRepository;
public EntryEditorTab() {
ViewLoader.view(this)
.root(this)
.load();
}
@Override
public String getTabName() {
return Localization.lang("Entry editor");
}
public void initialize() {
this.viewModel = new EntryEditorTabViewModel(dialogService, preferencesService);
openOnNewEntry.selectedProperty().bindBidirectional(viewModel.openOnNewEntryProperty());
defaultSource.selectedProperty().bindBidirectional(viewModel.defaultSourceProperty());
enableRelatedArticlesTab.selectedProperty().bindBidirectional(viewModel.enableRelatedArticlesTabProperty());
acceptRecommendations.selectedProperty().bindBidirectional(viewModel.acceptRecommendationsProperty());
enableLatexCitationsTab.selectedProperty().bindBidirectional(viewModel.enableLatexCitationsTabProperty());
enableValidation.selectedProperty().bindBidirectional(viewModel.enableValidationProperty());
allowIntegerEdition.selectedProperty().bindBidirectional(viewModel.allowIntegerEditionProperty());
autoLinkFilesEnabled.selectedProperty().bindBidirectional(viewModel.autoLinkFilesEnabledProperty());
fieldsTextArea.textProperty().bindBidirectional(viewModel.fieldsProperty());
ActionFactory actionFactory = new ActionFactory(keyBindingRepository);
actionFactory.configureIconButton(StandardActions.HELP, new HelpAction(HelpFile.GENERAL_FIELDS, dialogService), generalFieldsHelp);
}
@FXML
void resetToDefaults() {
viewModel.resetToDefaults();
}
}
| 2,895
| 40.371429
| 139
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/entryeditor/EntryEditorTabViewModel.java
|
package org.jabref.gui.preferences.entryeditor;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import org.jabref.gui.DialogService;
import org.jabref.gui.entryeditor.EntryEditorPreferences;
import org.jabref.gui.preferences.PreferenceTabViewModel;
import org.jabref.logic.citationkeypattern.CitationKeyGenerator;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.FieldFactory;
import org.jabref.preferences.PreferencesService;
public class EntryEditorTabViewModel implements PreferenceTabViewModel {
private final BooleanProperty openOnNewEntryProperty = new SimpleBooleanProperty();
private final BooleanProperty defaultSourceProperty = new SimpleBooleanProperty();
private final BooleanProperty enableRelatedArticlesTabProperty = new SimpleBooleanProperty();
private final BooleanProperty acceptRecommendationsProperty = new SimpleBooleanProperty();
private final BooleanProperty enableLatexCitationsTabProperty = new SimpleBooleanProperty();
private final BooleanProperty enableValidationProperty = new SimpleBooleanProperty();
private final BooleanProperty allowIntegerEditionProperty = new SimpleBooleanProperty();
private final BooleanProperty autoLinkEnabledProperty = new SimpleBooleanProperty();
private final StringProperty fieldsProperty = new SimpleStringProperty();
private final DialogService dialogService;
private final PreferencesService preferencesService;
private final EntryEditorPreferences entryEditorPreferences;
public EntryEditorTabViewModel(DialogService dialogService, PreferencesService preferencesService) {
this.dialogService = dialogService;
this.preferencesService = preferencesService;
this.entryEditorPreferences = preferencesService.getEntryEditorPreferences();
}
@Override
public void setValues() {
// ToDo: Include CustomizeGeneralFieldsDialog in PreferencesDialog
// therefore yet unused: entryEditorPreferences.getEntryEditorTabList();
openOnNewEntryProperty.setValue(entryEditorPreferences.shouldOpenOnNewEntry());
defaultSourceProperty.setValue(entryEditorPreferences.showSourceTabByDefault());
enableRelatedArticlesTabProperty.setValue(entryEditorPreferences.shouldShowRecommendationsTab());
acceptRecommendationsProperty.setValue(entryEditorPreferences.isMrdlibAccepted());
enableLatexCitationsTabProperty.setValue(entryEditorPreferences.shouldShowLatexCitationsTab());
enableValidationProperty.setValue(entryEditorPreferences.shouldEnableValidation());
allowIntegerEditionProperty.setValue(entryEditorPreferences.shouldAllowIntegerEditionBibtex());
autoLinkEnabledProperty.setValue(entryEditorPreferences.autoLinkFilesEnabled());
setFields(entryEditorPreferences.getEntryEditorTabs());
}
public void resetToDefaults() {
setFields(preferencesService.getEntryEditorPreferences().getDefaultEntryEditorTabs());
}
private void setFields(Map<String, Set<Field>> tabNamesAndFields) {
StringBuilder sb = new StringBuilder();
// Fill with customized vars
for (Map.Entry<String, Set<Field>> tab : tabNamesAndFields.entrySet()) {
sb.append(tab.getKey());
sb.append(':');
sb.append(FieldFactory.serializeFieldsList(tab.getValue()));
sb.append('\n');
}
fieldsProperty.set(sb.toString());
}
@Override
public void storeSettings() {
// entryEditorPreferences.setEntryEditorTabList();
entryEditorPreferences.setShouldOpenOnNewEntry(openOnNewEntryProperty.getValue());
entryEditorPreferences.setShouldShowRecommendationsTab(enableRelatedArticlesTabProperty.getValue());
entryEditorPreferences.setIsMrdlibAccepted(acceptRecommendationsProperty.getValue());
entryEditorPreferences.setShouldShowLatexCitationsTab(enableLatexCitationsTabProperty.getValue());
entryEditorPreferences.setShowSourceTabByDefault(defaultSourceProperty.getValue());
entryEditorPreferences.setEnableValidation(enableValidationProperty.getValue());
entryEditorPreferences.setAllowIntegerEditionBibtex(allowIntegerEditionProperty.getValue());
// entryEditorPreferences.setDividerPosition();
entryEditorPreferences.setAutoLinkFilesEnabled(autoLinkEnabledProperty.getValue());
Map<String, Set<Field>> customTabsMap = new LinkedHashMap<>();
String[] lines = fieldsProperty.get().split("\n");
for (String line : lines) {
String[] parts = line.split(":");
if (parts.length != 2) {
dialogService.showInformationDialogAndWait(
Localization.lang("Error"),
Localization.lang("Each line must be of the following form: 'tab:field1;field2;...;fieldN'."));
return;
}
// Use literal string of unwanted characters specified below as opposed to exporting characters
// from preferences because the list of allowable characters in this particular differs
// i.e. ';' character is allowed in this window, but it's on the list of unwanted chars in preferences
String unwantedChars = "#{}()~,^&-\"'`ʹ\\";
String testString = CitationKeyGenerator.cleanKey(parts[1], unwantedChars);
if (!testString.equals(parts[1])) {
dialogService.showInformationDialogAndWait(
Localization.lang("Error"),
Localization.lang("Field names are not allowed to contain white spaces or certain characters (%0).",
"# { } ( ) ~ , ^ & - \" ' ` ʹ \\"));
return;
}
customTabsMap.put(parts[0], FieldFactory.parseFieldList(parts[1]));
}
entryEditorPreferences.setEntryEditorTabList(customTabsMap);
}
public BooleanProperty openOnNewEntryProperty() {
return openOnNewEntryProperty;
}
public BooleanProperty defaultSourceProperty() {
return defaultSourceProperty;
}
public BooleanProperty enableRelatedArticlesTabProperty() {
return enableRelatedArticlesTabProperty;
}
public BooleanProperty acceptRecommendationsProperty() {
return acceptRecommendationsProperty;
}
public BooleanProperty enableLatexCitationsTabProperty() {
return enableLatexCitationsTabProperty;
}
public BooleanProperty enableValidationProperty() {
return enableValidationProperty;
}
public BooleanProperty allowIntegerEditionProperty() {
return this.allowIntegerEditionProperty;
}
public StringProperty fieldsProperty() {
return fieldsProperty;
}
public BooleanProperty autoLinkFilesEnabledProperty() {
return autoLinkEnabledProperty;
}
}
| 7,170
| 44.386076
| 124
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/export/ExportTab.java
|
package org.jabref.gui.preferences.export;
import javafx.fxml.FXML;
import org.jabref.gui.commonfxcontrols.SaveOrderConfigPanel;
import org.jabref.gui.preferences.AbstractPreferenceTabView;
import org.jabref.gui.preferences.PreferencesTab;
import org.jabref.logic.l10n.Localization;
import com.airhacks.afterburner.views.ViewLoader;
public class ExportTab extends AbstractPreferenceTabView<ExportTabViewModel> implements PreferencesTab {
@FXML private SaveOrderConfigPanel exportOrderPanel;
public ExportTab() {
ViewLoader.view(this)
.root(this)
.load();
}
@Override
public String getTabName() {
return Localization.lang("Export");
}
public void initialize() {
this.viewModel = new ExportTabViewModel(preferencesService.getExportPreferences());
exportOrderPanel.saveInOriginalProperty().bindBidirectional(viewModel.saveInOriginalProperty());
exportOrderPanel.saveInTableOrderProperty().bindBidirectional(viewModel.saveInTableOrderProperty());
exportOrderPanel.saveInSpecifiedOrderProperty().bindBidirectional(viewModel.saveInSpecifiedOrderProperty());
exportOrderPanel.sortableFieldsProperty().bind(viewModel.sortableFieldsProperty());
exportOrderPanel.sortCriteriaProperty().bindBidirectional(viewModel.sortCriteriaProperty());
exportOrderPanel.setCriteriaLimit(3);
}
}
| 1,419
| 37.378378
| 116
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/export/ExportTabViewModel.java
|
package org.jabref.gui.preferences.export;
import java.util.ArrayList;
import java.util.Set;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.FXCollections;
import org.jabref.gui.commonfxcontrols.SortCriterionViewModel;
import org.jabref.gui.preferences.PreferenceTabViewModel;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.FieldFactory;
import org.jabref.model.entry.field.InternalField;
import org.jabref.model.metadata.SaveOrder;
import org.jabref.preferences.ExportPreferences;
public class ExportTabViewModel implements PreferenceTabViewModel {
// SaveOrderConfigPanel
private final BooleanProperty exportInOriginalProperty = new SimpleBooleanProperty();
private final BooleanProperty exportInTableOrderProperty = new SimpleBooleanProperty();
private final BooleanProperty exportInSpecifiedOrderProperty = new SimpleBooleanProperty();
private final ListProperty<Field> sortableFieldsProperty = new SimpleListProperty<>(FXCollections.observableArrayList());
private final ListProperty<SortCriterionViewModel> sortCriteriaProperty = new SimpleListProperty<>(FXCollections.observableArrayList(new ArrayList<>()));
private final ExportPreferences exportPreferences;
public ExportTabViewModel(ExportPreferences exportPreferences) {
this.exportPreferences = exportPreferences;
}
@Override
public void setValues() {
SaveOrder exportSaveOrder = exportPreferences.getExportSaveOrder();
switch (exportSaveOrder.getOrderType()) {
case SPECIFIED -> exportInSpecifiedOrderProperty.setValue(true);
case ORIGINAL -> exportInOriginalProperty.setValue(true);
case TABLE -> exportInTableOrderProperty.setValue(true);
}
sortCriteriaProperty.addAll(exportSaveOrder.getSortCriteria().stream()
.map(SortCriterionViewModel::new)
.toList());
Set<Field> fields = FieldFactory.getAllFieldsWithOutInternal();
fields.add(InternalField.INTERNAL_ALL_FIELD);
fields.add(InternalField.INTERNAL_ALL_TEXT_FIELDS_FIELD);
fields.add(InternalField.KEY_FIELD);
fields.add(InternalField.TYPE_HEADER);
sortableFieldsProperty.addAll(FieldFactory.getStandardFieldsWithCitationKey());
}
@Override
public void storeSettings() {
SaveOrder newSaveOrder = new SaveOrder(
SaveOrder.OrderType.fromBooleans(exportInSpecifiedOrderProperty.getValue(), exportInOriginalProperty.getValue()),
sortCriteriaProperty.stream().map(SortCriterionViewModel::getCriterion).toList());
exportPreferences.setExportSaveOrder(newSaveOrder);
}
public BooleanProperty saveInOriginalProperty() {
return exportInOriginalProperty;
}
public BooleanProperty saveInTableOrderProperty() {
return exportInTableOrderProperty;
}
public BooleanProperty saveInSpecifiedOrderProperty() {
return exportInSpecifiedOrderProperty;
}
public ListProperty<Field> sortableFieldsProperty() {
return sortableFieldsProperty;
}
public ListProperty<SortCriterionViewModel> sortCriteriaProperty() {
return sortCriteriaProperty;
}
}
| 3,469
| 40.807229
| 157
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/external/ExternalTab.java
|
package org.jabref.gui.preferences.external;
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.preferences.AbstractPreferenceTabView;
import org.jabref.gui.preferences.PreferencesTab;
import org.jabref.gui.push.PushToApplication;
import org.jabref.gui.util.IconValidationDecorator;
import org.jabref.gui.util.ViewModelListCellFactory;
import org.jabref.logic.l10n.Localization;
import com.airhacks.afterburner.views.ViewLoader;
import de.saxsys.mvvmfx.utils.validation.visualization.ControlsFxVisualizer;
public class ExternalTab extends AbstractPreferenceTabView<ExternalTabViewModel> implements PreferencesTab {
@FXML private TextField eMailReferenceSubject;
@FXML private CheckBox autoOpenAttachedFolders;
@FXML private ComboBox<PushToApplication> pushToApplicationCombo;
@FXML private TextField citeCommand;
@FXML private CheckBox useCustomTerminal;
@FXML private TextField customTerminalCommand;
@FXML private Button customTerminalBrowse;
@FXML private CheckBox useCustomFileBrowser;
@FXML private TextField customFileBrowserCommand;
@FXML private Button customFileBrowserBrowse;
@FXML private TextField kindleEmail;
private final ControlsFxVisualizer validationVisualizer = new ControlsFxVisualizer();
public ExternalTab() {
ViewLoader.view(this)
.root(this)
.load();
}
@Override
public String getTabName() {
return Localization.lang("External programs");
}
public void initialize() {
this.viewModel = new ExternalTabViewModel(dialogService, preferencesService);
new ViewModelListCellFactory<PushToApplication>()
.withText(PushToApplication::getDisplayName)
.withIcon(PushToApplication::getApplicationIcon)
.install(pushToApplicationCombo);
eMailReferenceSubject.textProperty().bindBidirectional(viewModel.eMailReferenceSubjectProperty());
autoOpenAttachedFolders.selectedProperty().bindBidirectional(viewModel.autoOpenAttachedFoldersProperty());
pushToApplicationCombo.itemsProperty().bind(viewModel.pushToApplicationsListProperty());
pushToApplicationCombo.valueProperty().bindBidirectional(viewModel.selectedPushToApplication());
citeCommand.textProperty().bindBidirectional(viewModel.citeCommandProperty());
useCustomTerminal.selectedProperty().bindBidirectional(viewModel.useCustomTerminalProperty());
customTerminalCommand.textProperty().bindBidirectional(viewModel.customTerminalCommandProperty());
customTerminalCommand.disableProperty().bind(useCustomTerminal.selectedProperty().not());
customTerminalBrowse.disableProperty().bind(useCustomTerminal.selectedProperty().not());
useCustomFileBrowser.selectedProperty().bindBidirectional(viewModel.useCustomFileBrowserProperty());
customFileBrowserCommand.textProperty().bindBidirectional(viewModel.customFileBrowserCommandProperty());
customFileBrowserCommand.disableProperty().bind(useCustomFileBrowser.selectedProperty().not());
customFileBrowserBrowse.disableProperty().bind(useCustomFileBrowser.selectedProperty().not());
kindleEmail.textProperty().bindBidirectional(viewModel.kindleEmailProperty());
validationVisualizer.setDecoration(new IconValidationDecorator());
Platform.runLater(() -> {
validationVisualizer.initVisualization(viewModel.terminalCommandValidationStatus(), customTerminalCommand);
validationVisualizer.initVisualization(viewModel.fileBrowserCommandValidationStatus(), customFileBrowserCommand);
});
}
@FXML
void pushToApplicationSettings() {
viewModel.pushToApplicationSettings();
}
@FXML
void useTerminalCommandBrowse() {
viewModel.customTerminalBrowse();
}
@FXML
void useFileBrowserSpecialCommandBrowse() {
viewModel.customFileBrowserBrowse();
}
}
| 4,152
| 42.260417
| 125
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/external/ExternalTabViewModel.java
|
package org.jabref.gui.preferences.external;
import java.util.HashMap;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ListProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.scene.control.ButtonType;
import javafx.scene.control.DialogPane;
import org.jabref.gui.DialogService;
import org.jabref.gui.preferences.PreferenceTabViewModel;
import org.jabref.gui.push.PushToApplication;
import org.jabref.gui.push.PushToApplicationSettings;
import org.jabref.gui.push.PushToApplications;
import org.jabref.gui.push.PushToEmacs;
import org.jabref.gui.util.FileDialogConfiguration;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.strings.StringUtil;
import org.jabref.preferences.ExternalApplicationsPreferences;
import org.jabref.preferences.PreferencesService;
import org.jabref.preferences.PushToApplicationPreferences;
import de.saxsys.mvvmfx.utils.validation.CompositeValidator;
import de.saxsys.mvvmfx.utils.validation.FunctionBasedValidator;
import de.saxsys.mvvmfx.utils.validation.ValidationMessage;
import de.saxsys.mvvmfx.utils.validation.ValidationStatus;
import de.saxsys.mvvmfx.utils.validation.Validator;
public class ExternalTabViewModel implements PreferenceTabViewModel {
private final StringProperty eMailReferenceSubjectProperty = new SimpleStringProperty("");
private final BooleanProperty autoOpenAttachedFoldersProperty = new SimpleBooleanProperty();
private final ListProperty<PushToApplication> pushToApplicationsListProperty = new SimpleListProperty<>();
private final ObjectProperty<PushToApplication> selectedPushToApplicationProperty = new SimpleObjectProperty<>();
private final StringProperty citeCommandProperty = new SimpleStringProperty("");
private final BooleanProperty useCustomTerminalProperty = new SimpleBooleanProperty();
private final StringProperty customTerminalCommandProperty = new SimpleStringProperty("");
private final BooleanProperty useCustomFileBrowserProperty = new SimpleBooleanProperty();
private final StringProperty customFileBrowserCommandProperty = new SimpleStringProperty("");
private final StringProperty kindleEmailProperty = new SimpleStringProperty("");
private final Validator terminalCommandValidator;
private final Validator fileBrowserCommandValidator;
private final DialogService dialogService;
private final PreferencesService preferences;
private final FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder().build();
private final ExternalApplicationsPreferences initialExternalApplicationPreferences;
private final PushToApplicationPreferences initialPushToApplicationPreferences;
private final PushToApplicationPreferences workingPushToApplicationPreferences;
public ExternalTabViewModel(DialogService dialogService, PreferencesService preferencesService) {
this.dialogService = dialogService;
this.preferences = preferencesService;
this.initialExternalApplicationPreferences = preferences.getExternalApplicationsPreferences();
this.initialPushToApplicationPreferences = preferences.getPushToApplicationPreferences();
this.workingPushToApplicationPreferences = new PushToApplicationPreferences(
initialPushToApplicationPreferences.getActiveApplicationName(),
new HashMap<>(initialPushToApplicationPreferences.getCommandPaths()),
initialPushToApplicationPreferences.getEmacsArguments(),
initialPushToApplicationPreferences.getVimServer());
terminalCommandValidator = new FunctionBasedValidator<>(
customTerminalCommandProperty,
input -> !StringUtil.isNullOrEmpty(input),
ValidationMessage.error(String.format("%s > %s %n %n %s",
Localization.lang("External programs"),
Localization.lang("Custom applications"),
Localization.lang("Please specify a terminal application."))));
fileBrowserCommandValidator = new FunctionBasedValidator<>(
customFileBrowserCommandProperty,
input -> !StringUtil.isNullOrEmpty(input),
ValidationMessage.error(String.format("%s > %s %n %n %s",
Localization.lang("External programs"),
Localization.lang("Custom applications"),
Localization.lang("Please specify a file browser."))));
}
public void setValues() {
eMailReferenceSubjectProperty.setValue(initialExternalApplicationPreferences.getEmailSubject());
autoOpenAttachedFoldersProperty.setValue(initialExternalApplicationPreferences.shouldAutoOpenEmailAttachmentsFolder());
pushToApplicationsListProperty.setValue(
FXCollections.observableArrayList(PushToApplications.getAllApplications(dialogService, preferences)));
selectedPushToApplicationProperty.setValue(
PushToApplications.getApplicationByName(initialPushToApplicationPreferences.getActiveApplicationName(), dialogService, preferences)
.orElse(new PushToEmacs(dialogService, preferences)));
citeCommandProperty.setValue(initialExternalApplicationPreferences.getCiteCommand());
useCustomTerminalProperty.setValue(initialExternalApplicationPreferences.useCustomTerminal());
customTerminalCommandProperty.setValue(initialExternalApplicationPreferences.getCustomTerminalCommand());
useCustomFileBrowserProperty.setValue(initialExternalApplicationPreferences.useCustomFileBrowser());
customFileBrowserCommandProperty.setValue(initialExternalApplicationPreferences.getCustomFileBrowserCommand());
kindleEmailProperty.setValue(initialExternalApplicationPreferences.getKindleEmail());
}
public void storeSettings() {
ExternalApplicationsPreferences externalPreferences = preferences.getExternalApplicationsPreferences();
externalPreferences.setEMailSubject(eMailReferenceSubjectProperty.getValue());
externalPreferences.setAutoOpenEmailAttachmentsFolder(autoOpenAttachedFoldersProperty.getValue());
externalPreferences.setCiteCommand(citeCommandProperty.getValue());
externalPreferences.setUseCustomTerminal(useCustomTerminalProperty.getValue());
externalPreferences.setCustomTerminalCommand(customTerminalCommandProperty.getValue());
externalPreferences.setUseCustomFileBrowser(useCustomFileBrowserProperty.getValue());
externalPreferences.setCustomFileBrowserCommand(customFileBrowserCommandProperty.getValue());
externalPreferences.setKindleEmail(kindleEmailProperty.getValue());
PushToApplicationPreferences pushPreferences = preferences.getPushToApplicationPreferences();
pushPreferences.setActiveApplicationName(selectedPushToApplicationProperty.getValue().getDisplayName());
pushPreferences.setCommandPaths(workingPushToApplicationPreferences.getCommandPaths());
pushPreferences.setEmacsArguments(workingPushToApplicationPreferences.getEmacsArguments());
pushPreferences.setVimServer(workingPushToApplicationPreferences.getVimServer());
}
public ValidationStatus terminalCommandValidationStatus() {
return terminalCommandValidator.getValidationStatus();
}
public ValidationStatus fileBrowserCommandValidationStatus() {
return fileBrowserCommandValidator.getValidationStatus();
}
public boolean validateSettings() {
CompositeValidator validator = new CompositeValidator();
if (useCustomTerminalProperty.getValue()) {
validator.addValidators(terminalCommandValidator);
}
if (useCustomFileBrowserProperty.getValue()) {
validator.addValidators(fileBrowserCommandValidator);
}
ValidationStatus validationStatus = validator.getValidationStatus();
if (!validationStatus.isValid()) {
validationStatus.getHighestMessage().ifPresent(message ->
dialogService.showErrorDialogAndWait(message.getMessage()));
return false;
}
return true;
}
public void pushToApplicationSettings() {
PushToApplication selectedApplication = selectedPushToApplicationProperty.getValue();
PushToApplicationSettings settings = selectedApplication.getSettings(selectedApplication, workingPushToApplicationPreferences);
DialogPane dialogPane = new DialogPane();
dialogPane.setContent(settings.getSettingsPane());
dialogService.showCustomDialogAndWait(
Localization.lang("Application settings"),
dialogPane,
ButtonType.OK, ButtonType.CANCEL)
.ifPresent(btn -> {
if (btn == ButtonType.OK) {
settings.storeSettings();
}
}
);
}
public void customTerminalBrowse() {
dialogService.showFileOpenDialog(fileDialogConfiguration)
.ifPresent(file -> customTerminalCommandProperty.setValue(file.toAbsolutePath().toString()));
}
public void customFileBrowserBrowse() {
dialogService.showFileOpenDialog(fileDialogConfiguration)
.ifPresent(file -> customFileBrowserCommandProperty.setValue(file.toAbsolutePath().toString()));
}
// EMail
public StringProperty eMailReferenceSubjectProperty() {
return this.eMailReferenceSubjectProperty;
}
public StringProperty kindleEmailProperty() {
return this.kindleEmailProperty;
}
public BooleanProperty autoOpenAttachedFoldersProperty() {
return this.autoOpenAttachedFoldersProperty;
}
// Push-To-Application
public ListProperty<PushToApplication> pushToApplicationsListProperty() {
return this.pushToApplicationsListProperty;
}
public ObjectProperty<PushToApplication> selectedPushToApplication() {
return this.selectedPushToApplicationProperty;
}
public StringProperty citeCommandProperty() {
return this.citeCommandProperty;
}
// Open console
public BooleanProperty useCustomTerminalProperty() {
return this.useCustomTerminalProperty;
}
public StringProperty customTerminalCommandProperty() {
return this.customTerminalCommandProperty;
}
// Open File Browser
public BooleanProperty useCustomFileBrowserProperty() {
return this.useCustomFileBrowserProperty;
}
public StringProperty customFileBrowserCommandProperty() {
return this.customFileBrowserCommandProperty;
}
}
| 11,100
| 47.265217
| 147
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/externalfiletypes/EditExternalFileTypeEntryDialog.java
|
package org.jabref.gui.preferences.externalfiletypes;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import org.jabref.gui.DialogService;
import org.jabref.gui.desktop.os.NativeDesktop;
import org.jabref.gui.util.BaseDialog;
import org.jabref.gui.util.FileDialogConfiguration;
import org.jabref.logic.util.OS;
import com.airhacks.afterburner.views.ViewLoader;
import jakarta.inject.Inject;
public class EditExternalFileTypeEntryDialog extends BaseDialog<Void> {
@FXML private RadioButton defaultApplication;
@FXML private ToggleGroup applicationToggleGroup;
@FXML private TextField extension;
@FXML private TextField name;
@FXML private TextField mimeType;
@FXML private RadioButton customApplication;
@FXML private TextField selectedApplication;
@FXML private Button btnBrowse;
@FXML private Label icon;
@Inject private DialogService dialogService;
private final NativeDesktop nativeDesktop = OS.getNativeDesktop();
private final FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder().withInitialDirectory(nativeDesktop.getApplicationDirectory()).build();
private final ExternalFileTypeItemViewModel item;
private EditExternalFileTypeViewModel viewModel;
public EditExternalFileTypeEntryDialog(ExternalFileTypeItemViewModel item, String dialogTitle) {
this.item = item;
this.setTitle(dialogTitle);
ViewLoader.view(this)
.load()
.setAsDialogPane(this);
this.setResultConverter(button -> {
if (button == ButtonType.OK) {
viewModel.storeSettings();
}
return null;
});
}
@FXML
public void initialize() {
viewModel = new EditExternalFileTypeViewModel(item);
icon.setGraphic(viewModel.getIcon());
defaultApplication.selectedProperty().bindBidirectional(viewModel.defaultApplicationSelectedProperty());
customApplication.selectedProperty().bindBidirectional(viewModel.customApplicationSelectedProperty());
selectedApplication.disableProperty().bind(viewModel.defaultApplicationSelectedProperty());
btnBrowse.disableProperty().bind(viewModel.defaultApplicationSelectedProperty());
extension.textProperty().bindBidirectional(viewModel.extensionProperty());
name.textProperty().bindBidirectional(viewModel.nameProperty());
mimeType.textProperty().bindBidirectional(viewModel.mimeTypeProperty());
selectedApplication.textProperty().bindBidirectional(viewModel.selectedApplicationProperty());
}
@FXML
private void openFileChooser(ActionEvent event) {
dialogService.showFileOpenDialog(fileDialogConfiguration).ifPresent(path -> viewModel.selectedApplicationProperty().setValue(path.toAbsolutePath().toString()));
}
}
| 3,102
| 37.7875
| 176
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/externalfiletypes/EditExternalFileTypeViewModel.java
|
package org.jabref.gui.preferences.externalfiletypes;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.Node;
public class EditExternalFileTypeViewModel {
private final ExternalFileTypeItemViewModel fileTypeViewModel;
private final StringProperty nameProperty = new SimpleStringProperty("");
private final StringProperty mimeTypeProperty = new SimpleStringProperty("");
private final StringProperty extensionProperty = new SimpleStringProperty("");
private final StringProperty selectedApplicationProperty = new SimpleStringProperty("");
private final BooleanProperty defaultApplicationSelectedProperty = new SimpleBooleanProperty(false);
private final BooleanProperty customApplicationSelectedProperty = new SimpleBooleanProperty(false);
public EditExternalFileTypeViewModel(ExternalFileTypeItemViewModel fileTypeViewModel) {
this.fileTypeViewModel = fileTypeViewModel;
extensionProperty.setValue(fileTypeViewModel.extensionProperty().getValue());
nameProperty.setValue(fileTypeViewModel.nameProperty().getValue());
mimeTypeProperty.setValue(fileTypeViewModel.mimetypeProperty().getValue());
if (fileTypeViewModel.applicationProperty().getValue().isEmpty()) {
defaultApplicationSelectedProperty.setValue(true);
} else {
customApplicationSelectedProperty.setValue(true);
selectedApplicationProperty.setValue(fileTypeViewModel.applicationProperty().getValue());
}
}
public Node getIcon() {
return fileTypeViewModel.iconProperty().getValue().getGraphicNode();
}
public StringProperty nameProperty() {
return nameProperty;
}
public StringProperty extensionProperty() {
return extensionProperty;
}
public StringProperty mimeTypeProperty() {
return mimeTypeProperty;
}
public StringProperty selectedApplicationProperty() {
return selectedApplicationProperty;
}
public BooleanProperty defaultApplicationSelectedProperty() {
return defaultApplicationSelectedProperty;
}
public BooleanProperty customApplicationSelectedProperty() {
return customApplicationSelectedProperty;
}
public void storeSettings() {
fileTypeViewModel.nameProperty().setValue(nameProperty.getValue().trim());
fileTypeViewModel.mimetypeProperty().setValue(mimeTypeProperty.getValue().trim());
String ext = extensionProperty.getValue().trim();
if (!ext.isEmpty() && (ext.charAt(0) == '.')) {
fileTypeViewModel.extensionProperty().setValue(ext.substring(1));
} else {
fileTypeViewModel.extensionProperty().setValue(ext);
}
String application = selectedApplicationProperty.getValue().trim();
// store application as empty if the "Default" option is selected, or if the application name is empty:
if (defaultApplicationSelectedProperty.getValue() || application.isEmpty()) {
fileTypeViewModel.applicationProperty().setValue("");
selectedApplicationProperty.setValue("");
} else {
fileTypeViewModel.applicationProperty().setValue(application);
}
}
}
| 3,385
| 39.309524
| 111
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/externalfiletypes/ExternalFileTypeItemViewModel.java
|
package org.jabref.gui.preferences.externalfiletypes;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import org.jabref.gui.externalfiletype.CustomExternalFileType;
import org.jabref.gui.externalfiletype.ExternalFileType;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.icon.JabRefIcon;
public class ExternalFileTypeItemViewModel {
private final ObjectProperty<JabRefIcon> icon = new SimpleObjectProperty<>();
private final StringProperty name = new SimpleStringProperty();
private final StringProperty extension = new SimpleStringProperty();
private final StringProperty mimetype = new SimpleStringProperty();
private final StringProperty application = new SimpleStringProperty();
public ExternalFileTypeItemViewModel(ExternalFileType fileType) {
this.icon.setValue(fileType.getIcon());
this.name.setValue(fileType.getName());
this.extension.setValue(fileType.getExtension());
this.mimetype.setValue(fileType.getMimeType());
this.application.setValue(fileType.getOpenWithApplication());
}
public ExternalFileTypeItemViewModel() {
this(new CustomExternalFileType("", "", "", "", "new", IconTheme.JabRefIcons.FILE));
}
public ObjectProperty<JabRefIcon> iconProperty() {
return icon;
}
/**
* Used for sorting in the table
*/
public String getName() {
return name.get();
}
public StringProperty nameProperty() {
return name;
}
public StringProperty extensionProperty() {
return extension;
}
public StringProperty mimetypeProperty() {
return mimetype;
}
public StringProperty applicationProperty() {
return application;
}
public ExternalFileType toExternalFileType() {
return new CustomExternalFileType(
this.name.get(),
this.extension.get(),
this.mimetype.get(),
this.application.get(),
this.icon.get().name(),
this.icon.get());
}
}
| 2,204
| 30.956522
| 92
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/externalfiletypes/ExternalFileTypesTab.java
|
package org.jabref.gui.preferences.externalfiletypes;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.icon.JabRefIcon;
import org.jabref.gui.preferences.AbstractPreferenceTabView;
import org.jabref.gui.preferences.PreferencesTab;
import org.jabref.gui.util.BindingsHelper;
import org.jabref.gui.util.ValueTableCellFactory;
import org.jabref.logic.l10n.Localization;
import com.airhacks.afterburner.views.ViewLoader;
/**
* Editor for external file types.
*/
public class ExternalFileTypesTab extends AbstractPreferenceTabView<ExternalFileTypesTabViewModel> implements PreferencesTab {
@FXML private TableColumn<ExternalFileTypeItemViewModel, JabRefIcon> fileTypesTableIconColumn;
@FXML private TableColumn<ExternalFileTypeItemViewModel, String> fileTypesTableNameColumn;
@FXML private TableColumn<ExternalFileTypeItemViewModel, String> fileTypesTableExtensionColumn;
@FXML private TableColumn<ExternalFileTypeItemViewModel, String> fileTypesTableMimeTypeColumn;
@FXML private TableColumn<ExternalFileTypeItemViewModel, String> fileTypesTableApplicationColumn;
@FXML private TableColumn<ExternalFileTypeItemViewModel, Boolean> fileTypesTableEditColumn;
@FXML private TableColumn<ExternalFileTypeItemViewModel, Boolean> fileTypesTableDeleteColumn;
@FXML private TableView<ExternalFileTypeItemViewModel> fileTypesTable;
public ExternalFileTypesTab() {
ViewLoader.view(this)
.root(this)
.load();
}
@Override
public String getTabName() {
return Localization.lang("External file types");
}
@FXML
public void initialize() {
viewModel = new ExternalFileTypesTabViewModel(preferencesService.getFilePreferences(), dialogService);
fileTypesTable.setItems(viewModel.getFileTypes());
fileTypesTableIconColumn.setCellValueFactory(cellData -> cellData.getValue().iconProperty());
new ValueTableCellFactory<ExternalFileTypeItemViewModel, JabRefIcon>()
.withGraphic(JabRefIcon::getGraphicNode)
.install(fileTypesTableIconColumn);
fileTypesTableNameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
new ValueTableCellFactory<ExternalFileTypeItemViewModel, String>()
.withText(name -> name)
.install(fileTypesTableNameColumn);
fileTypesTableExtensionColumn.setCellValueFactory(cellData -> cellData.getValue().extensionProperty());
new ValueTableCellFactory<ExternalFileTypeItemViewModel, String>()
.withText(extension -> extension)
.install(fileTypesTableExtensionColumn);
fileTypesTableMimeTypeColumn.setCellValueFactory(cellData -> cellData.getValue().mimetypeProperty());
new ValueTableCellFactory<ExternalFileTypeItemViewModel, String>()
.withText(mimetype -> mimetype)
.install(fileTypesTableMimeTypeColumn);
fileTypesTableApplicationColumn.setCellValueFactory(cellData -> cellData.getValue().applicationProperty());
new ValueTableCellFactory<ExternalFileTypeItemViewModel, String>()
.withText(extension -> extension)
.install(fileTypesTableApplicationColumn);
fileTypesTableEditColumn.setCellValueFactory(data -> BindingsHelper.constantOf(true));
fileTypesTableDeleteColumn.setCellValueFactory(data -> BindingsHelper.constantOf(true));
new ValueTableCellFactory<ExternalFileTypeItemViewModel, JabRefIcon>()
.withGraphic(JabRefIcon::getGraphicNode)
.install(fileTypesTableIconColumn);
new ValueTableCellFactory<ExternalFileTypeItemViewModel, Boolean>()
.withGraphic(none -> IconTheme.JabRefIcons.EDIT.getGraphicNode())
.withOnMouseClickedEvent((type, none) -> event -> viewModel.edit(type))
.install(fileTypesTableEditColumn);
new ValueTableCellFactory<ExternalFileTypeItemViewModel, Boolean>()
.withGraphic(none -> IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode())
.withOnMouseClickedEvent((type, none) -> event -> viewModel.remove(type))
.install(fileTypesTableDeleteColumn);
}
@FXML
private void addNewType() {
viewModel.addNewType();
fileTypesTable.getSelectionModel().selectLast();
fileTypesTable.scrollTo(viewModel.getFileTypes().size() - 1);
}
@FXML
private void resetToDefault() {
viewModel.resetToDefaults();
}
}
| 4,669
| 45.237624
| 126
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/externalfiletypes/ExternalFileTypesTabViewModel.java
|
package org.jabref.gui.preferences.externalfiletypes;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.jabref.gui.DialogService;
import org.jabref.gui.externalfiletype.ExternalFileType;
import org.jabref.gui.externalfiletype.ExternalFileTypes;
import org.jabref.gui.preferences.PreferenceTabViewModel;
import org.jabref.logic.l10n.Localization;
import org.jabref.preferences.FilePreferences;
public class ExternalFileTypesTabViewModel implements PreferenceTabViewModel {
private final ObservableList<ExternalFileTypeItemViewModel> fileTypes = FXCollections.observableArrayList();
private final FilePreferences filePreferences;
private final DialogService dialogService;
public ExternalFileTypesTabViewModel(FilePreferences filePreferences, DialogService dialogService) {
this.filePreferences = filePreferences;
this.dialogService = dialogService;
}
@Override
public void setValues() {
fileTypes.addAll(filePreferences.getExternalFileTypes().stream()
.map(ExternalFileTypeItemViewModel::new)
.toList());
fileTypes.sort(Comparator.comparing(ExternalFileTypeItemViewModel::getName));
}
public void storeSettings() {
Set<ExternalFileType> saveList = new HashSet<>();
fileTypes.stream().map(ExternalFileTypeItemViewModel::toExternalFileType)
.forEach(type -> ExternalFileTypes.getDefaultExternalFileTypes().stream()
.filter(type::equals).findAny()
.ifPresentOrElse(saveList::add, () -> saveList.add(type)));
filePreferences.getExternalFileTypes().clear();
filePreferences.getExternalFileTypes().addAll(saveList);
}
public void resetToDefaults() {
fileTypes.setAll(ExternalFileTypes.getDefaultExternalFileTypes().stream()
.map(ExternalFileTypeItemViewModel::new)
.toList());
fileTypes.sort(Comparator.comparing(ExternalFileTypeItemViewModel::getName));
}
public void addNewType() {
ExternalFileTypeItemViewModel item = new ExternalFileTypeItemViewModel();
fileTypes.add(item);
showEditDialog(item, Localization.lang("Add new file type"));
}
public ObservableList<ExternalFileTypeItemViewModel> getFileTypes() {
return fileTypes;
}
private void showEditDialog(ExternalFileTypeItemViewModel item, String dialogTitle) {
dialogService.showCustomDialogAndWait(new EditExternalFileTypeEntryDialog(item, dialogTitle));
}
public void edit(ExternalFileTypeItemViewModel type) {
showEditDialog(type, Localization.lang("Edit file type"));
}
public void remove(ExternalFileTypeItemViewModel type) {
fileTypes.remove(type);
}
}
| 3,021
| 37.74359
| 112
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/general/GeneralTab.java
|
package org.jabref.gui.preferences.general;
import java.util.regex.Pattern;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Spinner;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.util.converter.IntegerStringConverter;
import org.jabref.gui.Globals;
import org.jabref.gui.actions.ActionFactory;
import org.jabref.gui.actions.StandardActions;
import org.jabref.gui.help.HelpAction;
import org.jabref.gui.preferences.AbstractPreferenceTabView;
import org.jabref.gui.preferences.PreferencesTab;
import org.jabref.gui.util.IconValidationDecorator;
import org.jabref.gui.util.ViewModelListCellFactory;
import org.jabref.logic.help.HelpFile;
import org.jabref.logic.l10n.Language;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabaseMode;
import com.airhacks.afterburner.views.ViewLoader;
import com.tobiasdiez.easybind.EasyBind;
import de.saxsys.mvvmfx.utils.validation.visualization.ControlsFxVisualizer;
public class GeneralTab extends AbstractPreferenceTabView<GeneralTabViewModel> implements PreferencesTab {
@FXML private ComboBox<Language> language;
@FXML private ComboBox<GeneralTabViewModel.ThemeTypes> theme;
@FXML private TextField customThemePath;
@FXML private Button customThemeBrowse;
@FXML private CheckBox fontOverride;
@FXML private Spinner<Integer> fontSize;
@FXML private CheckBox openLastStartup;
@FXML private CheckBox showAdvancedHints;
@FXML private CheckBox inspectionWarningDuplicate;
@FXML private CheckBox confirmDelete;
@FXML private CheckBox collectTelemetry;
@FXML private ComboBox<BibDatabaseMode> biblatexMode;
@FXML private CheckBox alwaysReformatBib;
@FXML private CheckBox autosaveLocalLibraries;
@FXML private Button autosaveLocalLibrariesHelp;
@FXML private CheckBox createBackup;
@FXML private TextField backupDirectory;
private final ControlsFxVisualizer validationVisualizer = new ControlsFxVisualizer();
// The fontSizeFormatter formats the input given to the fontSize spinner so that non valid values cannot be entered.
private final TextFormatter<Integer> fontSizeFormatter = new TextFormatter<>(new IntegerStringConverter(), 9,
c -> {
if (Pattern.matches("\\d*", c.getText())) {
return c;
}
c.setText("0");
return c;
});
public GeneralTab() {
ViewLoader.view(this)
.root(this)
.load();
}
@Override
public String getTabName() {
return Localization.lang("General");
}
public void initialize() {
this.viewModel = new GeneralTabViewModel(dialogService, preferencesService);
new ViewModelListCellFactory<Language>()
.withText(Language::getDisplayName)
.install(language);
language.itemsProperty().bind(viewModel.languagesListProperty());
language.valueProperty().bindBidirectional(viewModel.selectedLanguageProperty());
fontOverride.selectedProperty().bindBidirectional(viewModel.fontOverrideProperty());
// Spinner does neither support alignment nor disableProperty in FXML
fontSize.disableProperty().bind(fontOverride.selectedProperty().not());
fontSize.getEditor().setAlignment(Pos.CENTER_RIGHT);
fontSize.setValueFactory(GeneralTabViewModel.fontSizeValueFactory);
fontSize.getEditor().textProperty().bindBidirectional(viewModel.fontSizeProperty());
fontSize.getEditor().setTextFormatter(fontSizeFormatter);
new ViewModelListCellFactory<GeneralTabViewModel.ThemeTypes>()
.withText(GeneralTabViewModel.ThemeTypes::getDisplayName)
.install(theme);
theme.itemsProperty().bind(viewModel.themesListProperty());
theme.valueProperty().bindBidirectional(viewModel.selectedThemeProperty());
customThemePath.textProperty().bindBidirectional(viewModel.customPathToThemeProperty());
EasyBind.subscribe(viewModel.selectedThemeProperty(), theme -> {
boolean isCustomTheme = theme == GeneralTabViewModel.ThemeTypes.CUSTOM;
customThemePath.disableProperty().set(!isCustomTheme);
customThemeBrowse.disableProperty().set(!isCustomTheme);
});
validationVisualizer.setDecoration(new IconValidationDecorator());
openLastStartup.selectedProperty().bindBidirectional(viewModel.openLastStartupProperty());
showAdvancedHints.selectedProperty().bindBidirectional(viewModel.showAdvancedHintsProperty());
inspectionWarningDuplicate.selectedProperty().bindBidirectional(viewModel.inspectionWarningDuplicateProperty());
confirmDelete.selectedProperty().bindBidirectional(viewModel.confirmDeleteProperty());
collectTelemetry.selectedProperty().bindBidirectional(viewModel.collectTelemetryProperty());
new ViewModelListCellFactory<BibDatabaseMode>()
.withText(BibDatabaseMode::getFormattedName)
.install(biblatexMode);
biblatexMode.itemsProperty().bind(viewModel.biblatexModeListProperty());
biblatexMode.valueProperty().bindBidirectional(viewModel.selectedBiblatexModeProperty());
alwaysReformatBib.selectedProperty().bindBidirectional(viewModel.alwaysReformatBibProperty());
autosaveLocalLibraries.selectedProperty().bindBidirectional(viewModel.autosaveLocalLibrariesProperty());
ActionFactory actionFactory = new ActionFactory(Globals.getKeyPrefs());
actionFactory.configureIconButton(StandardActions.HELP, new HelpAction(HelpFile.AUTOSAVE, dialogService), autosaveLocalLibrariesHelp);
createBackup.selectedProperty().bindBidirectional(viewModel.createBackupProperty());
backupDirectory.textProperty().bindBidirectional(viewModel.backupDirectoryProperty());
backupDirectory.disableProperty().bind(viewModel.createBackupProperty().not());
Platform.runLater(() -> {
validationVisualizer.initVisualization(viewModel.fontSizeValidationStatus(), fontSize);
validationVisualizer.initVisualization(viewModel.customPathToThemeValidationStatus(), customThemePath);
});
}
@FXML
void importTheme() {
viewModel.importCSSFile();
}
public void backupFileDirBrowse() {
viewModel.backupFileDirBrowse();
}
}
| 6,628
| 44.717241
| 142
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/general/GeneralTabViewModel.java
|
package org.jabref.gui.preferences.general;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ListProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ReadOnlyListProperty;
import javafx.beans.property.ReadOnlyListWrapper;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.scene.control.SpinnerValueFactory;
import org.jabref.gui.DialogService;
import org.jabref.gui.preferences.PreferenceTabViewModel;
import org.jabref.gui.theme.Theme;
import org.jabref.gui.util.DirectoryDialogConfiguration;
import org.jabref.gui.util.FileDialogConfiguration;
import org.jabref.logic.l10n.Language;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.StandardFileType;
import org.jabref.model.database.BibDatabaseMode;
import org.jabref.model.strings.StringUtil;
import org.jabref.preferences.FilePreferences;
import org.jabref.preferences.LibraryPreferences;
import org.jabref.preferences.PreferencesService;
import org.jabref.preferences.TelemetryPreferences;
import org.jabref.preferences.WorkspacePreferences;
import de.saxsys.mvvmfx.utils.validation.CompositeValidator;
import de.saxsys.mvvmfx.utils.validation.FunctionBasedValidator;
import de.saxsys.mvvmfx.utils.validation.ValidationMessage;
import de.saxsys.mvvmfx.utils.validation.ValidationStatus;
import de.saxsys.mvvmfx.utils.validation.Validator;
public class GeneralTabViewModel implements PreferenceTabViewModel {
protected enum ThemeTypes {
LIGHT(Localization.lang("Light")),
DARK(Localization.lang("Dark")),
CUSTOM(Localization.lang("Custom..."));
private final String displayName;
ThemeTypes(String displayName) {
this.displayName = displayName;
}
public String getDisplayName() {
return displayName;
}
}
protected static SpinnerValueFactory<Integer> fontSizeValueFactory =
new SpinnerValueFactory.IntegerSpinnerValueFactory(9, Integer.MAX_VALUE);
private final ReadOnlyListProperty<Language> languagesListProperty =
new ReadOnlyListWrapper<>(FXCollections.observableArrayList(Language.values()));;
private final ObjectProperty<Language> selectedLanguageProperty = new SimpleObjectProperty<>();
private final ReadOnlyListProperty<ThemeTypes> themesListProperty =
new ReadOnlyListWrapper<>(FXCollections.observableArrayList(ThemeTypes.values()));;
private final ObjectProperty<ThemeTypes> selectedThemeProperty = new SimpleObjectProperty<>();
private final StringProperty customPathToThemeProperty = new SimpleStringProperty();
private final BooleanProperty fontOverrideProperty = new SimpleBooleanProperty();
private final StringProperty fontSizeProperty = new SimpleStringProperty();
private final BooleanProperty openLastStartupProperty = new SimpleBooleanProperty();
private final BooleanProperty showAdvancedHintsProperty = new SimpleBooleanProperty();
private final BooleanProperty inspectionWarningDuplicateProperty = new SimpleBooleanProperty();
private final BooleanProperty confirmDeleteProperty = new SimpleBooleanProperty();
private final BooleanProperty collectTelemetryProperty = new SimpleBooleanProperty();
private final ListProperty<BibDatabaseMode> bibliographyModeListProperty = new SimpleListProperty<>();
private final ObjectProperty<BibDatabaseMode> selectedBiblatexModeProperty = new SimpleObjectProperty<>();
private final BooleanProperty alwaysReformatBibProperty = new SimpleBooleanProperty();
private final BooleanProperty autosaveLocalLibraries = new SimpleBooleanProperty();
private final BooleanProperty createBackupProperty = new SimpleBooleanProperty();
private final StringProperty backupDirectoryProperty = new SimpleStringProperty("");
private final DialogService dialogService;
private final PreferencesService preferences;
private final WorkspacePreferences workspacePreferences;
private final TelemetryPreferences telemetryPreferences;
private final LibraryPreferences libraryPreferences;
private final FilePreferences filePreferences;
private final Validator fontSizeValidator;
private final Validator customPathToThemeValidator;
private final List<String> restartWarning = new ArrayList<>();
public GeneralTabViewModel(DialogService dialogService, PreferencesService preferences) {
this.dialogService = dialogService;
this.preferences = preferences;
this.workspacePreferences = preferences.getWorkspacePreferences();
this.telemetryPreferences = preferences.getTelemetryPreferences();
this.libraryPreferences = preferences.getLibraryPreferences();
this.filePreferences = preferences.getFilePreferences();
fontSizeValidator = new FunctionBasedValidator<>(
fontSizeProperty,
input -> {
try {
return Integer.parseInt(fontSizeProperty().getValue()) > 8;
} catch (NumberFormatException ex) {
return false;
}
},
ValidationMessage.error(String.format("%s > %s %n %n %s",
Localization.lang("General"),
Localization.lang("Font settings"),
Localization.lang("You must enter an integer value higher than 8."))));
customPathToThemeValidator = new FunctionBasedValidator<>(
customPathToThemeProperty,
input -> !StringUtil.isNullOrEmpty(input),
ValidationMessage.error(String.format("%s > %s %n %n %s",
Localization.lang("General"),
Localization.lang("Visual theme"),
Localization.lang("Please specify a css theme file."))));
}
@Override
public void setValues() {
selectedLanguageProperty.setValue(workspacePreferences.getLanguage());
// The light theme is in fact the absence of any theme modifying 'base.css'. Another embedded theme like
// 'dark.css', stored in the classpath, can be introduced in {@link org.jabref.gui.theme.Theme}.
switch (workspacePreferences.getTheme().getType()) {
case DEFAULT -> selectedThemeProperty.setValue(ThemeTypes.LIGHT);
case EMBEDDED -> selectedThemeProperty.setValue(ThemeTypes.DARK);
case CUSTOM -> {
selectedThemeProperty.setValue(ThemeTypes.CUSTOM);
customPathToThemeProperty.setValue(workspacePreferences.getTheme().getName());
}
}
fontOverrideProperty.setValue(workspacePreferences.shouldOverrideDefaultFontSize());
fontSizeProperty.setValue(String.valueOf(workspacePreferences.getMainFontSize()));
openLastStartupProperty.setValue(workspacePreferences.shouldOpenLastEdited());
showAdvancedHintsProperty.setValue(workspacePreferences.shouldShowAdvancedHints());
inspectionWarningDuplicateProperty.setValue(workspacePreferences.shouldWarnAboutDuplicatesInInspection());
confirmDeleteProperty.setValue(workspacePreferences.shouldConfirmDelete());
collectTelemetryProperty.setValue(telemetryPreferences.shouldCollectTelemetry());
bibliographyModeListProperty.setValue(FXCollections.observableArrayList(BibDatabaseMode.values()));
selectedBiblatexModeProperty.setValue(libraryPreferences.getDefaultBibDatabaseMode());
alwaysReformatBibProperty.setValue(libraryPreferences.shouldAlwaysReformatOnSave());
autosaveLocalLibraries.setValue(libraryPreferences.shouldAutoSave());
createBackupProperty.setValue(filePreferences.shouldCreateBackup());
backupDirectoryProperty.setValue(filePreferences.getBackupDirectory().toString());
}
@Override
public void storeSettings() {
Language newLanguage = selectedLanguageProperty.getValue();
if (newLanguage != workspacePreferences.getLanguage()) {
workspacePreferences.setLanguage(newLanguage);
Localization.setLanguage(newLanguage);
restartWarning.add(Localization.lang("Changed language") + ": " + newLanguage.getDisplayName());
}
workspacePreferences.setShouldOverrideDefaultFontSize(fontOverrideProperty.getValue());
workspacePreferences.setMainFontSize(Integer.parseInt(fontSizeProperty.getValue()));
switch (selectedThemeProperty.get()) {
case LIGHT -> workspacePreferences.setTheme(Theme.light());
case DARK -> workspacePreferences.setTheme(Theme.dark());
case CUSTOM -> workspacePreferences.setTheme(Theme.custom(customPathToThemeProperty.getValue()));
}
workspacePreferences.setOpenLastEdited(openLastStartupProperty.getValue());
workspacePreferences.setShowAdvancedHints(showAdvancedHintsProperty.getValue());
workspacePreferences.setWarnAboutDuplicatesInInspection(inspectionWarningDuplicateProperty.getValue());
workspacePreferences.setConfirmDelete(confirmDeleteProperty.getValue());
telemetryPreferences.setCollectTelemetry(collectTelemetryProperty.getValue());
libraryPreferences.setDefaultBibDatabaseMode(selectedBiblatexModeProperty.getValue());
libraryPreferences.setAlwaysReformatOnSave(alwaysReformatBibProperty.getValue());
libraryPreferences.setAutoSave(autosaveLocalLibraries.getValue());
filePreferences.createBackupProperty().setValue(createBackupProperty.getValue());
filePreferences.backupDirectoryProperty().setValue(Path.of(backupDirectoryProperty.getValue()));
}
public ValidationStatus fontSizeValidationStatus() {
return fontSizeValidator.getValidationStatus();
}
public ValidationStatus customPathToThemeValidationStatus() {
return customPathToThemeValidator.getValidationStatus();
}
@Override
public boolean validateSettings() {
CompositeValidator validator = new CompositeValidator();
if (fontOverrideProperty.getValue()) {
validator.addValidators(fontSizeValidator);
}
if (selectedThemeProperty.getValue() == ThemeTypes.CUSTOM) {
validator.addValidators(customPathToThemeValidator);
}
ValidationStatus validationStatus = validator.getValidationStatus();
if (!validationStatus.isValid()) {
validationStatus.getHighestMessage().ifPresent(message ->
dialogService.showErrorDialogAndWait(message.getMessage()));
return false;
}
return true;
}
@Override
public List<String> getRestartWarnings() {
return restartWarning;
}
public ReadOnlyListProperty<Language> languagesListProperty() {
return this.languagesListProperty;
}
public ObjectProperty<Language> selectedLanguageProperty() {
return this.selectedLanguageProperty;
}
public ReadOnlyListProperty<ThemeTypes> themesListProperty() {
return this.themesListProperty;
}
public ObjectProperty<ThemeTypes> selectedThemeProperty() {
return this.selectedThemeProperty;
}
public StringProperty customPathToThemeProperty() {
return customPathToThemeProperty;
}
public void importCSSFile() {
FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
.addExtensionFilter(StandardFileType.CSS)
.withDefaultExtension(StandardFileType.CSS)
.withInitialDirectory(preferences.getInternalPreferences().getLastPreferencesExportPath()).build();
dialogService.showFileOpenDialog(fileDialogConfiguration).ifPresent(file ->
customPathToThemeProperty.setValue(file.toAbsolutePath().toString()));
}
public BooleanProperty fontOverrideProperty() {
return fontOverrideProperty;
}
public StringProperty fontSizeProperty() {
return fontSizeProperty;
}
public BooleanProperty openLastStartupProperty() {
return openLastStartupProperty;
}
public BooleanProperty showAdvancedHintsProperty() {
return this.showAdvancedHintsProperty;
}
public BooleanProperty inspectionWarningDuplicateProperty() {
return this.inspectionWarningDuplicateProperty;
}
public BooleanProperty confirmDeleteProperty() {
return this.confirmDeleteProperty;
}
public BooleanProperty collectTelemetryProperty() {
return this.collectTelemetryProperty;
}
public ListProperty<BibDatabaseMode> biblatexModeListProperty() {
return this.bibliographyModeListProperty;
}
public ObjectProperty<BibDatabaseMode> selectedBiblatexModeProperty() {
return this.selectedBiblatexModeProperty;
}
public BooleanProperty alwaysReformatBibProperty() {
return alwaysReformatBibProperty;
}
public BooleanProperty autosaveLocalLibrariesProperty() {
return autosaveLocalLibraries;
}
public BooleanProperty createBackupProperty() {
return this.createBackupProperty;
}
public StringProperty backupDirectoryProperty() {
return this.backupDirectoryProperty;
}
public void backupFileDirBrowse() {
DirectoryDialogConfiguration dirDialogConfiguration =
new DirectoryDialogConfiguration.Builder().withInitialDirectory(Path.of(backupDirectoryProperty().getValue())).build();
dialogService.showDirectorySelectionDialog(dirDialogConfiguration)
.ifPresent(dir -> backupDirectoryProperty.setValue(dir.toString()));
}
}
| 14,042
| 42.209231
| 135
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/groups/GroupsTab.java
|
package org.jabref.gui.preferences.groups;
import javafx.fxml.FXML;
import javafx.scene.control.CheckBox;
import javafx.scene.control.RadioButton;
import org.jabref.gui.preferences.AbstractPreferenceTabView;
import org.jabref.gui.preferences.PreferencesTab;
import org.jabref.logic.l10n.Localization;
import com.airhacks.afterburner.views.ViewLoader;
public class GroupsTab extends AbstractPreferenceTabView<GroupsTabViewModel> implements PreferencesTab {
@FXML private RadioButton groupViewModeIntersection;
@FXML private RadioButton groupViewModeUnion;
@FXML private CheckBox autoAssignGroup;
@FXML private CheckBox displayGroupCount;
public GroupsTab() {
ViewLoader.view(this)
.root(this)
.load();
}
@Override
public String getTabName() {
return Localization.lang("Groups");
}
public void initialize() {
this.viewModel = new GroupsTabViewModel(preferencesService.getGroupsPreferences());
groupViewModeIntersection.selectedProperty().bindBidirectional(viewModel.groupViewModeIntersectionProperty());
groupViewModeUnion.selectedProperty().bindBidirectional(viewModel.groupViewModeUnionProperty());
autoAssignGroup.selectedProperty().bindBidirectional(viewModel.autoAssignGroupProperty());
displayGroupCount.selectedProperty().bindBidirectional(viewModel.displayGroupCount());
}
}
| 1,426
| 34.675
| 118
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/groups/GroupsTabViewModel.java
|
package org.jabref.gui.preferences.groups;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import org.jabref.gui.groups.GroupViewMode;
import org.jabref.gui.groups.GroupsPreferences;
import org.jabref.gui.preferences.PreferenceTabViewModel;
public class GroupsTabViewModel implements PreferenceTabViewModel {
private final BooleanProperty groupViewModeIntersectionProperty = new SimpleBooleanProperty();
private final BooleanProperty groupViewModeUnionProperty = new SimpleBooleanProperty();
private final BooleanProperty autoAssignGroupProperty = new SimpleBooleanProperty();
private final BooleanProperty displayGroupCountProperty = new SimpleBooleanProperty();
private final GroupsPreferences groupsPreferences;
public GroupsTabViewModel(GroupsPreferences groupsPreferences) {
this.groupsPreferences = groupsPreferences;
}
@Override
public void setValues() {
switch (groupsPreferences.getGroupViewMode()) {
case INTERSECTION -> {
groupViewModeIntersectionProperty.setValue(true);
groupViewModeUnionProperty.setValue(false);
}
case UNION -> {
groupViewModeIntersectionProperty.setValue(false);
groupViewModeUnionProperty.setValue(true);
}
}
autoAssignGroupProperty.setValue(groupsPreferences.shouldAutoAssignGroup());
displayGroupCountProperty.setValue(groupsPreferences.shouldDisplayGroupCount());
}
@Override
public void storeSettings() {
groupsPreferences.setGroupViewMode(groupViewModeIntersectionProperty.getValue() ? GroupViewMode.INTERSECTION : GroupViewMode.UNION);
groupsPreferences.setAutoAssignGroup(autoAssignGroupProperty.getValue());
groupsPreferences.setDisplayGroupCount(displayGroupCountProperty.getValue());
}
public BooleanProperty groupViewModeIntersectionProperty() {
return groupViewModeIntersectionProperty;
}
public BooleanProperty groupViewModeUnionProperty() {
return groupViewModeUnionProperty;
}
public BooleanProperty autoAssignGroupProperty() {
return autoAssignGroupProperty;
}
public BooleanProperty displayGroupCount() {
return displayGroupCountProperty;
}
}
| 2,348
| 36.887097
| 140
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/journals/AbbreviationViewModel.java
|
package org.jabref.gui.preferences.journals;
import java.util.Locale;
import java.util.Objects;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import org.jabref.logic.journals.Abbreviation;
/**
* This class provides a view model for abbreviation objects which can also define placeholder objects of abbreviations.
* This is indicated by using the {@code pseudoAbbreviation} property.
*/
public class AbbreviationViewModel {
private final StringProperty name = new SimpleStringProperty("");
private final StringProperty abbreviation = new SimpleStringProperty("");
private final StringProperty shortestUniqueAbbreviation = new SimpleStringProperty("");
// Used when a "null" abbreviation object is added
private final BooleanProperty pseudoAbbreviation = new SimpleBooleanProperty();
public AbbreviationViewModel(Abbreviation abbreviationObject) {
this.pseudoAbbreviation.set(abbreviationObject == null);
if (abbreviationObject != null) {
this.name.setValue(abbreviationObject.getName());
this.abbreviation.setValue(abbreviationObject.getAbbreviation());
// the view model stores the "real" values, not the default fallback
String shortestUniqueAbbreviationOfAbbreviation = abbreviationObject.getShortestUniqueAbbreviation();
boolean shortestUniqueAbbreviationIsDefaultValue = shortestUniqueAbbreviationOfAbbreviation.equals(abbreviationObject.getAbbreviation());
if (shortestUniqueAbbreviationIsDefaultValue) {
this.shortestUniqueAbbreviation.set("");
} else {
this.shortestUniqueAbbreviation.setValue(shortestUniqueAbbreviationOfAbbreviation);
}
}
}
public Abbreviation getAbbreviationObject() {
return new Abbreviation(getName(), getAbbreviation(), getShortestUniqueAbbreviation());
}
public String getName() {
return name.get();
}
public void setName(String name) {
this.name.set(name);
}
public String getAbbreviation() {
return abbreviation.get();
}
public void setAbbreviation(String abbreviation) {
this.abbreviation.set(abbreviation);
}
public String getShortestUniqueAbbreviation() {
return shortestUniqueAbbreviation.get();
}
public void setShortestUniqueAbbreviation(String shortestUniqueAbbreviation) {
this.shortestUniqueAbbreviation.set(shortestUniqueAbbreviation);
}
public boolean isPseudoAbbreviation() {
return pseudoAbbreviation.get();
}
public StringProperty nameProperty() {
return name;
}
public StringProperty abbreviationProperty() {
return abbreviation;
}
public StringProperty shortestUniqueAbbreviationProperty() {
return shortestUniqueAbbreviation;
}
public BooleanProperty isPseudoAbbreviationProperty() {
return pseudoAbbreviation;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AbbreviationViewModel that = (AbbreviationViewModel) o;
return getName().equals(that.getName())
&& getAbbreviation().equals(that.getAbbreviation())
&& getShortestUniqueAbbreviation().equals(that.getShortestUniqueAbbreviation())
&& (isPseudoAbbreviation() == that.isPseudoAbbreviation());
}
@Override
public int hashCode() {
return Objects.hash(getName(), getAbbreviation(), getShortestUniqueAbbreviation(), isPseudoAbbreviation());
}
public boolean containsCaseIndependent(String searchTerm) {
searchTerm = searchTerm.toLowerCase(Locale.ROOT);
return this.abbreviation.get().toLowerCase(Locale.ROOT).contains(searchTerm) ||
this.name.get().toLowerCase(Locale.ROOT).contains(searchTerm) ||
this.shortestUniqueAbbreviation.get().toLowerCase(Locale.ROOT).contains(searchTerm);
}
}
| 4,234
| 34.889831
| 149
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/journals/AbbreviationsFileViewModel.java
|
package org.jabref.gui.preferences.journals;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import javafx.beans.property.ReadOnlyBooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.FXCollections;
import org.jabref.logic.journals.Abbreviation;
import org.jabref.logic.journals.AbbreviationWriter;
import org.jabref.logic.journals.JournalAbbreviationLoader;
/**
* This class provides a model for abbreviation files. It actually doesn't save the files as objects but rather saves
* their paths. This also allows to specify pseudo files as placeholder objects.
*/
public class AbbreviationsFileViewModel {
private final SimpleListProperty<AbbreviationViewModel> abbreviations = new SimpleListProperty<>(
FXCollections.observableArrayList());
private final ReadOnlyBooleanProperty isBuiltInList;
private final String name;
private final Optional<Path> path;
public AbbreviationsFileViewModel(Path filePath) {
this.path = Optional.ofNullable(filePath);
this.name = path.get().toAbsolutePath().toString();
this.isBuiltInList = new SimpleBooleanProperty(false);
}
/**
* This constructor should only be called to create a pseudo abbreviation file for built in lists. This means it is
* a placeholder and its path will be null meaning it has no place on the filesystem. Its isPseudoFile property
* will therefore be set to true.
*/
public AbbreviationsFileViewModel(List<AbbreviationViewModel> abbreviations, String name) {
this.abbreviations.addAll(abbreviations);
this.name = name;
this.path = Optional.empty();
this.isBuiltInList = new SimpleBooleanProperty(true);
}
public void readAbbreviations() throws IOException {
if (path.isPresent()) {
Collection<Abbreviation> abbreviationList = JournalAbbreviationLoader.readJournalListFromFile(path.get());
abbreviationList.forEach(abbreviation -> abbreviations.addAll(new AbbreviationViewModel(abbreviation)));
} else {
throw new FileNotFoundException();
}
}
/**
* This method will write all abbreviations of this abbreviation file to the file on the file system.
* It essentially will check if the current file is a builtin list and if not it will call
* {@link AbbreviationWriter#writeOrCreate}.
*/
public void writeOrCreate() throws IOException {
if (!isBuiltInList.get()) {
List<Abbreviation> actualAbbreviations =
abbreviations.stream().filter(abb -> !abb.isPseudoAbbreviation())
.map(AbbreviationViewModel::getAbbreviationObject)
.collect(Collectors.toList());
AbbreviationWriter.writeOrCreate(path.get(), actualAbbreviations);
}
}
public SimpleListProperty<AbbreviationViewModel> abbreviationsProperty() {
return abbreviations;
}
public boolean exists() {
return path.isPresent() && Files.exists(path.get());
}
public Optional<Path> getAbsolutePath() {
return path;
}
public ReadOnlyBooleanProperty isBuiltInListProperty() {
return isBuiltInList;
}
@Override
public String toString() {
return name;
}
@Override
public int hashCode() {
return Objects.hash(name);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof AbbreviationsFileViewModel model) {
return Objects.equals(this.name, model.name);
} else {
return false;
}
}
}
| 3,925
| 34.369369
| 119
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/journals/JournalAbbreviationsTab.java
|
package org.jabref.gui.preferences.journals;
import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.transformation.FilteredList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.paint.Color;
import javafx.util.Duration;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.preferences.AbstractPreferenceTabView;
import org.jabref.gui.preferences.PreferencesTab;
import org.jabref.gui.util.ColorUtil;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.gui.util.ValueTableCellFactory;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.logic.l10n.Localization;
import com.airhacks.afterburner.views.ViewLoader;
import com.tobiasdiez.easybind.EasyBind;
import jakarta.inject.Inject;
import org.controlsfx.control.textfield.CustomTextField;
/**
* This class controls the user interface of the journal abbreviations dialog. The UI elements and their layout are
* defined in the FXML file.
*/
public class JournalAbbreviationsTab extends AbstractPreferenceTabView<JournalAbbreviationsTabViewModel> implements PreferencesTab {
@FXML private Label loadingLabel;
@FXML private ProgressIndicator progressIndicator;
@FXML private TableView<AbbreviationViewModel> journalAbbreviationsTable;
@FXML private TableColumn<AbbreviationViewModel, String> journalTableNameColumn;
@FXML private TableColumn<AbbreviationViewModel, String> journalTableAbbreviationColumn;
@FXML private TableColumn<AbbreviationViewModel, String> journalTableShortestUniqueAbbreviationColumn;
@FXML private TableColumn<AbbreviationViewModel, String> actionsColumn;
private FilteredList<AbbreviationViewModel> filteredAbbreviations;
@FXML private ComboBox<AbbreviationsFileViewModel> journalFilesBox;
@FXML private Button addAbbreviationButton;
@FXML private Button removeAbbreviationListButton;
@FXML private CustomTextField searchBox;
@FXML private CheckBox useFJournal;
@Inject private TaskExecutor taskExecutor;
@Inject private JournalAbbreviationRepository abbreviationRepository;
private Timeline invalidateSearch;
public JournalAbbreviationsTab() {
ViewLoader.view(this)
.root(this)
.load();
}
@FXML
private void initialize() {
viewModel = new JournalAbbreviationsTabViewModel(
preferencesService.getJournalAbbreviationPreferences(),
dialogService,
taskExecutor,
abbreviationRepository);
filteredAbbreviations = new FilteredList<>(viewModel.abbreviationsProperty());
setUpTable();
setBindings();
setAnimations();
searchBox.setPromptText(Localization.lang("Search") + "...");
searchBox.setLeft(IconTheme.JabRefIcons.SEARCH.getGraphicNode());
}
private void setUpTable() {
journalTableNameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
journalTableNameColumn.setCellFactory(TextFieldTableCell.forTableColumn());
journalTableAbbreviationColumn.setCellValueFactory(cellData -> cellData.getValue().abbreviationProperty());
journalTableAbbreviationColumn.setCellFactory(TextFieldTableCell.forTableColumn());
journalTableShortestUniqueAbbreviationColumn.setCellValueFactory(cellData -> cellData.getValue().shortestUniqueAbbreviationProperty());
journalTableShortestUniqueAbbreviationColumn.setCellFactory(TextFieldTableCell.forTableColumn());
actionsColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
new ValueTableCellFactory<AbbreviationViewModel, String>()
.withGraphic(name -> IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode())
.withTooltip(name -> Localization.lang("Remove journal '%0'", name))
.withDisableExpression(item -> viewModel.isEditableAndRemovableProperty().not())
.withVisibleExpression(item -> viewModel.isEditableAndRemovableProperty())
.withOnMouseClickedEvent(item -> evt ->
viewModel.removeAbbreviation(journalAbbreviationsTable.getFocusModel().getFocusedItem()))
.install(actionsColumn);
}
private void setBindings() {
journalAbbreviationsTable.setItems(filteredAbbreviations);
EasyBind.subscribe(journalAbbreviationsTable.getSelectionModel().selectedItemProperty(), newValue ->
viewModel.currentAbbreviationProperty().set(newValue));
EasyBind.subscribe(viewModel.currentAbbreviationProperty(), newValue ->
journalAbbreviationsTable.getSelectionModel().select(newValue));
journalTableNameColumn.editableProperty().bind(viewModel.isAbbreviationEditableAndRemovable());
journalTableAbbreviationColumn.editableProperty().bind(viewModel.isAbbreviationEditableAndRemovable());
journalTableShortestUniqueAbbreviationColumn.editableProperty().bind(viewModel.isAbbreviationEditableAndRemovable());
removeAbbreviationListButton.disableProperty().bind(viewModel.isFileRemovableProperty().not());
journalFilesBox.itemsProperty().bindBidirectional(viewModel.journalFilesProperty());
journalFilesBox.valueProperty().bindBidirectional(viewModel.currentFileProperty());
addAbbreviationButton.disableProperty().bind(viewModel.isEditableAndRemovableProperty().not());
loadingLabel.visibleProperty().bind(viewModel.isLoadingProperty());
progressIndicator.visibleProperty().bind(viewModel.isLoadingProperty());
searchBox.textProperty().addListener((observable, previousText, searchTerm) ->
filteredAbbreviations.setPredicate(abbreviation -> searchTerm.isEmpty() || abbreviation.containsCaseIndependent(searchTerm)));
useFJournal.selectedProperty().bindBidirectional(viewModel.useFJournalProperty());
}
private void setAnimations() {
ObjectProperty<Color> flashingColor = new SimpleObjectProperty<>(Color.TRANSPARENT);
StringProperty flashingColorStringProperty = createFlashingColorStringProperty(flashingColor);
searchBox.styleProperty().bind(
new SimpleStringProperty("-fx-control-inner-background: ").concat(flashingColorStringProperty).concat(";")
);
invalidateSearch = new Timeline(
new KeyFrame(Duration.seconds(0), new KeyValue(flashingColor, Color.TRANSPARENT, Interpolator.LINEAR)),
new KeyFrame(Duration.seconds(0.25), new KeyValue(flashingColor, Color.RED, Interpolator.LINEAR)),
new KeyFrame(Duration.seconds(0.25), new KeyValue(searchBox.textProperty(), "", Interpolator.DISCRETE)),
new KeyFrame(Duration.seconds(0.25), (ActionEvent event) -> addAbbreviationActions()),
new KeyFrame(Duration.seconds(0.5), new KeyValue(flashingColor, Color.TRANSPARENT, Interpolator.LINEAR))
);
}
@FXML
private void addList() {
viewModel.addNewFile();
}
@FXML
private void openList() {
viewModel.openFile();
}
@FXML
private void removeList() {
viewModel.removeCurrentFile();
}
@FXML
private void addAbbreviation() {
if (!searchBox.getText().isEmpty()) {
invalidateSearch.play();
} else {
addAbbreviationActions();
}
}
private void addAbbreviationActions() {
viewModel.addAbbreviation();
selectNewAbbreviation();
editAbbreviation();
}
private static StringProperty createFlashingColorStringProperty(final ObjectProperty<Color> flashingColor) {
final StringProperty flashingColorStringProperty = new SimpleStringProperty();
setColorStringFromColor(flashingColorStringProperty, flashingColor);
flashingColor.addListener((observable, oldValue, newValue) -> setColorStringFromColor(flashingColorStringProperty, flashingColor));
return flashingColorStringProperty;
}
private static void setColorStringFromColor(StringProperty colorStringProperty, ObjectProperty<Color> color) {
colorStringProperty.set(ColorUtil.toRGBACode(color.get()));
}
@FXML
private void editAbbreviation() {
journalAbbreviationsTable.edit(
journalAbbreviationsTable.getSelectionModel().getSelectedIndex(),
journalTableNameColumn);
}
private void selectNewAbbreviation() {
int lastRow = viewModel.abbreviationsCountProperty().get() - 1;
journalAbbreviationsTable.scrollTo(lastRow);
journalAbbreviationsTable.getSelectionModel().select(lastRow);
journalAbbreviationsTable.getFocusModel().focus(lastRow, journalTableNameColumn);
}
@Override
public String getTabName() {
return Localization.lang("Journal abbreviations");
}
}
| 9,531
| 43.12963
| 143
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/journals/JournalAbbreviationsTabViewModel.java
|
package org.jabref.gui.preferences.journals;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import org.jabref.gui.DialogService;
import org.jabref.gui.Globals;
import org.jabref.gui.preferences.PreferenceTabViewModel;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.gui.util.FileDialogConfiguration;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.journals.Abbreviation;
import org.jabref.logic.journals.JournalAbbreviationLoader;
import org.jabref.logic.journals.JournalAbbreviationPreferences;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.StandardFileType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class provides a model for managing journal abbreviation lists. It provides all necessary methods to create,
* modify or delete journal abbreviations and files. To visualize the model one can bind the properties to UI elements.
*/
public class JournalAbbreviationsTabViewModel implements PreferenceTabViewModel {
private final Logger LOGGER = LoggerFactory.getLogger(JournalAbbreviationsTabViewModel.class);
private final SimpleListProperty<AbbreviationsFileViewModel> journalFiles = new SimpleListProperty<>(FXCollections.observableArrayList());
private final SimpleListProperty<AbbreviationViewModel> abbreviations = new SimpleListProperty<>(FXCollections.observableArrayList());
private final SimpleIntegerProperty abbreviationsCount = new SimpleIntegerProperty();
private final SimpleObjectProperty<AbbreviationsFileViewModel> currentFile = new SimpleObjectProperty<>();
private final SimpleObjectProperty<AbbreviationViewModel> currentAbbreviation = new SimpleObjectProperty<>();
private final SimpleBooleanProperty isFileRemovable = new SimpleBooleanProperty();
private final SimpleBooleanProperty isLoading = new SimpleBooleanProperty(false);
private final SimpleBooleanProperty isEditableAndRemovable = new SimpleBooleanProperty(false);
private final SimpleBooleanProperty isAbbreviationEditableAndRemovable = new SimpleBooleanProperty(false);
private final SimpleBooleanProperty useFJournal = new SimpleBooleanProperty(true);
private final DialogService dialogService;
private final TaskExecutor taskExecutor;
private final JournalAbbreviationPreferences abbreviationsPreferences;
private final JournalAbbreviationRepository journalAbbreviationRepository;
private boolean shouldWriteLists;
public JournalAbbreviationsTabViewModel(JournalAbbreviationPreferences abbreviationsPreferences,
DialogService dialogService,
TaskExecutor taskExecutor,
JournalAbbreviationRepository journalAbbreviationRepository) {
this.dialogService = Objects.requireNonNull(dialogService);
this.taskExecutor = Objects.requireNonNull(taskExecutor);
this.journalAbbreviationRepository = Objects.requireNonNull(journalAbbreviationRepository);
this.abbreviationsPreferences = abbreviationsPreferences;
abbreviationsCount.bind(abbreviations.sizeProperty());
currentAbbreviation.addListener((observable, oldValue, newValue) -> {
boolean isAbbreviation = (newValue != null) && !newValue.isPseudoAbbreviation();
boolean isEditableFile = (currentFile.get() != null) && !currentFile.get().isBuiltInListProperty().get();
isEditableAndRemovable.set(isEditableFile);
isAbbreviationEditableAndRemovable.set(isAbbreviation && isEditableFile);
});
currentFile.addListener((observable, oldValue, newValue) -> {
if (oldValue != null) {
abbreviations.unbindBidirectional(oldValue.abbreviationsProperty());
currentAbbreviation.set(null);
}
if (newValue != null) {
isFileRemovable.set(!newValue.isBuiltInListProperty().get());
abbreviations.bindBidirectional(newValue.abbreviationsProperty());
if (!abbreviations.isEmpty()) {
currentAbbreviation.set(abbreviations.get(abbreviations.size() - 1));
}
} else {
isFileRemovable.set(false);
if (journalFiles.isEmpty()) {
currentAbbreviation.set(null);
abbreviations.clear();
} else {
currentFile.set(journalFiles.get(0));
}
}
});
journalFiles.addListener((ListChangeListener<AbbreviationsFileViewModel>) lcl -> {
if (lcl.next()) {
if (!lcl.wasReplaced()) {
if (lcl.wasAdded() && !lcl.getAddedSubList().get(0).isBuiltInListProperty().get()) {
currentFile.set(lcl.getAddedSubList().get(0));
}
}
}
});
}
@Override
public void setValues() {
journalFiles.clear();
createFileObjects();
selectLastJournalFile();
addBuiltInList();
}
/**
* Read all saved file paths and read their abbreviations.
*/
public void createFileObjects() {
List<String> externalFiles = abbreviationsPreferences.getExternalJournalLists();
externalFiles.forEach(name -> openFile(Path.of(name)));
}
/**
* This will set the {@code currentFile} property to the {@link AbbreviationsFileViewModel} object that was added to
* the {@code journalFiles} list property lastly. If there are no files in the list property this method will do
* nothing as the {@code currentFile} property is already {@code null}.
*/
public void selectLastJournalFile() {
if (!journalFiles.isEmpty()) {
currentFile.set(journalFilesProperty().get(journalFilesProperty().size() - 1));
}
}
/**
* This will load the built in abbreviation files and add it to the list of journal abbreviation files.
*/
public void addBuiltInList() {
BackgroundTask
.wrap(journalAbbreviationRepository::getAllLoaded)
.onRunning(() -> isLoading.setValue(true))
.onSuccess(result -> {
isLoading.setValue(false);
List<AbbreviationViewModel> builtInViewModels = result.stream()
.map(AbbreviationViewModel::new)
.collect(Collectors.toList());
journalFiles.add(new AbbreviationsFileViewModel(builtInViewModels, Localization.lang("JabRef built in list")));
selectLastJournalFile();
})
.onFailure(dialogService::showErrorDialogAndWait)
.executeWith(taskExecutor);
}
/**
* This method shall be used to add a new journal abbreviation file to the set of journal abbreviation files. It
* basically just calls the {@link #openFile(Path)}} method.
*/
public void addNewFile() {
FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
.addExtensionFilter(StandardFileType.CSV)
.build();
dialogService.showFileSaveDialog(fileDialogConfiguration).ifPresent(this::openFile);
}
/**
* Checks whether the file exists or if a new file should be opened. The file will be added to the set of journal
* abbreviation files. If the file also exists its abbreviations will be read and written to the abbreviations
* property.
*
* @param filePath path to the file
*/
private void openFile(Path filePath) {
AbbreviationsFileViewModel abbreviationsFile = new AbbreviationsFileViewModel(filePath);
if (journalFiles.contains(abbreviationsFile)) {
dialogService.showErrorDialogAndWait(Localization.lang("Duplicated Journal File"),
Localization.lang("Journal file %s already added", filePath.toString()));
return;
}
if (abbreviationsFile.exists()) {
try {
abbreviationsFile.readAbbreviations();
} catch (IOException e) {
LOGGER.debug("Could not read abbreviations file", e);
}
}
journalFiles.add(abbreviationsFile);
}
public void openFile() {
FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
.addExtensionFilter(StandardFileType.CSV)
.build();
dialogService.showFileOpenDialog(fileDialogConfiguration).ifPresent(this::openFile);
}
/**
* This method removes the currently selected file from the set of journal abbreviation files. This will not remove
* existing files from the file system. The {@code activeFile} property will always change to the previous file in
* the {@code journalFiles} list property, except the first file is selected. If so the next file will be selected
* except if there are no more files than the {@code activeFile} property will be set to {@code null}.
*/
public void removeCurrentFile() {
if (isFileRemovable.get()) {
journalFiles.remove(currentFile.get());
if (journalFiles.isEmpty()) {
currentFile.set(null);
}
}
}
/**
* Method to add a new abbreviation to the abbreviations list property. It also sets the currentAbbreviation
* property to the new abbreviation.
*/
public void addAbbreviation(Abbreviation abbreviationObject) {
AbbreviationViewModel abbreviationViewModel = new AbbreviationViewModel(abbreviationObject);
if (abbreviations.contains(abbreviationViewModel)) {
dialogService.showErrorDialogAndWait(Localization.lang("Duplicated Journal Abbreviation"),
Localization.lang("Abbreviation '%0' for journal '%1' already defined.", abbreviationObject.getAbbreviation(), abbreviationObject.getName()));
} else {
abbreviations.add(abbreviationViewModel);
currentAbbreviation.set(abbreviationViewModel);
shouldWriteLists = true;
}
}
public void addAbbreviation() {
addAbbreviation(new Abbreviation(
Localization.lang("Name"),
Localization.lang("Abbreviation"),
Localization.lang("Shortest unique abbreviation")));
}
/**
* Method to change the currentAbbreviation property to a new abbreviation.
*/
void editAbbreviation(Abbreviation abbreviationObject) {
if (isEditableAndRemovable.get()) {
AbbreviationViewModel abbViewModel = new AbbreviationViewModel(abbreviationObject);
if (abbreviations.contains(abbViewModel)) {
if (abbViewModel.equals(currentAbbreviation.get())) {
setCurrentAbbreviationNameAndAbbreviationIfValid(abbreviationObject);
} else {
dialogService.showErrorDialogAndWait(Localization.lang("Duplicated Journal Abbreviation"),
Localization.lang("Abbreviation '%0' for journal '%1' already defined.", abbreviationObject.getAbbreviation(), abbreviationObject.getName()));
}
} else {
setCurrentAbbreviationNameAndAbbreviationIfValid(abbreviationObject);
}
}
}
private void setCurrentAbbreviationNameAndAbbreviationIfValid(Abbreviation abbreviationObject) {
if (abbreviationObject.getName().trim().isEmpty()) {
dialogService.showErrorDialogAndWait(Localization.lang("Name cannot be empty"));
return;
}
if (abbreviationObject.getAbbreviation().trim().isEmpty()) {
dialogService.showErrorDialogAndWait(Localization.lang("Abbreviation cannot be empty"));
return;
}
AbbreviationViewModel abbreviationViewModel = currentAbbreviation.get();
abbreviationViewModel.setName(abbreviationObject.getName());
abbreviationViewModel.setAbbreviation(abbreviationObject.getAbbreviation());
if (abbreviationObject.isDefaultShortestUniqueAbbreviation()) {
abbreviationViewModel.setShortestUniqueAbbreviation("");
} else {
abbreviationViewModel.setShortestUniqueAbbreviation(abbreviationObject.getShortestUniqueAbbreviation());
}
shouldWriteLists = true;
}
/**
* Method to delete the abbreviation set in the currentAbbreviation property. The currentAbbreviationProperty will
* be set to the previous or next abbreviation in the abbreviations property if applicable. Else it will be set to
* {@code null} if there are no abbreviations left.
*/
public void deleteAbbreviation() {
if ((currentAbbreviation.get() != null) && !currentAbbreviation.get().isPseudoAbbreviation()) {
int index = abbreviations.indexOf(currentAbbreviation.get());
if (index > 1) {
currentAbbreviation.set(abbreviations.get(index - 1));
} else if ((index + 1) < abbreviationsCount.get()) {
currentAbbreviation.set(abbreviations.get(index + 1));
} else {
currentAbbreviation.set(null);
}
abbreviations.remove(index);
shouldWriteLists = true;
}
}
public void removeAbbreviation(AbbreviationViewModel abbreviation) {
Objects.requireNonNull(abbreviation);
if (abbreviation.isPseudoAbbreviation()) {
return;
}
abbreviations.remove(abbreviation);
shouldWriteLists = true;
}
/**
* Calls the {@link AbbreviationsFileViewModel#writeOrCreate()} method for each file in the journalFiles property
* which will overwrite the existing files with the content of the abbreviations property of the AbbreviationsFile.
* Non-existing files will be created.
*/
public void saveJournalAbbreviationFiles() {
journalFiles.forEach(file -> {
try {
file.writeOrCreate();
} catch (IOException e) {
LOGGER.debug("Error during writing journal CSV", e);
}
});
}
/**
* This method first saves all external files to its internal list, then writes all abbreviations to their files and
* finally updates the abbreviations auto complete.
*/
@Override
public void storeSettings() {
BackgroundTask
.wrap(() -> {
List<String> journalStringList = journalFiles.stream()
.filter(path -> !path.isBuiltInListProperty().get())
.filter(path -> path.getAbsolutePath().isPresent())
.map(path -> path.getAbsolutePath().get().toAbsolutePath().toString())
.collect(Collectors.toList());
abbreviationsPreferences.setExternalJournalLists(journalStringList);
abbreviationsPreferences.setUseFJournalField(useFJournal.get());
if (shouldWriteLists) {
saveJournalAbbreviationFiles();
shouldWriteLists = false;
}
})
.onSuccess(success -> Globals.journalAbbreviationRepository =
JournalAbbreviationLoader.loadRepository(abbreviationsPreferences))
.onFailure(exception -> LOGGER.error("Failed to store journal preferences.", exception))
.executeWith(taskExecutor);
}
public SimpleBooleanProperty isLoadingProperty() {
return isLoading;
}
public SimpleListProperty<AbbreviationsFileViewModel> journalFilesProperty() {
return journalFiles;
}
public SimpleListProperty<AbbreviationViewModel> abbreviationsProperty() {
return abbreviations;
}
public SimpleIntegerProperty abbreviationsCountProperty() {
return abbreviationsCount;
}
public SimpleObjectProperty<AbbreviationsFileViewModel> currentFileProperty() {
return currentFile;
}
public SimpleObjectProperty<AbbreviationViewModel> currentAbbreviationProperty() {
return currentAbbreviation;
}
public SimpleBooleanProperty isEditableAndRemovableProperty() {
return isEditableAndRemovable;
}
public SimpleBooleanProperty isAbbreviationEditableAndRemovable() {
return isAbbreviationEditableAndRemovable;
}
public SimpleBooleanProperty isFileRemovableProperty() {
return isFileRemovable;
}
public SimpleBooleanProperty useFJournalProperty() {
return useFJournal;
}
}
| 17,525
| 43.938462
| 170
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/keybindings/KeyBindingViewModel.java
|
package org.jabref.gui.preferences.keybindings;
import java.util.Optional;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.icon.JabRefIcon;
import org.jabref.gui.keyboard.KeyBinding;
import org.jabref.gui.keyboard.KeyBindingCategory;
import org.jabref.gui.keyboard.KeyBindingRepository;
import com.google.common.base.CaseFormat;
/**
* This class represents a view model for objects of the KeyBinding
* class. It has two properties representing the localized name of an
* action and its key bind. It can also represent a key binding category
* instead of a key bind itself.
*
*/
public class KeyBindingViewModel {
private KeyBinding keyBinding = null;
private String realBinding = "";
private final ObservableList<KeyBindingViewModel> children = FXCollections.observableArrayList();
private final KeyBindingRepository keyBindingRepository;
private final SimpleStringProperty displayName = new SimpleStringProperty();
private final SimpleStringProperty shownBinding = new SimpleStringProperty();
private final KeyBindingCategory category;
public KeyBindingViewModel(KeyBindingRepository keyBindingRepository, KeyBinding keyBinding, String binding) {
this(keyBindingRepository, keyBinding.getCategory());
this.keyBinding = keyBinding;
setDisplayName();
setBinding(binding);
}
public KeyBindingViewModel(KeyBindingRepository keyBindingRepository, KeyBindingCategory category) {
this.keyBindingRepository = keyBindingRepository;
this.category = category;
setDisplayName();
}
public ObservableList<KeyBindingViewModel> getChildren() {
return children;
}
public KeyBinding getKeyBinding() {
return keyBinding;
}
public StringProperty shownBindingProperty() {
return this.shownBinding;
}
public String getBinding() {
return realBinding;
}
private void setBinding(String bind) {
this.realBinding = bind;
String[] parts = bind.split(" ");
StringBuilder displayBind = new StringBuilder();
for (String part : parts) {
displayBind.append(CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, part)).append(" ");
}
this.shownBinding.set(displayBind.toString().trim().replace(" ", " + "));
}
private void setDisplayName() {
this.displayName.set((keyBinding == null) ? this.category.getName() : keyBinding.getLocalization());
}
public StringProperty nameProperty() {
return this.displayName;
}
public boolean isCategory() {
return keyBinding == null;
}
/**
* Sets a a new key bind to this objects key binding object if
* the given key event is a valid combination of keys.
*
* @param evt as KeyEvent
* @return true if the KeyEvent is a valid binding, false else
*/
public boolean setNewBinding(KeyEvent evt) {
// validate the shortcut is no modifier key
KeyCode code = evt.getCode();
if (code.isModifierKey() || (code == KeyCode.BACK_SPACE) || (code == KeyCode.SPACE) || (code == KeyCode.TAB)
|| (code == KeyCode.ENTER) || (code == KeyCode.UNDEFINED)) {
return false;
}
// gather the pressed modifier keys
String modifiers = "";
if (evt.isControlDown()) {
modifiers = "ctrl+";
}
if (evt.isShiftDown()) {
modifiers += "shift+";
}
if (evt.isAltDown()) {
modifiers += "alt+";
}
// if no modifier keys are pressed, only special keys can be shortcuts
if (modifiers.isEmpty()) {
if (!(code.isFunctionKey() || (code == KeyCode.ESCAPE) || (code == KeyCode.DELETE))) {
return false;
}
}
String newShortcut = modifiers + code;
setBinding(newShortcut);
return true;
}
/**
* This method will reset the key bind of this models KeyBinding object to it's default bind
*/
public void resetToDefault() {
if (!isCategory()) {
String key = getKeyBinding().getConstant();
keyBindingRepository.resetToDefault(key);
setBinding(keyBindingRepository.get(key));
}
}
public void clear() {
if (!isCategory()) {
String key = getKeyBinding().getConstant();
keyBindingRepository.put(key, "");
setBinding(keyBindingRepository.get(key));
}
}
public Optional<JabRefIcon> getResetIcon() {
return isCategory() ? Optional.empty() : Optional.of(IconTheme.JabRefIcons.REFRESH);
}
public Optional<JabRefIcon> getClearIcon() {
return isCategory() ? Optional.empty() : Optional.of(IconTheme.JabRefIcons.CLEANUP_ENTRIES);
}
}
| 5,095
| 31.458599
| 116
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/keybindings/KeyBindingsTab.java
|
package org.jabref.gui.preferences.keybindings;
import javafx.fxml.FXML;
import javafx.scene.control.MenuButton;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.SelectionModel;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeTableColumn;
import javafx.scene.control.TreeTableView;
import org.jabref.gui.icon.JabRefIcon;
import org.jabref.gui.keyboard.KeyBindingRepository;
import org.jabref.gui.preferences.AbstractPreferenceTabView;
import org.jabref.gui.preferences.PreferencesTab;
import org.jabref.gui.preferences.keybindings.presets.KeyBindingPreset;
import org.jabref.gui.util.RecursiveTreeItem;
import org.jabref.gui.util.ViewModelTreeTableCellFactory;
import org.jabref.logic.l10n.Localization;
import com.airhacks.afterburner.views.ViewLoader;
import com.tobiasdiez.easybind.EasyBind;
import jakarta.inject.Inject;
public class KeyBindingsTab extends AbstractPreferenceTabView<KeyBindingsTabViewModel> implements PreferencesTab {
@FXML private TreeTableView<KeyBindingViewModel> keyBindingsTable;
@FXML private TreeTableColumn<KeyBindingViewModel, String> actionColumn;
@FXML private TreeTableColumn<KeyBindingViewModel, String> shortcutColumn;
@FXML private TreeTableColumn<KeyBindingViewModel, KeyBindingViewModel> resetColumn;
@FXML private TreeTableColumn<KeyBindingViewModel, KeyBindingViewModel> clearColumn;
@FXML private MenuButton presetsButton;
@Inject private KeyBindingRepository keyBindingRepository;
public KeyBindingsTab() {
ViewLoader.view(this)
.root(this)
.load();
}
@Override
public String getTabName() {
return Localization.lang("Key bindings");
}
@FXML
private void initialize() {
viewModel = new KeyBindingsTabViewModel(keyBindingRepository, dialogService, preferencesService);
keyBindingsTable.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
viewModel.selectedKeyBindingProperty().bind(
EasyBind.wrapNullable(keyBindingsTable.selectionModelProperty())
.mapObservable(SelectionModel::selectedItemProperty)
.mapObservable(TreeItem::valueProperty)
);
keyBindingsTable.setOnKeyPressed(viewModel::setNewBindingForCurrent);
keyBindingsTable.rootProperty().bind(
EasyBind.map(viewModel.rootKeyBindingProperty(),
keybinding -> new RecursiveTreeItem<>(keybinding, KeyBindingViewModel::getChildren))
);
actionColumn.setCellValueFactory(cellData -> cellData.getValue().getValue().nameProperty());
shortcutColumn.setCellValueFactory(cellData -> cellData.getValue().getValue().shownBindingProperty());
new ViewModelTreeTableCellFactory<KeyBindingViewModel>()
.withGraphic(keyBinding -> keyBinding.getResetIcon().map(JabRefIcon::getGraphicNode).orElse(null))
.withOnMouseClickedEvent(keyBinding -> evt -> keyBinding.resetToDefault())
.install(resetColumn);
new ViewModelTreeTableCellFactory<KeyBindingViewModel>()
.withGraphic(keyBinding -> keyBinding.getClearIcon().map(JabRefIcon::getGraphicNode).orElse(null))
.withOnMouseClickedEvent(keyBinding -> evt -> keyBinding.clear())
.install(clearColumn);
viewModel.keyBindingPresets().forEach(preset -> presetsButton.getItems().add(createMenuItem(preset)));
}
private MenuItem createMenuItem(KeyBindingPreset preset) {
MenuItem item = new MenuItem(preset.getName());
item.setOnAction(event -> viewModel.loadPreset(preset));
return item;
}
@FXML
private void resetBindings() {
viewModel.resetToDefault();
}
}
| 3,841
| 43.16092
| 114
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/keybindings/KeyBindingsTabViewModel.java
|
package org.jabref.gui.preferences.keybindings;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import javafx.beans.property.ListProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonType;
import javafx.scene.input.KeyEvent;
import org.jabref.gui.DialogService;
import org.jabref.gui.keyboard.KeyBindingCategory;
import org.jabref.gui.keyboard.KeyBindingRepository;
import org.jabref.gui.preferences.PreferenceTabViewModel;
import org.jabref.gui.preferences.keybindings.presets.BashKeyBindingPreset;
import org.jabref.gui.preferences.keybindings.presets.KeyBindingPreset;
import org.jabref.gui.preferences.keybindings.presets.NewEntryBindingPreset;
import org.jabref.gui.util.OptionalObjectProperty;
import org.jabref.logic.l10n.Localization;
import org.jabref.preferences.PreferencesService;
public class KeyBindingsTabViewModel implements PreferenceTabViewModel {
private final KeyBindingRepository keyBindingRepository;
private final KeyBindingRepository initialKeyBindingRepository;
private final PreferencesService preferences;
private final OptionalObjectProperty<KeyBindingViewModel> selectedKeyBinding = OptionalObjectProperty.empty();
private final ObjectProperty<KeyBindingViewModel> rootKeyBinding = new SimpleObjectProperty<>();
private final ListProperty<KeyBindingPreset> keyBindingPresets = new SimpleListProperty<>(FXCollections.observableArrayList());
private final DialogService dialogService;
private final List<String> restartWarning = new ArrayList<>();
public KeyBindingsTabViewModel(KeyBindingRepository keyBindingRepository, DialogService dialogService, PreferencesService preferences) {
this.keyBindingRepository = Objects.requireNonNull(keyBindingRepository);
this.initialKeyBindingRepository = new KeyBindingRepository(keyBindingRepository.getKeyBindings());
this.dialogService = Objects.requireNonNull(dialogService);
this.preferences = Objects.requireNonNull(preferences);
keyBindingPresets.add(new BashKeyBindingPreset());
keyBindingPresets.add(new NewEntryBindingPreset());
}
/**
* Read all keybindings from the keybinding repository and create table keybinding models for them
*/
@Override
public void setValues() {
KeyBindingViewModel root = new KeyBindingViewModel(keyBindingRepository, KeyBindingCategory.FILE);
for (KeyBindingCategory category : KeyBindingCategory.values()) {
KeyBindingViewModel categoryItem = new KeyBindingViewModel(keyBindingRepository, category);
keyBindingRepository.getKeyBindings().forEach((keyBinding, bind) -> {
if (keyBinding.getCategory() == category) {
KeyBindingViewModel keyBindViewModel = new KeyBindingViewModel(keyBindingRepository, keyBinding, bind);
categoryItem.getChildren().add(keyBindViewModel);
}
});
root.getChildren().add(categoryItem);
}
rootKeyBinding.set(root);
}
public void setNewBindingForCurrent(KeyEvent event) {
Optional<KeyBindingViewModel> selectedKeyBindingValue = selectedKeyBinding.getValue();
if (selectedKeyBindingValue.isEmpty()) {
return;
}
KeyBindingViewModel selectedEntry = selectedKeyBindingValue.get();
if (selectedEntry.isCategory()) {
return;
}
if (selectedEntry.setNewBinding(event)) {
keyBindingRepository.put(selectedEntry.getKeyBinding(), selectedEntry.getBinding());
}
}
public void storeSettings() {
preferences.storeKeyBindingRepository(keyBindingRepository);
if (!keyBindingRepository.equals(initialKeyBindingRepository)) {
restartWarning.add(Localization.lang("Key bindings changed"));
}
}
public void resetToDefault() {
String title = Localization.lang("Resetting all key bindings");
String content = Localization.lang("All key bindings will be reset to their defaults.");
ButtonType resetButtonType = new ButtonType("Reset", ButtonBar.ButtonData.OK_DONE);
dialogService.showCustomButtonDialogAndWait(Alert.AlertType.INFORMATION, title, content, resetButtonType,
ButtonType.CANCEL).ifPresent(response -> {
if (response == resetButtonType) {
keyBindingRepository.resetToDefault();
setValues();
}
});
}
public void loadPreset(KeyBindingPreset preset) {
if (preset == null) {
return;
}
preset.getKeyBindings().forEach(keyBindingRepository::put);
setValues();
}
public ListProperty<KeyBindingPreset> keyBindingPresets() {
return keyBindingPresets;
}
@Override
public List<String> getRestartWarnings() {
return restartWarning;
}
public OptionalObjectProperty<KeyBindingViewModel> selectedKeyBindingProperty() {
return selectedKeyBinding;
}
public ObjectProperty<KeyBindingViewModel> rootKeyBindingProperty() {
return rootKeyBinding;
}
}
| 5,433
| 39.552239
| 140
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/keybindings/presets/BashKeyBindingPreset.java
|
package org.jabref.gui.preferences.keybindings.presets;
import java.util.HashMap;
import java.util.Map;
import org.jabref.gui.keyboard.KeyBinding;
public class BashKeyBindingPreset implements KeyBindingPreset {
@Override
public String getName() {
return "Bash";
}
@Override
public Map<KeyBinding, String> getKeyBindings() {
final Map<KeyBinding, String> keyBindings = new HashMap<>();
keyBindings.put(KeyBinding.EDITOR_DELETE, "ctrl+D");
// DELETE BACKWARDS = Rubout
keyBindings.put(KeyBinding.EDITOR_BACKWARD, "ctrl+B");
keyBindings.put(KeyBinding.EDITOR_FORWARD, "ctrl+F");
keyBindings.put(KeyBinding.EDITOR_WORD_BACKWARD, "alt+B");
keyBindings.put(KeyBinding.EDITOR_WORD_FORWARD, "alt+F");
keyBindings.put(KeyBinding.EDITOR_BEGINNING, "ctrl+A");
keyBindings.put(KeyBinding.EDITOR_END, "ctrl+E");
keyBindings.put(KeyBinding.EDITOR_BEGINNING_DOC, "alt+LESS");
keyBindings.put(KeyBinding.EDITOR_END_DOC, "alt+shift+LESS");
keyBindings.put(KeyBinding.EDITOR_UP, "ctrl+P");
keyBindings.put(KeyBinding.EDITOR_DOWN, "ctrl+N");
keyBindings.put(KeyBinding.EDITOR_CAPITALIZE, "alt+C");
keyBindings.put(KeyBinding.EDITOR_LOWERCASE, "alt+L");
keyBindings.put(KeyBinding.EDITOR_UPPERCASE, "alt+U");
keyBindings.put(KeyBinding.EDITOR_KILL_LINE, "ctrl+K");
keyBindings.put(KeyBinding.EDITOR_KILL_WORD, "alt+D");
keyBindings.put(KeyBinding.EDITOR_KILL_WORD_BACKWARD, "alt+DELETE");
return keyBindings;
}
}
| 1,592
| 37.853659
| 76
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/keybindings/presets/KeyBindingPreset.java
|
package org.jabref.gui.preferences.keybindings.presets;
import java.util.Map;
import org.jabref.gui.keyboard.KeyBinding;
public interface KeyBindingPreset {
String getName();
Map<KeyBinding, String> getKeyBindings();
}
| 231
| 18.333333
| 55
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/keybindings/presets/NewEntryBindingPreset.java
|
package org.jabref.gui.preferences.keybindings.presets;
import java.util.HashMap;
import java.util.Map;
import org.jabref.gui.keyboard.KeyBinding;
import org.jabref.logic.l10n.Localization;
public class NewEntryBindingPreset implements KeyBindingPreset {
@Override
public String getName() {
return Localization.lang("New entry by type");
}
@Override
public Map<KeyBinding, String> getKeyBindings() {
final Map<KeyBinding, String> keyBindings = new HashMap<>();
// Clear conflicting default presets
keyBindings.put(KeyBinding.PULL_CHANGES_FROM_SHARED_DATABASE, "");
keyBindings.put(KeyBinding.COPY_PREVIEW, "");
// Add new entry presets
keyBindings.put(KeyBinding.NEW_ARTICLE, "ctrl+shift+A");
keyBindings.put(KeyBinding.NEW_BOOK, "ctrl+shift+B");
keyBindings.put(KeyBinding.NEW_ENTRY, "ctrl+N");
keyBindings.put(KeyBinding.NEW_ENTRY_FROM_PLAIN_TEXT, "ctrl+shift+N");
keyBindings.put(KeyBinding.NEW_INBOOK, "ctrl+shift+I");
keyBindings.put(KeyBinding.NEW_INPROCEEDINGS, "ctrl+shift+C");
keyBindings.put(KeyBinding.NEW_MASTERSTHESIS, "ctrl+shift+M");
keyBindings.put(KeyBinding.NEW_PHDTHESIS, "ctrl+shift+T");
keyBindings.put(KeyBinding.NEW_PROCEEDINGS, "ctrl+shift+P");
keyBindings.put(KeyBinding.NEW_TECHREPORT, "ctrl+shift+R");
keyBindings.put(KeyBinding.NEW_UNPUBLISHED, "ctrl+shift+U");
return keyBindings;
}
}
| 1,490
| 36.275
| 78
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/linkedfiles/LinkedFilesTab.java
|
package org.jabref.gui.preferences.linkedfiles;
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.RadioButton;
import javafx.scene.control.TextField;
import org.jabref.gui.Globals;
import org.jabref.gui.actions.ActionFactory;
import org.jabref.gui.actions.StandardActions;
import org.jabref.gui.help.HelpAction;
import org.jabref.gui.preferences.AbstractPreferenceTabView;
import org.jabref.gui.preferences.PreferencesTab;
import org.jabref.gui.util.IconValidationDecorator;
import org.jabref.logic.help.HelpFile;
import org.jabref.logic.l10n.Localization;
import com.airhacks.afterburner.views.ViewLoader;
import de.saxsys.mvvmfx.utils.validation.visualization.ControlsFxVisualizer;
public class LinkedFilesTab extends AbstractPreferenceTabView<LinkedFilesTabViewModel> implements PreferencesTab {
@FXML private TextField mainFileDirectory;
@FXML private RadioButton useMainFileDirectory;
@FXML private RadioButton useBibLocationAsPrimary;
@FXML private Button browseDirectory;
@FXML private Button autolinkRegexHelp;
@FXML private RadioButton autolinkFileStartsBibtex;
@FXML private RadioButton autolinkFileExactBibtex;
@FXML private RadioButton autolinkUseRegex;
@FXML private TextField autolinkRegexKey;
@FXML private CheckBox fulltextIndex;
@FXML private ComboBox<String> fileNamePattern;
@FXML private TextField fileDirectoryPattern;
private final ControlsFxVisualizer validationVisualizer = new ControlsFxVisualizer();
public LinkedFilesTab() {
ViewLoader.view(this)
.root(this)
.load();
}
@Override
public String getTabName() {
return Localization.lang("Linked files");
}
public void initialize() {
this.viewModel = new LinkedFilesTabViewModel(dialogService, preferencesService);
mainFileDirectory.textProperty().bindBidirectional(viewModel.mainFileDirectoryProperty());
mainFileDirectory.disableProperty().bind(viewModel.useBibLocationAsPrimaryProperty());
browseDirectory.disableProperty().bind(viewModel.useBibLocationAsPrimaryProperty());
useBibLocationAsPrimary.selectedProperty().bindBidirectional(viewModel.useBibLocationAsPrimaryProperty());
useMainFileDirectory.selectedProperty().bindBidirectional(viewModel.useMainFileDirectoryProperty());
autolinkFileStartsBibtex.selectedProperty().bindBidirectional(viewModel.autolinkFileStartsBibtexProperty());
autolinkFileExactBibtex.selectedProperty().bindBidirectional(viewModel.autolinkFileExactBibtexProperty());
autolinkUseRegex.selectedProperty().bindBidirectional(viewModel.autolinkUseRegexProperty());
autolinkRegexKey.textProperty().bindBidirectional(viewModel.autolinkRegexKeyProperty());
autolinkRegexKey.disableProperty().bind(autolinkUseRegex.selectedProperty().not());
fulltextIndex.selectedProperty().bindBidirectional(viewModel.fulltextIndexProperty());
fileNamePattern.valueProperty().bindBidirectional(viewModel.fileNamePatternProperty());
fileNamePattern.itemsProperty().bind(viewModel.defaultFileNamePatternsProperty());
fileDirectoryPattern.textProperty().bindBidirectional(viewModel.fileDirectoryPatternProperty());
ActionFactory actionFactory = new ActionFactory(Globals.getKeyPrefs());
actionFactory.configureIconButton(StandardActions.HELP_REGEX_SEARCH, new HelpAction(HelpFile.REGEX_SEARCH, dialogService), autolinkRegexHelp);
validationVisualizer.setDecoration(new IconValidationDecorator());
Platform.runLater(() -> validationVisualizer.initVisualization(viewModel.mainFileDirValidationStatus(), mainFileDirectory));
}
public void mainFileDirBrowse() {
viewModel.mainFileDirBrowse();
}
}
| 3,941
| 45.928571
| 150
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/linkedfiles/LinkedFilesTabViewModel.java
|
package org.jabref.gui.preferences.linkedfiles;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import org.jabref.gui.DialogService;
import org.jabref.gui.preferences.PreferenceTabViewModel;
import org.jabref.gui.util.DirectoryDialogConfiguration;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.io.AutoLinkPreferences;
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;
public class LinkedFilesTabViewModel implements PreferenceTabViewModel {
private final StringProperty mainFileDirectoryProperty = new SimpleStringProperty("");
private final BooleanProperty useMainFileDirectoryProperty = new SimpleBooleanProperty();
private final BooleanProperty useBibLocationAsPrimaryProperty = new SimpleBooleanProperty();
private final BooleanProperty autolinkFileStartsBibtexProperty = new SimpleBooleanProperty();
private final BooleanProperty autolinkFileExactBibtexProperty = new SimpleBooleanProperty();
private final BooleanProperty autolinkUseRegexProperty = new SimpleBooleanProperty();
private final StringProperty autolinkRegexKeyProperty = new SimpleStringProperty("");
private final ListProperty<String> defaultFileNamePatternsProperty =
new SimpleListProperty<>(FXCollections.observableArrayList(FilePreferences.DEFAULT_FILENAME_PATTERNS));
private final BooleanProperty fulltextIndex = new SimpleBooleanProperty();
private final StringProperty fileNamePatternProperty = new SimpleStringProperty();
private final StringProperty fileDirectoryPatternProperty = new SimpleStringProperty();
private final Validator mainFileDirValidator;
private final DialogService dialogService;
private final FilePreferences filePreferences;
private final AutoLinkPreferences autoLinkPreferences;
public LinkedFilesTabViewModel(DialogService dialogService, PreferencesService preferences) {
this.dialogService = dialogService;
this.filePreferences = preferences.getFilePreferences();
this.autoLinkPreferences = preferences.getAutoLinkPreferences();
mainFileDirValidator = new FunctionBasedValidator<>(
mainFileDirectoryProperty,
mainDirectoryPath -> {
ValidationMessage error = ValidationMessage.error(
Localization.lang("Main file directory '%0' not found.\nCheck the tab \"Linked files\".", mainDirectoryPath)
);
try {
Path path = Path.of(mainDirectoryPath);
if (!(Files.exists(path) && Files.isDirectory(path))) {
return error;
}
} catch (InvalidPathException ex) {
return error;
}
// main directory is valid
return null;
}
);
}
@Override
public void setValues() {
// External files preferences / Attached files preferences / File preferences
mainFileDirectoryProperty.setValue(filePreferences.getMainFileDirectory().orElse(Path.of("")).toString());
useMainFileDirectoryProperty.setValue(!filePreferences.shouldStoreFilesRelativeToBibFile());
useBibLocationAsPrimaryProperty.setValue(filePreferences.shouldStoreFilesRelativeToBibFile());
fulltextIndex.setValue(filePreferences.shouldFulltextIndexLinkedFiles());
fileNamePatternProperty.setValue(filePreferences.getFileNamePattern());
fileDirectoryPatternProperty.setValue(filePreferences.getFileDirectoryPattern());
// Autolink preferences
switch (autoLinkPreferences.getCitationKeyDependency()) {
case START -> autolinkFileStartsBibtexProperty.setValue(true);
case EXACT -> autolinkFileExactBibtexProperty.setValue(true);
case REGEX -> autolinkUseRegexProperty.setValue(true);
}
autolinkRegexKeyProperty.setValue(autoLinkPreferences.getRegularExpression());
}
@Override
public void storeSettings() {
// External files preferences / Attached files preferences / File preferences
filePreferences.setMainFileDirectory(mainFileDirectoryProperty.getValue());
filePreferences.setStoreFilesRelativeToBibFile(useBibLocationAsPrimaryProperty.getValue());
filePreferences.setFileNamePattern(fileNamePatternProperty.getValue());
filePreferences.setFileDirectoryPattern(fileDirectoryPatternProperty.getValue());
filePreferences.setFulltextIndexLinkedFiles(fulltextIndex.getValue());
// Autolink preferences
if (autolinkFileStartsBibtexProperty.getValue()) {
autoLinkPreferences.setCitationKeyDependency(AutoLinkPreferences.CitationKeyDependency.START);
} else if (autolinkFileExactBibtexProperty.getValue()) {
autoLinkPreferences.setCitationKeyDependency(AutoLinkPreferences.CitationKeyDependency.EXACT);
} else if (autolinkUseRegexProperty.getValue()) {
autoLinkPreferences.setCitationKeyDependency(AutoLinkPreferences.CitationKeyDependency.REGEX);
}
autoLinkPreferences.setRegularExpression(autolinkRegexKeyProperty.getValue());
}
ValidationStatus mainFileDirValidationStatus() {
return mainFileDirValidator.getValidationStatus();
}
@Override
public boolean validateSettings() {
ValidationStatus validationStatus = mainFileDirValidationStatus();
if (!validationStatus.isValid() && useMainFileDirectoryProperty().get()) {
validationStatus.getHighestMessage().ifPresent(message ->
dialogService.showErrorDialogAndWait(message.getMessage()));
return false;
}
return true;
}
public void mainFileDirBrowse() {
DirectoryDialogConfiguration dirDialogConfiguration =
new DirectoryDialogConfiguration.Builder().withInitialDirectory(Path.of(mainFileDirectoryProperty.getValue())).build();
dialogService.showDirectorySelectionDialog(dirDialogConfiguration)
.ifPresent(f -> mainFileDirectoryProperty.setValue(f.toString()));
}
// External file links
public StringProperty mainFileDirectoryProperty() {
return mainFileDirectoryProperty;
}
public BooleanProperty useBibLocationAsPrimaryProperty() {
return useBibLocationAsPrimaryProperty;
}
public BooleanProperty autolinkFileStartsBibtexProperty() {
return autolinkFileStartsBibtexProperty;
}
public BooleanProperty autolinkFileExactBibtexProperty() {
return autolinkFileExactBibtexProperty;
}
public BooleanProperty autolinkUseRegexProperty() {
return autolinkUseRegexProperty;
}
public StringProperty autolinkRegexKeyProperty() {
return autolinkRegexKeyProperty;
}
public BooleanProperty fulltextIndexProperty() {
return fulltextIndex;
}
public ListProperty<String> defaultFileNamePatternsProperty() {
return defaultFileNamePatternsProperty;
}
public StringProperty fileNamePatternProperty() {
return fileNamePatternProperty;
}
public StringProperty fileDirectoryPatternProperty() {
return fileDirectoryPatternProperty;
}
public BooleanProperty useMainFileDirectoryProperty() {
return useMainFileDirectoryProperty;
}
}
| 8,087
| 43.196721
| 136
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/nameformatter/NameFormatterItemModel.java
|
package org.jabref.gui.preferences.nameformatter;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import org.jabref.logic.layout.format.NameFormatter;
public class NameFormatterItemModel {
private final StringProperty name = new SimpleStringProperty("");
private final StringProperty format = new SimpleStringProperty("");
NameFormatterItemModel() {
this("");
}
NameFormatterItemModel(String name) {
this(name, NameFormatter.DEFAULT_FORMAT);
}
NameFormatterItemModel(String name, String format) {
this.name.setValue(name);
this.format.setValue(format);
}
public void setName(String name) {
this.name.setValue(name);
}
public String getName() {
return name.getValue();
}
public StringProperty nameProperty() {
return name;
}
public void setFormat(String format) {
this.format.setValue(format);
}
public String getFormat() {
return format.getValue();
}
public StringProperty formatProperty() {
return format;
}
@Override
public String toString() {
return "[" + name.getValue() + "," + format.getValue() + "]";
}
}
| 1,253
| 22.222222
| 71
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/nameformatter/NameFormatterTab.java
|
package org.jabref.gui.preferences.nameformatter;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import org.jabref.gui.Globals;
import org.jabref.gui.actions.ActionFactory;
import org.jabref.gui.actions.StandardActions;
import org.jabref.gui.help.HelpAction;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.preferences.AbstractPreferenceTabView;
import org.jabref.gui.preferences.PreferencesTab;
import org.jabref.gui.util.ValueTableCellFactory;
import org.jabref.logic.help.HelpFile;
import org.jabref.logic.l10n.Localization;
import com.airhacks.afterburner.views.ViewLoader;
public class NameFormatterTab extends AbstractPreferenceTabView<NameFormatterTabViewModel> implements PreferencesTab {
@FXML private TableView<NameFormatterItemModel> formatterList;
@FXML private TableColumn<NameFormatterItemModel, String> formatterNameColumn;
@FXML private TableColumn<NameFormatterItemModel, String> formatterStringColumn;
@FXML private TableColumn<NameFormatterItemModel, String> actionsColumn;
@FXML private TextField addFormatterName;
@FXML private TextField addFormatterString;
@FXML private Button formatterHelp;
public NameFormatterTab() {
ViewLoader.view(this)
.root(this)
.load();
}
@Override
public String getTabName() {
return Localization.lang("Name formatter");
}
public void initialize() {
this.viewModel = new NameFormatterTabViewModel(preferencesService.getNameFormatterPreferences());
formatterNameColumn.setSortable(true);
formatterNameColumn.setReorderable(false);
formatterNameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
formatterNameColumn.setCellFactory(TextFieldTableCell.forTableColumn());
formatterNameColumn.setEditable(true);
formatterNameColumn.setOnEditCommit(
(TableColumn.CellEditEvent<NameFormatterItemModel, String> event) ->
event.getRowValue().setName(event.getNewValue()));
formatterStringColumn.setSortable(true);
formatterStringColumn.setReorderable(false);
formatterStringColumn.setCellValueFactory(cellData -> cellData.getValue().formatProperty());
formatterStringColumn.setCellFactory(TextFieldTableCell.forTableColumn());
formatterStringColumn.setEditable(true);
formatterStringColumn.setOnEditCommit(
(TableColumn.CellEditEvent<NameFormatterItemModel, String> event) ->
event.getRowValue().setFormat(event.getNewValue()));
actionsColumn.setSortable(false);
actionsColumn.setReorderable(false);
actionsColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
new ValueTableCellFactory<NameFormatterItemModel, String>()
.withGraphic(name -> IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode())
.withTooltip(name -> Localization.lang("Remove formatter '%0'", name))
.withOnMouseClickedEvent(item -> evt ->
viewModel.removeFormatter(formatterList.getFocusModel().getFocusedItem()))
.install(actionsColumn);
formatterList.addEventFilter(KeyEvent.KEY_PRESSED, event -> {
if (event.getCode() == KeyCode.DELETE) {
viewModel.removeFormatter(formatterList.getSelectionModel().getSelectedItem());
event.consume();
}
});
formatterList.setEditable(true);
formatterList.itemsProperty().bindBidirectional(viewModel.formatterListProperty());
addFormatterName.textProperty().bindBidirectional(viewModel.addFormatterNameProperty());
addFormatterName.addEventFilter(KeyEvent.KEY_PRESSED, event -> {
if (event.getCode() == KeyCode.ENTER) {
addFormatterString.requestFocus();
addFormatterString.selectAll();
event.consume();
}
});
addFormatterString.textProperty().bindBidirectional(viewModel.addFormatterStringProperty());
addFormatterString.addEventFilter(KeyEvent.KEY_PRESSED, event -> {
if (event.getCode() == KeyCode.ENTER) {
viewModel.addFormatter();
addFormatterName.requestFocus();
event.consume();
}
});
ActionFactory actionFactory = new ActionFactory(Globals.getKeyPrefs());
actionFactory.configureIconButton(StandardActions.HELP_NAME_FORMATTER, new HelpAction(HelpFile.CUSTOM_EXPORTS_NAME_FORMATTER, dialogService), formatterHelp);
}
public void addFormatter() {
viewModel.addFormatter();
}
}
| 4,983
| 43.106195
| 165
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/nameformatter/NameFormatterTabViewModel.java
|
package org.jabref.gui.preferences.nameformatter;
import java.util.ArrayList;
import java.util.List;
import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import org.jabref.gui.preferences.PreferenceTabViewModel;
import org.jabref.logic.layout.format.NameFormatterPreferences;
import org.jabref.model.strings.StringUtil;
public class NameFormatterTabViewModel implements PreferenceTabViewModel {
private final ListProperty<NameFormatterItemModel> formatterListProperty = new SimpleListProperty<>(FXCollections.observableArrayList());
private final StringProperty addFormatterNameProperty = new SimpleStringProperty();
private final StringProperty addFormatterStringProperty = new SimpleStringProperty();
private final NameFormatterPreferences nameFormatterPreferences;
NameFormatterTabViewModel(NameFormatterPreferences preferences) {
this.nameFormatterPreferences = preferences;
}
@Override
public void setValues() {
formatterListProperty.clear();
List<String> names = nameFormatterPreferences.getNameFormatterKey();
List<String> formats = nameFormatterPreferences.getNameFormatterValue();
for (int i = 0; i < names.size(); i++) {
if (i < formats.size()) {
formatterListProperty.add(new NameFormatterItemModel(names.get(i), formats.get(i)));
} else {
formatterListProperty.add(new NameFormatterItemModel(names.get(i)));
}
}
}
@Override
public void storeSettings() {
formatterListProperty.removeIf(formatter -> formatter.getName().isEmpty());
List<String> names = new ArrayList<>(formatterListProperty.size());
List<String> formats = new ArrayList<>(formatterListProperty.size());
for (NameFormatterItemModel formatterListItem : formatterListProperty) {
names.add(formatterListItem.getName());
formats.add(formatterListItem.getFormat());
}
nameFormatterPreferences.setNameFormatterKey(names);
nameFormatterPreferences.setNameFormatterValue(formats);
}
public void addFormatter() {
if (!StringUtil.isNullOrEmpty(addFormatterNameProperty.getValue()) &&
!StringUtil.isNullOrEmpty(addFormatterStringProperty.getValue())) {
formatterListProperty.add(new NameFormatterItemModel(
addFormatterNameProperty.getValue(), addFormatterStringProperty.getValue()));
addFormatterNameProperty.setValue("");
addFormatterStringProperty.setValue("");
}
}
public void removeFormatter(NameFormatterItemModel formatter) {
formatterListProperty.remove(formatter);
}
public ListProperty<NameFormatterItemModel> formatterListProperty() {
return formatterListProperty;
}
public StringProperty addFormatterNameProperty() {
return addFormatterNameProperty;
}
public StringProperty addFormatterStringProperty() {
return addFormatterStringProperty;
}
}
| 3,219
| 36.882353
| 141
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/network/CustomCertificateViewModel.java
|
package org.jabref.gui.preferences.network;
import java.time.LocalDate;
import java.util.Optional;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.property.ReadOnlyStringProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import org.jabref.gui.AbstractViewModel;
import org.jabref.logic.net.ssl.SSLCertificate;
public class CustomCertificateViewModel extends AbstractViewModel {
private final StringProperty serialNumberProperty = new SimpleStringProperty("");
private final StringProperty issuerProperty = new SimpleStringProperty("");
private final ObjectProperty<LocalDate> validFromProperty = new SimpleObjectProperty<>();
private final ObjectProperty<LocalDate> validToProperty = new SimpleObjectProperty<>();
private final StringProperty signatureAlgorithmProperty = new SimpleStringProperty("");
private final StringProperty versionProperty = new SimpleStringProperty("");
private final StringProperty thumbprintProperty = new SimpleStringProperty("");
private final StringProperty pathProperty = new SimpleStringProperty("");
public CustomCertificateViewModel(String thumbprint, String serialNumber, String issuer, LocalDate validFrom, LocalDate validTo, String sigAlgorithm, String version) {
serialNumberProperty.setValue(serialNumber);
issuerProperty.setValue(issuer);
validFromProperty.setValue(validFrom);
validToProperty.setValue(validTo);
signatureAlgorithmProperty.setValue(sigAlgorithm);
versionProperty.setValue(version);
thumbprintProperty.setValue(thumbprint);
}
public ReadOnlyStringProperty serialNumberProperty() {
return serialNumberProperty;
}
public ReadOnlyStringProperty issuerProperty() {
return issuerProperty;
}
public ReadOnlyObjectProperty<LocalDate> validFromProperty() {
return validFromProperty;
}
public ReadOnlyObjectProperty<LocalDate> validToProperty() {
return validToProperty;
}
public ReadOnlyStringProperty signatureAlgorithmProperty() {
return signatureAlgorithmProperty;
}
public ReadOnlyStringProperty versionProperty() {
return versionProperty;
}
public String getVersion() {
return versionProperty.getValue();
}
public String getThumbprint() {
return thumbprintProperty.getValue();
}
public LocalDate getValidFrom() {
return validFromProperty.getValue();
}
public LocalDate getValidTo() {
return validToProperty.getValue();
}
public StringProperty pathPropertyProperty() {
return pathProperty;
}
public Optional<String> getPath() {
if (pathProperty.getValue() == null || pathProperty.getValue().isEmpty()) {
return Optional.empty();
} else {
return Optional.of(pathProperty.getValue());
}
}
public CustomCertificateViewModel setPath(String path) {
pathProperty.setValue(path);
return this;
}
public String getSerialNumber() {
return serialNumberProperty.getValue();
}
public String getIssuer() {
return issuerProperty.getValue();
}
public String getSignatureAlgorithm() {
return signatureAlgorithmProperty.getValue();
}
public static CustomCertificateViewModel fromSSLCertificate(SSLCertificate sslCertificate) {
return new CustomCertificateViewModel(
sslCertificate.getSHA256Thumbprint(),
sslCertificate.getSerialNumber(),
sslCertificate.getIssuer(),
sslCertificate.getValidFrom(),
sslCertificate.getValidTo(),
sslCertificate.getSignatureAlgorithm(),
sslCertificate.getVersion().toString());
}
}
| 3,971
| 33.241379
| 171
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/network/NetworkTab.java
|
package org.jabref.gui.preferences.network;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import javafx.application.Platform;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.property.SimpleStringProperty;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import org.jabref.gui.Globals;
import org.jabref.gui.actions.ActionFactory;
import org.jabref.gui.actions.StandardActions;
import org.jabref.gui.help.HelpAction;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.preferences.AbstractPreferenceTabView;
import org.jabref.gui.preferences.PreferencesTab;
import org.jabref.gui.util.IconValidationDecorator;
import org.jabref.gui.util.ValueTableCellFactory;
import org.jabref.logic.help.HelpFile;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.util.FileUpdateMonitor;
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.textfield.CustomPasswordField;
public class NetworkTab extends AbstractPreferenceTabView<NetworkTabViewModel> implements PreferencesTab {
@FXML private Label remoteLabel;
@FXML private CheckBox remoteServer;
@FXML private TextField remotePort;
@FXML private Button remoteHelp;
@FXML private CheckBox proxyUse;
@FXML private Label proxyHostnameLabel;
@FXML private TextField proxyHostname;
@FXML private Label proxyPortLabel;
@FXML private TextField proxyPort;
@FXML private CheckBox proxyUseAuthentication;
@FXML private Label proxyUsernameLabel;
@FXML private TextField proxyUsername;
@FXML private Label proxyPasswordLabel;
@FXML private CustomPasswordField proxyPassword;
@FXML private Button checkConnectionButton;
@FXML private CheckBox proxyPersistPassword;
@FXML private TableView<CustomCertificateViewModel> customCertificatesTable;
@FXML private TableColumn<CustomCertificateViewModel, String> certIssuer;
@FXML private TableColumn<CustomCertificateViewModel, String> certSerialNumber;
@FXML private TableColumn<CustomCertificateViewModel, String> certSignatureAlgorithm;
@FXML private TableColumn<CustomCertificateViewModel, String> certValidFrom;
@FXML private TableColumn<CustomCertificateViewModel, String> certValidTo;
@FXML private TableColumn<CustomCertificateViewModel, String> certVersion;
@FXML private TableColumn<CustomCertificateViewModel, String> actionsColumn;
@Inject private FileUpdateMonitor fileUpdateMonitor;
private String proxyPasswordText = "";
private int proxyPasswordCaretPosition = 0;
private final ControlsFxVisualizer validationVisualizer = new ControlsFxVisualizer();
public NetworkTab() {
ViewLoader.view(this)
.root(this)
.load();
}
@Override
public String getTabName() {
return Localization.lang("Network");
}
public void initialize() {
this.viewModel = new NetworkTabViewModel(dialogService, preferencesService, fileUpdateMonitor);
remoteLabel.setVisible(preferencesService.getWorkspacePreferences().shouldShowAdvancedHints());
remoteServer.selectedProperty().bindBidirectional(viewModel.remoteServerProperty());
remotePort.textProperty().bindBidirectional(viewModel.remotePortProperty());
remotePort.disableProperty().bind(remoteServer.selectedProperty().not());
proxyUse.selectedProperty().bindBidirectional(viewModel.proxyUseProperty());
proxyHostnameLabel.disableProperty().bind(proxyUse.selectedProperty().not());
proxyHostname.textProperty().bindBidirectional(viewModel.proxyHostnameProperty());
proxyHostname.disableProperty().bind(proxyUse.selectedProperty().not());
proxyPortLabel.disableProperty().bind(proxyUse.selectedProperty().not());
proxyPort.textProperty().bindBidirectional(viewModel.proxyPortProperty());
proxyPort.disableProperty().bind(proxyUse.selectedProperty().not());
proxyUseAuthentication.selectedProperty().bindBidirectional(viewModel.proxyUseAuthenticationProperty());
proxyUseAuthentication.disableProperty().bind(proxyUse.selectedProperty().not());
BooleanBinding proxyCustomAndAuthentication = proxyUse.selectedProperty().and(proxyUseAuthentication.selectedProperty());
proxyUsernameLabel.disableProperty().bind(proxyCustomAndAuthentication.not());
proxyUsername.textProperty().bindBidirectional(viewModel.proxyUsernameProperty());
proxyUsername.disableProperty().bind(proxyCustomAndAuthentication.not());
proxyPasswordLabel.disableProperty().bind(proxyCustomAndAuthentication.not());
proxyPassword.textProperty().bindBidirectional(viewModel.proxyPasswordProperty());
proxyPassword.disableProperty().bind(proxyCustomAndAuthentication.not());
proxyPersistPassword.selectedProperty().bindBidirectional(viewModel.proxyPersistPasswordProperty());
proxyPersistPassword.disableProperty().bind(proxyCustomAndAuthentication.not());
proxyPassword.setRight(IconTheme.JabRefIcons.PASSWORD_REVEALED.getGraphicNode());
proxyPassword.getRight().addEventFilter(MouseEvent.MOUSE_PRESSED, this::proxyPasswordReveal);
proxyPassword.getRight().addEventFilter(MouseEvent.MOUSE_RELEASED, this::proxyPasswordMask);
proxyPassword.getRight().addEventFilter(MouseEvent.MOUSE_EXITED, this::proxyPasswordMask);
ActionFactory actionFactory = new ActionFactory(Globals.getKeyPrefs());
actionFactory.configureIconButton(StandardActions.HELP, new HelpAction(HelpFile.REMOTE, dialogService), remoteHelp);
validationVisualizer.setDecoration(new IconValidationDecorator());
Platform.runLater(() -> {
validationVisualizer.initVisualization(viewModel.remotePortValidationStatus(), remotePort);
validationVisualizer.initVisualization(viewModel.proxyHostnameValidationStatus(), proxyHostname);
validationVisualizer.initVisualization(viewModel.proxyPortValidationStatus(), proxyPort);
validationVisualizer.initVisualization(viewModel.proxyUsernameValidationStatus(), proxyUsername);
validationVisualizer.initVisualization(viewModel.proxyPasswordValidationStatus(), proxyPassword);
});
certSerialNumber.setCellValueFactory(data -> data.getValue().serialNumberProperty());
certIssuer.setCellValueFactory(data -> data.getValue().issuerProperty());
certSignatureAlgorithm.setCellValueFactory(data -> data.getValue().signatureAlgorithmProperty());
certVersion.setCellValueFactory(data -> EasyBind.map(data.getValue().versionProperty(), this::formatVersion));
certValidFrom.setCellValueFactory(data -> EasyBind.map(data.getValue().validFromProperty(), this::formatDate));
certValidTo.setCellValueFactory(data -> EasyBind.map(data.getValue().validToProperty(), this::formatDate));
customCertificatesTable.itemsProperty().set(viewModel.customCertificateListProperty());
actionsColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getThumbprint()));
new ValueTableCellFactory<CustomCertificateViewModel, String>()
.withGraphic(name -> IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode())
.withTooltip(name -> Localization.lang("Remove formatter '%0'", name))
.withOnMouseClickedEvent(thumbprint -> evt -> viewModel.customCertificateListProperty().removeIf(cert -> cert.getThumbprint().equals(thumbprint)))
.install(actionsColumn);
}
private String formatDate(LocalDate localDate) {
return localDate.format(DateTimeFormatter.ofPattern("dd-MMM-yyyy"));
}
private String formatVersion(String version) {
return String.format("V%s", version);
}
private void proxyPasswordReveal(MouseEvent event) {
proxyPasswordText = proxyPassword.getText();
proxyPasswordCaretPosition = proxyPassword.getCaretPosition();
proxyPassword.clear();
proxyPassword.setPromptText(proxyPasswordText);
}
private void proxyPasswordMask(MouseEvent event) {
if (!"".equals(proxyPasswordText)) {
proxyPassword.setText(proxyPasswordText);
proxyPassword.positionCaret(proxyPasswordCaretPosition);
proxyPassword.setPromptText("");
proxyPasswordText = "";
proxyPasswordCaretPosition = 0;
}
}
@FXML
void checkConnection() {
viewModel.checkConnection();
}
@FXML
void addCertificateFile() {
viewModel.addCertificateFile();
}
}
| 9,021
| 48.845304
| 162
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/network/NetworkTabViewModel.java
|
package org.jabref.gui.preferences.network;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.stage.FileChooser;
import org.jabref.gui.DialogService;
import org.jabref.gui.Globals;
import org.jabref.gui.preferences.PreferenceTabViewModel;
import org.jabref.gui.remote.CLIMessageHandler;
import org.jabref.gui.util.FileDialogConfiguration;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.net.ProxyPreferences;
import org.jabref.logic.net.ProxyRegisterer;
import org.jabref.logic.net.URLDownload;
import org.jabref.logic.net.ssl.SSLCertificate;
import org.jabref.logic.net.ssl.SSLPreferences;
import org.jabref.logic.net.ssl.TrustStoreManager;
import org.jabref.logic.remote.RemotePreferences;
import org.jabref.logic.remote.RemoteUtil;
import org.jabref.logic.util.StandardFileType;
import org.jabref.model.strings.StringUtil;
import org.jabref.model.util.FileUpdateMonitor;
import org.jabref.preferences.PreferencesService;
import de.saxsys.mvvmfx.utils.validation.CompositeValidator;
import de.saxsys.mvvmfx.utils.validation.FunctionBasedValidator;
import de.saxsys.mvvmfx.utils.validation.ValidationMessage;
import de.saxsys.mvvmfx.utils.validation.ValidationStatus;
import de.saxsys.mvvmfx.utils.validation.Validator;
import kong.unirest.UnirestException;
public class NetworkTabViewModel implements PreferenceTabViewModel {
private final BooleanProperty remoteServerProperty = new SimpleBooleanProperty();
private final StringProperty remotePortProperty = new SimpleStringProperty("");
private final BooleanProperty proxyUseProperty = new SimpleBooleanProperty();
private final StringProperty proxyHostnameProperty = new SimpleStringProperty("");
private final StringProperty proxyPortProperty = new SimpleStringProperty("");
private final BooleanProperty proxyUseAuthenticationProperty = new SimpleBooleanProperty();
private final StringProperty proxyUsernameProperty = new SimpleStringProperty("");
private final StringProperty proxyPasswordProperty = new SimpleStringProperty("");
private final BooleanProperty proxyPersistPasswordProperty = new SimpleBooleanProperty();
private final ListProperty<CustomCertificateViewModel> customCertificateListProperty = new SimpleListProperty<>(FXCollections.observableArrayList());
private final Validator remotePortValidator;
private final Validator proxyHostnameValidator;
private final Validator proxyPortValidator;
private final Validator proxyUsernameValidator;
private final Validator proxyPasswordValidator;
private final DialogService dialogService;
private final PreferencesService preferences;
private final FileUpdateMonitor fileUpdateMonitor;
private final RemotePreferences remotePreferences;
private final ProxyPreferences proxyPreferences;
private final ProxyPreferences backupProxyPreferences;
private final SSLPreferences sslPreferences;
private final TrustStoreManager trustStoreManager;
private final AtomicBoolean sslCertificatesChanged = new AtomicBoolean(false);
public NetworkTabViewModel(DialogService dialogService, PreferencesService preferences, FileUpdateMonitor fileUpdateMonitor) {
this.dialogService = dialogService;
this.preferences = preferences;
this.fileUpdateMonitor = fileUpdateMonitor;
this.remotePreferences = preferences.getRemotePreferences();
this.proxyPreferences = preferences.getProxyPreferences();
this.sslPreferences = preferences.getSSLPreferences();
backupProxyPreferences = new ProxyPreferences(
proxyPreferences.shouldUseProxy(),
proxyPreferences.getHostname(),
proxyPreferences.getPort(),
proxyPreferences.shouldUseAuthentication(),
proxyPreferences.getUsername(),
proxyPreferences.getPassword(),
proxyPreferences.shouldPersistPassword());
remotePortValidator = new FunctionBasedValidator<>(
remotePortProperty,
input -> {
try {
int portNumber = Integer.parseInt(remotePortProperty().getValue());
return RemoteUtil.isUserPort(portNumber);
} catch (NumberFormatException ex) {
return false;
}
},
ValidationMessage.error(String.format("%s > %s %n %n %s",
Localization.lang("Network"),
Localization.lang("Remote operation"),
Localization.lang("You must enter an integer value in the interval 1025-65535"))));
proxyHostnameValidator = new FunctionBasedValidator<>(
proxyHostnameProperty,
input -> !StringUtil.isNullOrEmpty(input),
ValidationMessage.error(String.format("%s > %s %n %n %s",
Localization.lang("Network"),
Localization.lang("Proxy configuration"),
Localization.lang("Please specify a hostname"))));
proxyPortValidator = new FunctionBasedValidator<>(
proxyPortProperty,
input -> getPortAsInt(input).isPresent(),
ValidationMessage.error(String.format("%s > %s %n %n %s",
Localization.lang("Network"),
Localization.lang("Proxy configuration"),
Localization.lang("Please specify a port"))));
proxyUsernameValidator = new FunctionBasedValidator<>(
proxyUsernameProperty,
input -> !StringUtil.isNullOrEmpty(input),
ValidationMessage.error(String.format("%s > %s %n %n %s",
Localization.lang("Network"),
Localization.lang("Proxy configuration"),
Localization.lang("Please specify a username"))));
proxyPasswordValidator = new FunctionBasedValidator<>(
proxyPasswordProperty,
input -> input.length() > 0,
ValidationMessage.error(String.format("%s > %s %n %n %s",
Localization.lang("Network"),
Localization.lang("Proxy configuration"),
Localization.lang("Please specify a password"))));
this.trustStoreManager = new TrustStoreManager(Path.of(sslPreferences.getTruststorePath()));
}
@Override
public void setValues() {
remoteServerProperty.setValue(remotePreferences.useRemoteServer());
remotePortProperty.setValue(String.valueOf(remotePreferences.getPort()));
setProxyValues();
setSSLValues();
}
private void setProxyValues() {
proxyUseProperty.setValue(proxyPreferences.shouldUseProxy());
proxyHostnameProperty.setValue(proxyPreferences.getHostname());
proxyPortProperty.setValue(proxyPreferences.getPort());
proxyUseAuthenticationProperty.setValue(proxyPreferences.shouldUseAuthentication());
proxyUsernameProperty.setValue(proxyPreferences.getUsername());
proxyPasswordProperty.setValue(proxyPreferences.getPassword());
proxyPersistPasswordProperty.setValue(proxyPreferences.shouldPersistPassword());
}
private void setSSLValues() {
customCertificateListProperty.clear();
trustStoreManager.getCustomCertificates().forEach(cert -> customCertificateListProperty.add(CustomCertificateViewModel.fromSSLCertificate(cert)));
customCertificateListProperty.addListener((ListChangeListener<CustomCertificateViewModel>) c -> {
sslCertificatesChanged.set(true);
while (c.next()) {
if (c.wasAdded()) {
CustomCertificateViewModel certificate = c.getAddedSubList().get(0);
certificate.getPath().ifPresent(path -> trustStoreManager
.addCertificate(formatCustomAlias(certificate.getThumbprint()), Path.of(path)));
} else if (c.wasRemoved()) {
CustomCertificateViewModel certificate = c.getRemoved().get(0);
trustStoreManager.deleteCertificate(formatCustomAlias(certificate.getThumbprint()));
}
}
});
}
@Override
public void storeSettings() {
getPortAsInt(remotePortProperty.getValue()).ifPresent(newPort -> {
if (remotePreferences.isDifferentPort(newPort)) {
remotePreferences.setPort(newPort);
}
});
if (remoteServerProperty.getValue()) {
remotePreferences.setUseRemoteServer(true);
Globals.REMOTE_LISTENER.openAndStart(new CLIMessageHandler(preferences, fileUpdateMonitor), remotePreferences.getPort());
} else {
remotePreferences.setUseRemoteServer(false);
Globals.REMOTE_LISTENER.stop();
}
proxyPreferences.setUseProxy(proxyUseProperty.getValue());
proxyPreferences.setHostname(proxyHostnameProperty.getValue().trim());
proxyPreferences.setPort(proxyPortProperty.getValue().trim());
proxyPreferences.setUseAuthentication(proxyUseAuthenticationProperty.getValue());
proxyPreferences.setUsername(proxyUsernameProperty.getValue().trim());
proxyPreferences.setPersistPassword(proxyPersistPasswordProperty.getValue()); // Set before the password to actually persist
proxyPreferences.setPassword(proxyPasswordProperty.getValue());
ProxyRegisterer.register(proxyPreferences);
trustStoreManager.flush();
}
private Optional<Integer> getPortAsInt(String value) {
try {
return Optional.of(Integer.parseInt(value));
} catch (NumberFormatException ex) {
return Optional.empty();
}
}
public ValidationStatus remotePortValidationStatus() {
return remotePortValidator.getValidationStatus();
}
public ValidationStatus proxyHostnameValidationStatus() {
return proxyHostnameValidator.getValidationStatus();
}
public ValidationStatus proxyPortValidationStatus() {
return proxyPortValidator.getValidationStatus();
}
public ValidationStatus proxyUsernameValidationStatus() {
return proxyUsernameValidator.getValidationStatus();
}
public ValidationStatus proxyPasswordValidationStatus() {
return proxyPasswordValidator.getValidationStatus();
}
@Override
public boolean validateSettings() {
CompositeValidator validator = new CompositeValidator();
if (remoteServerProperty.getValue()) {
validator.addValidators(remotePortValidator);
}
if (proxyUseProperty.getValue()) {
validator.addValidators(proxyHostnameValidator);
validator.addValidators(proxyPortValidator);
if (proxyUseAuthenticationProperty.getValue()) {
validator.addValidators(proxyUsernameValidator);
validator.addValidators(proxyPasswordValidator);
}
}
ValidationStatus validationStatus = validator.getValidationStatus();
if (!validationStatus.isValid()) {
validationStatus.getHighestMessage().ifPresent(message ->
dialogService.showErrorDialogAndWait(message.getMessage()));
return false;
}
return true;
}
/**
* Check the connection by using the given url. Used for validating the http proxy. The checking result will be appear when request finished. The checking result could be either success or fail, if fail, the cause will be displayed.
*/
public void checkConnection() {
final String connectionSuccessText = Localization.lang("Connection successful!");
final String connectionFailedText = Localization.lang("Connection failed!");
final String dialogTitle = Localization.lang("Check Proxy Setting");
final String testUrl = "http://jabref.org";
ProxyRegisterer.register(new ProxyPreferences(
proxyUseProperty.getValue(),
proxyHostnameProperty.getValue().trim(),
proxyPortProperty.getValue().trim(),
proxyUseAuthenticationProperty.getValue(),
proxyUsernameProperty.getValue().trim(),
proxyPasswordProperty.getValue(),
proxyPersistPasswordProperty.getValue()
));
URLDownload urlDownload;
try {
urlDownload = new URLDownload(testUrl);
if (urlDownload.canBeReached()) {
dialogService.showInformationDialogAndWait(dialogTitle, connectionSuccessText);
} else {
dialogService.showErrorDialogAndWait(dialogTitle, connectionFailedText);
}
} catch (MalformedURLException e) {
// Why would that happen? Because one of developers inserted a failing url in testUrl...
} catch (UnirestException e) {
dialogService.showErrorDialogAndWait(dialogTitle, connectionFailedText);
}
ProxyRegisterer.register(backupProxyPreferences);
}
@Override
public List<String> getRestartWarnings() {
if (sslCertificatesChanged.get()) {
return List.of(Localization.lang("SSL configuration changed"));
} else {
return Collections.emptyList();
}
}
public BooleanProperty remoteServerProperty() {
return remoteServerProperty;
}
public StringProperty remotePortProperty() {
return remotePortProperty;
}
public BooleanProperty proxyUseProperty() {
return proxyUseProperty;
}
public StringProperty proxyHostnameProperty() {
return proxyHostnameProperty;
}
public StringProperty proxyPortProperty() {
return proxyPortProperty;
}
public BooleanProperty proxyUseAuthenticationProperty() {
return proxyUseAuthenticationProperty;
}
public StringProperty proxyUsernameProperty() {
return proxyUsernameProperty;
}
public StringProperty proxyPasswordProperty() {
return proxyPasswordProperty;
}
public BooleanProperty proxyPersistPasswordProperty() {
return proxyPersistPasswordProperty;
}
public ListProperty<CustomCertificateViewModel> customCertificateListProperty() {
return customCertificateListProperty;
}
public void addCertificateFile() {
FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
.addExtensionFilter(new FileChooser.ExtensionFilter(Localization.lang("SSL certificate file"), "*.crt", "*.cer"))
.withDefaultExtension(Localization.lang("SSL certificate file"), StandardFileType.CER)
.withInitialDirectory(preferences.getFilePreferences().getWorkingDirectory())
.build();
dialogService.showFileOpenDialog(fileDialogConfiguration).ifPresent(certPath -> SSLCertificate.fromPath(certPath).ifPresent(sslCertificate -> {
if (!trustStoreManager.certificateExists(formatCustomAlias(sslCertificate.getSHA256Thumbprint()))) {
customCertificateListProperty.add(CustomCertificateViewModel.fromSSLCertificate(sslCertificate)
.setPath(certPath.toAbsolutePath().toString()));
} else {
dialogService.showWarningDialogAndWait(Localization.lang("Duplicate Certificates"), Localization.lang("You already added this certificate"));
}
}));
}
private String formatCustomAlias(String thumbprint) {
return String.format("%s[custom]", thumbprint);
}
}
| 16,357
| 43.091644
| 236
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/preview/PreviewTab.java
|
package org.jabref.gui.preferences.preview;
import java.util.ArrayList;
import java.util.List;
import javafx.application.Platform;
import javafx.beans.property.ListProperty;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.Tab;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;
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.preferences.AbstractPreferenceTabView;
import org.jabref.gui.preferences.PreferencesTab;
import org.jabref.gui.preview.PreviewViewer;
import org.jabref.gui.theme.ThemeManager;
import org.jabref.gui.util.BindingsHelper;
import org.jabref.gui.util.IconValidationDecorator;
import org.jabref.gui.util.ViewModelListCellFactory;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.preview.PreviewLayout;
import org.jabref.logic.util.TestEntry;
import org.jabref.model.database.BibDatabaseContext;
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.textfield.CustomTextField;
import org.fxmisc.richtext.CodeArea;
import org.fxmisc.richtext.LineNumberFactory;
public class PreviewTab extends AbstractPreferenceTabView<PreviewTabViewModel> implements PreferencesTab {
@FXML private CheckBox showAsTabCheckBox;
@FXML private ListView<PreviewLayout> availableListView;
@FXML private ListView<PreviewLayout> chosenListView;
@FXML private Button toRightButton;
@FXML private Button toLeftButton;
@FXML private Button sortUpButton;
@FXML private Button sortDownButton;
@FXML private Label readOnlyLabel;
@FXML private Button resetDefaultButton;
@FXML private Tab previewTab;
@FXML private CodeArea editArea;
@FXML private CustomTextField searchBox;
@Inject private StateManager stateManager;
@Inject private ThemeManager themeManager;
private final ContextMenu contextMenu = new ContextMenu();
private long lastKeyPressTime;
private String listSearchTerm;
private final ControlsFxVisualizer validationVisualizer = new ControlsFxVisualizer();
public PreviewTab() {
ViewLoader.view(this)
.root(this)
.load();
}
private class EditAction extends SimpleCommand {
private final StandardActions command;
public EditAction(StandardActions command) {
this.command = command;
}
@Override
public void execute() {
if (editArea != null) {
switch (command) {
case COPY -> editArea.copy();
case CUT -> editArea.cut();
case PASTE -> editArea.paste();
case SELECT_ALL -> editArea.selectAll();
}
editArea.requestFocus();
}
}
}
@Override
public String getTabName() {
return Localization.lang("Entry preview");
}
public void initialize() {
this.viewModel = new PreviewTabViewModel(dialogService, preferencesService.getPreviewPreferences(), taskExecutor, stateManager);
lastKeyPressTime = System.currentTimeMillis();
showAsTabCheckBox.selectedProperty().bindBidirectional(viewModel.showAsExtraTabProperty());
searchBox.setPromptText(Localization.lang("Search") + "...");
searchBox.setLeft(IconTheme.JabRefIcons.SEARCH.getGraphicNode());
ActionFactory factory = new ActionFactory(Globals.getKeyPrefs());
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.getItems().forEach(item -> item.setGraphic(null));
contextMenu.getStyleClass().add("context-menu");
availableListView.setItems(viewModel.getFilteredAvailableLayouts());
viewModel.availableSelectionModelProperty().setValue(availableListView.getSelectionModel());
new ViewModelListCellFactory<PreviewLayout>()
.withText(PreviewLayout::getDisplayName)
.install(availableListView);
availableListView.setOnDragOver(this::dragOver);
availableListView.setOnDragDetected(this::dragDetectedInAvailable);
availableListView.setOnDragDropped(event -> dragDropped(viewModel.availableListProperty(), event));
availableListView.setOnKeyTyped(event -> jumpToSearchKey(availableListView, event));
availableListView.setOnMouseClicked(this::mouseClickedAvailable);
availableListView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
availableListView.selectionModelProperty().getValue().selectedItemProperty().addListener((observable, oldValue, newValue) ->
viewModel.setPreviewLayout(newValue));
chosenListView.itemsProperty().bindBidirectional(viewModel.chosenListProperty());
viewModel.chosenSelectionModelProperty().setValue(chosenListView.getSelectionModel());
new ViewModelListCellFactory<PreviewLayout>()
.withText(PreviewLayout::getDisplayName)
.setOnDragDropped(this::dragDroppedInChosenCell)
.install(chosenListView);
chosenListView.setOnDragOver(this::dragOver);
chosenListView.setOnDragDetected(this::dragDetectedInChosen);
chosenListView.setOnDragDropped(event -> dragDropped(viewModel.chosenListProperty(), event));
chosenListView.setOnKeyTyped(event -> jumpToSearchKey(chosenListView, event));
chosenListView.setOnMouseClicked(this::mouseClickedChosen);
chosenListView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
chosenListView.selectionModelProperty().getValue().selectedItemProperty().addListener((observable, oldValue, newValue) ->
viewModel.setPreviewLayout(newValue));
toRightButton.disableProperty().bind(viewModel.availableSelectionModelProperty().getValue().selectedItemProperty().isNull());
toLeftButton.disableProperty().bind(viewModel.chosenSelectionModelProperty().getValue().selectedItemProperty().isNull());
sortUpButton.disableProperty().bind(viewModel.chosenSelectionModelProperty().getValue().selectedItemProperty().isNull());
sortDownButton.disableProperty().bind(viewModel.chosenSelectionModelProperty().getValue().selectedItemProperty().isNull());
PreviewViewer previewViewer = new PreviewViewer(new BibDatabaseContext(), dialogService, stateManager, themeManager);
previewViewer.setEntry(TestEntry.getTestEntry());
EasyBind.subscribe(viewModel.selectedLayoutProperty(), previewViewer::setLayout);
previewViewer.visibleProperty().bind(viewModel.chosenSelectionModelProperty().getValue().selectedItemProperty().isNotNull()
.or(viewModel.availableSelectionModelProperty().getValue().selectedItemProperty().isNotNull()));
previewTab.setContent(previewViewer);
editArea.clear();
editArea.setParagraphGraphicFactory(LineNumberFactory.get(editArea));
editArea.setContextMenu(contextMenu);
editArea.visibleProperty().bind(viewModel.chosenSelectionModelProperty().getValue().selectedItemProperty().isNotNull()
.or(viewModel.availableSelectionModelProperty().getValue().selectedItemProperty().isNotNull()));
BindingsHelper.bindBidirectional(
editArea.textProperty(),
viewModel.sourceTextProperty(),
newSourceText -> editArea.replaceText(newSourceText),
newEditText -> {
viewModel.sourceTextProperty().setValue(newEditText);
viewModel.refreshPreview();
});
editArea.textProperty().addListener((obs, oldValue, newValue) ->
editArea.setStyleSpans(0, viewModel.computeHighlighting(newValue)));
editArea.focusedProperty().addListener((observable, oldValue, newValue) -> {
if (!newValue) {
viewModel.refreshPreview();
}
});
searchBox.textProperty().addListener((observable, previousText, searchTerm) -> viewModel.setAvailableFilter(searchTerm));
readOnlyLabel.visibleProperty().bind(viewModel.selectedIsEditableProperty().not());
resetDefaultButton.disableProperty().bind(viewModel.selectedIsEditableProperty().not());
contextMenu.getItems().get(0).disableProperty().bind(viewModel.selectedIsEditableProperty().not());
contextMenu.getItems().get(2).disableProperty().bind(viewModel.selectedIsEditableProperty().not());
editArea.editableProperty().bind(viewModel.selectedIsEditableProperty());
validationVisualizer.setDecoration(new IconValidationDecorator());
Platform.runLater(() -> validationVisualizer.initVisualization(viewModel.chosenListValidationStatus(), chosenListView));
}
/**
* This is called, if a user starts typing some characters into the keyboard with focus on one ListView. The
* ListView will scroll to the next cell with the name of the PreviewLayout fitting those characters.
*
* @param list The ListView currently focused
* @param keypressed The pressed character
*/
private void jumpToSearchKey(ListView<PreviewLayout> list, KeyEvent keypressed) {
if (keypressed.getCharacter() == null) {
return;
}
if ((System.currentTimeMillis() - lastKeyPressTime) < 1000) {
listSearchTerm += keypressed.getCharacter().toLowerCase();
} else {
listSearchTerm = keypressed.getCharacter().toLowerCase();
}
lastKeyPressTime = System.currentTimeMillis();
list.getItems().stream().filter(item -> item.getDisplayName().toLowerCase().startsWith(listSearchTerm))
.findFirst().ifPresent(list::scrollTo);
}
private void dragOver(DragEvent event) {
viewModel.dragOver(event);
}
private void dragDetectedInAvailable(MouseEvent event) {
List<PreviewLayout> selectedLayouts = new ArrayList<>(viewModel.availableSelectionModelProperty().getValue().getSelectedItems());
if (!selectedLayouts.isEmpty()) {
Dragboard dragboard = startDragAndDrop(TransferMode.MOVE);
viewModel.dragDetected(viewModel.availableListProperty(), viewModel.availableSelectionModelProperty(), selectedLayouts, dragboard);
}
event.consume();
}
private void dragDetectedInChosen(MouseEvent event) {
List<PreviewLayout> selectedLayouts = new ArrayList<>(viewModel.chosenSelectionModelProperty().getValue().getSelectedItems());
if (!selectedLayouts.isEmpty()) {
Dragboard dragboard = startDragAndDrop(TransferMode.MOVE);
viewModel.dragDetected(viewModel.chosenListProperty(), viewModel.chosenSelectionModelProperty(), selectedLayouts, dragboard);
}
event.consume();
}
private void dragDropped(ListProperty<PreviewLayout> targetList, DragEvent event) {
boolean success = viewModel.dragDropped(targetList, event.getDragboard());
event.setDropCompleted(success);
event.consume();
}
private void dragDroppedInChosenCell(PreviewLayout targetLayout, DragEvent event) {
boolean success = viewModel.dragDroppedInChosenCell(targetLayout, event.getDragboard());
event.setDropCompleted(success);
event.consume();
}
public void toRightButtonAction() {
viewModel.addToChosen();
}
public void toLeftButtonAction() {
viewModel.removeFromChosen();
}
public void sortUpButtonAction() {
viewModel.selectedInChosenUp();
}
public void sortDownButtonAction() {
viewModel.selectedInChosenDown();
}
public void resetDefaultButtonAction() {
viewModel.resetDefaultLayout();
}
private void mouseClickedAvailable(MouseEvent event) {
if (event.getClickCount() == 2) {
viewModel.addToChosen();
event.consume();
}
}
private void mouseClickedChosen(MouseEvent event) {
if (event.getClickCount() == 2) {
viewModel.removeFromChosen();
event.consume();
}
}
}
| 13,236
| 43.871186
| 150
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/preview/PreviewTabViewModel.java
|
package org.jabref.gui.preferences.preview;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ListProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.transformation.FilteredList;
import javafx.scene.control.MultipleSelectionModel;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;
import org.jabref.gui.DialogService;
import org.jabref.gui.DragAndDropDataFormats;
import org.jabref.gui.Globals;
import org.jabref.gui.StateManager;
import org.jabref.gui.preferences.PreferenceTabViewModel;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.gui.util.CustomLocalDragboard;
import org.jabref.gui.util.NoSelectionModel;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.citationstyle.CitationStyle;
import org.jabref.logic.citationstyle.CitationStylePreviewLayout;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.layout.TextBasedPreviewLayout;
import org.jabref.logic.preview.PreviewLayout;
import org.jabref.preferences.PreviewPreferences;
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.fxmisc.richtext.model.StyleSpans;
import org.fxmisc.richtext.model.StyleSpansBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class is Preferences -> Entry Preview tab model
* <p>
* {@link PreviewTab} is the controller of Entry Preview tab
* </p>
*
* @see PreviewTab
* */
public class PreviewTabViewModel implements PreferenceTabViewModel {
private static final Logger LOGGER = LoggerFactory.getLogger(PreviewTabViewModel.class);
private final BooleanProperty showAsExtraTabProperty = new SimpleBooleanProperty(false);
private final ListProperty<PreviewLayout> availableListProperty = new SimpleListProperty<>(FXCollections.observableArrayList());
private final ObjectProperty<MultipleSelectionModel<PreviewLayout>> availableSelectionModelProperty = new SimpleObjectProperty<>(new NoSelectionModel<>());
private final FilteredList<PreviewLayout> filteredAvailableLayouts = new FilteredList<>(this.availableListProperty());
private final ListProperty<PreviewLayout> chosenListProperty = new SimpleListProperty<>(FXCollections.observableArrayList());
private final ObjectProperty<MultipleSelectionModel<PreviewLayout>> chosenSelectionModelProperty = new SimpleObjectProperty<>(new NoSelectionModel<>());
private final BooleanProperty selectedIsEditableProperty = new SimpleBooleanProperty(false);
private final ObjectProperty<PreviewLayout> selectedLayoutProperty = new SimpleObjectProperty<>();
private final StringProperty sourceTextProperty = new SimpleStringProperty("");
private final DialogService dialogService;
private final PreviewPreferences previewPreferences;
private final TaskExecutor taskExecutor;
private final Validator chosenListValidator;
private final CustomLocalDragboard localDragboard;
private ListProperty<PreviewLayout> dragSourceList = null;
private ObjectProperty<MultipleSelectionModel<PreviewLayout>> dragSourceSelectionModel = null;
public PreviewTabViewModel(DialogService dialogService,
PreviewPreferences previewPreferences,
TaskExecutor taskExecutor,
StateManager stateManager) {
this.dialogService = dialogService;
this.taskExecutor = taskExecutor;
this.localDragboard = stateManager.getLocalDragboard();
this.previewPreferences = previewPreferences;
sourceTextProperty.addListener((observable, oldValue, newValue) -> {
if (selectedLayoutProperty.getValue() instanceof TextBasedPreviewLayout layout) {
layout.setText(sourceTextProperty.getValue());
}
});
chosenListValidator = new FunctionBasedValidator<>(
chosenListProperty,
input -> !chosenListProperty.getValue().isEmpty(),
ValidationMessage.error(String.format("%s > %s %n %n %s",
Localization.lang("Entry preview"),
Localization.lang("Selected"),
Localization.lang("Selected Layouts can not be empty")
)
)
);
}
@Override
public void setValues() {
showAsExtraTabProperty.set(previewPreferences.shouldShowPreviewAsExtraTab());
chosenListProperty().getValue().clear();
chosenListProperty.getValue().addAll(previewPreferences.getLayoutCycle());
availableListProperty.clear();
if (chosenListProperty.stream().noneMatch(TextBasedPreviewLayout.class::isInstance)) {
availableListProperty.getValue().add(previewPreferences.getCustomPreviewLayout());
}
BackgroundTask.wrap(CitationStyle::discoverCitationStyles)
.onSuccess(styles -> styles.stream()
.map(style -> new CitationStylePreviewLayout(style, Globals.entryTypesManager))
.filter(style -> chosenListProperty.getValue().filtered(item ->
item.getName().equals(style.getName())).isEmpty())
.sorted(Comparator.comparing(PreviewLayout::getName))
.forEach(availableListProperty::add))
.onFailure(ex -> {
LOGGER.error("Something went wrong while adding the discovered CitationStyles to the list.", ex);
dialogService.showErrorDialogAndWait(Localization.lang("Error adding discovered CitationStyles"), ex);
})
.executeWith(taskExecutor);
}
public void setPreviewLayout(PreviewLayout selectedLayout) {
if (selectedLayout == null) {
selectedIsEditableProperty.setValue(false);
selectedLayoutProperty.setValue(null);
return;
}
try {
selectedLayoutProperty.setValue(selectedLayout);
} catch (StringIndexOutOfBoundsException exception) {
LOGGER.warn("Parsing error.", exception);
dialogService.showErrorDialogAndWait(
Localization.lang("Parsing error"),
Localization.lang("Parsing error") + ": " + Localization.lang("illegal backslash expression"), exception);
}
if (selectedLayout instanceof TextBasedPreviewLayout layout) {
sourceTextProperty.setValue(layout.getText().replace("__NEWLINE__", "\n"));
selectedIsEditableProperty.setValue(true);
} else {
sourceTextProperty.setValue(((CitationStylePreviewLayout) selectedLayout).getSource());
selectedIsEditableProperty.setValue(false);
}
}
public void refreshPreview() {
setPreviewLayout(null);
setPreviewLayout(chosenSelectionModelProperty.getValue().getSelectedItem());
}
private PreviewLayout findLayoutByName(String name) {
return availableListProperty.getValue().stream().filter(layout -> layout.getName().equals(name))
.findAny()
.orElse(chosenListProperty.getValue().stream().filter(layout -> layout.getName().equals(name))
.findAny()
.orElse(null));
}
/**
* Store the changes of preference-preview settings.
*/
@Override
public void storeSettings() {
if (chosenListProperty.isEmpty()) {
chosenListProperty.add(previewPreferences.getCustomPreviewLayout());
}
PreviewLayout customLayout = findLayoutByName(TextBasedPreviewLayout.NAME);
if (customLayout == null) {
customLayout = previewPreferences.getCustomPreviewLayout();
}
previewPreferences.getLayoutCycle().clear();
previewPreferences.getLayoutCycle().addAll(chosenListProperty);
previewPreferences.setShowPreviewAsExtraTab(showAsExtraTabProperty.getValue());
previewPreferences.setCustomPreviewLayout((TextBasedPreviewLayout) customLayout);
if (!chosenSelectionModelProperty.getValue().getSelectedItems().isEmpty()) {
previewPreferences.setLayoutCyclePosition(chosenListProperty.getValue().indexOf(
chosenSelectionModelProperty.getValue().getSelectedItems().get(0)));
}
}
public ValidationStatus chosenListValidationStatus() {
return chosenListValidator.getValidationStatus();
}
@Override
public boolean validateSettings() {
ValidationStatus validationStatus = chosenListValidationStatus();
if (!validationStatus.isValid()) {
if (validationStatus.getHighestMessage().isPresent()) {
validationStatus.getHighestMessage().ifPresent(message ->
dialogService.showErrorDialogAndWait(message.getMessage()));
}
return false;
}
return true;
}
public void addToChosen() {
List<PreviewLayout> selected = new ArrayList<>(availableSelectionModelProperty.getValue().getSelectedItems());
availableSelectionModelProperty.getValue().clearSelection();
availableListProperty.removeAll(selected);
chosenListProperty.addAll(selected);
}
public void removeFromChosen() {
List<PreviewLayout> selected = new ArrayList<>(chosenSelectionModelProperty.getValue().getSelectedItems());
chosenSelectionModelProperty.getValue().clearSelection();
chosenListProperty.removeAll(selected);
availableListProperty.addAll(selected);
availableListProperty.sort((a, b) -> a.getDisplayName().compareToIgnoreCase(b.getDisplayName()));
}
public void selectedInChosenUp() {
if (chosenSelectionModelProperty.getValue().isEmpty()) {
return;
}
List<Integer> selected = new ArrayList<>(chosenSelectionModelProperty.getValue().getSelectedIndices());
List<Integer> newIndices = new ArrayList<>();
chosenSelectionModelProperty.getValue().clearSelection();
for (int oldIndex : selected) {
boolean alreadyTaken = newIndices.contains(oldIndex - 1);
int newIndex = ((oldIndex > 0) && !alreadyTaken) ? oldIndex - 1 : oldIndex;
chosenListProperty.add(newIndex, chosenListProperty.remove(oldIndex));
newIndices.add(newIndex);
}
newIndices.forEach(index -> chosenSelectionModelProperty.getValue().select(index));
chosenSelectionModelProperty.getValue().select(newIndices.get(0));
refreshPreview();
}
public void selectedInChosenDown() {
if (chosenSelectionModelProperty.getValue().isEmpty()) {
return;
}
List<Integer> selected = new ArrayList<>(chosenSelectionModelProperty.getValue().getSelectedIndices());
List<Integer> newIndices = new ArrayList<>();
chosenSelectionModelProperty.getValue().clearSelection();
for (int i = selected.size() - 1; i >= 0; i--) {
int oldIndex = selected.get(i);
boolean alreadyTaken = newIndices.contains(oldIndex + 1);
int newIndex = ((oldIndex < (chosenListProperty.size() - 1)) && !alreadyTaken) ? oldIndex + 1 : oldIndex;
chosenListProperty.add(newIndex, chosenListProperty.remove(oldIndex));
newIndices.add(newIndex);
}
newIndices.forEach(index -> chosenSelectionModelProperty.getValue().select(index));
chosenSelectionModelProperty.getValue().select(newIndices.get(0));
refreshPreview();
}
public void resetDefaultLayout() {
PreviewLayout defaultLayout = findLayoutByName(TextBasedPreviewLayout.NAME);
if (defaultLayout instanceof TextBasedPreviewLayout layout) {
layout.setText(previewPreferences.getDefaultCustomPreviewLayout());
}
refreshPreview();
}
/**
* XML-Syntax-Highlighting for RichTextFX-Codearea created by (c) Carlos Martins (github:
* <a href="https://github.com/cmartins">@cemartins</a>)
* <p>
* License: <a href="https://github.com/FXMisc/RichTextFX/blob/master/LICENSE">BSD-2-Clause</a>
* <p>
* See also
* <a href="https://github.com/FXMisc/RichTextFX/blob/master/richtextfx-demos/README.md#xml-editor">https://github.com/FXMisc/RichTextFX/blob/master/richtextfx-demos/README.md#xml-editor</a>
*
* @param text to parse and highlight
* @return highlighted span for codeArea
*/
public StyleSpans<Collection<String>> computeHighlighting(String text) {
final Pattern XML_TAG = Pattern.compile("(?<ELEMENT>(</?\\h*)(\\w+)([^<>]*)(\\h*/?>))"
+ "|(?<COMMENT><!--[^<>]+-->)");
final Pattern ATTRIBUTES = Pattern.compile("(\\w+\\h*)(=)(\\h*\"[^\"]+\")");
final int GROUP_OPEN_BRACKET = 2;
final int GROUP_ELEMENT_NAME = 3;
final int GROUP_ATTRIBUTES_SECTION = 4;
final int GROUP_CLOSE_BRACKET = 5;
final int GROUP_ATTRIBUTE_NAME = 1;
final int GROUP_EQUAL_SYMBOL = 2;
final int GROUP_ATTRIBUTE_VALUE = 3;
Matcher matcher = XML_TAG.matcher(text);
int lastKeywordEnd = 0;
StyleSpansBuilder<Collection<String>> spansBuilder = new StyleSpansBuilder<>();
while (matcher.find()) {
spansBuilder.add(Collections.emptyList(), matcher.start() - lastKeywordEnd);
if (matcher.group("COMMENT") != null) {
spansBuilder.add(Collections.singleton("comment"), matcher.end() - matcher.start());
} else {
if (matcher.group("ELEMENT") != null) {
String attributesText = matcher.group(GROUP_ATTRIBUTES_SECTION);
spansBuilder.add(Collections.singleton("tagmark"), matcher.end(GROUP_OPEN_BRACKET) - matcher.start(GROUP_OPEN_BRACKET));
spansBuilder.add(Collections.singleton("anytag"), matcher.end(GROUP_ELEMENT_NAME) - matcher.end(GROUP_OPEN_BRACKET));
if (!attributesText.isEmpty()) {
lastKeywordEnd = 0;
Matcher attributesMatcher = ATTRIBUTES.matcher(attributesText);
while (attributesMatcher.find()) {
spansBuilder.add(Collections.emptyList(), attributesMatcher.start() - lastKeywordEnd);
spansBuilder.add(Collections.singleton("attribute"), attributesMatcher.end(GROUP_ATTRIBUTE_NAME) - attributesMatcher.start(GROUP_ATTRIBUTE_NAME));
spansBuilder.add(Collections.singleton("tagmark"), attributesMatcher.end(GROUP_EQUAL_SYMBOL) - attributesMatcher.end(GROUP_ATTRIBUTE_NAME));
spansBuilder.add(Collections.singleton("avalue"), attributesMatcher.end(GROUP_ATTRIBUTE_VALUE) - attributesMatcher.end(GROUP_EQUAL_SYMBOL));
lastKeywordEnd = attributesMatcher.end();
}
if (attributesText.length() > lastKeywordEnd) {
spansBuilder.add(Collections.emptyList(), attributesText.length() - lastKeywordEnd);
}
}
lastKeywordEnd = matcher.end(GROUP_ATTRIBUTES_SECTION);
spansBuilder.add(Collections.singleton("tagmark"), matcher.end(GROUP_CLOSE_BRACKET) - lastKeywordEnd);
}
}
lastKeywordEnd = matcher.end();
}
spansBuilder.add(Collections.emptyList(), text.length() - lastKeywordEnd);
return spansBuilder.create();
}
public void dragOver(DragEvent event) {
if (event.getDragboard().hasContent(DragAndDropDataFormats.PREVIEWLAYOUTS)) {
event.acceptTransferModes(TransferMode.MOVE);
}
}
public void dragDetected(ListProperty<PreviewLayout> sourceList, ObjectProperty<MultipleSelectionModel<PreviewLayout>> sourceSelectionModel, List<PreviewLayout> selectedLayouts, Dragboard dragboard) {
ClipboardContent content = new ClipboardContent();
content.put(DragAndDropDataFormats.PREVIEWLAYOUTS, "");
dragboard.setContent(content);
localDragboard.putPreviewLayouts(selectedLayouts);
dragSourceList = sourceList;
dragSourceSelectionModel = sourceSelectionModel;
}
/**
* This is called, when the user drops some PreviewLayouts either in the availableListView or in the empty space of chosenListView
*
* @param targetList either availableListView or chosenListView
*/
public boolean dragDropped(ListProperty<PreviewLayout> targetList, Dragboard dragboard) {
boolean success = false;
if (dragboard.hasContent(DragAndDropDataFormats.PREVIEWLAYOUTS)) {
List<PreviewLayout> draggedLayouts = localDragboard.getPreviewLayouts();
if (!draggedLayouts.isEmpty()) {
dragSourceSelectionModel.getValue().clearSelection();
dragSourceList.getValue().removeAll(draggedLayouts);
targetList.getValue().addAll(draggedLayouts);
success = true;
if (targetList == availableListProperty) {
targetList.getValue().sort((a, b) -> a.getDisplayName().compareToIgnoreCase(b.getDisplayName()));
}
}
}
return success;
}
/**
* This is called, when the user drops some PreviewLayouts on another cell in chosenListView to sort them
*
* @param targetLayout the Layout, the user drops a layout on
*/
public boolean dragDroppedInChosenCell(PreviewLayout targetLayout, Dragboard dragboard) {
boolean success = false;
if (dragboard.hasContent(DragAndDropDataFormats.PREVIEWLAYOUTS)) {
List<PreviewLayout> draggedSelectedLayouts = new ArrayList<>(localDragboard.getPreviewLayouts());
if (!draggedSelectedLayouts.isEmpty()) {
chosenSelectionModelProperty.getValue().clearSelection();
int targetId = chosenListProperty.getValue().indexOf(targetLayout);
// see https://stackoverflow.com/questions/28603224/sort-tableview-with-drag-and-drop-rows
int onSelectedDelta = 0;
while (draggedSelectedLayouts.contains(targetLayout)) {
onSelectedDelta = 1;
targetId--;
if (targetId < 0) {
targetId = 0;
targetLayout = null;
break;
}
targetLayout = chosenListProperty.getValue().get(targetId);
}
dragSourceSelectionModel.getValue().clearSelection();
dragSourceList.getValue().removeAll(draggedSelectedLayouts);
if (targetLayout != null) {
targetId = chosenListProperty.getValue().indexOf(targetLayout) + onSelectedDelta;
} else if (targetId != 0) {
targetId = chosenListProperty.getValue().size();
}
chosenListProperty.getValue().addAll(targetId, draggedSelectedLayouts);
draggedSelectedLayouts.forEach(layout -> chosenSelectionModelProperty.getValue().select(layout));
success = true;
}
}
return success;
}
public BooleanProperty showAsExtraTabProperty() {
return showAsExtraTabProperty;
}
public ListProperty<PreviewLayout> availableListProperty() {
return availableListProperty;
}
public FilteredList<PreviewLayout> getFilteredAvailableLayouts() {
return this.filteredAvailableLayouts;
}
public void setAvailableFilter(String searchTerm) {
this.filteredAvailableLayouts.setPredicate(
preview -> searchTerm.isEmpty()
|| preview.containsCaseIndependent(searchTerm));
}
public ObjectProperty<MultipleSelectionModel<PreviewLayout>> availableSelectionModelProperty() {
return availableSelectionModelProperty;
}
public ListProperty<PreviewLayout> chosenListProperty() {
return chosenListProperty;
}
public ObjectProperty<MultipleSelectionModel<PreviewLayout>> chosenSelectionModelProperty() {
return chosenSelectionModelProperty;
}
public BooleanProperty selectedIsEditableProperty() {
return selectedIsEditableProperty;
}
public ObjectProperty<PreviewLayout> selectedLayoutProperty() {
return selectedLayoutProperty;
}
public StringProperty sourceTextProperty() {
return sourceTextProperty;
}
}
| 21,779
| 44.375
| 204
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/protectedterms/NewProtectedTermsFileDialog.java
|
package org.jabref.gui.preferences.protectedterms;
import java.util.ArrayList;
import java.util.List;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import org.jabref.gui.DialogService;
import org.jabref.gui.util.BaseDialog;
import org.jabref.gui.util.FileDialogConfiguration;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.protectedterms.ProtectedTermsList;
import org.jabref.logic.util.StandardFileType;
import org.jabref.preferences.FilePreferences;
public class NewProtectedTermsFileDialog extends BaseDialog<Void> {
private final TextField newFile = new TextField();
private final DialogService dialogService;
public NewProtectedTermsFileDialog(List<ProtectedTermsListItemModel> termsLists, DialogService dialogService, FilePreferences filePreferences) {
this.dialogService = dialogService;
this.setTitle(Localization.lang("New protected terms file"));
FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
.addExtensionFilter(Localization.lang("Protected terms file"), StandardFileType.TERMS)
.withDefaultExtension(Localization.lang("Protected terms file"), StandardFileType.TERMS)
.withInitialDirectory(filePreferences.getWorkingDirectory())
.build();
Button browse = new Button(Localization.lang("Browse"));
browse.setOnAction(event -> this.dialogService.showFileSaveDialog(fileDialogConfiguration)
.ifPresent(file -> newFile.setText(file.toAbsolutePath().toString())));
TextField newDescription = new TextField();
VBox container = new VBox(10,
new VBox(5, new Label(Localization.lang("Description")), newDescription),
new VBox(5, new Label(Localization.lang("File")), new HBox(10, newFile, browse))
);
getDialogPane().setContent(container);
getDialogPane().getButtonTypes().setAll(
ButtonType.OK,
ButtonType.CANCEL
);
setResultConverter(button -> {
if (button == ButtonType.OK) {
ProtectedTermsList newList = new ProtectedTermsList(newDescription.getText(), new ArrayList<>(), newFile.getText(), false);
newList.setEnabled(true);
newList.createAndWriteHeading(newDescription.getText());
termsLists.add(new ProtectedTermsListItemModel(newList));
}
return null;
});
}
}
| 2,714
| 41.421875
| 148
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/protectedterms/ProtectedTermsListItemModel.java
|
package org.jabref.gui.preferences.protectedterms;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ReadOnlyBooleanProperty;
import javafx.beans.property.ReadOnlyBooleanWrapper;
import javafx.beans.property.ReadOnlyStringProperty;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.beans.property.SimpleBooleanProperty;
import org.jabref.logic.protectedterms.ProtectedTermsList;
public class ProtectedTermsListItemModel {
private final ProtectedTermsList termsList;
private final BooleanProperty enabledProperty = new SimpleBooleanProperty();
public ProtectedTermsListItemModel(ProtectedTermsList termsList) {
this.termsList = termsList;
this.enabledProperty.setValue(termsList.isEnabled());
}
public ProtectedTermsList getTermsList() {
termsList.setEnabled(enabledProperty.getValue());
return termsList;
}
public ReadOnlyStringProperty descriptionProperty() {
return new ReadOnlyStringWrapper(termsList.getDescription());
}
public ReadOnlyStringProperty locationProperty() {
return new ReadOnlyStringWrapper(termsList.getLocation());
}
public ReadOnlyBooleanProperty internalProperty() {
return new ReadOnlyBooleanWrapper(termsList.isInternalList());
}
public BooleanProperty enabledProperty() {
return enabledProperty;
}
}
| 1,396
| 31.488372
| 80
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/protectedterms/ProtectedTermsTab.java
|
package org.jabref.gui.preferences.protectedterms;
import javafx.beans.property.ReadOnlyBooleanWrapper;
import javafx.fxml.FXML;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.CheckBoxTableCell;
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.icon.IconTheme;
import org.jabref.gui.preferences.AbstractPreferenceTabView;
import org.jabref.gui.preferences.PreferencesTab;
import org.jabref.gui.util.BindingsHelper;
import org.jabref.gui.util.ValueTableCellFactory;
import org.jabref.gui.util.ViewModelTableRowFactory;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.protectedterms.ProtectedTermsList;
import org.jabref.logic.protectedterms.ProtectedTermsLoader;
import com.airhacks.afterburner.views.ViewLoader;
import jakarta.inject.Inject;
/**
* Dialog for managing term list files.
*/
public class ProtectedTermsTab extends AbstractPreferenceTabView<ProtectedTermsTabViewModel> implements PreferencesTab {
@FXML private TableView<ProtectedTermsListItemModel> filesTable;
@FXML private TableColumn<ProtectedTermsListItemModel, Boolean> filesTableEnabledColumn;
@FXML private TableColumn<ProtectedTermsListItemModel, String> filesTableDescriptionColumn;
@FXML private TableColumn<ProtectedTermsListItemModel, String> filesTableFileColumn;
@FXML private TableColumn<ProtectedTermsListItemModel, Boolean> filesTableEditColumn;
@FXML private TableColumn<ProtectedTermsListItemModel, Boolean> filesTableDeleteColumn;
@Inject private ProtectedTermsLoader termsLoader;
public ProtectedTermsTab() {
ViewLoader.view(this)
.root(this)
.load();
}
@Override
public String getTabName() {
return Localization.lang("Protected terms files");
}
@FXML
public void initialize() {
viewModel = new ProtectedTermsTabViewModel(termsLoader, dialogService, preferencesService);
new ViewModelTableRowFactory<ProtectedTermsListItemModel>()
.withContextMenu(this::createContextMenu)
.install(filesTable);
filesTableEnabledColumn.setCellFactory(CheckBoxTableCell.forTableColumn(filesTableEnabledColumn));
filesTableEnabledColumn.setCellValueFactory(data -> data.getValue().enabledProperty());
filesTableDescriptionColumn.setCellValueFactory(data -> BindingsHelper.constantOf(data.getValue().getTermsList().getDescription()));
filesTableFileColumn.setCellValueFactory(data -> {
ProtectedTermsList list = data.getValue().getTermsList();
if (list.isInternalList()) {
return BindingsHelper.constantOf(Localization.lang("Internal list"));
} else {
return BindingsHelper.constantOf(list.getLocation());
}
});
filesTableEditColumn.setCellValueFactory(data -> data.getValue().internalProperty().not());
new ValueTableCellFactory<ProtectedTermsListItemModel, Boolean>()
.withGraphic(none -> IconTheme.JabRefIcons.EDIT.getGraphicNode())
.withVisibleExpression(ReadOnlyBooleanWrapper::new)
.withOnMouseClickedEvent((item, none) -> event -> viewModel.edit(item))
.install(filesTableEditColumn);
filesTableDeleteColumn.setCellValueFactory(data -> data.getValue().internalProperty().not());
new ValueTableCellFactory<ProtectedTermsListItemModel, Boolean>()
.withGraphic(none -> IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode())
.withVisibleExpression(ReadOnlyBooleanWrapper::new)
.withTooltip(none -> Localization.lang("Remove protected terms file"))
.withOnMouseClickedEvent((item, none) -> event -> viewModel.removeList(item))
.install(filesTableDeleteColumn);
filesTable.itemsProperty().set(viewModel.termsFilesProperty());
}
private ContextMenu createContextMenu(ProtectedTermsListItemModel file) {
ActionFactory factory = new ActionFactory(Globals.getKeyPrefs());
ContextMenu contextMenu = new ContextMenu();
contextMenu.getItems().addAll(
factory.createMenuItem(StandardActions.EDIT_LIST, new ProtectedTermsTab.ContextAction(StandardActions.EDIT_LIST, file)),
factory.createMenuItem(StandardActions.VIEW_LIST, new ProtectedTermsTab.ContextAction(StandardActions.VIEW_LIST, file)),
factory.createMenuItem(StandardActions.REMOVE_LIST, new ProtectedTermsTab.ContextAction(StandardActions.REMOVE_LIST, file)),
factory.createMenuItem(StandardActions.RELOAD_LIST, new ProtectedTermsTab.ContextAction(StandardActions.RELOAD_LIST, file))
);
contextMenu.getItems().forEach(item -> item.setGraphic(null));
contextMenu.getStyleClass().add("context-menu");
return contextMenu;
}
@FXML
private void addFile() {
viewModel.addFile();
}
@FXML
private void createNewFile() {
viewModel.createNewFile();
}
private class ContextAction extends SimpleCommand {
private final StandardActions command;
private final ProtectedTermsListItemModel itemModel;
public ContextAction(StandardActions command, ProtectedTermsListItemModel itemModel) {
this.command = command;
this.itemModel = itemModel;
this.executable.bind(BindingsHelper.constantOf(
switch (command) {
case EDIT_LIST, REMOVE_LIST, RELOAD_LIST -> !itemModel.getTermsList().isInternalList();
default -> true;
}));
}
@Override
public void execute() {
switch (command) {
case EDIT_LIST -> viewModel.edit(itemModel);
case VIEW_LIST -> viewModel.displayContent(itemModel);
case REMOVE_LIST -> viewModel.removeList(itemModel);
case RELOAD_LIST -> viewModel.reloadList(itemModel);
}
}
}
}
| 6,282
| 43.560284
| 140
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/protectedterms/ProtectedTermsTabViewModel.java
|
package org.jabref.gui.preferences.protectedterms;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.FXCollections;
import javafx.scene.control.ButtonType;
import javafx.scene.control.DialogPane;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import org.jabref.gui.DialogService;
import org.jabref.gui.desktop.JabRefDesktop;
import org.jabref.gui.externalfiletype.ExternalFileType;
import org.jabref.gui.externalfiletype.ExternalFileTypes;
import org.jabref.gui.preferences.PreferenceTabViewModel;
import org.jabref.gui.util.FileDialogConfiguration;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.protectedterms.ProtectedTermsList;
import org.jabref.logic.protectedterms.ProtectedTermsLoader;
import org.jabref.logic.protectedterms.ProtectedTermsPreferences;
import org.jabref.logic.util.StandardFileType;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.util.OptionalUtil;
import org.jabref.preferences.PreferencesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ProtectedTermsTabViewModel implements PreferenceTabViewModel {
private static final Logger LOGGER = LoggerFactory.getLogger(ProtectedTermsTabViewModel.class);
private final ProtectedTermsLoader termsLoader;
private final ListProperty<ProtectedTermsListItemModel> termsFilesProperty = new SimpleListProperty<>(FXCollections.observableArrayList());
private final PreferencesService preferences;
private final DialogService dialogService;
private final ProtectedTermsPreferences protectedTermsPreferences;
public ProtectedTermsTabViewModel(ProtectedTermsLoader termsLoader,
DialogService dialogService,
PreferencesService preferences) {
this.termsLoader = termsLoader;
this.dialogService = dialogService;
this.preferences = preferences;
this.protectedTermsPreferences = preferences.getProtectedTermsPreferences();
}
@Override
public void setValues() {
termsFilesProperty.clear();
termsFilesProperty.addAll(termsLoader.getProtectedTermsLists().stream().map(ProtectedTermsListItemModel::new).toList());
}
@Override
public void storeSettings() {
List<String> enabledExternalList = new ArrayList<>();
List<String> disabledExternalList = new ArrayList<>();
List<String> enabledInternalList = new ArrayList<>();
List<String> disabledInternalList = new ArrayList<>();
for (ProtectedTermsList list : termsFilesProperty.getValue().stream()
.map(ProtectedTermsListItemModel::getTermsList).toList()) {
if (list.isInternalList()) {
if (list.isEnabled()) {
enabledInternalList.add(list.getLocation());
} else {
disabledInternalList.add(list.getLocation());
}
} else {
if (list.isEnabled()) {
enabledExternalList.add(list.getLocation());
} else {
disabledExternalList.add(list.getLocation());
}
}
}
protectedTermsPreferences.setEnabledInternalTermLists(enabledInternalList);
protectedTermsPreferences.setEnabledExternalTermLists(enabledExternalList);
protectedTermsPreferences.setDisabledInternalTermLists(disabledInternalList);
protectedTermsPreferences.setDisabledExternalTermLists(disabledExternalList);
termsLoader.update(protectedTermsPreferences);
}
public void addFile() {
FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
.addExtensionFilter(Localization.lang("Protected terms file"), StandardFileType.TERMS)
.withDefaultExtension(Localization.lang("Protected terms file"), StandardFileType.TERMS)
.withInitialDirectory(preferences.getFilePreferences().getWorkingDirectory())
.build();
dialogService.showFileOpenDialog(fileDialogConfiguration)
.ifPresent(file -> {
Path fileName = file.toAbsolutePath();
termsFilesProperty.add(new ProtectedTermsListItemModel(ProtectedTermsLoader.readProtectedTermsListFromFile(fileName, true)));
});
}
public void removeList(ProtectedTermsListItemModel itemModel) {
ProtectedTermsList list = itemModel.getTermsList();
if (!list.isInternalList() && dialogService.showConfirmationDialogAndWait(Localization.lang("Remove protected terms file"),
Localization.lang("Are you sure you want to remove the protected terms file?"),
Localization.lang("Remove protected terms file"),
Localization.lang("Cancel"))) {
itemModel.enabledProperty().setValue(false);
if (!termsFilesProperty.remove(itemModel)) {
LOGGER.info("Problem removing protected terms file");
}
}
}
public void createNewFile() {
dialogService.showCustomDialogAndWait(new NewProtectedTermsFileDialog(termsFilesProperty, dialogService, preferences.getFilePreferences()));
}
public void edit(ProtectedTermsListItemModel file) {
Optional<ExternalFileType> termsFileType = OptionalUtil.<ExternalFileType>orElse(
ExternalFileTypes.getExternalFileTypeByExt("terms", preferences.getFilePreferences()),
ExternalFileTypes.getExternalFileTypeByExt("txt", preferences.getFilePreferences())
);
String fileName = file.getTermsList().getLocation();
try {
JabRefDesktop.openExternalFileAnyFormat(new BibDatabaseContext(), preferences, fileName, termsFileType);
} catch (IOException e) {
LOGGER.warn("Problem open protected terms file editor", e);
}
}
public void displayContent(ProtectedTermsListItemModel itemModel) {
ProtectedTermsList list = itemModel.getTermsList();
TextArea listingView = new TextArea(list.getTermListing());
listingView.setEditable(false);
ScrollPane scrollPane = new ScrollPane();
scrollPane.setFitToHeight(true);
scrollPane.setFitToWidth(true);
scrollPane.setContent(listingView);
DialogPane dialogPane = new DialogPane();
dialogPane.setContent(scrollPane);
dialogService.showCustomDialogAndWait(list.getDescription() + " - " + list.getLocation(), dialogPane, ButtonType.OK);
}
public void reloadList(ProtectedTermsListItemModel oldItemModel) {
ProtectedTermsList oldList = oldItemModel.getTermsList();
ProtectedTermsList newList = ProtectedTermsLoader.readProtectedTermsListFromFile(Path.of(oldList.getLocation()), oldList.isEnabled());
int index = termsFilesProperty.indexOf(oldItemModel);
if (index >= 0) {
termsFilesProperty.set(index, new ProtectedTermsListItemModel(newList));
} else {
LOGGER.warn("Problem reloading protected terms file {}.", oldList.getLocation());
}
}
public ListProperty<ProtectedTermsListItemModel> termsFilesProperty() {
return termsFilesProperty;
}
}
| 7,567
| 44.317365
| 150
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/table/TableTab.java
|
package org.jabref.gui.preferences.table;
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.RadioButton;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import org.jabref.gui.actions.ActionFactory;
import org.jabref.gui.actions.StandardActions;
import org.jabref.gui.help.HelpAction;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.maintable.MainTableColumnModel;
import org.jabref.gui.preferences.AbstractPreferenceTabView;
import org.jabref.gui.preferences.PreferencesTab;
import org.jabref.gui.util.IconValidationDecorator;
import org.jabref.gui.util.ValueTableCellFactory;
import org.jabref.gui.util.ViewModelListCellFactory;
import org.jabref.logic.help.HelpFile;
import org.jabref.logic.l10n.Localization;
import com.airhacks.afterburner.views.ViewLoader;
import de.saxsys.mvvmfx.utils.validation.visualization.ControlsFxVisualizer;
public class TableTab extends AbstractPreferenceTabView<TableTabViewModel> implements PreferencesTab {
@FXML private TableView<MainTableColumnModel> columnsList;
@FXML private TableColumn<MainTableColumnModel, String> nameColumn;
@FXML private TableColumn<MainTableColumnModel, String> actionsColumn;
@FXML private ComboBox<MainTableColumnModel> addColumnName;
@FXML private CheckBox specialFieldsEnable;
@FXML private Button specialFieldsHelp;
@FXML private CheckBox extraFileColumnsEnable;
@FXML private CheckBox autoResizeColumns;
@FXML private RadioButton namesNatbib;
@FXML private RadioButton nameAsIs;
@FXML private RadioButton nameFirstLast;
@FXML private RadioButton nameLastFirst;
@FXML private RadioButton abbreviationDisabled;
@FXML private RadioButton abbreviationEnabled;
@FXML private RadioButton abbreviationLastNameOnly;
private final ControlsFxVisualizer validationVisualizer = new ControlsFxVisualizer();
public TableTab() {
ViewLoader.view(this)
.root(this)
.load();
}
@Override
public String getTabName() {
return Localization.lang("Entry table");
}
public void initialize() {
this.viewModel = new TableTabViewModel(dialogService, preferencesService);
setupTable();
setupBindings();
ActionFactory actionFactory = new ActionFactory(preferencesService.getKeyBindingRepository());
actionFactory.configureIconButton(StandardActions.HELP_SPECIAL_FIELDS, new HelpAction(HelpFile.SPECIAL_FIELDS, dialogService), specialFieldsHelp);
}
private void setupTable() {
nameColumn.setSortable(false);
nameColumn.setReorderable(false);
nameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
new ValueTableCellFactory<MainTableColumnModel, String>()
.withText(name -> name)
.install(nameColumn);
actionsColumn.setSortable(false);
actionsColumn.setReorderable(false);
actionsColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
new ValueTableCellFactory<MainTableColumnModel, String>()
.withGraphic(item -> IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode())
.withTooltip(name -> Localization.lang("Remove column") + " " + name)
.withOnMouseClickedEvent(item -> evt ->
viewModel.removeColumn(columnsList.getFocusModel().getFocusedItem()))
.install(actionsColumn);
viewModel.selectedColumnModelProperty().setValue(columnsList.getSelectionModel());
columnsList.addEventFilter(KeyEvent.KEY_PRESSED, event -> {
if (event.getCode() == KeyCode.DELETE) {
viewModel.removeColumn(columnsList.getSelectionModel().getSelectedItem());
event.consume();
}
});
columnsList.itemsProperty().bind(viewModel.columnsListProperty());
new ViewModelListCellFactory<MainTableColumnModel>()
.withText(MainTableColumnModel::getDisplayName)
.install(addColumnName);
addColumnName.itemsProperty().bind(viewModel.availableColumnsProperty());
addColumnName.valueProperty().bindBidirectional(viewModel.addColumnProperty());
addColumnName.setConverter(TableTabViewModel.columnNameStringConverter);
addColumnName.addEventFilter(KeyEvent.KEY_PRESSED, event -> {
if (event.getCode() == KeyCode.ENTER) {
viewModel.insertColumnInList();
event.consume();
}
});
validationVisualizer.setDecoration(new IconValidationDecorator());
Platform.runLater(() -> validationVisualizer.initVisualization(viewModel.columnsListValidationStatus(), columnsList));
}
private void setupBindings() {
specialFieldsEnable.selectedProperty().bindBidirectional(viewModel.specialFieldsEnabledProperty());
extraFileColumnsEnable.selectedProperty().bindBidirectional(viewModel.extraFileColumnsEnabledProperty());
autoResizeColumns.selectedProperty().bindBidirectional(viewModel.autoResizeColumnsProperty());
namesNatbib.selectedProperty().bindBidirectional(viewModel.namesNatbibProperty());
nameAsIs.selectedProperty().bindBidirectional(viewModel.nameAsIsProperty());
nameFirstLast.selectedProperty().bindBidirectional(viewModel.nameFirstLastProperty());
nameLastFirst.selectedProperty().bindBidirectional(viewModel.nameLastFirstProperty());
abbreviationDisabled.selectedProperty().bindBidirectional(viewModel.abbreviationDisabledProperty());
abbreviationDisabled.disableProperty().bind(namesNatbib.selectedProperty().or(nameAsIs.selectedProperty()));
abbreviationEnabled.selectedProperty().bindBidirectional(viewModel.abbreviationEnabledProperty());
abbreviationEnabled.disableProperty().bind(namesNatbib.selectedProperty().or(nameAsIs.selectedProperty()));
abbreviationLastNameOnly.selectedProperty().bindBidirectional(viewModel.abbreviationLastNameOnlyProperty());
abbreviationLastNameOnly.disableProperty().bind(namesNatbib.selectedProperty().or(nameAsIs.selectedProperty()));
}
public void updateToCurrentColumnOrder() {
viewModel.fillColumnList();
}
public void sortColumnUp() {
viewModel.moveColumnUp();
}
public void sortColumnDown() {
viewModel.moveColumnDown();
}
public void addColumn() {
viewModel.insertColumnInList();
}
}
| 6,745
| 43.675497
| 154
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/table/TableTabViewModel.java
|
package org.jabref.gui.preferences.table;
import java.util.EnumSet;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ListProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.scene.control.SelectionModel;
import javafx.util.StringConverter;
import org.jabref.gui.DialogService;
import org.jabref.gui.externalfiletype.ExternalFileType;
import org.jabref.gui.maintable.ColumnPreferences;
import org.jabref.gui.maintable.MainTableColumnModel;
import org.jabref.gui.maintable.MainTablePreferences;
import org.jabref.gui.maintable.NameDisplayPreferences;
import org.jabref.gui.maintable.NameDisplayPreferences.AbbreviationStyle;
import org.jabref.gui.maintable.NameDisplayPreferences.DisplayStyle;
import org.jabref.gui.preferences.PreferenceTabViewModel;
import org.jabref.gui.specialfields.SpecialFieldsPreferences;
import org.jabref.gui.util.NoSelectionModel;
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.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;
public class TableTabViewModel implements PreferenceTabViewModel {
static StringConverter<MainTableColumnModel> columnNameStringConverter = new StringConverter<>() {
@Override
public String toString(MainTableColumnModel object) {
if (object != null) {
return object.getName();
} else {
return "";
}
}
@Override
public MainTableColumnModel fromString(String string) {
return MainTableColumnModel.parse(string);
}
};
private final ListProperty<MainTableColumnModel> columnsListProperty = new SimpleListProperty<>(FXCollections.observableArrayList());
private final ObjectProperty<SelectionModel<MainTableColumnModel>> selectedColumnModelProperty = new SimpleObjectProperty<>(new NoSelectionModel<>());
private final ListProperty<MainTableColumnModel> availableColumnsProperty = new SimpleListProperty<>(FXCollections.observableArrayList());
private final ObjectProperty<MainTableColumnModel> addColumnProperty = new SimpleObjectProperty<>();
private final BooleanProperty specialFieldsEnabledProperty = new SimpleBooleanProperty();
private final BooleanProperty extraFileColumnsEnabledProperty = new SimpleBooleanProperty();
private final BooleanProperty autoResizeColumnsProperty = new SimpleBooleanProperty();
private final BooleanProperty namesNatbibProperty = new SimpleBooleanProperty();
private final BooleanProperty nameAsIsProperty = new SimpleBooleanProperty();
private final BooleanProperty nameFirstLastProperty = new SimpleBooleanProperty();
private final BooleanProperty nameLastFirstProperty = new SimpleBooleanProperty();
private final BooleanProperty abbreviationDisabledProperty = new SimpleBooleanProperty();
private final BooleanProperty abbreviationEnabledProperty = new SimpleBooleanProperty();
private final BooleanProperty abbreviationLastNameOnlyProperty = new SimpleBooleanProperty();
private final Validator columnsNotEmptyValidator;
private final DialogService dialogService;
private final PreferencesService preferences;
private ColumnPreferences initialColumnPreferences;
private final SpecialFieldsPreferences specialFieldsPreferences;
private final NameDisplayPreferences nameDisplayPreferences;
private final MainTablePreferences mainTablePreferences;
public TableTabViewModel(DialogService dialogService, PreferencesService preferences) {
this.dialogService = dialogService;
this.preferences = preferences;
this.specialFieldsPreferences = preferences.getSpecialFieldsPreferences();
this.nameDisplayPreferences = preferences.getNameDisplayPreferences();
this.mainTablePreferences = preferences.getMainTablePreferences();
specialFieldsEnabledProperty.addListener((observable, oldValue, newValue) -> {
if (newValue) {
insertSpecialFieldColumns();
} else {
removeSpecialFieldColumns();
}
});
extraFileColumnsEnabledProperty.addListener((observable, oldValue, newValue) -> {
if (newValue) {
insertExtraFileColumns();
} else {
removeExtraFileColumns();
}
});
columnsNotEmptyValidator = new FunctionBasedValidator<>(
columnsListProperty,
list -> list.size() > 0,
ValidationMessage.error(String.format("%s > %s %n %n %s",
Localization.lang("Entry table columns"),
Localization.lang("Columns"),
Localization.lang("List must not be empty."))));
}
@Override
public void setValues() {
initialColumnPreferences = mainTablePreferences.getColumnPreferences();
specialFieldsEnabledProperty.setValue(specialFieldsPreferences.isSpecialFieldsEnabled());
extraFileColumnsEnabledProperty.setValue(mainTablePreferences.getExtraFileColumnsEnabled());
autoResizeColumnsProperty.setValue(mainTablePreferences.getResizeColumnsToFit());
fillColumnList();
availableColumnsProperty.clear();
availableColumnsProperty.addAll(
new MainTableColumnModel(MainTableColumnModel.Type.INDEX),
new MainTableColumnModel(MainTableColumnModel.Type.LINKED_IDENTIFIER),
new MainTableColumnModel(MainTableColumnModel.Type.GROUPS),
new MainTableColumnModel(MainTableColumnModel.Type.FILES),
new MainTableColumnModel(MainTableColumnModel.Type.NORMALFIELD, StandardField.TIMESTAMP.getName()),
new MainTableColumnModel(MainTableColumnModel.Type.NORMALFIELD, StandardField.OWNER.getName()),
new MainTableColumnModel(MainTableColumnModel.Type.NORMALFIELD, StandardField.GROUPS.getName()),
new MainTableColumnModel(MainTableColumnModel.Type.NORMALFIELD, InternalField.KEY_FIELD.getName()),
new MainTableColumnModel(MainTableColumnModel.Type.NORMALFIELD, InternalField.TYPE_HEADER.getName())
);
EnumSet.allOf(StandardField.class).stream()
.map(Field::getName)
.map(name -> new MainTableColumnModel(MainTableColumnModel.Type.NORMALFIELD, name))
.forEach(item -> availableColumnsProperty.getValue().add(item));
if (specialFieldsEnabledProperty.getValue()) {
insertSpecialFieldColumns();
}
if (mainTablePreferences.getExtraFileColumnsEnabled()) {
insertExtraFileColumns();
}
switch (nameDisplayPreferences.getDisplayStyle()) {
case NATBIB -> namesNatbibProperty.setValue(true);
case AS_IS -> nameAsIsProperty.setValue(true);
case FIRSTNAME_LASTNAME -> nameFirstLastProperty.setValue(true);
case LASTNAME_FIRSTNAME -> nameLastFirstProperty.setValue(true);
}
switch (nameDisplayPreferences.getAbbreviationStyle()) {
case FULL -> abbreviationEnabledProperty.setValue(true);
case LASTNAME_ONLY -> abbreviationLastNameOnlyProperty.setValue(true);
case NONE -> abbreviationDisabledProperty.setValue(true);
}
}
public void fillColumnList() {
columnsListProperty.getValue().clear();
if (initialColumnPreferences != null) {
initialColumnPreferences.getColumns().forEach(columnsListProperty.getValue()::add);
}
}
private void insertSpecialFieldColumns() {
EnumSet.allOf(SpecialField.class).stream()
.map(Field::getName)
.map(name -> new MainTableColumnModel(MainTableColumnModel.Type.SPECIALFIELD, name))
.forEach(item -> availableColumnsProperty.getValue().add(0, item));
}
private void removeSpecialFieldColumns() {
columnsListProperty.getValue().removeIf(column -> column.getType().equals(MainTableColumnModel.Type.SPECIALFIELD));
availableColumnsProperty.getValue().removeIf(column -> column.getType().equals(MainTableColumnModel.Type.SPECIALFIELD));
}
private void insertExtraFileColumns() {
preferences.getFilePreferences().getExternalFileTypes().stream()
.map(ExternalFileType::getName)
.map(name -> new MainTableColumnModel(MainTableColumnModel.Type.EXTRAFILE, name))
.forEach(item -> availableColumnsProperty.getValue().add(item));
}
private void removeExtraFileColumns() {
columnsListProperty.getValue().removeIf(column -> column.getType().equals(MainTableColumnModel.Type.EXTRAFILE));
availableColumnsProperty.getValue().removeIf(column -> column.getType().equals(MainTableColumnModel.Type.EXTRAFILE));
}
public void insertColumnInList() {
if (addColumnProperty.getValue() == null ||
addColumnProperty.getValue().getQualifier().isEmpty()) {
return;
}
if (columnsListProperty.getValue().stream().filter(item -> item.equals(addColumnProperty.getValue())).findAny().isEmpty()) {
columnsListProperty.add(addColumnProperty.getValue());
addColumnProperty.setValue(null);
}
}
public void removeColumn(MainTableColumnModel column) {
columnsListProperty.remove(column);
}
public void moveColumnUp() {
MainTableColumnModel selectedColumn = selectedColumnModelProperty.getValue().getSelectedItem();
int row = columnsListProperty.getValue().indexOf(selectedColumn);
if ((selectedColumn == null) || (row < 1)) {
return;
}
columnsListProperty.remove(selectedColumn);
columnsListProperty.add(row - 1, selectedColumn);
selectedColumnModelProperty.getValue().clearAndSelect(row - 1);
}
public void moveColumnDown() {
MainTableColumnModel selectedColumn = selectedColumnModelProperty.getValue().getSelectedItem();
int row = columnsListProperty.getValue().indexOf(selectedColumn);
if ((selectedColumn == null) || (row > (columnsListProperty.getValue().size() - 2))) {
return;
}
columnsListProperty.remove(selectedColumn);
columnsListProperty.add(row + 1, selectedColumn);
selectedColumnModelProperty.getValue().clearAndSelect(row + 1);
}
@Override
public void storeSettings() {
mainTablePreferences.getColumnPreferences().setColumns(columnsListProperty.getValue());
mainTablePreferences.setResizeColumnsToFit(autoResizeColumnsProperty.getValue());
mainTablePreferences.setExtraFileColumnsEnabled(extraFileColumnsEnabledProperty.getValue());
specialFieldsPreferences.setSpecialFieldsEnabled(specialFieldsEnabledProperty.getValue());
if (nameLastFirstProperty.getValue()) {
nameDisplayPreferences.setDisplayStyle(DisplayStyle.LASTNAME_FIRSTNAME);
} else if (namesNatbibProperty.getValue()) {
nameDisplayPreferences.setDisplayStyle(DisplayStyle.NATBIB);
} else if (nameAsIsProperty.getValue()) {
nameDisplayPreferences.setDisplayStyle(DisplayStyle.AS_IS);
} else if (nameFirstLastProperty.getValue()) {
nameDisplayPreferences.setDisplayStyle(DisplayStyle.FIRSTNAME_LASTNAME);
}
if (abbreviationDisabledProperty.getValue()) {
nameDisplayPreferences.setAbbreviationStyle(AbbreviationStyle.NONE);
} else if (abbreviationEnabledProperty.getValue()) {
nameDisplayPreferences.setAbbreviationStyle(AbbreviationStyle.FULL);
} else if (abbreviationLastNameOnlyProperty.getValue()) {
nameDisplayPreferences.setAbbreviationStyle(AbbreviationStyle.LASTNAME_ONLY);
}
}
ValidationStatus columnsListValidationStatus() {
return columnsNotEmptyValidator.getValidationStatus();
}
@Override
public boolean validateSettings() {
ValidationStatus validationStatus = columnsListValidationStatus();
if (!validationStatus.isValid()) {
validationStatus.getHighestMessage().ifPresent(message ->
dialogService.showErrorDialogAndWait(message.getMessage()));
return false;
}
return true;
}
public ListProperty<MainTableColumnModel> columnsListProperty() {
return this.columnsListProperty;
}
public ObjectProperty<SelectionModel<MainTableColumnModel>> selectedColumnModelProperty() {
return selectedColumnModelProperty;
}
public ListProperty<MainTableColumnModel> availableColumnsProperty() {
return this.availableColumnsProperty;
}
public ObjectProperty<MainTableColumnModel> addColumnProperty() {
return this.addColumnProperty;
}
public BooleanProperty specialFieldsEnabledProperty() {
return this.specialFieldsEnabledProperty;
}
public BooleanProperty extraFileColumnsEnabledProperty() {
return this.extraFileColumnsEnabledProperty;
}
public BooleanProperty autoResizeColumnsProperty() {
return autoResizeColumnsProperty;
}
public BooleanProperty namesNatbibProperty() {
return namesNatbibProperty;
}
public BooleanProperty nameAsIsProperty() {
return nameAsIsProperty;
}
public BooleanProperty nameFirstLastProperty() {
return nameFirstLastProperty;
}
public BooleanProperty nameLastFirstProperty() {
return nameLastFirstProperty;
}
public BooleanProperty abbreviationDisabledProperty() {
return abbreviationDisabledProperty;
}
public BooleanProperty abbreviationEnabledProperty() {
return abbreviationEnabledProperty;
}
public BooleanProperty abbreviationLastNameOnlyProperty() {
return abbreviationLastNameOnlyProperty;
}
}
| 14,544
| 42.678679
| 154
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/websearch/WebSearchTab.java
|
package org.jabref.gui.preferences.websearch;
import javafx.beans.InvalidationListener;
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.preferences.AbstractPreferenceTabView;
import org.jabref.gui.preferences.PreferencesTab;
import org.jabref.gui.util.ViewModelListCellFactory;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.preferences.FetcherApiKey;
import com.airhacks.afterburner.views.ViewLoader;
public class WebSearchTab extends AbstractPreferenceTabView<WebSearchTabViewModel> implements PreferencesTab {
@FXML private CheckBox generateNewKeyOnImport;
@FXML private CheckBox warnAboutDuplicatesOnImport;
@FXML private CheckBox downloadLinkedOnlineFiles;
@FXML private CheckBox useCustomDOI;
@FXML private TextField useCustomDOIName;
@FXML private CheckBox grobidEnabled;
@FXML private TextField grobidURL;
@FXML private ComboBox<FetcherApiKey> apiKeySelector;
@FXML private TextField customApiKey;
@FXML private CheckBox useCustomApiKey;
@FXML private Button testCustomApiKey;
public WebSearchTab() {
ViewLoader.view(this)
.root(this)
.load();
}
@Override
public String getTabName() {
return Localization.lang("Web search");
}
public void initialize() {
this.viewModel = new WebSearchTabViewModel(preferencesService, dialogService);
generateNewKeyOnImport.selectedProperty().bindBidirectional(viewModel.generateKeyOnImportProperty());
warnAboutDuplicatesOnImport.selectedProperty().bindBidirectional(viewModel.warnAboutDuplicatesOnImportProperty());
downloadLinkedOnlineFiles.selectedProperty().bindBidirectional(viewModel.shouldDownloadLinkedOnlineFiles());
grobidEnabled.selectedProperty().bindBidirectional(viewModel.grobidEnabledProperty());
grobidURL.textProperty().bindBidirectional(viewModel.grobidURLProperty());
grobidURL.disableProperty().bind(grobidEnabled.selectedProperty().not());
useCustomDOI.selectedProperty().bindBidirectional(viewModel.useCustomDOIProperty());
useCustomDOIName.textProperty().bindBidirectional(viewModel.useCustomDOINameProperty());
useCustomDOIName.disableProperty().bind(useCustomDOI.selectedProperty().not());
new ViewModelListCellFactory<FetcherApiKey>()
.withText(FetcherApiKey::getName)
.install(apiKeySelector);
apiKeySelector.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
if (oldValue != null) {
updateFetcherApiKey(oldValue);
}
if (newValue != null) {
useCustomApiKey.setSelected(newValue.shouldUse());
customApiKey.setText(newValue.getKey());
}
});
customApiKey.textProperty().addListener(listener -> updateFetcherApiKey(apiKeySelector.valueProperty().get()));
customApiKey.disableProperty().bind(useCustomApiKey.selectedProperty().not());
testCustomApiKey.disableProperty().bind(useCustomApiKey.selectedProperty().not());
apiKeySelector.setItems(viewModel.fetcherApiKeys());
viewModel.selectedApiKeyProperty().bind(apiKeySelector.valueProperty());
// Content is set later
viewModel.fetcherApiKeys().addListener((InvalidationListener) change -> apiKeySelector.getSelectionModel().selectFirst());
}
private void updateFetcherApiKey(FetcherApiKey apiKey) {
if (apiKey != null) {
apiKey.setUse(useCustomApiKey.isSelected());
apiKey.setKey(customApiKey.getText().trim());
}
}
@FXML
void checkCustomApiKey() {
viewModel.checkCustomApiKey();
}
}
| 3,911
| 39.329897
| 130
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/websearch/WebSearchTabViewModel.java
|
package org.jabref.gui.preferences.websearch;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.Optional;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ListProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import org.jabref.gui.DialogService;
import org.jabref.gui.preferences.PreferenceTabViewModel;
import org.jabref.logic.importer.ImporterPreferences;
import org.jabref.logic.importer.WebFetchers;
import org.jabref.logic.importer.fetcher.CustomizableKeyFetcher;
import org.jabref.logic.importer.fetcher.GrobidPreferences;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.net.URLDownload;
import org.jabref.logic.preferences.DOIPreferences;
import org.jabref.logic.preferences.FetcherApiKey;
import org.jabref.preferences.FilePreferences;
import org.jabref.preferences.PreferencesService;
public class WebSearchTabViewModel implements PreferenceTabViewModel {
private final BooleanProperty generateKeyOnImportProperty = new SimpleBooleanProperty();
private final BooleanProperty warnAboutDuplicatesOnImportProperty = new SimpleBooleanProperty();
private final BooleanProperty shouldDownloadLinkedOnlineFiles = new SimpleBooleanProperty();
private final BooleanProperty useCustomDOIProperty = new SimpleBooleanProperty();
private final StringProperty useCustomDOINameProperty = new SimpleStringProperty("");
private final BooleanProperty grobidEnabledProperty = new SimpleBooleanProperty();
private final StringProperty grobidURLProperty = new SimpleStringProperty("");
private final ListProperty<FetcherApiKey> apiKeys = new SimpleListProperty<>();
private final ObjectProperty<FetcherApiKey> selectedApiKeyProperty = new SimpleObjectProperty<>();
private final DialogService dialogService;
private final PreferencesService preferencesService;
private final DOIPreferences doiPreferences;
private final GrobidPreferences grobidPreferences;
private final ImporterPreferences importerPreferences;
private final FilePreferences filePreferences;
public WebSearchTabViewModel(PreferencesService preferencesService, DialogService dialogService) {
this.dialogService = dialogService;
this.preferencesService = preferencesService;
this.importerPreferences = preferencesService.getImporterPreferences();
this.grobidPreferences = preferencesService.getGrobidPreferences();
this.doiPreferences = preferencesService.getDOIPreferences();
this.filePreferences = preferencesService.getFilePreferences();
}
@Override
public void setValues() {
generateKeyOnImportProperty.setValue(importerPreferences.isGenerateNewKeyOnImport());
warnAboutDuplicatesOnImportProperty.setValue(importerPreferences.shouldWarnAboutDuplicatesOnImport());
shouldDownloadLinkedOnlineFiles.setValue(filePreferences.shouldDownloadLinkedFiles());
useCustomDOIProperty.setValue(doiPreferences.isUseCustom());
useCustomDOINameProperty.setValue(doiPreferences.getDefaultBaseURI());
grobidEnabledProperty.setValue(grobidPreferences.isGrobidEnabled());
grobidURLProperty.setValue(grobidPreferences.getGrobidURL());
apiKeys.setValue(FXCollections.observableArrayList(preferencesService.getImporterPreferences().getApiKeys()));
}
@Override
public void storeSettings() {
importerPreferences.setGenerateNewKeyOnImport(generateKeyOnImportProperty.getValue());
importerPreferences.setWarnAboutDuplicatesOnImport(warnAboutDuplicatesOnImportProperty.getValue());
filePreferences.setDownloadLinkedFiles(shouldDownloadLinkedOnlineFiles.getValue());
grobidPreferences.setGrobidEnabled(grobidEnabledProperty.getValue());
grobidPreferences.setGrobidOptOut(grobidPreferences.isGrobidOptOut());
grobidPreferences.setGrobidURL(grobidURLProperty.getValue());
doiPreferences.setUseCustom(useCustomDOIProperty.get());
doiPreferences.setDefaultBaseURI(useCustomDOINameProperty.getValue().trim());
preferencesService.getImporterPreferences().getApiKeys().clear();
preferencesService.getImporterPreferences().getApiKeys().addAll(apiKeys);
}
public BooleanProperty generateKeyOnImportProperty() {
return generateKeyOnImportProperty;
}
public BooleanProperty useCustomDOIProperty() {
return this.useCustomDOIProperty;
}
public StringProperty useCustomDOINameProperty() {
return this.useCustomDOINameProperty;
}
public BooleanProperty grobidEnabledProperty() {
return grobidEnabledProperty;
}
public StringProperty grobidURLProperty() {
return grobidURLProperty;
}
public ListProperty<FetcherApiKey> fetcherApiKeys() {
return apiKeys;
}
public ObjectProperty<FetcherApiKey> selectedApiKeyProperty() {
return selectedApiKeyProperty;
}
public BooleanProperty warnAboutDuplicatesOnImportProperty() {
return warnAboutDuplicatesOnImportProperty;
}
public BooleanProperty shouldDownloadLinkedOnlineFiles() {
return shouldDownloadLinkedOnlineFiles;
}
public void checkCustomApiKey() {
final String apiKeyName = selectedApiKeyProperty.get().getName();
final Optional<CustomizableKeyFetcher> fetcherOpt =
WebFetchers.getCustomizableKeyFetchers(
preferencesService.getImportFormatPreferences(),
preferencesService.getImporterPreferences())
.stream()
.filter(fetcher -> fetcher.getName().equals(apiKeyName))
.findFirst();
if (fetcherOpt.isEmpty()) {
dialogService.showErrorDialogAndWait(
Localization.lang("Check %0 API Key Setting", apiKeyName),
Localization.lang("Fetcher unknown!"));
return;
}
final String testUrlWithoutApiKey = fetcherOpt.get().getTestUrl();
if (testUrlWithoutApiKey == null) {
dialogService.showWarningDialogAndWait(
Localization.lang("Check %0 API Key Setting", apiKeyName),
Localization.lang("Fetcher cannot be tested!"));
return;
}
final String apiKey = selectedApiKeyProperty.get().getKey();
boolean keyValid;
if (!apiKey.isEmpty()) {
URLDownload urlDownload;
try {
SSLSocketFactory defaultSslSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
HostnameVerifier defaultHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
urlDownload = new URLDownload(testUrlWithoutApiKey + apiKey);
// The HEAD request cannot be used because its response is not 200 (maybe 404 or 596...).
int statusCode = ((HttpURLConnection) urlDownload.getSource().openConnection()).getResponseCode();
keyValid = (statusCode >= 200) && (statusCode < 300);
URLDownload.setSSLVerification(defaultSslSocketFactory, defaultHostnameVerifier);
} catch (IOException | kong.unirest.UnirestException e) {
keyValid = false;
}
} else {
keyValid = false;
}
if (keyValid) {
dialogService.showInformationDialogAndWait(Localization.lang("Check %0 API Key Setting", apiKeyName), Localization.lang("Connection successful!"));
} else {
dialogService.showErrorDialogAndWait(Localization.lang("Check %0 API Key Setting", apiKeyName), Localization.lang("Connection failed!"));
}
}
}
| 8,195
| 42.828877
| 159
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/xmp/XmpPrivacyTab.java
|
package org.jabref.gui.preferences.xmp;
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.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.preferences.AbstractPreferenceTabView;
import org.jabref.gui.preferences.PreferencesTab;
import org.jabref.gui.util.BindingsHelper;
import org.jabref.gui.util.FieldsUtil;
import org.jabref.gui.util.IconValidationDecorator;
import org.jabref.gui.util.ValueTableCellFactory;
import org.jabref.gui.util.ViewModelListCellFactory;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.entry.field.Field;
import com.airhacks.afterburner.views.ViewLoader;
import de.saxsys.mvvmfx.utils.validation.visualization.ControlsFxVisualizer;
public class XmpPrivacyTab extends AbstractPreferenceTabView<XmpPrivacyTabViewModel> implements PreferencesTab {
@FXML private CheckBox enableXmpFilter;
@FXML private TableView<Field> filterList;
@FXML private TableColumn<Field, Field> fieldColumn;
@FXML private TableColumn<Field, Field> actionsColumn;
@FXML private ComboBox<Field> addFieldName;
@FXML private Button addField;
private final ControlsFxVisualizer validationVisualizer = new ControlsFxVisualizer();
public XmpPrivacyTab() {
ViewLoader.view(this)
.root(this)
.load();
}
@Override
public String getTabName() {
return Localization.lang("XMP metadata");
}
public void initialize() {
this.viewModel = new XmpPrivacyTabViewModel(dialogService, preferencesService.getXmpPreferences());
enableXmpFilter.selectedProperty().bindBidirectional(viewModel.xmpFilterEnabledProperty());
filterList.disableProperty().bind(viewModel.xmpFilterEnabledProperty().not());
addFieldName.disableProperty().bind(viewModel.xmpFilterEnabledProperty().not());
addField.disableProperty().bind(viewModel.xmpFilterEnabledProperty().not());
fieldColumn.setSortable(true);
fieldColumn.setReorderable(false);
fieldColumn.setCellValueFactory(cellData -> BindingsHelper.constantOf(cellData.getValue()));
new ValueTableCellFactory<Field, Field>()
.withText(FieldsUtil::getNameWithType)
.install(fieldColumn);
actionsColumn.setSortable(false);
actionsColumn.setReorderable(false);
actionsColumn.setCellValueFactory(cellData -> BindingsHelper.constantOf(cellData.getValue()));
new ValueTableCellFactory<Field, Field>()
.withGraphic(item -> IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode())
.withTooltip(item -> Localization.lang("Remove") + " " + item.getName())
.withOnMouseClickedEvent(
item -> evt -> viewModel.removeFilter(filterList.getFocusModel().getFocusedItem()))
.install(actionsColumn);
filterList.addEventFilter(KeyEvent.KEY_PRESSED, event -> {
if (event.getCode() == KeyCode.DELETE) {
viewModel.removeFilter(filterList.getSelectionModel().getSelectedItem());
event.consume();
}
});
filterList.itemsProperty().bind(viewModel.filterListProperty());
addFieldName.setEditable(true);
new ViewModelListCellFactory<Field>()
.withText(FieldsUtil::getNameWithType)
.install(addFieldName);
addFieldName.itemsProperty().bind(viewModel.availableFieldsProperty());
addFieldName.valueProperty().bindBidirectional(viewModel.addFieldNameProperty());
addFieldName.setConverter(FieldsUtil.FIELD_STRING_CONVERTER);
addFieldName.addEventFilter(KeyEvent.KEY_PRESSED, event -> {
if (event.getCode() == KeyCode.ENTER) {
viewModel.addField();
event.consume();
}
});
validationVisualizer.setDecoration(new IconValidationDecorator());
Platform.runLater(() -> validationVisualizer.initVisualization(viewModel.xmpFilterListValidationStatus(), filterList));
}
public void addField() {
viewModel.addField();
}
}
| 4,392
| 40.838095
| 127
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preferences/xmp/XmpPrivacyTabViewModel.java
|
package org.jabref.gui.preferences.xmp;
import java.util.Comparator;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ListProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import org.jabref.gui.DialogService;
import org.jabref.gui.preferences.PreferenceTabViewModel;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.xmp.XmpPreferences;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.FieldFactory;
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 XmpPrivacyTabViewModel implements PreferenceTabViewModel {
private final BooleanProperty xmpFilterEnabledProperty = new SimpleBooleanProperty();
private final ListProperty<Field> xmpFilterListProperty = new SimpleListProperty<>(FXCollections.observableArrayList());
private final ListProperty<Field> availableFieldsProperty = new SimpleListProperty<>(FXCollections.observableArrayList());
private final ObjectProperty<Field> addFieldProperty = new SimpleObjectProperty<>();
private final DialogService dialogService;
private final XmpPreferences xmpPreferences;
private final Validator xmpFilterListValidator;
XmpPrivacyTabViewModel(DialogService dialogService, XmpPreferences xmpPreferences) {
this.dialogService = dialogService;
this.xmpPreferences = xmpPreferences;
xmpFilterListValidator = new FunctionBasedValidator<>(
xmpFilterListProperty,
input -> input.size() > 0,
ValidationMessage.error(String.format("%s > %s %n %n %s",
Localization.lang("XMP metadata"),
Localization.lang("Filter List"),
Localization.lang("List must not be empty."))));
}
@Override
public void setValues() {
xmpFilterEnabledProperty.setValue(xmpPreferences.shouldUseXmpPrivacyFilter());
xmpFilterListProperty.clear();
xmpFilterListProperty.addAll(xmpPreferences.getXmpPrivacyFilter());
availableFieldsProperty.clear();
availableFieldsProperty.addAll(FieldFactory.getCommonFields());
availableFieldsProperty.sort((Comparator.comparing(Field::getDisplayName)));
}
@Override
public void storeSettings() {
xmpPreferences.setUseXmpPrivacyFilter(xmpFilterEnabledProperty.getValue());
xmpPreferences.getXmpPrivacyFilter().clear();
xmpPreferences.getXmpPrivacyFilter().addAll(xmpFilterListProperty.getValue());
}
public void addField() {
if (addFieldProperty.getValue() == null) {
return;
}
if (xmpFilterListProperty.getValue().stream().filter(item -> item.equals(addFieldProperty.getValue())).findAny().isEmpty()) {
xmpFilterListProperty.add(addFieldProperty.getValue());
addFieldProperty.setValue(null);
}
}
public void removeFilter(Field filter) {
xmpFilterListProperty.remove(filter);
}
public ValidationStatus xmpFilterListValidationStatus() {
return xmpFilterListValidator.getValidationStatus();
}
@Override
public boolean validateSettings() {
ValidationStatus validationStatus = xmpFilterListValidationStatus();
if (xmpFilterEnabledProperty.getValue() && !validationStatus.isValid()) {
validationStatus.getHighestMessage().ifPresent(message ->
dialogService.showErrorDialogAndWait(message.getMessage()));
return false;
}
return true;
}
public BooleanProperty xmpFilterEnabledProperty() {
return xmpFilterEnabledProperty;
}
public ListProperty<Field> filterListProperty() {
return xmpFilterListProperty;
}
public ListProperty<Field> availableFieldsProperty() {
return availableFieldsProperty;
}
public ObjectProperty<Field> addFieldNameProperty() {
return addFieldProperty;
}
}
| 4,335
| 36.704348
| 133
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preview/CopyCitationAction.java
|
package org.jabref.gui.preview;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
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.citationstyle.CitationStyleGenerator;
import org.jabref.logic.citationstyle.CitationStyleOutputFormat;
import org.jabref.logic.citationstyle.CitationStylePreviewLayout;
import org.jabref.logic.journals.JournalAbbreviationRepository;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.layout.Layout;
import org.jabref.logic.layout.LayoutHelper;
import org.jabref.logic.layout.TextBasedPreviewLayout;
import org.jabref.logic.preview.PreviewLayout;
import org.jabref.logic.util.OS;
import org.jabref.model.entry.BibEntry;
import org.jabref.preferences.PreferencesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Copies the selected entries and formats them with the selected citation style (or preview), then it is copied to the clipboard. This worker cannot be reused.
*/
public class CopyCitationAction extends SimpleCommand {
private static final Logger LOGGER = LoggerFactory.getLogger(CopyCitationAction.class);
private final List<BibEntry> selectedEntries;
private final CitationStyleOutputFormat outputFormat;
private final StateManager stateManager;
private final DialogService dialogService;
private final ClipBoardManager clipBoardManager;
private final TaskExecutor taskExecutor;
private final PreferencesService preferencesService;
private final JournalAbbreviationRepository abbreviationRepository;
public CopyCitationAction(CitationStyleOutputFormat outputFormat,
DialogService dialogService,
StateManager stateManager,
ClipBoardManager clipBoardManager,
TaskExecutor taskExecutor,
PreferencesService preferencesService,
JournalAbbreviationRepository abbreviationRepository) {
this.outputFormat = outputFormat;
this.dialogService = dialogService;
this.stateManager = stateManager;
this.selectedEntries = stateManager.getSelectedEntries();
this.clipBoardManager = clipBoardManager;
this.taskExecutor = taskExecutor;
this.preferencesService = preferencesService;
this.abbreviationRepository = abbreviationRepository;
this.executable.bind(ActionHelper.needsEntriesSelected(stateManager));
}
@Override
public void execute() {
BackgroundTask.wrap(this::generateCitations)
.onFailure(ex -> LOGGER.error("Error while copying citations to the clipboard", ex))
.onSuccess(this::setClipBoardContent)
.executeWith(taskExecutor);
}
private List<String> generateCitations() throws IOException {
// This worker stored the style as filename. The CSLAdapter and the CitationStyleCache store the source of the
// style. Therefore, we extract the style source from the file.
String styleSource = null;
PreviewLayout previewLayout = preferencesService.getPreviewPreferences().getSelectedPreviewLayout();
if (previewLayout instanceof CitationStylePreviewLayout citationStyleLayout) {
styleSource = citationStyleLayout.getSource();
}
if (styleSource != null) {
return CitationStyleGenerator.generateCitations(selectedEntries, styleSource, outputFormat, stateManager.getActiveDatabase().get(), Globals.entryTypesManager);
} else {
return generateTextBasedPreviewLayoutCitations();
}
}
private List<String> generateTextBasedPreviewLayoutCitations() throws IOException {
if (stateManager.getActiveDatabase().isEmpty()) {
return Collections.emptyList();
}
TextBasedPreviewLayout customPreviewLayout = preferencesService.getPreviewPreferences().getCustomPreviewLayout();
StringReader customLayoutReader = new StringReader(customPreviewLayout.getText().replace("__NEWLINE__", "\n"));
Layout layout = new LayoutHelper(customLayoutReader, preferencesService.getLayoutFormatterPreferences(), abbreviationRepository)
.getLayoutFromText();
List<String> citations = new ArrayList<>(selectedEntries.size());
for (BibEntry entry : selectedEntries) {
citations.add(layout.doLayout(entry, stateManager.getActiveDatabase().get().getDatabase()));
}
return citations;
}
/**
* Generates a plain text string out of the preview and copies it additionally to the html to the clipboard (WYSIWYG Editors use the HTML, plain text editors the text)
*/
protected static ClipboardContent processPreview(List<String> citations) {
ClipboardContent content = new ClipboardContent();
content.putHtml(String.join(CitationStyleOutputFormat.HTML.getLineSeparator(), citations));
content.putString(String.join(CitationStyleOutputFormat.HTML.getLineSeparator(), citations));
return content;
}
/**
* Joins every citation with a newline and returns it.
*/
protected static ClipboardContent processText(List<String> citations) {
ClipboardContent content = new ClipboardContent();
content.putString(String.join(CitationStyleOutputFormat.TEXT.getLineSeparator(), citations));
return content;
}
/**
* Inserts each citation into a HTML body and copies it to the clipboard
*/
protected static ClipboardContent processHtml(List<String> citations) {
String result = "<!DOCTYPE html>" + OS.NEWLINE +
"<html>" + OS.NEWLINE +
" <head>" + OS.NEWLINE +
" <meta charset=\"utf-8\">" + OS.NEWLINE +
" </head>" + OS.NEWLINE +
" <body>" + OS.NEWLINE + OS.NEWLINE;
result += String.join(CitationStyleOutputFormat.HTML.getLineSeparator(), citations);
result += OS.NEWLINE +
" </body>" + OS.NEWLINE +
"</html>" + OS.NEWLINE;
ClipboardContent content = new ClipboardContent();
content.putString(result);
content.putHtml(result);
return content;
}
private void setClipBoardContent(List<String> citations) {
PreviewLayout previewLayout = preferencesService.getPreviewPreferences().getSelectedPreviewLayout();
// if it's not a citation style take care of the preview
if (!(previewLayout instanceof CitationStylePreviewLayout)) {
clipBoardManager.setContent(processPreview(citations));
} else {
// if it's generated by a citation style take care of each output format
ClipboardContent content;
switch (outputFormat) {
case HTML -> content = processHtml(citations);
case TEXT -> content = processText(citations);
default -> {
LOGGER.warn("unknown output format: '" + outputFormat + "', processing it via the default.");
content = processText(citations);
}
}
clipBoardManager.setContent(content);
}
dialogService.notify(Localization.lang("Copied %0 citations.", String.valueOf(selectedEntries.size())));
}
}
| 7,804
| 43.096045
| 171
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preview/PreviewPanel.java
|
package org.jabref.gui.preview;
import java.io.File;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.DataFormat;
import javafx.scene.input.Dragboard;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.VBox;
import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.externalfiles.ExternalFilesEntryLinker;
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.logic.l10n.Localization;
import org.jabref.logic.pdf.search.indexing.IndexingTaskManager;
import org.jabref.logic.preview.PreviewLayout;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.preferences.PreferencesService;
import org.jabref.preferences.PreviewPreferences;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PreviewPanel extends VBox {
private static final Logger LOGGER = LoggerFactory.getLogger(PreviewPanel.class);
private final ExternalFilesEntryLinker fileLinker;
private final KeyBindingRepository keyBindingRepository;
private final PreviewViewer previewView;
private final PreviewPreferences previewPreferences;
private final DialogService dialogService;
private final StateManager stateManager;
private final IndexingTaskManager indexingTaskManager;
private BibEntry entry;
public PreviewPanel(BibDatabaseContext database,
DialogService dialogService,
KeyBindingRepository keyBindingRepository,
PreferencesService preferences,
StateManager stateManager,
ThemeManager themeManager,
IndexingTaskManager indexingTaskManager) {
this.keyBindingRepository = keyBindingRepository;
this.dialogService = dialogService;
this.stateManager = stateManager;
this.previewPreferences = preferences.getPreviewPreferences();
this.indexingTaskManager = indexingTaskManager;
this.fileLinker = new ExternalFilesEntryLinker(preferences.getFilePreferences(), database);
PreviewPreferences previewPreferences = preferences.getPreviewPreferences();
previewView = new PreviewViewer(database, dialogService, stateManager, themeManager);
previewView.setLayout(previewPreferences.getSelectedPreviewLayout());
previewView.setContextMenu(createPopupMenu());
previewView.setOnDragDetected(event -> {
previewView.startFullDrag();
Dragboard dragboard = previewView.startDragAndDrop(TransferMode.COPY);
ClipboardContent content = new ClipboardContent();
content.putHtml(previewView.getSelectionHtmlContent());
dragboard.setContent(content);
event.consume();
});
previewView.setOnDragOver(event -> {
if (event.getDragboard().hasFiles()) {
event.acceptTransferModes(TransferMode.COPY, TransferMode.MOVE, TransferMode.LINK);
}
event.consume();
});
previewView.setOnDragDropped(event -> {
boolean success = false;
if (event.getDragboard().hasContent(DataFormat.FILES)) {
List<Path> files = event.getDragboard().getFiles().stream().map(File::toPath).collect(Collectors.toList());
if (event.getTransferMode() == TransferMode.MOVE) {
LOGGER.debug("Mode MOVE"); // shift on win or no modifier
fileLinker.moveFilesToFileDirAndAddToEntry(entry, files, indexingTaskManager);
}
if (event.getTransferMode() == TransferMode.LINK) {
LOGGER.debug("Node LINK"); // alt on win
fileLinker.addFilesToEntry(entry, files);
}
if (event.getTransferMode() == TransferMode.COPY) {
LOGGER.debug("Mode Copy"); // ctrl on win, no modifier on Xubuntu
fileLinker.copyFilesToFileDirAndAddToEntry(entry, files, indexingTaskManager);
}
success = true;
}
event.setDropCompleted(success);
event.consume();
});
this.getChildren().add(previewView);
createKeyBindings();
previewView.setLayout(previewPreferences.getSelectedPreviewLayout());
}
private void createKeyBindings() {
previewView.addEventFilter(KeyEvent.KEY_PRESSED, event -> {
Optional<KeyBinding> keyBinding = keyBindingRepository.mapToKeyBinding(event);
if (keyBinding.isPresent()) {
switch (keyBinding.get()) {
case COPY_PREVIEW:
previewView.copyPreviewToClipBoard();
event.consume();
break;
default:
}
}
});
}
private ContextMenu createPopupMenu() {
MenuItem copyPreview = new MenuItem(Localization.lang("Copy preview"), IconTheme.JabRefIcons.COPY.getGraphicNode());
keyBindingRepository.getKeyCombination(KeyBinding.COPY_PREVIEW).ifPresent(copyPreview::setAccelerator);
copyPreview.setOnAction(event -> previewView.copyPreviewToClipBoard());
MenuItem copySelection = new MenuItem(Localization.lang("Copy selection"));
copySelection.setOnAction(event -> previewView.copySelectionToClipBoard());
MenuItem printEntryPreview = new MenuItem(Localization.lang("Print entry preview"), IconTheme.JabRefIcons.PRINTED.getGraphicNode());
printEntryPreview.setOnAction(event -> previewView.print());
MenuItem previousPreviewLayout = new MenuItem(Localization.lang("Previous preview layout"));
keyBindingRepository.getKeyCombination(KeyBinding.PREVIOUS_PREVIEW_LAYOUT).ifPresent(previousPreviewLayout::setAccelerator);
previousPreviewLayout.setOnAction(event -> this.previousPreviewStyle());
MenuItem nextPreviewLayout = new MenuItem(Localization.lang("Next preview layout"));
keyBindingRepository.getKeyCombination(KeyBinding.NEXT_PREVIEW_LAYOUT).ifPresent(nextPreviewLayout::setAccelerator);
nextPreviewLayout.setOnAction(event -> this.nextPreviewStyle());
ContextMenu menu = new ContextMenu();
menu.getItems().add(copyPreview);
menu.getItems().add(copySelection);
menu.getItems().add(printEntryPreview);
menu.getItems().add(new SeparatorMenuItem());
menu.getItems().add(nextPreviewLayout);
menu.getItems().add(previousPreviewLayout);
return menu;
}
public void setEntry(BibEntry entry) {
this.entry = entry;
previewView.setLayout(previewPreferences.getSelectedPreviewLayout());
previewView.setEntry(entry);
}
public void print() {
previewView.print();
}
public void nextPreviewStyle() {
cyclePreview(previewPreferences.getLayoutCyclePosition() + 1);
}
public void previousPreviewStyle() {
cyclePreview(previewPreferences.getLayoutCyclePosition() - 1);
}
private void cyclePreview(int newPosition) {
previewPreferences.setLayoutCyclePosition(newPosition);
PreviewLayout layout = previewPreferences.getSelectedPreviewLayout();
previewView.setLayout(layout);
dialogService.notify(Localization.lang("Preview style changed to: %0", layout.getDisplayName()));
}
}
| 7,887
| 42.58011
| 140
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/preview/PreviewViewer.java
|
package org.jabref.gui.preview;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Pattern;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.value.ChangeListener;
import javafx.concurrent.Worker;
import javafx.print.PrinterJob;
import javafx.scene.control.ScrollPane;
import javafx.scene.input.ClipboardContent;
import javafx.scene.web.WebView;
import org.jabref.gui.ClipBoardManager;
import org.jabref.gui.DialogService;
import org.jabref.gui.Globals;
import org.jabref.gui.StateManager;
import org.jabref.gui.desktop.JabRefDesktop;
import org.jabref.gui.theme.ThemeManager;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.layout.format.Number;
import org.jabref.logic.preview.PreviewLayout;
import org.jabref.logic.search.SearchQuery;
import org.jabref.logic.util.WebViewStore;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.events.EventTarget;
import org.w3c.dom.html.HTMLAnchorElement;
/**
* Displays an BibEntry using the given layout format.
*/
public class PreviewViewer extends ScrollPane implements InvalidationListener {
private static final Logger LOGGER = LoggerFactory.getLogger(PreviewViewer.class);
// https://stackoverflow.com/questions/5669448/get-selected-texts-html-in-div/5670825#5670825
private static final String JS_GET_SELECTION_HTML_SCRIPT = """
function getSelectionHtml() {
var html = "";
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
html = container.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
return html;
}
getSelectionHtml();
""";
private static final String JS_HIGHLIGHT_FUNCTION =
"""
<head>
<meta charset="UTF-8">
<style>
mark{
background: orange;
color: black;
}
</style>
<script type="text/javascript">
/*!***************************************************
* mark.js v9.0.0
* https://markjs.io/
* Copyright (c) 2014–2018, Julian Kühnel
* Released under the MIT license https://git.io/vwTVl
*****************************************************/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.Mark=t()}(this,function(){"use strict";function e(t){return(e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(t)}function t(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function r(e,t,r){return t&&n(e.prototype,t),r&&n(e,r),e}function o(){return(o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(this,arguments)}var i=
/* */
function(){function e(n){var r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:5e3;t(this,e),this.ctx=n,this.iframes=r,this.exclude=o,this.iframesTimeout=i}return r(e,[{key:"getContexts",value:function(){var e=[];return(void 0!==this.ctx&&this.ctx?NodeList.prototype.isPrototypeOf(this.ctx)?Array.prototype.slice.call(this.ctx):Array.isArray(this.ctx)?this.ctx:"string"==typeof this.ctx?Array.prototype.slice.call(document.querySelectorAll(this.ctx)):[this.ctx]:[]).forEach(function(t){var n=e.filter(function(e){return e.contains(t)}).length>0;-1!==e.indexOf(t)||n||e.push(t)}),e}},{key:"getIframeContents",value:function(e,t){var n,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){};try{var o=e.contentWindow;if(n=o.document,!o||!n)throw new Error("iframe inaccessible")}catch(e){r()}n&&t(n)}},{key:"isIframeBlank",value:function(e){var t="about:blank",n=e.getAttribute("src").trim();return e.contentWindow.location.href===t&&n!==t&&n}},{key:"observeIframeLoad",value:function(e,t,n){var r=this,o=!1,i=null,a=function a(){if(!o){o=!0,clearTimeout(i);try{r.isIframeBlank(e)||(e.removeEventListener("load",a),r.getIframeContents(e,t,n))}catch(e){n()}}};e.addEventListener("load",a),i=setTimeout(a,this.iframesTimeout)}},{key:"onIframeReady",value:function(e,t,n){try{"complete"===e.contentWindow.document.readyState?this.isIframeBlank(e)?this.observeIframeLoad(e,t,n):this.getIframeContents(e,t,n):this.observeIframeLoad(e,t,n)}catch(e){n()}}},{key:"waitForIframes",value:function(e,t){var n=this,r=0;this.forEachIframe(e,function(){return!0},function(e){r++,n.waitForIframes(e.querySelector("html"),function(){--r||t()})},function(e){e||t()})}},{key:"forEachIframe",value:function(t,n,r){var o=this,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:function(){},a=t.querySelectorAll("iframe"),s=a.length,c=0;a=Array.prototype.slice.call(a);var u=function(){--s<=0&&i(c)};s||u(),a.forEach(function(t){e.matches(t,o.exclude)?u():o.onIframeReady(t,function(e){n(t)&&(c++,r(e)),u()},u)})}},{key:"createIterator",value:function(e,t,n){return document.createNodeIterator(e,t,n,!1)}},{key:"createInstanceOnIframe",value:function(t){return new e(t.querySelector("html"),this.iframes)}},{key:"compareNodeIframe",value:function(e,t,n){if(e.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_PRECEDING){if(null===t)return!0;if(t.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_FOLLOWING)return!0}return!1}},{key:"getIteratorNode",value:function(e){var t=e.previousNode();return{prevNode:t,node:null===t?e.nextNode():e.nextNode()&&e.nextNode()}}},{key:"checkIframeFilter",value:function(e,t,n,r){var o=!1,i=!1;return r.forEach(function(e,t){e.val===n&&(o=t,i=e.handled)}),this.compareNodeIframe(e,t,n)?(!1!==o||i?!1===o||i||(r[o].handled=!0):r.push({val:n,handled:!0}),!0):(!1===o&&r.push({val:n,handled:!1}),!1)}},{key:"handleOpenIframes",value:function(e,t,n,r){var o=this;e.forEach(function(e){e.handled||o.getIframeContents(e.val,function(e){o.createInstanceOnIframe(e).forEachNode(t,n,r)})})}},{key:"iterateThroughNodes",value:function(e,t,n,r,o){for(var i,a,s,c=this,u=this.createIterator(t,e,r),l=[],h=[];s=void 0,s=c.getIteratorNode(u),a=s.prevNode,i=s.node;)this.iframes&&this.forEachIframe(t,function(e){return c.checkIframeFilter(i,a,e,l)},function(t){c.createInstanceOnIframe(t).forEachNode(e,function(e){return h.push(e)},r)}),h.push(i);h.forEach(function(e){n(e)}),this.iframes&&this.handleOpenIframes(l,e,n,r),o()}},{key:"forEachNode",value:function(e,t,n){var r=this,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:function(){},i=this.getContexts(),a=i.length;a||o(),i.forEach(function(i){var s=function(){r.iterateThroughNodes(e,i,t,n,function(){--a<=0&&o()})};r.iframes?r.waitForIframes(i,s):s()})}}],[{key:"matches",value:function(e,t){var n="string"==typeof t?[t]:t,r=e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.oMatchesSelector||e.webkitMatchesSelector;if(r){var o=!1;return n.every(function(t){return!r.call(e,t)||(o=!0,!1)}),o}return!1}}]),e}(),a=
/* */
function(){function e(n){t(this,e),this.opt=o({},{diacritics:!0,synonyms:{},accuracy:"partially",caseSensitive:!1,ignoreJoiners:!1,ignorePunctuation:[],wildcards:"disabled"},n)}return r(e,[{key:"create",value:function(e){return"disabled"!==this.opt.wildcards&&(e=this.setupWildcardsRegExp(e)),e=this.escapeStr(e),Object.keys(this.opt.synonyms).length&&(e=this.createSynonymsRegExp(e)),(this.opt.ignoreJoiners||this.opt.ignorePunctuation.length)&&(e=this.setupIgnoreJoinersRegExp(e)),this.opt.diacritics&&(e=this.createDiacriticsRegExp(e)),e=this.createMergedBlanksRegExp(e),(this.opt.ignoreJoiners||this.opt.ignorePunctuation.length)&&(e=this.createJoinersRegExp(e)),"disabled"!==this.opt.wildcards&&(e=this.createWildcardsRegExp(e)),e=this.createAccuracyRegExp(e),new RegExp(e,"gm".concat(this.opt.caseSensitive?"":"i"))}},{key:"sortByLength",value:function(e){return e.sort(function(e,t){return e.length===t.length?e>t?1:-1:t.length-e.length})}},{key:"escapeStr",value:function(e){return e.replace(/[\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\\\^\\$\\|]/g,"\\\\$&")}},{key:"createSynonymsRegExp",value:function(e){var t=this,n=this.opt.synonyms,r=this.opt.caseSensitive?"":"i",o=this.opt.ignoreJoiners||this.opt.ignorePunctuation.length?"\\0":"";for(var i in n)if(n.hasOwnProperty(i)){var a=Array.isArray(n[i])?n[i]:[n[i]];a.unshift(i),(a=this.sortByLength(a).map(function(e){return"disabled"!==t.opt.wildcards&&(e=t.setupWildcardsRegExp(e)),e=t.escapeStr(e)}).filter(function(e){return""!==e})).length>1&&(e=e.replace(new RegExp("(".concat(a.map(function(e){return t.escapeStr(e)}).join("|"),")"),"gm".concat(r)),o+"(".concat(a.map(function(e){return t.processSynonyms(e)}).join("|"),")")+o))}return e}},{key:"processSynonyms",value:function(e){return(this.opt.ignoreJoiners||this.opt.ignorePunctuation.length)&&(e=this.setupIgnoreJoinersRegExp(e)),e}},{key:"setupWildcardsRegExp",value:function(e){return(e=e.replace(/(?:\\\\)*\\?/g,function(e){return"\\\\"===e.charAt(0)?"?":"\u0001"})).replace(/(?:\\\\)*\\*/g,function(e){return"\\\\"===e.charAt(0)?"*":"\u0002"})}},{key:"createWildcardsRegExp",value:function(e){var t="withSpaces"===this.opt.wildcards;return e.replace(/\\u0001/g,t?"[\\\\S\\\\s]?":"\\\\S?").replace(/\\u0002/g,t?"[\\\\S\\\\s]*?":"\\\\S*")}},{key:"setupIgnoreJoinersRegExp",value:function(e){return e.replace(/[^(|)\\\\]/g,function(e,t,n){var r=n.charAt(t+1);return/[(|)\\\\]/.test(r)||""===r?e:e+"\\0"})}},{key:"createJoinersRegExp",value:function(e){var t=[],n=this.opt.ignorePunctuation;return Array.isArray(n)&&n.length&&t.push(this.escapeStr(n.join(""))),this.opt.ignoreJoiners&&t.push("\\\\u00ad\\\\u200b\\\\u200c\\\\u200d"),t.length?e.split(/\\u0000+/).join("[".concat(t.join(""),"]*")):e}},{key:"createDiacriticsRegExp",value:function(e){var t=this.opt.caseSensitive?"":"i",n=this.opt.caseSensitive?["aàáảãạăằắẳẵặâầấẩẫậäåāą","AÀÁẢÃẠĂẰẮẲẴẶÂẦẤẨẪẬÄÅĀĄ","cçćč","CÇĆČ","dđď","DĐĎ","eèéẻẽẹêềếểễệëěēę","EÈÉẺẼẸÊỀẾỂỄỆËĚĒĘ","iìíỉĩịîïī","IÌÍỈĨỊÎÏĪ","lł","LŁ","nñňń","NÑŇŃ","oòóỏõọôồốổỗộơởỡớờợöøō","OÒÓỎÕỌÔỒỐỔỖỘƠỞỠỚỜỢÖØŌ","rř","RŘ","sšśșş","SŠŚȘŞ","tťțţ","TŤȚŢ","uùúủũụưừứửữựûüůū","UÙÚỦŨỤƯỪỨỬỮỰÛÜŮŪ","yýỳỷỹỵÿ","YÝỲỶỸỴŸ","zžżź","ZŽŻŹ"]:["aàáảãạăằắẳẵặâầấẩẫậäåāąAÀÁẢÃẠĂẰẮẲẴẶÂẦẤẨẪẬÄÅĀĄ","cçćčCÇĆČ","dđďDĐĎ","eèéẻẽẹêềếểễệëěēęEÈÉẺẼẸÊỀẾỂỄỆËĚĒĘ","iìíỉĩịîïīIÌÍỈĨỊÎÏĪ","lłLŁ","nñňńNÑŇŃ","oòóỏõọôồốổỗộơởỡớờợöøōOÒÓỎÕỌÔỒỐỔỖỘƠỞỠỚỜỢÖØŌ","rřRŘ","sšśșşSŠŚȘŞ","tťțţTŤȚŢ","uùúủũụưừứửữựûüůūUÙÚỦŨỤƯỪỨỬỮỰÛÜŮŪ","yýỳỷỹỵÿYÝỲỶỸỴŸ","zžżźZŽŻŹ"],r=[];return e.split("").forEach(function(o){n.every(function(n){if(-1!==n.indexOf(o)){if(r.indexOf(n)>-1)return!1;e=e.replace(new RegExp("[".concat(n,"]"),"gm".concat(t)),"[".concat(n,"]")),r.push(n)}return!0})}),e}},{key:"createMergedBlanksRegExp",value:function(e){return e.replace(/[\\s]+/gim,"[\\\\s]+")}},{key:"createAccuracyRegExp",value:function(e){var t=this,n=this.opt.accuracy,r="string"==typeof n?n:n.value,o="string"==typeof n?[]:n.limiters,i="";switch(o.forEach(function(e){i+="|".concat(t.escapeStr(e))}),r){case"partially":default:return"()(".concat(e,")");case"complementary":return i="\\\\s"+(i||this.escapeStr("!\\"#$%&'()*+,-./:;<=>?@[\\\\]^_`{|}~¡¿")),"()([^".concat(i,"]*").concat(e,"[^").concat(i,"]*)");case"exactly":return"(^|\\\\s".concat(i,")(").concat(e,")(?=$|\\\\s").concat(i,")")}}}]),e}(),s=
/* */
function(){function n(e){t(this,n),this.ctx=e,this.ie=!1;var r=window.navigator.userAgent;(r.indexOf("MSIE")>-1||r.indexOf("Trident")>-1)&&(this.ie=!0)}return r(n,[{key:"log",value:function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"debug",r=this.opt.log;this.opt.debug&&"object"===e(r)&&"function"==typeof r[n]&&r[n]("mark.js: ".concat(t))}},{key:"getSeparatedKeywords",value:function(e){var t=this,n=[];return e.forEach(function(e){t.opt.separateWordSearch?e.split(" ").forEach(function(e){e.trim()&&-1===n.indexOf(e)&&n.push(e)}):e.trim()&&-1===n.indexOf(e)&&n.push(e)}),{keywords:n.sort(function(e,t){return t.length-e.length}),length:n.length}}},{key:"isNumeric",value:function(e){return Number(parseFloat(e))==e}},{key:"checkRanges",value:function(e){var t=this;if(!Array.isArray(e)||"[object Object]"!==Object.prototype.toString.call(e[0]))return this.log("markRanges() will only accept an array of objects"),this.opt.noMatch(e),[];var n=[],r=0;return e.sort(function(e,t){return e.start-t.start}).forEach(function(e){var o=t.callNoMatchOnInvalidRanges(e,r),i=o.start,a=o.end;o.valid&&(e.start=i,e.length=a-i,n.push(e),r=a)}),n}},{key:"callNoMatchOnInvalidRanges",value:function(e,t){var n,r,o=!1;return e&&void 0!==e.start?(r=(n=parseInt(e.start,10))+parseInt(e.length,10),this.isNumeric(e.start)&&this.isNumeric(e.length)&&r-t>0&&r-n>0?o=!0:(this.log("Ignoring invalid or overlapping range: "+"".concat(JSON.stringify(e))),this.opt.noMatch(e))):(this.log("Ignoring invalid range: ".concat(JSON.stringify(e))),this.opt.noMatch(e)),{start:n,end:r,valid:o}}},{key:"checkWhitespaceRanges",value:function(e,t,n){var r,o=!0,i=n.length,a=t-i,s=parseInt(e.start,10)-a;return(r=(s=s>i?i:s)+parseInt(e.length,10))>i&&(r=i,this.log("End range automatically set to the max value of ".concat(i))),s<0||r-s<0||s>i||r>i?(o=!1,this.log("Invalid range: ".concat(JSON.stringify(e))),this.opt.noMatch(e)):""===n.substring(s,r).replace(/\\s+/g,"")&&(o=!1,this.log("Skipping whitespace only range: "+JSON.stringify(e)),this.opt.noMatch(e)),{start:s,end:r,valid:o}}},{key:"getTextNodes",value:function(e){var t=this,n="",r=[];this.iterator.forEachNode(NodeFilter.SHOW_TEXT,function(e){r.push({start:n.length,end:(n+=e.textContent).length,node:e})},function(e){return t.matchesExclude(e.parentNode)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT},function(){e({value:n,nodes:r})})}},{key:"matchesExclude",value:function(e){return i.matches(e,this.opt.exclude.concat(["script","style","title","head","html"]))}},{key:"wrapRangeInTextNode",value:function(e,t,n){var r=this.opt.element?this.opt.element:"mark",o=e.splitText(t),i=o.splitText(n-t),a=document.createElement(r);return a.setAttribute("data-markjs","true"),this.opt.className&&a.setAttribute("class",this.opt.className),a.textContent=o.textContent,o.parentNode.replaceChild(a,o),i}},{key:"wrapRangeInMappedTextNode",value:function(e,t,n,r,o){var i=this;e.nodes.every(function(a,s){var c=e.nodes[s+1];if(void 0===c||c.start>t){if(!r(a.node))return!1;var u=t-a.start,l=(n>a.end?a.end:n)-a.start,h=e.value.substr(0,a.start),f=e.value.substr(l+a.start);if(a.node=i.wrapRangeInTextNode(a.node,u,l),e.value=h+f,e.nodes.forEach(function(t,n){n>=s&&(e.nodes[n].start>0&&n!==s&&(e.nodes[n].start-=l),e.nodes[n].end-=l)}),n-=l,o(a.node.previousSibling,a.start),!(n>a.end))return!1;t=a.end}return!0})}},{key:"wrapGroups",value:function(e,t,n,r){return r((e=this.wrapRangeInTextNode(e,t,t+n)).previousSibling),e}},{key:"separateGroups",value:function(e,t,n,r,o){for(var i=t.length,a=1;a<i;a++){var s=e.textContent.indexOf(t[a]);t[a]&&s>-1&&r(t[a],e)&&(e=this.wrapGroups(e,s,t[a].length,o))}return e}},{key:"wrapMatches",value:function(e,t,n,r,o){var i=this,a=0===t?0:t+1;this.getTextNodes(function(t){t.nodes.forEach(function(t){var o;for(t=t.node;null!==(o=e.exec(t.textContent))&&""!==o[a];){if(i.opt.separateGroups)t=i.separateGroups(t,o,a,n,r);else{if(!n(o[a],t))continue;var s=o.index;if(0!==a)for(var c=1;c<a;c++)s+=o[c].length;t=i.wrapGroups(t,s,o[a].length,r)}e.lastIndex=0}}),o()})}},{key:"wrapMatchesAcrossElements",value:function(e,t,n,r,o){var i=this,a=0===t?0:t+1;this.getTextNodes(function(t){for(var s;null!==(s=e.exec(t.value))&&""!==s[a];){var c=s.index;if(0!==a)for(var u=1;u<a;u++)c+=s[u].length;var l=c+s[a].length;i.wrapRangeInMappedTextNode(t,c,l,function(e){return n(s[a],e)},function(t,n){e.lastIndex=n,r(t)})}o()})}},{key:"wrapRangeFromIndex",value:function(e,t,n,r){var o=this;this.getTextNodes(function(i){var a=i.value.length;e.forEach(function(e,r){var s=o.checkWhitespaceRanges(e,a,i.value),c=s.start,u=s.end;s.valid&&o.wrapRangeInMappedTextNode(i,c,u,function(n){return t(n,e,i.value.substring(c,u),r)},function(t){n(t,e)})}),r()})}},{key:"unwrapMatches",value:function(e){for(var t=e.parentNode,n=document.createDocumentFragment();e.firstChild;)n.appendChild(e.removeChild(e.firstChild));t.replaceChild(n,e),this.ie?this.normalizeTextNode(t):t.normalize()}},{key:"normalizeTextNode",value:function(e){if(e){if(3===e.nodeType)for(;e.nextSibling&&3===e.nextSibling.nodeType;)e.nodeValue+=e.nextSibling.nodeValue,e.parentNode.removeChild(e.nextSibling);else this.normalizeTextNode(e.firstChild);this.normalizeTextNode(e.nextSibling)}}},{key:"markRegExp",value:function(e,t){var n=this;this.opt=t,this.log('Searching with expression "'.concat(e,'"'));var r=0,o="wrapMatches";this.opt.acrossElements&&(o="wrapMatchesAcrossElements"),this[o](e,this.opt.ignoreGroups,function(e,t){return n.opt.filter(t,e,r)},function(e){r++,n.opt.each(e)},function(){0===r&&n.opt.noMatch(e),n.opt.done(r)})}},{key:"mark",value:function(e,t){var n=this;this.opt=t;var r=0,o="wrapMatches",i=this.getSeparatedKeywords("string"==typeof e?[e]:e),s=i.keywords,c=i.length;this.opt.acrossElements&&(o="wrapMatchesAcrossElements"),0===c?this.opt.done(r):function e(t){var i=new a(n.opt).create(t),u=0;n.log('Searching with expression "'.concat(i,'"')),n[o](i,1,function(e,o){return n.opt.filter(o,t,r,u)},function(e){u++,r++,n.opt.each(e)},function(){0===u&&n.opt.noMatch(t),s[c-1]===t?n.opt.done(r):e(s[s.indexOf(t)+1])})}(s[0])}},{key:"markRanges",value:function(e,t){var n=this;this.opt=t;var r=0,o=this.checkRanges(e);o&&o.length?(this.log("Starting to mark with the following ranges: "+JSON.stringify(o)),this.wrapRangeFromIndex(o,function(e,t,r,o){return n.opt.filter(e,t,r,o)},function(e,t){r++,n.opt.each(e,t)},function(){n.opt.done(r)})):this.opt.done(r)}},{key:"unmark",value:function(e){var t=this;this.opt=e;var n=this.opt.element?this.opt.element:"*";n+="[data-markjs]",this.opt.className&&(n+=".".concat(this.opt.className)),this.log('Removal selector "'.concat(n,'"')),this.iterator.forEachNode(NodeFilter.SHOW_ELEMENT,function(e){t.unwrapMatches(e)},function(e){var r=i.matches(e,n),o=t.matchesExclude(e);return!r||o?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT},this.opt.done)}},{key:"opt",set:function(e){this._opt=o({},{element:"",className:"",exclude:[],iframes:!1,iframesTimeout:5e3,separateWordSearch:!0,acrossElements:!1,ignoreGroups:0,each:function(){},noMatch:function(){},filter:function(){return!0},done:function(){},debug:!1,log:window.console},e)},get:function(){return this._opt}},{key:"iterator",get:function(){return new i(this.ctx,this.opt.iframes,this.opt.exclude,this.opt.iframesTimeout)}}]),n}();return function(e){var t=this,n=new s(e);return this.mark=function(e,r){return n.mark(e,r),t},this.markRegExp=function(e,r){return n.markRegExp(e,r),t},this.markRanges=function(e,r){return n.markRanges(e,r),t},this.unmark=function(e){return n.unmark(e),t},this}});
</script>
</head>""";
// This is a string format, and it takes a variable name as an argument to pass to the markInstance.markRegExp() Javascript method.
private static final String JS_MARK_REG_EXP_CALLBACK =
"""
{done: function(){
markInstance.markRegExp(%s);}
}""";
// This is a string format, and it takes a variable name as an argument to pass to the markInstance.unmark() Javascript method.
private static final String JS_UNMARK_WITH_CALLBACK =
"""
var markInstance = new Mark(document.getElementById("content"));
markInstance.unmark(%s);""";
private static final Pattern UNESCAPED_FORWARD_SLASH = Pattern.compile("(?<!\\\\)/");
private final ClipBoardManager clipBoardManager;
private final DialogService dialogService;
private final TaskExecutor taskExecutor = Globals.TASK_EXECUTOR;
private final WebView previewView;
private PreviewLayout layout;
/**
* The entry currently shown
*/
private Optional<BibEntry> entry = Optional.empty();
private Optional<Pattern> searchHighlightPattern = Optional.empty();
private final BibDatabaseContext database;
private boolean registered;
private final ChangeListener<Optional<SearchQuery>> listener = (queryObservable, queryOldValue, queryNewValue) -> {
searchHighlightPattern = queryNewValue.flatMap(SearchQuery::getJavaScriptPatternForWords);
highlightSearchPattern();
};
/**
* @param database Used for resolving strings and pdf directories for links.
*/
public PreviewViewer(BibDatabaseContext database,
DialogService dialogService,
StateManager stateManager,
ThemeManager themeManager) {
this.database = Objects.requireNonNull(database);
this.dialogService = dialogService;
this.clipBoardManager = Globals.getClipboardManager();
setFitToHeight(true);
setFitToWidth(true);
previewView = WebViewStore.get();
setContent(previewView);
previewView.setContextMenuEnabled(false);
previewView.getEngine().getLoadWorker().stateProperty().addListener((observable, oldValue, newValue) -> {
if (newValue != Worker.State.SUCCEEDED) {
return;
}
if (!registered) {
stateManager.activeSearchQueryProperty().addListener(listener);
registered = true;
}
highlightSearchPattern();
// https://stackoverflow.com/questions/15555510/javafx-stop-opening-url-in-webview-open-in-browser-instead
NodeList anchorList = previewView.getEngine().getDocument().getElementsByTagName("a");
for (int i = 0; i < anchorList.getLength(); i++) {
Node node = anchorList.item(i);
EventTarget eventTarget = (EventTarget) node;
eventTarget.addEventListener("click", evt -> {
EventTarget target = evt.getCurrentTarget();
HTMLAnchorElement anchorElement = (HTMLAnchorElement) target;
String href = anchorElement.getHref();
if (href != null) {
try {
JabRefDesktop.openBrowser(href);
} catch (MalformedURLException exception) {
LOGGER.error("Invalid URL", exception);
} catch (IOException exception) {
LOGGER.error("Invalid URL Input", exception);
}
}
evt.preventDefault();
}, false);
}
});
themeManager.installCss(previewView.getEngine());
}
private void highlightSearchPattern() {
String callbackForUnmark = "";
if (searchHighlightPattern.isPresent()) {
String javaScriptRegex = createJavaScriptRegex(searchHighlightPattern.get());
callbackForUnmark = String.format(JS_MARK_REG_EXP_CALLBACK, javaScriptRegex);
}
String unmarkInstance = String.format(JS_UNMARK_WITH_CALLBACK, callbackForUnmark);
previewView.getEngine().executeScript(unmarkInstance);
}
/**
* Returns the String representation of a JavaScript regex object. The method does not take into account differences between the regex implementations in Java and JavaScript.
*
* @param regex Java regex to print as a JavaScript regex
* @return JavaScript regex object
*/
private static String createJavaScriptRegex(Pattern regex) {
String pattern = regex.pattern();
// Create a JavaScript regular expression literal (https://ecma-international.org/ecma-262/10.0/index.html#sec-literals-regular-expression-literals)
// Forward slashes are reserved to delimit the regular expression body. Hence, they must be escaped.
pattern = UNESCAPED_FORWARD_SLASH.matcher(pattern).replaceAll("\\\\/");
return "/" + pattern + "/gmi";
}
public void setLayout(PreviewLayout newLayout) {
// Change listeners might set the layout to null while the update method is executing, therefore we need to prevent this here
if (newLayout == null) {
return;
}
layout = newLayout;
update();
}
public void setEntry(BibEntry newEntry) {
// Remove update listener for old entry
entry.ifPresent(oldEntry -> {
for (Observable observable : oldEntry.getObservables()) {
observable.removeListener(this);
}
});
entry = Optional.of(newEntry);
// Register for changes
for (Observable observable : newEntry.getObservables()) {
observable.addListener(this);
}
update();
}
private void update() {
if (entry.isEmpty() || (layout == null)) {
// Make sure that the preview panel is not completely white, especially with dark theme on
setPreviewText("");
return;
}
Number.serialExportNumber = 1; // Set entry number in case that is included in the preview layout.
BackgroundTask
.wrap(() -> layout.generatePreview(entry.get(), database))
.onRunning(() -> setPreviewText("<i>" + Localization.lang("Processing %0", Localization.lang("Citation Style")) + ": " + layout.getDisplayName() + " ..." + "</i>"))
.onSuccess(this::setPreviewText)
.onFailure(exception -> {
LOGGER.error("Error while generating citation style", exception);
setPreviewText(Localization.lang("Error while generating citation style"));
})
.executeWith(taskExecutor);
}
private void setPreviewText(String text) {
String myText = String.format("""
<html>
%s
<body id="previewBody">
<div id="content"> %s </div>
</body>
</html>
""", JS_HIGHLIGHT_FUNCTION, text);
previewView.getEngine().setJavaScriptEnabled(true);
previewView.getEngine().loadContent(myText);
this.setHvalue(0);
}
public void print() {
PrinterJob job = PrinterJob.createPrinterJob();
boolean proceed = dialogService.showPrintDialog(job);
if (!proceed) {
return;
}
BackgroundTask
.wrap(() -> {
job.getJobSettings().setJobName(entry.flatMap(BibEntry::getCitationKey).orElse("NO ENTRY"));
previewView.getEngine().print(job);
job.endJob();
})
.onFailure(exception -> dialogService.showErrorDialogAndWait(Localization.lang("Could not print preview"), exception))
.executeWith(taskExecutor);
}
public void copyPreviewToClipBoard() {
Document document = previewView.getEngine().getDocument();
ClipboardContent content = new ClipboardContent();
content.putString(document.getElementById("content").getTextContent());
content.putHtml((String) previewView.getEngine().executeScript("document.documentElement.outerHTML"));
clipBoardManager.setContent(content);
}
public void copySelectionToClipBoard() {
ClipboardContent content = new ClipboardContent();
content.putString(getSelectionTextContent());
content.putHtml(getSelectionHtmlContent());
clipBoardManager.setContent(content);
}
@Override
public void invalidated(Observable observable) {
update();
}
public String getSelectionTextContent() {
return (String) previewView.getEngine().executeScript("window.getSelection().toString()");
}
public String getSelectionHtmlContent() {
return (String) previewView.getEngine().executeScript(JS_GET_SELECTION_HTML_SCRIPT);
}
}
| 30,686
| 92.557927
| 7,578
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/push/AbstractPushToApplication.java
|
package org.jabref.gui.push;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import org.jabref.gui.DialogService;
import org.jabref.gui.actions.Action;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.icon.JabRefIcon;
import org.jabref.gui.keyboard.KeyBinding;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.OS;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.preferences.PreferencesService;
import org.jabref.preferences.PushToApplicationPreferences;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Abstract class for pushing entries into different editors.
*/
public abstract class AbstractPushToApplication implements PushToApplication {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractPushToApplication.class);
protected boolean couldNotCall; // Set to true in case the command could not be executed, e.g., if the file is not found
protected boolean couldNotConnect; // Set to true in case the tunnel to the program (if one is used) does not operate
protected boolean notDefined; // Set to true if the corresponding path is not defined in the preferences
protected String commandPath;
protected final DialogService dialogService;
protected final PreferencesService preferencesService;
public AbstractPushToApplication(DialogService dialogService, PreferencesService preferencesService) {
this.dialogService = dialogService;
this.preferencesService = preferencesService;
}
@Override
public JabRefIcon getApplicationIcon() {
return IconTheme.JabRefIcons.APPLICATION_GENERIC;
}
@Override
public String getTooltip() {
return Localization.lang("Push entries to external application (%0)", getDisplayName());
}
@Override
public Action getAction() {
return new PushToApplicationAction();
}
@Override
public void pushEntries(BibDatabaseContext database, List<BibEntry> entries, String keyString) {
couldNotConnect = false;
couldNotCall = false;
notDefined = false;
commandPath = preferencesService.getPushToApplicationPreferences().getCommandPaths().get(this.getDisplayName());
// Check if a path to the command has been specified
if ((commandPath == null) || commandPath.trim().isEmpty()) {
notDefined = true;
return;
}
// Execute command
try {
if (OS.OS_X) {
String[] commands = getCommandLine(keyString);
if (commands.length < 3) {
LOGGER.error("Commandline does not contain enough parameters to \"push to application\"");
return;
}
ProcessBuilder processBuilder = new ProcessBuilder(
"open",
"-a",
commands[0],
"-n",
"--args",
commands[1],
commands[2]
);
processBuilder.start();
} else {
ProcessBuilder processBuilder = new ProcessBuilder(getCommandLine(keyString));
processBuilder.start();
}
} catch (IOException excep) {
LOGGER.warn("Error: Could not call executable '{}'", commandPath, excep);
couldNotCall = true;
}
}
@Override
public void onOperationCompleted() {
if (notDefined) {
dialogService.showErrorDialogAndWait(
Localization.lang("Error pushing entries"),
Localization.lang("Path to %0 not defined", getDisplayName()) + ".");
} else if (couldNotCall) {
dialogService.showErrorDialogAndWait(
Localization.lang("Error pushing entries"),
Localization.lang("Could not call executable") + " '" + commandPath + "'.");
} else if (couldNotConnect) {
dialogService.showErrorDialogAndWait(
Localization.lang("Error pushing entries"),
Localization.lang("Could not connect to %0", getDisplayName()) + ".");
} else {
dialogService.notify(Localization.lang("Pushed citations to %0", getDisplayName()) + ".");
}
}
@Override
public boolean requiresCitationKeys() {
return true;
}
/**
* Function to get the command to be executed for pushing keys to be cited
*
* @param keyString String containing the Bibtex keys to be pushed to the application
* @return String array with the command to call and its arguments
*/
@SuppressWarnings("unused")
protected String[] getCommandLine(String keyString) {
return new String[0];
}
/**
* Function to get the command name in case it is different from the application name
*
* @return String with the command name
*/
protected String getCommandName() {
return null;
}
protected String getCiteCommand() {
return preferencesService.getExternalApplicationsPreferences().getCiteCommand();
}
public PushToApplicationSettings getSettings(PushToApplication application, PushToApplicationPreferences preferences) {
return new PushToApplicationSettings(application, dialogService, preferencesService.getFilePreferences(), preferences);
}
protected class PushToApplicationAction implements Action {
@Override
public String getText() {
return Localization.lang("Push entries to external application (%0)", getDisplayName());
}
@Override
public Optional<JabRefIcon> getIcon() {
return Optional.of(getApplicationIcon());
}
@Override
public Optional<KeyBinding> getKeyBinding() {
return Optional.of(KeyBinding.PUSH_TO_APPLICATION);
}
}
}
| 6,058
| 34.852071
| 127
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/push/PushToApplication.java
|
package org.jabref.gui.push;
import java.util.List;
import org.jabref.gui.actions.Action;
import org.jabref.gui.icon.JabRefIcon;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.preferences.PushToApplicationPreferences;
/**
* Class that defines interaction with an external application in the form of "pushing" selected entries to it.
*/
public interface PushToApplication {
String getDisplayName();
String getTooltip();
JabRefIcon getApplicationIcon();
/**
* The actual operation. This method will not be called on the event dispatch thread, so it should not do GUI
* operations without utilizing invokeLater().
*/
void pushEntries(BibDatabaseContext database, List<BibEntry> entries, String keyString);
/**
* Reporting etc., this method is called on the event dispatch thread after pushEntries() returns.
*/
void onOperationCompleted();
/**
* Check whether this operation requires citation keys to be set for the entries. If true is returned an error message
* will be displayed if keys are missing.
*
* @return true if citation keys are required for this operation.
*/
boolean requiresCitationKeys();
Action getAction();
PushToApplicationSettings getSettings(PushToApplication application, PushToApplicationPreferences pushToApplicationPreferences);
}
| 1,424
| 30.666667
| 132
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/push/PushToApplicationCommand.java
|
package org.jabref.gui.push;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import javafx.scene.control.ButtonBase;
import javafx.scene.control.MenuItem;
import org.jabref.gui.DialogService;
import org.jabref.gui.Globals;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.Action;
import org.jabref.gui.actions.ActionFactory;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.gui.util.BindingsHelper;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.strings.StringUtil;
import org.jabref.preferences.PreferencesService;
import com.tobiasdiez.easybind.EasyBind;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.jabref.gui.actions.ActionHelper.needsDatabase;
import static org.jabref.gui.actions.ActionHelper.needsEntriesSelected;
/**
* An Action class representing the process of invoking a PushToApplication operation.
*/
public class PushToApplicationCommand extends SimpleCommand {
private static final Logger LOGGER = LoggerFactory.getLogger(PushToApplicationCommand.class);
private final StateManager stateManager;
private final DialogService dialogService;
private final PreferencesService preferencesService;
private final List<Object> reconfigurableControls = new ArrayList<>();
private PushToApplication application;
public PushToApplicationCommand(StateManager stateManager, DialogService dialogService, PreferencesService preferencesService) {
this.stateManager = stateManager;
this.dialogService = dialogService;
this.preferencesService = preferencesService;
setApplication(preferencesService.getPushToApplicationPreferences()
.getActiveApplicationName());
EasyBind.subscribe(preferencesService.getPushToApplicationPreferences().activeApplicationNameProperty(),
this::setApplication);
this.executable.bind(needsDatabase(stateManager).and(needsEntriesSelected(stateManager)));
this.statusMessage.bind(BindingsHelper.ifThenElse(
this.executable,
"",
Localization.lang("This operation requires one or more entries to be selected.")));
}
public void registerReconfigurable(Object node) {
if (!(node instanceof MenuItem) && !(node instanceof ButtonBase)) {
LOGGER.error("Node must be either a MenuItem or a ButtonBase");
return;
}
this.reconfigurableControls.add(node);
}
private void setApplication(String applicationName) {
final ActionFactory factory = new ActionFactory(Globals.getKeyPrefs());
PushToApplication application = PushToApplications.getApplicationByName(
applicationName,
dialogService,
preferencesService)
.orElse(new PushToEmacs(dialogService, preferencesService));
preferencesService.getPushToApplicationPreferences().setActiveApplicationName(application.getDisplayName());
this.application = Objects.requireNonNull(application);
reconfigurableControls.forEach(object -> {
if (object instanceof MenuItem) {
factory.configureMenuItem(application.getAction(), this, (MenuItem) object);
} else if (object instanceof ButtonBase) {
factory.configureIconButton(application.getAction(), this, (ButtonBase) object);
}
});
}
public Action getAction() {
return application.getAction();
}
private static String getKeyString(List<BibEntry> entries) {
StringBuilder result = new StringBuilder();
Optional<String> citeKey;
boolean first = true;
for (BibEntry bes : entries) {
citeKey = bes.getCitationKey();
if (citeKey.isEmpty() || citeKey.get().isEmpty()) {
// Should never occur, because we made sure that all entries have keys
continue;
}
if (first) {
result.append(citeKey.get());
first = false;
} else {
result.append(',').append(citeKey.get());
}
}
return result.toString();
}
@Override
public void execute() {
// If required, check that all entries have citation keys defined:
if (application.requiresCitationKeys()) {
for (BibEntry entry : stateManager.getSelectedEntries()) {
if (StringUtil.isBlank(entry.getCitationKey())) {
dialogService.showErrorDialogAndWait(
application.getDisplayName(),
Localization.lang("This operation requires all selected entries to have citation keys defined."));
return;
}
}
}
// All set, call the operation in a new thread:
BackgroundTask.wrap(this::pushEntries)
.onSuccess(s -> application.onOperationCompleted())
.executeWith(Globals.TASK_EXECUTOR);
}
private void pushEntries() {
BibDatabaseContext database = stateManager.getActiveDatabase().orElseThrow(() -> new NullPointerException("Database null"));
application.pushEntries(database, stateManager.getSelectedEntries(), getKeyString(stateManager.getSelectedEntries()));
}
}
| 5,818
| 39.692308
| 132
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/push/PushToApplicationSettings.java
|
package org.jabref.gui.push;
import java.util.HashMap;
import java.util.Map;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import org.jabref.gui.DialogService;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.util.FileDialogConfiguration;
import org.jabref.logic.l10n.Localization;
import org.jabref.preferences.FilePreferences;
import org.jabref.preferences.PushToApplicationPreferences;
public class PushToApplicationSettings {
protected final Label commandLabel;
protected final TextField path;
protected final GridPane settingsPane;
protected final PushToApplicationPreferences preferences;
protected final AbstractPushToApplication application;
public PushToApplicationSettings(PushToApplication application,
DialogService dialogService,
FilePreferences filePreferences,
PushToApplicationPreferences preferences) {
this.application = (AbstractPushToApplication) application;
this.preferences = preferences;
settingsPane = new GridPane();
commandLabel = new Label();
path = new TextField();
Button browse = new Button();
settingsPane.setHgap(4.0);
settingsPane.setVgap(4.0);
browse.setTooltip(new Tooltip(Localization.lang("Browse")));
browse.setGraphic(IconTheme.JabRefIcons.OPEN.getGraphicNode());
browse.getStyleClass().addAll("icon-button", "narrow");
browse.setPrefHeight(20.0);
browse.setPrefWidth(20.0);
// In case the application name and the actual command is not the same, add the command in brackets
StringBuilder commandLine = new StringBuilder(Localization.lang("Path to %0", application.getDisplayName()));
if (this.application.getCommandName() == null) {
commandLine.append(':');
} else {
commandLine.append(" (").append(this.application.getCommandName()).append("):");
}
commandLabel.setText(commandLine.toString());
settingsPane.add(commandLabel, 0, 0);
path.setText(preferences.getCommandPaths().get(this.application.getDisplayName()));
settingsPane.add(path, 1, 0);
FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder()
.withInitialDirectory(filePreferences.getWorkingDirectory()).build();
browse.setOnAction(e -> dialogService.showFileOpenDialog(fileDialogConfiguration)
.ifPresent(f -> path.setText(f.toAbsolutePath().toString())));
settingsPane.add(browse, 2, 0);
ColumnConstraints textConstraints = new ColumnConstraints();
ColumnConstraints pathConstraints = new ColumnConstraints();
pathConstraints.setHgrow(Priority.ALWAYS);
ColumnConstraints browseConstraints = new ColumnConstraints(20.0);
browseConstraints.setHgrow(Priority.NEVER);
settingsPane.getColumnConstraints().addAll(textConstraints, pathConstraints, browseConstraints);
}
/**
* This method is called to indicate that the settings panel returned from the getSettingsPanel() method has been
* shown to the user and that the user has indicated that the settings should be stored. This method must store the
* state of the widgets in the settings panel to Globals.prefs.
*/
public void storeSettings() {
Map<String, String> commandPaths = new HashMap<>(preferences.getCommandPaths());
commandPaths.put(application.getDisplayName(), path.getText());
preferences.setCommandPaths(commandPaths);
}
public GridPane getSettingsPane() {
return this.settingsPane;
}
}
| 3,974
| 42.206522
| 119
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/push/PushToApplications.java
|
package org.jabref.gui.push;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.jabref.gui.DialogService;
import org.jabref.preferences.PreferencesService;
public class PushToApplications {
public static final String EMACS = "Emacs";
public static final String LYX = "LyX/Kile";
public static final String TEXMAKER = "Texmaker";
public static final String TEXSTUDIO = "TeXstudio";
public static final String VIM = "Vim";
public static final String WIN_EDT = "WinEdt";
private static final List<PushToApplication> APPLICATIONS = new ArrayList<>();
private PushToApplications() {
}
public static List<PushToApplication> getAllApplications(DialogService dialogService, PreferencesService preferencesService) {
if (!APPLICATIONS.isEmpty()) {
return APPLICATIONS;
}
APPLICATIONS.addAll(List.of(
new PushToEmacs(dialogService, preferencesService),
new PushToLyx(dialogService, preferencesService),
new PushToTexmaker(dialogService, preferencesService),
new PushToTeXstudio(dialogService, preferencesService),
new PushToVim(dialogService, preferencesService),
new PushToWinEdt(dialogService, preferencesService)));
return APPLICATIONS;
}
public static Optional<PushToApplication> getApplicationByName(String applicationName, DialogService dialogService, PreferencesService preferencesService) {
return getAllApplications(dialogService, preferencesService).stream()
.filter(application -> application.getDisplayName().equals(applicationName))
.findAny();
}
}
| 1,835
| 38.913043
| 160
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/push/PushToEmacs.java
|
package org.jabref.gui.push;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.jabref.gui.DialogService;
import org.jabref.gui.JabRefExecutorService;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.icon.JabRefIcon;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.util.OS;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.preferences.PreferencesService;
import org.jabref.preferences.PushToApplicationPreferences;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PushToEmacs extends AbstractPushToApplication {
public static final String NAME = PushToApplications.EMACS;
private static final Logger LOGGER = LoggerFactory.getLogger(PushToEmacs.class);
public PushToEmacs(DialogService dialogService, PreferencesService preferencesService) {
super(dialogService, preferencesService);
}
@Override
public String getDisplayName() {
return NAME;
}
@Override
public JabRefIcon getApplicationIcon() {
return IconTheme.JabRefIcons.APPLICATION_EMACS;
}
@Override
public void pushEntries(BibDatabaseContext database, List<BibEntry> entries, String keys) {
couldNotConnect = false;
couldNotCall = false;
notDefined = false;
commandPath = preferencesService.getPushToApplicationPreferences().getCommandPaths().get(this.getDisplayName());
if ((commandPath == null) || commandPath.trim().isEmpty()) {
notDefined = true;
return;
}
commandPath = preferencesService.getPushToApplicationPreferences().getCommandPaths().get(this.getDisplayName());
String[] addParams = preferencesService.getPushToApplicationPreferences().getEmacsArguments().split(" ");
try {
String[] com = new String[addParams.length + 2];
com[0] = commandPath;
System.arraycopy(addParams, 0, com, 1, addParams.length);
String prefix;
String suffix;
prefix = "(with-current-buffer (window-buffer) (insert ";
suffix = "))";
if (OS.WINDOWS) {
// Windows gnuclient/emacsclient escaping:
// java string: "(insert \\\"\\\\cite{Blah2001}\\\")";
// so cmd receives: (insert \"\\cite{Blah2001}\")
// so emacs receives: (insert "\cite{Blah2001}")
com[com.length - 1] = prefix.concat("\\\"\\" + getCiteCommand().replaceAll("\\\\", "\\\\\\\\") + "{" + keys + "}\\\"").concat(suffix);
} else {
// Linux gnuclient/emacslient escaping:
// java string: "(insert \"\\\\cite{Blah2001}\")"
// so sh receives: (insert "\\cite{Blah2001}")
// so emacs receives: (insert "\cite{Blah2001}")
com[com.length - 1] = prefix.concat("\"" + getCiteCommand().replaceAll("\\\\", "\\\\\\\\") + "{" + keys + "}\"").concat(suffix);
}
final Process p = Runtime.getRuntime().exec(com);
JabRefExecutorService.INSTANCE.executeAndWait(() -> {
try (InputStream out = p.getErrorStream()) {
int c;
StringBuilder sb = new StringBuilder();
try {
while ((c = out.read()) != -1) {
sb.append((char) c);
}
} catch (IOException e) {
LOGGER.warn("Could not read from stderr.", e);
}
// Error stream has been closed. See if there were any errors:
if (!sb.toString().trim().isEmpty()) {
LOGGER.warn("Push to Emacs error: " + sb);
couldNotConnect = true;
}
} catch (IOException e) {
LOGGER.warn("File problem.", e);
}
});
} catch (IOException excep) {
couldNotCall = true;
LOGGER.warn("Problem pushing to Emacs.", excep);
}
}
@Override
public void onOperationCompleted() {
if (couldNotConnect) {
dialogService.showErrorDialogAndWait(Localization.lang("Error pushing entries"),
Localization.lang("Could not connect to a running gnuserv process. Make sure that "
+ "Emacs or XEmacs is running, and that the server has been started "
+ "(by running the command 'server-start'/'gnuserv-start')."));
} else if (couldNotCall) {
dialogService.showErrorDialogAndWait(Localization.lang("Error pushing entries"),
Localization.lang("Could not run the gnuclient/emacsclient program. Make sure you have "
+ "the emacsclient/gnuclient program installed and available in the PATH."));
} else {
super.onOperationCompleted();
}
}
@Override
protected String getCommandName() {
return "gnuclient " + Localization.lang("or") + " emacsclient";
}
@Override
public PushToApplicationSettings getSettings(PushToApplication application, PushToApplicationPreferences preferences) {
return new PushToEmacsSettings(application, dialogService, preferencesService.getFilePreferences(), preferences);
}
}
| 5,490
| 39.977612
| 150
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/push/PushToEmacsSettings.java
|
package org.jabref.gui.push;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import org.jabref.gui.DialogService;
import org.jabref.logic.l10n.Localization;
import org.jabref.preferences.FilePreferences;
import org.jabref.preferences.PushToApplicationPreferences;
public class PushToEmacsSettings extends PushToApplicationSettings {
private final TextField additionalParams = new TextField();
public PushToEmacsSettings(PushToApplication application,
DialogService dialogService,
FilePreferences filePreferences,
PushToApplicationPreferences preferences) {
super(application, dialogService, filePreferences, preferences);
settingsPane.add(new Label(Localization.lang("Additional parameters") + ":"), 0, 1);
settingsPane.add(additionalParams, 1, 1);
additionalParams.setText(preferences.getEmacsArguments());
}
@Override
public void storeSettings() {
super.storeSettings();
preferences.setEmacsArguments(additionalParams.getText());
}
}
| 1,134
| 34.46875
| 92
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/push/PushToLyx.java
|
package org.jabref.gui.push;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.jabref.gui.DialogService;
import org.jabref.gui.JabRefExecutorService;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.icon.JabRefIcon;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.preferences.PreferencesService;
import org.jabref.preferences.PushToApplicationPreferences;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PushToLyx extends AbstractPushToApplication {
public static final String NAME = PushToApplications.LYX;
private static final Logger LOGGER = LoggerFactory.getLogger(PushToLyx.class);
public PushToLyx(DialogService dialogService, PreferencesService preferencesService) {
super(dialogService, preferencesService);
}
@Override
public String getDisplayName() {
return NAME;
}
@Override
public JabRefIcon getApplicationIcon() {
return IconTheme.JabRefIcons.APPLICATION_LYX;
}
@Override
public void onOperationCompleted() {
if (couldNotConnect) {
dialogService.showErrorDialogAndWait(Localization.lang("Error pushing entries"),
Localization.lang("Verify that LyX is running and that the lyxpipe is valid.")
+ "[" + commandPath + "]");
} else if (couldNotCall) {
dialogService.showErrorDialogAndWait(Localization.lang("Unable to write to %0.", commandPath + ".in"));
} else {
super.onOperationCompleted();
}
}
@Override
public PushToApplicationSettings getSettings(PushToApplication application, PushToApplicationPreferences preferences) {
return new PushToLyxSettings(application, dialogService, preferencesService.getFilePreferences(), preferences);
}
@Override
public void pushEntries(BibDatabaseContext database, final List<BibEntry> entries, final String keyString) {
couldNotConnect = false;
couldNotCall = false;
notDefined = false;
commandPath = preferencesService.getPushToApplicationPreferences().getCommandPaths().get(this.getDisplayName());
if ((commandPath == null) || commandPath.trim().isEmpty()) {
notDefined = true;
return;
}
if (!commandPath.endsWith(".in")) {
commandPath = commandPath + ".in";
}
File lp = new File(commandPath); // this needs to fixed because it gives "asdf" when going prefs.get("lyxpipe")
if (!lp.exists() || !lp.canWrite()) {
// See if it helps to append ".in":
lp = new File(commandPath + ".in");
if (!lp.exists() || !lp.canWrite()) {
couldNotConnect = true;
return;
}
}
final File lyxpipe = lp;
JabRefExecutorService.INSTANCE.executeAndWait(() -> {
try (FileWriter fw = new FileWriter(lyxpipe, StandardCharsets.UTF_8); BufferedWriter lyxOut = new BufferedWriter(fw)) {
String citeStr = "LYXCMD:sampleclient:citation-insert:" + keyString;
lyxOut.write(citeStr + "\n");
} catch (IOException excep) {
couldNotCall = true;
LOGGER.warn("Problem pushing to LyX/Kile.", excep);
}
});
}
}
| 3,561
| 34.62
| 131
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/push/PushToLyxSettings.java
|
package org.jabref.gui.push;
import org.jabref.gui.DialogService;
import org.jabref.logic.l10n.Localization;
import org.jabref.preferences.FilePreferences;
import org.jabref.preferences.PushToApplicationPreferences;
public class PushToLyxSettings extends PushToApplicationSettings {
public PushToLyxSettings(PushToApplication application,
DialogService dialogService,
FilePreferences filePreferences,
PushToApplicationPreferences preferences) {
super(application, dialogService, filePreferences, preferences);
commandLabel.setText(Localization.lang("Path to LyX pipe") + ":");
}
}
| 696
| 35.684211
| 74
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/push/PushToTeXstudio.java
|
package org.jabref.gui.push;
import org.jabref.gui.DialogService;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.icon.JabRefIcon;
import org.jabref.preferences.PreferencesService;
public class PushToTeXstudio extends AbstractPushToApplication {
public static final String NAME = PushToApplications.TEXSTUDIO;
public PushToTeXstudio(DialogService dialogService, PreferencesService preferencesService) {
super(dialogService, preferencesService);
}
@Override
public String getDisplayName() {
return NAME;
}
@Override
public JabRefIcon getApplicationIcon() {
return IconTheme.JabRefIcons.APPLICATION_TEXSTUDIO;
}
@Override
protected String[] getCommandLine(String keyString) {
return new String[] {commandPath, "--insert-cite", String.format("%s{%s}", getCiteCommand(), keyString)};
}
}
| 883
| 27.516129
| 113
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/push/PushToTexmaker.java
|
package org.jabref.gui.push;
import org.jabref.gui.DialogService;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.icon.JabRefIcon;
import org.jabref.preferences.PreferencesService;
/**
* Class for pushing entries into TexMaker.
*/
public class PushToTexmaker extends AbstractPushToApplication {
public static final String NAME = "Texmaker";
public PushToTexmaker(DialogService dialogService, PreferencesService preferencesService) {
super(dialogService, preferencesService);
}
@Override
public String getDisplayName() {
return NAME;
}
@Override
public JabRefIcon getApplicationIcon() {
return IconTheme.JabRefIcons.APPLICATION_TEXMAKER;
}
@Override
protected String[] getCommandLine(String keyString) {
return new String[] {commandPath, "-insert", getCiteCommand() + "{" + keyString + "}"};
}
}
| 896
| 25.382353
| 95
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/push/PushToVim.java
|
package org.jabref.gui.push;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.jabref.gui.DialogService;
import org.jabref.gui.JabRefExecutorService;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.icon.JabRefIcon;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.preferences.PreferencesService;
import org.jabref.preferences.PushToApplicationPreferences;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PushToVim extends AbstractPushToApplication {
public static final String NAME = PushToApplications.VIM;
private static final Logger LOGGER = LoggerFactory.getLogger(PushToVim.class);
public PushToVim(DialogService dialogService, PreferencesService preferencesService) {
super(dialogService, preferencesService);
}
@Override
public String getDisplayName() {
return NAME;
}
@Override
public JabRefIcon getApplicationIcon() {
return IconTheme.JabRefIcons.APPLICATION_VIM;
}
@Override
public PushToApplicationSettings getSettings(PushToApplication application, PushToApplicationPreferences preferences) {
return new PushToVimSettings(application, dialogService, preferencesService.getFilePreferences(), preferences);
}
@Override
public void pushEntries(BibDatabaseContext database, List<BibEntry> entries, String keys) {
couldNotConnect = false;
couldNotCall = false;
notDefined = false;
commandPath = preferencesService.getPushToApplicationPreferences().getCommandPaths().get(this.getDisplayName());
if ((commandPath == null) || commandPath.trim().isEmpty()) {
notDefined = true;
return;
}
try {
String[] com = new String[]{commandPath, "--servername",
preferencesService.getPushToApplicationPreferences().getVimServer(), "--remote-send",
"<C-\\><C-N>a" + getCiteCommand() +
"{" + keys + "}"};
final Process p = Runtime.getRuntime().exec(com);
JabRefExecutorService.INSTANCE.executeAndWait(() -> {
try (InputStream out = p.getErrorStream()) {
int c;
StringBuilder sb = new StringBuilder();
try {
while ((c = out.read()) != -1) {
sb.append((char) c);
}
} catch (IOException e) {
LOGGER.warn("Could not read from stderr.", e);
}
// Error stream has been closed. See if there were any errors:
if (!sb.toString().trim().isEmpty()) {
LOGGER.warn("Push to Vim error: " + sb);
couldNotConnect = true;
}
} catch (IOException e) {
LOGGER.warn("File problem.", e);
}
});
} catch (IOException excep) {
couldNotCall = true;
LOGGER.warn("Problem pushing to Vim.", excep);
}
}
@Override
public void onOperationCompleted() {
if (couldNotConnect) {
dialogService.showErrorDialogAndWait(Localization.lang("Error pushing entries"),
Localization.lang("Could not connect to Vim server. Make sure that Vim is running with correct server name."));
} else if (couldNotCall) {
dialogService.showErrorDialogAndWait(Localization.lang("Error pushing entries"),
Localization.lang("Could not run the 'vim' program."));
} else {
super.onOperationCompleted();
}
}
}
| 3,860
| 35.771429
| 131
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/push/PushToVimSettings.java
|
package org.jabref.gui.push;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import org.jabref.gui.DialogService;
import org.jabref.logic.l10n.Localization;
import org.jabref.preferences.FilePreferences;
import org.jabref.preferences.PushToApplicationPreferences;
public class PushToVimSettings extends PushToApplicationSettings {
private final TextField vimServer = new TextField();
public PushToVimSettings(PushToApplication application,
DialogService dialogService,
FilePreferences filePreferences,
PushToApplicationPreferences preferences) {
super(application, dialogService, filePreferences, preferences);
settingsPane.add(new Label(Localization.lang("Vim server name") + ":"), 0, 1);
settingsPane.add(vimServer, 1, 1);
vimServer.setText(preferences.getVimServer());
}
@Override
public void storeSettings() {
super.storeSettings();
preferences.setVimServer(vimServer.getText());
}
}
| 1,080
| 32.78125
| 86
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/push/PushToWinEdt.java
|
package org.jabref.gui.push;
import org.jabref.gui.DialogService;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.icon.JabRefIcon;
import org.jabref.preferences.PreferencesService;
public class PushToWinEdt extends AbstractPushToApplication {
public static final String NAME = PushToApplications.WIN_EDT;
public PushToWinEdt(DialogService dialogService, PreferencesService preferencesService) {
super(dialogService, preferencesService);
}
@Override
public String getDisplayName() {
return NAME;
}
@Override
public JabRefIcon getApplicationIcon() {
return IconTheme.JabRefIcons.APPLICATION_WINEDT;
}
@Override
protected String[] getCommandLine(String keyString) {
return new String[] {commandPath,
"\"[InsText('" + getCiteCommand() + "{" + keyString.replace("'", "''") + "}');]\""};
}
}
| 901
| 27.1875
| 100
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/remote/CLIMessageHandler.java
|
package org.jabref.gui.remote;
import java.util.List;
import javafx.application.Platform;
import org.jabref.cli.ArgumentProcessor;
import org.jabref.gui.JabRefGUI;
import org.jabref.logic.importer.ParserResult;
import org.jabref.logic.remote.server.RemoteMessageHandler;
import org.jabref.model.util.FileUpdateMonitor;
import org.jabref.preferences.PreferencesService;
import org.apache.commons.cli.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CLIMessageHandler implements RemoteMessageHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(CLIMessageHandler.class);
private final PreferencesService preferencesService;
private final FileUpdateMonitor fileUpdateMonitor;
public CLIMessageHandler(PreferencesService preferencesService, FileUpdateMonitor fileUpdateMonitor) {
this.preferencesService = preferencesService;
this.fileUpdateMonitor = fileUpdateMonitor;
}
@Override
public void handleCommandLineArguments(String[] message) {
try {
ArgumentProcessor argumentProcessor = new ArgumentProcessor(
message,
ArgumentProcessor.Mode.REMOTE_START,
preferencesService,
fileUpdateMonitor);
List<ParserResult> loaded = argumentProcessor.getParserResults();
for (int i = 0; i < loaded.size(); i++) {
ParserResult pr = loaded.get(i);
boolean focusPanel = i == 0;
Platform.runLater(() ->
// Need to run this on the JavaFX thread
JabRefGUI.getMainFrame().addParserResult(pr, focusPanel)
);
}
} catch (ParseException e) {
LOGGER.error("Error when parsing CLI args", e);
}
}
}
| 1,858
| 34.75
| 106
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/search/GlobalSearchBar.java
|
package org.jabref.gui.search;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.swing.undo.UndoManager;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.css.PseudoClass;
import javafx.event.Event;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBase;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.Skin;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.Tooltip;
import javafx.scene.control.cell.TextFieldListCell;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import org.jabref.gui.ClipBoardManager;
import org.jabref.gui.DialogService;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.StateManager;
import org.jabref.gui.autocompleter.AppendPersonNamesStrategy;
import org.jabref.gui.autocompleter.AutoCompleteFirstNameMode;
import org.jabref.gui.autocompleter.AutoCompletionTextInputBinding;
import org.jabref.gui.autocompleter.PersonNameStringConverter;
import org.jabref.gui.autocompleter.SuggestionProvider;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.keyboard.KeyBinding;
import org.jabref.gui.keyboard.KeyBindingRepository;
import org.jabref.gui.search.rules.describer.SearchDescribers;
import org.jabref.gui.undo.CountingUndoManager;
import org.jabref.gui.util.BindingsHelper;
import org.jabref.gui.util.DefaultTaskExecutor;
import org.jabref.gui.util.IconValidationDecorator;
import org.jabref.gui.util.TooltipTextUtil;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.search.SearchQuery;
import org.jabref.model.entry.Author;
import org.jabref.model.search.rules.SearchRules;
import org.jabref.preferences.PreferencesService;
import org.jabref.preferences.SearchPreferences;
import de.saxsys.mvvmfx.utils.validation.FunctionBasedValidator;
import de.saxsys.mvvmfx.utils.validation.ValidationMessage;
import de.saxsys.mvvmfx.utils.validation.Validator;
import de.saxsys.mvvmfx.utils.validation.visualization.ControlsFxVisualizer;
import impl.org.controlsfx.skin.AutoCompletePopup;
import org.controlsfx.control.textfield.AutoCompletionBinding;
import org.controlsfx.control.textfield.CustomTextField;
import org.reactfx.util.FxTimer;
import org.reactfx.util.Timer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.jabref.gui.actions.ActionHelper.needsDatabase;
public class GlobalSearchBar extends HBox {
private static final Logger LOGGER = LoggerFactory.getLogger(GlobalSearchBar.class);
private static final int SEARCH_DELAY = 400;
private static final PseudoClass CLASS_NO_RESULTS = PseudoClass.getPseudoClass("emptyResult");
private static final PseudoClass CLASS_RESULTS_FOUND = PseudoClass.getPseudoClass("emptyResult");
private final CustomTextField searchField = SearchTextField.create();
private final ToggleButton caseSensitiveButton;
private final ToggleButton regularExpressionButton;
private final ToggleButton fulltextButton;
private final Button openGlobalSearchButton;
private final ToggleButton keepSearchString;
// private final Button searchModeButton;
private final Tooltip searchFieldTooltip = new Tooltip();
private final Label currentResults = new Label("");
private final StateManager stateManager;
private final PreferencesService preferencesService;
private final Validator regexValidator;
private final UndoManager undoManager;
private final SearchPreferences searchPreferences;
private final DialogService dialogService;
private final BooleanProperty globalSearchActive = new SimpleBooleanProperty(false);
private GlobalSearchResultDialog globalSearchResultDialog;
private final JabRefFrame frame;
public GlobalSearchBar(JabRefFrame frame, StateManager stateManager, PreferencesService preferencesService, CountingUndoManager undoManager, DialogService dialogService) {
super();
this.stateManager = stateManager;
this.preferencesService = preferencesService;
this.searchPreferences = preferencesService.getSearchPreferences();
this.undoManager = undoManager;
this.dialogService = dialogService;
this.frame = frame;
searchField.disableProperty().bind(needsDatabase(stateManager).not());
// fits the standard "found x entries"-message thus hinders the searchbar to jump around while searching if the frame width is too small
currentResults.setPrefWidth(150);
searchField.setTooltip(searchFieldTooltip);
searchFieldTooltip.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
searchFieldTooltip.setMaxHeight(10);
updateHintVisibility();
KeyBindingRepository keyBindingRepository = preferencesService.getKeyBindingRepository();
searchField.addEventFilter(KeyEvent.KEY_PRESSED, event -> {
Optional<KeyBinding> keyBinding = keyBindingRepository.mapToKeyBinding(event);
if (keyBinding.isPresent()) {
if (keyBinding.get() == KeyBinding.CLOSE) {
// Clear search and select first entry, if available
searchField.setText("");
frame.getCurrentLibraryTab().getMainTable().getSelectionModel().selectFirst();
event.consume();
}
}
});
searchField.setContextMenu(SearchFieldRightClickMenu.create(
keyBindingRepository,
stateManager,
searchField,
frame));
ObservableList<String> search = stateManager.getWholeSearchHistory();
search.addListener((ListChangeListener.Change<? extends String> change) -> {
searchField.setContextMenu(SearchFieldRightClickMenu.create(
keyBindingRepository,
stateManager,
searchField,
frame));
});
ClipBoardManager.addX11Support(searchField);
regularExpressionButton = IconTheme.JabRefIcons.REG_EX.asToggleButton();
caseSensitiveButton = IconTheme.JabRefIcons.CASE_SENSITIVE.asToggleButton();
fulltextButton = IconTheme.JabRefIcons.FULLTEXT.asToggleButton();
openGlobalSearchButton = IconTheme.JabRefIcons.OPEN_GLOBAL_SEARCH.asButton();
keepSearchString = IconTheme.JabRefIcons.KEEP_SEARCH_STRING.asToggleButton();
initSearchModifierButtons();
BooleanBinding focusedOrActive = searchField.focusedProperty()
.or(regularExpressionButton.focusedProperty())
.or(caseSensitiveButton.focusedProperty())
.or(fulltextButton.focusedProperty())
.or(keepSearchString.focusedProperty())
.or(searchField.textProperty()
.isNotEmpty());
regularExpressionButton.visibleProperty().unbind();
regularExpressionButton.visibleProperty().bind(focusedOrActive);
caseSensitiveButton.visibleProperty().unbind();
caseSensitiveButton.visibleProperty().bind(focusedOrActive);
fulltextButton.visibleProperty().unbind();
fulltextButton.visibleProperty().bind(focusedOrActive);
keepSearchString.visibleProperty().unbind();
keepSearchString.visibleProperty().bind(focusedOrActive);
StackPane modifierButtons = new StackPane(new HBox(regularExpressionButton, caseSensitiveButton, fulltextButton, keepSearchString));
modifierButtons.setAlignment(Pos.CENTER);
searchField.setRight(new HBox(searchField.getRight(), modifierButtons));
searchField.getStyleClass().add("search-field");
searchField.setMinWidth(100);
HBox.setHgrow(searchField, Priority.ALWAYS);
regexValidator = new FunctionBasedValidator<>(
searchField.textProperty(),
query -> !(regularExpressionButton.isSelected() && !validRegex()),
ValidationMessage.error(Localization.lang("Invalid regular expression")));
ControlsFxVisualizer visualizer = new ControlsFxVisualizer();
visualizer.setDecoration(new IconValidationDecorator(Pos.CENTER_LEFT));
Platform.runLater(() -> visualizer.initVisualization(regexValidator.getValidationStatus(), searchField));
this.getChildren().addAll(searchField, openGlobalSearchButton, currentResults);
this.setSpacing(4.0);
this.setAlignment(Pos.CENTER_LEFT);
Timer searchTask = FxTimer.create(java.time.Duration.ofMillis(SEARCH_DELAY), this::performSearch);
BindingsHelper.bindBidirectional(
stateManager.activeSearchQueryProperty(),
searchField.textProperty(),
searchTerm -> {
// Async update
searchTask.restart();
},
query -> setSearchTerm(query.map(SearchQuery::getQuery).orElse("")));
this.stateManager.activeSearchQueryProperty().addListener((obs, oldvalue, newValue) -> newValue.ifPresent(this::updateSearchResultsForQuery));
this.stateManager.activeDatabaseProperty().addListener((obs, oldValue, newValue) -> stateManager.activeSearchQueryProperty().get().ifPresent(this::updateSearchResultsForQuery));
/*
* The listener tracks a change on the focus property value.
* This happens, from active (user types a query) to inactive / focus
* lost (e.g., user selects an entry or triggers the search).
* The search history should only be filled, if focus is lost.
*/
searchField.focusedProperty().addListener((obs, oldValue, newValue) -> {
// Focus lost can be derived by checking that there is no newValue (or the text is empty)
if (oldValue && !(newValue || searchField.getText().isBlank())) {
this.stateManager.addSearchHistory(searchField.textProperty().get());
}
});
}
private void updateSearchResultsForQuery(SearchQuery query) {
updateResults(this.stateManager.getSearchResultSize().intValue(), SearchDescribers.getSearchDescriberFor(query).getDescription(),
query.isGrammarBasedSearch());
}
private void initSearchModifierButtons() {
regularExpressionButton.setSelected(searchPreferences.isRegularExpression());
regularExpressionButton.setTooltip(new Tooltip(Localization.lang("regular expression")));
initSearchModifierButton(regularExpressionButton);
regularExpressionButton.setOnAction(event -> {
searchPreferences.setSearchFlag(SearchRules.SearchFlags.REGULAR_EXPRESSION, regularExpressionButton.isSelected());
performSearch();
});
caseSensitiveButton.setSelected(searchPreferences.isCaseSensitive());
caseSensitiveButton.setTooltip(new Tooltip(Localization.lang("Case sensitive")));
initSearchModifierButton(caseSensitiveButton);
caseSensitiveButton.setOnAction(event -> {
searchPreferences.setSearchFlag(SearchRules.SearchFlags.CASE_SENSITIVE, caseSensitiveButton.isSelected());
performSearch();
});
fulltextButton.setSelected(searchPreferences.isFulltext());
fulltextButton.setTooltip(new Tooltip(Localization.lang("Fulltext search")));
initSearchModifierButton(fulltextButton);
fulltextButton.setOnAction(event -> {
searchPreferences.setSearchFlag(SearchRules.SearchFlags.FULLTEXT, fulltextButton.isSelected());
performSearch();
});
keepSearchString.setSelected(searchPreferences.shouldKeepSearchString());
keepSearchString.setTooltip(new Tooltip(Localization.lang("Keep search string across libraries")));
initSearchModifierButton(keepSearchString);
keepSearchString.setOnAction(evt -> {
searchPreferences.setSearchFlag(SearchRules.SearchFlags.KEEP_SEARCH_STRING, keepSearchString.isSelected());
performSearch();
});
openGlobalSearchButton.disableProperty().bindBidirectional(globalSearchActive);
openGlobalSearchButton.setTooltip(new Tooltip(Localization.lang("Search across libraries in a new window")));
initSearchModifierButton(openGlobalSearchButton);
openGlobalSearchButton.setOnAction(evt -> {
globalSearchActive.setValue(true);
globalSearchResultDialog = new GlobalSearchResultDialog(undoManager);
performSearch();
dialogService.showCustomDialogAndWait(globalSearchResultDialog);
globalSearchActive.setValue(false);
});
}
private void initSearchModifierButton(ButtonBase searchButton) {
searchButton.setCursor(Cursor.DEFAULT);
searchButton.setMinHeight(28);
searchButton.setMaxHeight(28);
searchButton.setMinWidth(28);
searchButton.setMaxWidth(28);
searchButton.setPadding(new Insets(1.0));
searchButton.managedProperty().bind(searchField.editableProperty());
searchButton.visibleProperty().bind(searchField.editableProperty());
}
/**
* Focuses the search field if it is not focused.
*/
public void focus() {
if (!searchField.isFocused()) {
searchField.requestFocus();
}
searchField.selectAll();
}
public void performSearch() {
LOGGER.debug("Flags: {}", searchPreferences.getSearchFlags());
LOGGER.debug("Run search " + searchField.getText());
// An empty search field should cause the search to be cleared.
if (searchField.getText().isEmpty()) {
currentResults.setText("");
setSearchFieldHintTooltip(null);
stateManager.clearSearchQuery();
return;
}
// Invalid regular expression
if (!regexValidator.getValidationStatus().isValid()) {
currentResults.setText(Localization.lang("Invalid regular expression"));
return;
}
SearchQuery searchQuery = new SearchQuery(this.searchField.getText(), searchPreferences.getSearchFlags());
if (!searchQuery.isValid()) {
informUserAboutInvalidSearchQuery();
return;
}
stateManager.setSearchQuery(searchQuery);
}
private boolean validRegex() {
try {
Pattern.compile(searchField.getText());
} catch (PatternSyntaxException e) {
LOGGER.debug(e.getMessage());
return false;
}
return true;
}
private void informUserAboutInvalidSearchQuery() {
searchField.pseudoClassStateChanged(CLASS_NO_RESULTS, true);
stateManager.clearSearchQuery();
String illegalSearch = Localization.lang("Search failed: illegal search expression");
currentResults.setText(illegalSearch);
}
public void setAutoCompleter(SuggestionProvider<Author> searchCompleter) {
if (preferencesService.getAutoCompletePreferences().shouldAutoComplete()) {
AutoCompletionTextInputBinding<Author> autoComplete = AutoCompletionTextInputBinding.autoComplete(searchField,
searchCompleter::provideSuggestions,
new PersonNameStringConverter(false, false, AutoCompleteFirstNameMode.BOTH),
new AppendPersonNamesStrategy());
AutoCompletePopup<Author> popup = getPopup(autoComplete);
popup.setSkin(new SearchPopupSkin<>(popup));
}
}
/**
* The popup has private access in {@link AutoCompletionBinding}, so we use reflection to access it.
*/
@SuppressWarnings("unchecked")
private <T> AutoCompletePopup<T> getPopup(AutoCompletionBinding<T> autoCompletionBinding) {
try {
// TODO: reflective access, should be removed
Field privatePopup = AutoCompletionBinding.class.getDeclaredField("autoCompletionPopup");
privatePopup.setAccessible(true);
return (AutoCompletePopup<T>) privatePopup.get(autoCompletionBinding);
} catch (IllegalAccessException | NoSuchFieldException e) {
LOGGER.error("Could not get access to auto completion popup", e);
return new AutoCompletePopup<>();
}
}
private void updateResults(int matched, TextFlow description, boolean grammarBasedSearch) {
if (matched == 0) {
currentResults.setText(Localization.lang("No results found."));
searchField.pseudoClassStateChanged(CLASS_NO_RESULTS, true);
} else {
currentResults.setText(Localization.lang("Found %0 results.", String.valueOf(matched)));
searchField.pseudoClassStateChanged(CLASS_RESULTS_FOUND, true);
}
if (grammarBasedSearch) {
// TODO: switch Icon color
// searchIcon.setIcon(IconTheme.JabRefIcon.ADVANCED_SEARCH.getIcon());
} else {
// TODO: switch Icon color
// searchIcon.setIcon(IconTheme.JabRefIcon.SEARCH.getIcon());
}
setSearchFieldHintTooltip(description);
}
private void setSearchFieldHintTooltip(TextFlow description) {
if (preferencesService.getWorkspacePreferences().shouldShowAdvancedHints()) {
String genericDescription = Localization.lang("Hint:\n\nTo search all fields for <b>Smith</b>, enter:\n<tt>smith</tt>\n\nTo search the field <b>author</b> for <b>Smith</b> and the field <b>title</b> for <b>electrical</b>, enter:\n<tt>author=Smith and title=electrical</tt>");
List<Text> genericDescriptionTexts = TooltipTextUtil.createTextsFromHtml(genericDescription);
if (description == null) {
TextFlow emptyHintTooltip = new TextFlow();
emptyHintTooltip.getChildren().setAll(genericDescriptionTexts);
searchFieldTooltip.setGraphic(emptyHintTooltip);
} else {
description.getChildren().add(new Text("\n\n"));
description.getChildren().addAll(genericDescriptionTexts);
searchFieldTooltip.setGraphic(description);
}
}
}
public void updateHintVisibility() {
setSearchFieldHintTooltip(null);
}
public void setSearchTerm(String searchTerm) {
if (searchTerm.equals(searchField.getText())) {
return;
}
DefaultTaskExecutor.runInJavaFXThread(() -> searchField.setText(searchTerm));
}
private static class SearchPopupSkin<T> implements Skin<AutoCompletePopup<T>> {
private final AutoCompletePopup<T> control;
private final ListView<T> suggestionList;
private final BorderPane container;
public SearchPopupSkin(AutoCompletePopup<T> control) {
this.control = control;
this.suggestionList = new ListView<>(control.getSuggestions());
this.suggestionList.getStyleClass().add("auto-complete-popup");
this.suggestionList.getStylesheets().add(Objects.requireNonNull(AutoCompletionBinding.class.getResource("autocompletion.css")).toExternalForm());
this.suggestionList.prefHeightProperty().bind(Bindings.min(control.visibleRowCountProperty(), Bindings.size(this.suggestionList.getItems())).multiply(24).add(18));
this.suggestionList.setCellFactory(TextFieldListCell.forListView(control.getConverter()));
this.suggestionList.prefWidthProperty().bind(control.prefWidthProperty());
this.suggestionList.maxWidthProperty().bind(control.maxWidthProperty());
this.suggestionList.minWidthProperty().bind(control.minWidthProperty());
this.container = new BorderPane();
this.container.setCenter(suggestionList);
this.registerEventListener();
}
private void registerEventListener() {
this.suggestionList.setOnMouseClicked(me -> {
if (me.getButton() == MouseButton.PRIMARY) {
this.onSuggestionChosen(this.suggestionList.getSelectionModel().getSelectedItem());
}
});
this.suggestionList.setOnKeyPressed(ke -> {
switch (ke.getCode()) {
case TAB:
case ENTER:
this.onSuggestionChosen(this.suggestionList.getSelectionModel().getSelectedItem());
break;
case ESCAPE:
if (this.control.isHideOnEscape()) {
this.control.hide();
}
break;
default:
break;
}
});
}
private void onSuggestionChosen(T suggestion) {
if (suggestion != null) {
Event.fireEvent(this.control, new AutoCompletePopup.SuggestionEvent<>(suggestion));
}
}
@Override
public Node getNode() {
return this.container;
}
@Override
public AutoCompletePopup<T> getSkinnable() {
return this.control;
}
@Override
public void dispose() {
// empty
}
}
}
| 22,196
| 44.207739
| 287
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/search/GlobalSearchResultDialog.java
|
package org.jabref.gui.search;
import javax.swing.undo.UndoManager;
import javafx.fxml.FXML;
import javafx.scene.control.SplitPane;
import javafx.scene.control.ToggleButton;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.icon.IconTheme;
import org.jabref.gui.maintable.columns.SpecialFieldColumn;
import org.jabref.gui.preview.PreviewViewer;
import org.jabref.gui.theme.ThemeManager;
import org.jabref.gui.util.BaseDialog;
import org.jabref.logic.l10n.Localization;
import org.jabref.preferences.PreferencesService;
import com.airhacks.afterburner.views.ViewLoader;
import com.tobiasdiez.easybind.EasyBind;
import jakarta.inject.Inject;
public class GlobalSearchResultDialog extends BaseDialog<Void> {
@FXML private SplitPane container;
@FXML private ToggleButton keepOnTop;
private final UndoManager undoManager;
@Inject private PreferencesService preferencesService;
@Inject private StateManager stateManager;
@Inject private DialogService dialogService;
@Inject private ThemeManager themeManager;
private GlobalSearchResultDialogViewModel viewModel;
public GlobalSearchResultDialog(UndoManager undoManager) {
this.undoManager = undoManager;
setTitle(Localization.lang("Search results from open libraries"));
ViewLoader.view(this)
.load()
.setAsDialogPane(this);
initModality(Modality.NONE);
}
@FXML
private void initialize() {
viewModel = new GlobalSearchResultDialogViewModel(preferencesService);
PreviewViewer previewViewer = new PreviewViewer(viewModel.getSearchDatabaseContext(), dialogService, stateManager, themeManager);
previewViewer.setLayout(preferencesService.getPreviewPreferences().getSelectedPreviewLayout());
SearchResultsTableDataModel model = new SearchResultsTableDataModel(viewModel.getSearchDatabaseContext(), preferencesService, stateManager);
SearchResultsTable resultsTable = new SearchResultsTable(model, viewModel.getSearchDatabaseContext(), preferencesService, undoManager, dialogService, stateManager);
resultsTable.getColumns().removeIf(SpecialFieldColumn.class::isInstance);
resultsTable.getSelectionModel().selectFirst();
if (resultsTable.getSelectionModel().getSelectedItem() != null) {
previewViewer.setEntry(resultsTable.getSelectionModel().getSelectedItem().getEntry());
}
resultsTable.getSelectionModel().selectedItemProperty().addListener((obs, old, newValue) -> {
if (newValue != null) {
previewViewer.setEntry(newValue.getEntry());
} else {
previewViewer.setEntry(old.getEntry());
}
});
container.getItems().addAll(resultsTable, previewViewer);
keepOnTop.selectedProperty().bindBidirectional(viewModel.keepOnTop());
EasyBind.subscribe(viewModel.keepOnTop(), value -> {
Stage stage = (Stage) getDialogPane().getScene().getWindow();
stage.setAlwaysOnTop(value);
keepOnTop.setGraphic(value
? IconTheme.JabRefIcons.KEEP_ON_TOP.getGraphicNode()
: IconTheme.JabRefIcons.KEEP_ON_TOP_OFF.getGraphicNode());
});
getDialogPane().getScene().getWindow().addEventHandler(WindowEvent.WINDOW_SHOWN, event -> {
getDialogPane().setPrefHeight(preferencesService.getSearchPreferences().getSearchWindowHeight());
getDialogPane().setPrefWidth(preferencesService.getSearchPreferences().getSearchWindowWidth());
});
getDialogPane().getScene().getWindow().addEventHandler(WindowEvent.WINDOW_HIDDEN, event -> {
preferencesService.getSearchPreferences().setSearchWindowHeight(getHeight());
preferencesService.getSearchPreferences().setSearchWindowWidth(getWidth());
});
}
}
| 4,024
| 40.494845
| 172
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/search/GlobalSearchResultDialogViewModel.java
|
package org.jabref.gui.search;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.preferences.PreferencesService;
import org.jabref.preferences.SearchPreferences;
import com.tobiasdiez.easybind.EasyBind;
public class GlobalSearchResultDialogViewModel {
private final BibDatabaseContext searchDatabaseContext = new BibDatabaseContext();
private final BooleanProperty keepOnTop = new SimpleBooleanProperty();
public GlobalSearchResultDialogViewModel(PreferencesService preferencesService) {
SearchPreferences searchPreferences = preferencesService.getSearchPreferences();
keepOnTop.set(searchPreferences.shouldKeepWindowOnTop());
EasyBind.subscribe(this.keepOnTop, searchPreferences::setKeepWindowOnTop);
}
public BibDatabaseContext getSearchDatabaseContext() {
return searchDatabaseContext;
}
public BooleanProperty keepOnTop() {
return this.keepOnTop;
}
}
| 1,055
| 32
| 88
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/search/RebuildFulltextSearchIndexAction.java
|
package org.jabref.gui.search;
import java.io.IOException;
import org.jabref.gui.DialogService;
import org.jabref.gui.Globals;
import org.jabref.gui.LibraryTab;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.gui.util.BackgroundTask;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.pdf.search.indexing.PdfIndexer;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.preferences.FilePreferences;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.jabref.gui.actions.ActionHelper.needsDatabase;
public class RebuildFulltextSearchIndexAction extends SimpleCommand {
private static final Logger LOGGER = LoggerFactory.getLogger(LibraryTab.class);
private final StateManager stateManager;
private final GetCurrentLibraryTab currentLibraryTab;
private final DialogService dialogService;
private final FilePreferences filePreferences;
private BibDatabaseContext databaseContext;
private boolean shouldContinue = true;
public RebuildFulltextSearchIndexAction(StateManager stateManager, GetCurrentLibraryTab currentLibraryTab, DialogService dialogService, FilePreferences filePreferences) {
this.stateManager = stateManager;
this.currentLibraryTab = currentLibraryTab;
this.dialogService = dialogService;
this.filePreferences = filePreferences;
this.executable.bind(needsDatabase(stateManager));
}
@Override
public void execute() {
init();
BackgroundTask.wrap(this::rebuildIndex)
.executeWith(Globals.TASK_EXECUTOR);
}
public void init() {
if (stateManager.getActiveDatabase().isEmpty()) {
return;
}
databaseContext = stateManager.getActiveDatabase().get();
boolean confirm = dialogService.showConfirmationDialogAndWait(
Localization.lang("Rebuild fulltext search index"),
Localization.lang("Rebuild fulltext search index for current library?"));
if (!confirm) {
shouldContinue = false;
return;
}
dialogService.notify(Localization.lang("Rebuilding fulltext search index..."));
}
private void rebuildIndex() {
if (!shouldContinue || stateManager.getActiveDatabase().isEmpty()) {
return;
}
try {
currentLibraryTab.get().getIndexingTaskManager().createIndex(PdfIndexer.of(databaseContext, filePreferences));
currentLibraryTab.get().getIndexingTaskManager().updateIndex(PdfIndexer.of(databaseContext, filePreferences), databaseContext);
} catch (IOException e) {
dialogService.notify(Localization.lang("Failed to access fulltext search index"));
LOGGER.error("Failed to access fulltext search index", e);
}
}
public interface GetCurrentLibraryTab {
LibraryTab get();
}
}
| 2,969
| 34.783133
| 174
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/search/SearchDisplayMode.java
|
package org.jabref.gui.search;
import java.util.function.Supplier;
import org.jabref.logic.l10n.Localization;
/**
* Collects the possible search modes
*/
public enum SearchDisplayMode {
FLOAT(() -> Localization.lang("Float"), () -> Localization.lang("Gray out non-hits")),
FILTER(() -> Localization.lang("Filter"), () -> Localization.lang("Hide non-hits"));
private final Supplier<String> displayName;
private final Supplier<String> toolTipText;
/**
* We have to use supplier for the localized text so that language changes are correctly reflected.
*/
SearchDisplayMode(Supplier<String> displayName, Supplier<String> toolTipText) {
this.displayName = displayName;
this.toolTipText = toolTipText;
}
public String getDisplayName() {
return displayName.get();
}
public String getToolTipText() {
return toolTipText.get();
}
}
| 918
| 26.029412
| 103
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/search/SearchFieldRightClickMenu.java
|
package org.jabref.gui.search;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import org.jabref.gui.JabRefFrame;
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.edit.EditAction;
import org.jabref.gui.keyboard.KeyBindingRepository;
import org.jabref.logic.l10n.Localization;
import org.controlsfx.control.textfield.CustomTextField;
public class SearchFieldRightClickMenu {
public static ContextMenu create(KeyBindingRepository keyBindingRepository,
StateManager stateManager,
CustomTextField searchField,
JabRefFrame frame) {
ActionFactory factory = new ActionFactory(keyBindingRepository);
ContextMenu contextMenu = new ContextMenu();
contextMenu.getItems().addAll(
factory.createMenuItem(StandardActions.UNDO, new EditAction(StandardActions.UNDO, frame, stateManager)),
factory.createMenuItem(StandardActions.REDO, new EditAction(StandardActions.REDO, frame, stateManager)),
factory.createMenuItem(StandardActions.CUT, new EditAction(StandardActions.CUT, frame, stateManager)),
factory.createMenuItem(StandardActions.COPY, new EditAction(StandardActions.COPY, frame, stateManager)),
factory.createMenuItem(StandardActions.PASTE, new EditAction(StandardActions.PASTE, frame, stateManager)),
factory.createMenuItem(StandardActions.DELETE, new EditAction(StandardActions.DELETE, frame, stateManager)),
new SeparatorMenuItem(),
factory.createMenuItem(StandardActions.SELECT_ALL, new EditAction(StandardActions.SELECT_ALL, null, stateManager)),
createSearchFromHistorySubMenu(factory, stateManager, searchField)
);
return contextMenu;
}
private static Menu createSearchFromHistorySubMenu(ActionFactory factory,
StateManager stateManager,
CustomTextField searchField) {
Menu searchFromHistorySubMenu = factory.createMenu(() -> Localization.lang("Search from history..."));
int num = stateManager.getLastSearchHistory(10).size();
if (num == 0) {
MenuItem item = new MenuItem(Localization.lang("your search history is empty"));
searchFromHistorySubMenu.getItems().addAll(item);
} else {
for (int i = 0; i < num; i++) {
int finalI = i;
MenuItem item = factory.createMenuItem(() -> stateManager.getLastSearchHistory(10).get(finalI), new SimpleCommand() {
@Override
public void execute() {
searchField.setText(stateManager.getLastSearchHistory(10).get(finalI));
}
});
searchFromHistorySubMenu.getItems().addAll(item);
}
MenuItem clear = factory.createMenuItem(() -> Localization.lang("Clear history"), new SimpleCommand() {
@Override
public void execute() {
stateManager.clearSearchHistory();
}
});
searchFromHistorySubMenu.getItems().addAll(new SeparatorMenuItem(), clear);
}
return searchFromHistorySubMenu;
}
}
| 3,643
| 47.586667
| 133
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/search/SearchResultsTable.java
|
package org.jabref.gui.search;
import java.util.List;
import javax.swing.undo.UndoManager;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.maintable.BibEntryTableViewModel;
import org.jabref.gui.maintable.MainTable;
import org.jabref.gui.maintable.MainTableColumnFactory;
import org.jabref.gui.maintable.MainTablePreferences;
import org.jabref.gui.maintable.PersistenceVisualStateTable;
import org.jabref.gui.maintable.SmartConstrainedResizePolicy;
import org.jabref.gui.maintable.columns.LibraryColumn;
import org.jabref.gui.maintable.columns.MainTableColumn;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.preferences.PreferencesService;
public class SearchResultsTable extends TableView<BibEntryTableViewModel> {
public SearchResultsTable(SearchResultsTableDataModel model,
BibDatabaseContext database,
PreferencesService preferencesService,
UndoManager undoManager,
DialogService dialogService,
StateManager stateManager) {
super();
MainTablePreferences mainTablePreferences = preferencesService.getMainTablePreferences();
List<TableColumn<BibEntryTableViewModel, ?>> allCols = new MainTableColumnFactory(
database,
preferencesService,
preferencesService.getSearchDialogColumnPreferences(),
undoManager,
dialogService,
stateManager).createColumns();
if (allCols.stream().noneMatch(LibraryColumn.class::isInstance)) {
allCols.add(0, new LibraryColumn());
}
this.getColumns().addAll(allCols);
this.getSortOrder().clear();
preferencesService.getSearchDialogColumnPreferences().getColumnSortOrder().forEach(columnModel ->
this.getColumns().stream()
.map(column -> (MainTableColumn<?>) column)
.filter(column -> column.getModel().equals(columnModel))
.findFirst()
.ifPresent(column -> this.getSortOrder().add(column)));
if (mainTablePreferences.getResizeColumnsToFit()) {
this.setColumnResizePolicy(new SmartConstrainedResizePolicy());
}
this.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
this.setItems(model.getEntriesFilteredAndSorted());
// Enable sorting
model.getEntriesFilteredAndSorted().comparatorProperty().bind(this.comparatorProperty());
this.getStylesheets().add(MainTable.class.getResource("MainTable.css").toExternalForm());
// Store visual state
new PersistenceVisualStateTable(this, preferencesService.getSearchDialogColumnPreferences());
database.getDatabase().registerListener(this);
}
}
| 3,161
| 41.16
| 105
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/search/SearchResultsTableDataModel.java
|
package org.jabref.gui.search;
import java.util.List;
import java.util.Optional;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import org.jabref.gui.StateManager;
import org.jabref.gui.maintable.BibEntryTableViewModel;
import org.jabref.gui.maintable.MainTableFieldValueFormatter;
import org.jabref.gui.maintable.NameDisplayPreferences;
import org.jabref.logic.search.SearchQuery;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.preferences.PreferencesService;
import com.tobiasdiez.easybind.EasyBind;
public class SearchResultsTableDataModel {
private final FilteredList<BibEntryTableViewModel> entriesFiltered;
private final SortedList<BibEntryTableViewModel> entriesSorted;
private final ObjectProperty<MainTableFieldValueFormatter> fieldValueFormatter;
private final NameDisplayPreferences nameDisplayPreferences;
private final BibDatabaseContext bibDatabaseContext;
public SearchResultsTableDataModel(BibDatabaseContext bibDatabaseContext, PreferencesService preferencesService, StateManager stateManager) {
this.nameDisplayPreferences = preferencesService.getNameDisplayPreferences();
this.bibDatabaseContext = bibDatabaseContext;
this.fieldValueFormatter = new SimpleObjectProperty<>(new MainTableFieldValueFormatter(nameDisplayPreferences, bibDatabaseContext));
ObservableList<BibEntryTableViewModel> entriesViewModel = FXCollections.observableArrayList();
for (BibDatabaseContext context : stateManager.getOpenDatabases()) {
ObservableList<BibEntry> entriesForDb = context.getDatabase().getEntries();
List<BibEntryTableViewModel> viewModelForDb = EasyBind.mapBacked(entriesForDb, entry -> new BibEntryTableViewModel(entry, context, fieldValueFormatter));
entriesViewModel.addAll(viewModelForDb);
}
entriesFiltered = new FilteredList<>(entriesViewModel);
entriesFiltered.predicateProperty().bind(EasyBind.map(stateManager.activeSearchQueryProperty(), query -> entry -> isMatchedBySearch(query, entry)));
// We need to wrap the list since otherwise sorting in the table does not work
entriesSorted = new SortedList<>(entriesFiltered);
}
private boolean isMatchedBySearch(Optional<SearchQuery> query, BibEntryTableViewModel entry) {
return query.map(matcher -> matcher.isMatch(entry.getEntry()))
.orElse(true);
}
public SortedList<BibEntryTableViewModel> getEntriesFilteredAndSorted() {
return entriesSorted;
}
public void refresh() {
this.fieldValueFormatter.setValue(new MainTableFieldValueFormatter(nameDisplayPreferences, bibDatabaseContext));
}
}
| 2,987
| 45.6875
| 165
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/search/SearchTextField.java
|
package org.jabref.gui.search;
import org.jabref.gui.icon.IconTheme;
import org.jabref.logic.l10n.Localization;
import org.controlsfx.control.textfield.CustomTextField;
import org.controlsfx.control.textfield.TextFields;
public class SearchTextField {
public static CustomTextField create() {
CustomTextField textField = (CustomTextField) TextFields.createClearableTextField();
textField.setPromptText(Localization.lang("Search") + "...");
textField.setLeft(IconTheme.JabRefIcons.SEARCH.getGraphicNode());
textField.setId("searchField");
return textField;
}
}
| 612
| 31.263158
| 92
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/search/rules/describer/ContainsAndRegexBasedSearchRuleDescriber.java
|
package org.jabref.gui.search.rules.describer;
import java.util.EnumSet;
import java.util.List;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import org.jabref.gui.util.TooltipTextUtil;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.search.rules.SearchRules;
import org.jabref.model.search.rules.SearchRules.SearchFlags;
import org.jabref.model.search.rules.SentenceAnalyzer;
public class ContainsAndRegexBasedSearchRuleDescriber implements SearchDescriber {
private final EnumSet<SearchFlags> searchFlags;
private final String query;
public ContainsAndRegexBasedSearchRuleDescriber(EnumSet<SearchFlags> searchFlags, String query) {
this.searchFlags = searchFlags;
this.query = query;
}
@Override
public TextFlow getDescription() {
List<String> words = new SentenceAnalyzer(query).getWords();
String firstWord = words.isEmpty() ? "" : words.get(0);
String temp = searchFlags.contains(SearchRules.SearchFlags.REGULAR_EXPRESSION) ? Localization.lang(
"This search contains entries in which any field contains the regular expression <b>%0</b>")
: Localization.lang("This search contains entries in which any field contains the term <b>%0</b>");
List<Text> textList = TooltipTextUtil.formatToTexts(temp, new TooltipTextUtil.TextReplacement("<b>%0</b>", firstWord, TooltipTextUtil.TextType.BOLD));
if (words.size() > 1) {
List<String> unprocessedWords = words.subList(1, words.size());
for (String word : unprocessedWords) {
textList.add(TooltipTextUtil.createText(String.format(" %s ", Localization.lang("and")), TooltipTextUtil.TextType.NORMAL));
textList.add(TooltipTextUtil.createText(word, TooltipTextUtil.TextType.BOLD));
}
}
textList.add(getCaseSensitiveDescription());
TextFlow searchDescription = new TextFlow();
searchDescription.getChildren().setAll(textList);
return searchDescription;
}
private Text getCaseSensitiveDescription() {
if (searchFlags.contains(SearchRules.SearchFlags.CASE_SENSITIVE)) {
return TooltipTextUtil.createText(String.format(" (%s). ", Localization.lang("case sensitive")), TooltipTextUtil.TextType.NORMAL);
} else {
return TooltipTextUtil.createText(String.format(" (%s). ", Localization.lang("case insensitive")), TooltipTextUtil.TextType.NORMAL);
}
}
}
| 2,519
| 42.448276
| 158
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/search/rules/describer/GrammarBasedSearchRuleDescriber.java
|
package org.jabref.gui.search.rules.describer;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Pattern;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import org.jabref.gui.util.TooltipTextUtil;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.search.rules.GrammarBasedSearchRule;
import org.jabref.model.search.rules.SearchRules;
import org.jabref.model.search.rules.SearchRules.SearchFlags;
import org.jabref.model.strings.StringUtil;
import org.jabref.search.SearchBaseVisitor;
import org.jabref.search.SearchParser;
import org.antlr.v4.runtime.tree.ParseTree;
public class GrammarBasedSearchRuleDescriber implements SearchDescriber {
private final EnumSet<SearchFlags> searchFlags;
private final ParseTree parseTree;
public GrammarBasedSearchRuleDescriber(EnumSet<SearchFlags> searchFlags, ParseTree parseTree) {
this.searchFlags = searchFlags;
this.parseTree = Objects.requireNonNull(parseTree);
}
@Override
public TextFlow getDescription() {
TextFlow textFlow = new TextFlow();
DescriptionSearchBaseVisitor descriptionSearchBaseVisitor = new DescriptionSearchBaseVisitor();
// describe advanced search expression
textFlow.getChildren().add(TooltipTextUtil.createText(String.format("%s ", Localization.lang("This search contains entries in which")), TooltipTextUtil.TextType.NORMAL));
textFlow.getChildren().addAll(descriptionSearchBaseVisitor.visit(parseTree));
textFlow.getChildren().add(TooltipTextUtil.createText(". ", TooltipTextUtil.TextType.NORMAL));
textFlow.getChildren().add(TooltipTextUtil.createText(searchFlags.contains(SearchRules.SearchFlags.CASE_SENSITIVE) ? Localization
.lang("The search is case-sensitive.") :
Localization.lang("The search is case-insensitive."), TooltipTextUtil.TextType.NORMAL));
return textFlow;
}
private class DescriptionSearchBaseVisitor extends SearchBaseVisitor<List<Text>> {
@Override
public List<Text> visitStart(SearchParser.StartContext context) {
return visit(context.expression());
}
@Override
public List<Text> visitUnaryExpression(SearchParser.UnaryExpressionContext context) {
List<Text> textList = visit(context.expression());
textList.add(0, TooltipTextUtil.createText(Localization.lang("not").concat(" "), TooltipTextUtil.TextType.NORMAL));
return textList;
}
@Override
public List<Text> visitParenExpression(SearchParser.ParenExpressionContext context) {
ArrayList<Text> textList = new ArrayList<>();
textList.add(TooltipTextUtil.createText(String.format("%s", context.expression()), TooltipTextUtil.TextType.NORMAL));
return textList;
}
@Override
public List<Text> visitBinaryExpression(SearchParser.BinaryExpressionContext context) {
List<Text> textList = visit(context.left);
if ("AND".equalsIgnoreCase(context.operator.getText())) {
textList.add(TooltipTextUtil.createText(String.format(" %s ", Localization.lang("and")), TooltipTextUtil.TextType.NORMAL));
} else {
textList.add(TooltipTextUtil.createText(String.format(" %s ", Localization.lang("or")), TooltipTextUtil.TextType.NORMAL));
}
textList.addAll(visit(context.right));
return textList;
}
@Override
public List<Text> visitComparison(SearchParser.ComparisonContext context) {
final List<Text> textList = new ArrayList<>();
final Optional<SearchParser.NameContext> fieldDescriptor = Optional.ofNullable(context.left);
final String value = StringUtil.unquote(context.right.getText(), '"');
if (!fieldDescriptor.isPresent()) {
TextFlow description = new ContainsAndRegexBasedSearchRuleDescriber(searchFlags, value).getDescription();
description.getChildren().forEach(it -> textList.add((Text) it));
return textList;
}
final String field = StringUtil.unquote(fieldDescriptor.get().getText(), '"');
final GrammarBasedSearchRule.ComparisonOperator operator = GrammarBasedSearchRule.ComparisonOperator.build(context.operator.getText());
final boolean regExpFieldSpec = !Pattern.matches("\\w+", field);
String temp = regExpFieldSpec ? Localization.lang(
"any field that matches the regular expression <b>%0</b>") : Localization.lang("the field <b>%0</b>");
if (operator == GrammarBasedSearchRule.ComparisonOperator.CONTAINS) {
if (searchFlags.contains(SearchRules.SearchFlags.REGULAR_EXPRESSION)) {
temp = Localization.lang("%0 contains the regular expression <b>%1</b>", temp);
} else {
temp = Localization.lang("%0 contains the term <b>%1</b>", temp);
}
} else if (operator == GrammarBasedSearchRule.ComparisonOperator.EXACT) {
if (searchFlags.contains(SearchRules.SearchFlags.REGULAR_EXPRESSION)) {
temp = Localization.lang("%0 matches the regular expression <b>%1</b>", temp);
} else {
temp = Localization.lang("%0 matches the term <b>%1</b>", temp);
}
} else if (operator == GrammarBasedSearchRule.ComparisonOperator.DOES_NOT_CONTAIN) {
if (searchFlags.contains(SearchRules.SearchFlags.REGULAR_EXPRESSION)) {
temp = Localization.lang("%0 doesn't contain the regular expression <b>%1</b>", temp);
} else {
temp = Localization.lang("%0 doesn't contain the term <b>%1</b>", temp);
}
} else {
throw new IllegalStateException("CANNOT HAPPEN!");
}
List<Text> formattedTexts = TooltipTextUtil.formatToTexts(temp,
new TooltipTextUtil.TextReplacement("<b>%0</b>", field, TooltipTextUtil.TextType.BOLD),
new TooltipTextUtil.TextReplacement("<b>%1</b>", value, TooltipTextUtil.TextType.BOLD));
textList.addAll(formattedTexts);
return textList;
}
}
}
| 6,470
| 48.776923
| 178
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/search/rules/describer/SearchDescriber.java
|
package org.jabref.gui.search.rules.describer;
import javafx.scene.text.TextFlow;
@FunctionalInterface
public interface SearchDescriber {
TextFlow getDescription();
}
| 174
| 16.5
| 46
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/search/rules/describer/SearchDescribers.java
|
package org.jabref.gui.search.rules.describer;
import org.jabref.logic.search.SearchQuery;
import org.jabref.model.search.rules.ContainsBasedSearchRule;
import org.jabref.model.search.rules.GrammarBasedSearchRule;
import org.jabref.model.search.rules.RegexBasedSearchRule;
public class SearchDescribers {
private SearchDescribers() {
}
/**
* Get the search describer for a given search query.
*
* @param searchQuery the search query
* @return the search describer to turn the search into something human understandable
*/
public static SearchDescriber getSearchDescriberFor(SearchQuery searchQuery) {
if (searchQuery.getRule() instanceof GrammarBasedSearchRule grammarBasedSearchRule) {
return new GrammarBasedSearchRuleDescriber(grammarBasedSearchRule.getSearchFlags(), grammarBasedSearchRule.getTree());
} else if (searchQuery.getRule() instanceof ContainsBasedSearchRule containBasedSearchRule) {
return new ContainsAndRegexBasedSearchRuleDescriber(containBasedSearchRule.getSearchFlags(), searchQuery.getQuery());
} else if (searchQuery.getRule() instanceof RegexBasedSearchRule regexBasedSearchRule) {
return new ContainsAndRegexBasedSearchRuleDescriber(regexBasedSearchRule.getSearchFlags(), searchQuery.getQuery());
} else {
throw new IllegalStateException("Cannot find a describer for searchRule " + searchQuery.getRule() + " and query " + searchQuery.getQuery());
}
}
}
| 1,516
| 47.935484
| 152
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/shared/ConnectToSharedDatabaseCommand.java
|
package org.jabref.gui.shared;
import org.jabref.gui.DialogService;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.actions.SimpleCommand;
import com.airhacks.afterburner.injection.Injector;
/**
* Opens a shared database.
*/
public class ConnectToSharedDatabaseCommand extends SimpleCommand {
private final JabRefFrame jabRefFrame;
public ConnectToSharedDatabaseCommand(JabRefFrame jabRefFrame) {
this.jabRefFrame = jabRefFrame;
}
@Override
public void execute() {
DialogService dialogService = Injector.instantiateModelOrService(DialogService.class);
dialogService.showCustomDialogAndWait(new SharedDatabaseLoginDialogView(jabRefFrame));
}
}
| 708
| 26.269231
| 94
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/shared/PullChangesFromSharedAction.java
|
package org.jabref.gui.shared;
import org.jabref.gui.StateManager;
import org.jabref.gui.actions.ActionHelper;
import org.jabref.gui.actions.SimpleCommand;
import org.jabref.logic.shared.DatabaseSynchronizer;
public class PullChangesFromSharedAction extends SimpleCommand {
private final StateManager stateManager;
public PullChangesFromSharedAction(StateManager stateManager) {
this.stateManager = stateManager;
this.executable.bind(ActionHelper.needsDatabase(stateManager).and(ActionHelper.needsSharedDatabase(stateManager)));
}
public void execute() {
stateManager.getActiveDatabase().ifPresent(databaseContext -> {
DatabaseSynchronizer dbmsSynchronizer = databaseContext.getDBMSSynchronizer();
dbmsSynchronizer.pullChanges();
});
}
}
| 820
| 31.84
| 123
|
java
|
null |
jabref-main/src/main/java/org/jabref/gui/shared/SharedDatabaseLoginDialogView.java
|
package org.jabref.gui.shared;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import org.jabref.gui.DialogService;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.util.BaseDialog;
import org.jabref.gui.util.ControlHelper;
import org.jabref.gui.util.IconValidationDecorator;
import org.jabref.logic.l10n.Localization;
import org.jabref.logic.shared.DBMSType;
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;
public class SharedDatabaseLoginDialogView extends BaseDialog<Void> {
private final JabRefFrame frame;
@FXML private ComboBox<DBMSType> databaseType;
@FXML private TextField host;
@FXML private TextField database;
@FXML private TextField port;
@FXML private TextField user;
@FXML private PasswordField password;
@FXML private CheckBox rememberPassword;
@FXML private TextField folder;
@FXML private Button browseButton;
@FXML private CheckBox autosave;
@FXML private ButtonType connectButton;
@FXML private CheckBox useSSL;
@FXML private TextField fileKeystore;
@FXML private PasswordField passwordKeystore;
@FXML private Button browseKeystore;
@FXML private TextField serverTimezone;
@Inject private DialogService dialogService;
@Inject private PreferencesService preferencesService;
@Inject private FileUpdateMonitor fileUpdateMonitor;
private SharedDatabaseLoginDialogViewModel viewModel;
private final ControlsFxVisualizer visualizer = new ControlsFxVisualizer();
public SharedDatabaseLoginDialogView(JabRefFrame frame) {
this.frame = frame;
this.setTitle(Localization.lang("Connect to shared database"));
ViewLoader.view(this)
.load()
.setAsDialogPane(this);
ControlHelper.setAction(connectButton, this.getDialogPane(), event -> openDatabase());
Button btnConnect = (Button) this.getDialogPane().lookupButton(connectButton);
// must be set here, because in initialize the button is still null
btnConnect.disableProperty().bind(viewModel.formValidation().validProperty().not());
btnConnect.textProperty().bind(EasyBind.map(viewModel.loadingProperty(), loading -> loading ? Localization.lang("Connecting...") : Localization.lang("Connect")));
}
@FXML
private void openDatabase() {
boolean connected = viewModel.openDatabase();
if (connected) {
this.close();
}
}
@FXML
private void initialize() {
visualizer.setDecoration(new IconValidationDecorator());
viewModel = new SharedDatabaseLoginDialogViewModel(frame, dialogService, preferencesService, fileUpdateMonitor);
databaseType.getItems().addAll(DBMSType.values());
databaseType.getSelectionModel().select(0);
database.textProperty().bindBidirectional(viewModel.databaseproperty());
host.textProperty().bindBidirectional(viewModel.hostProperty());
user.textProperty().bindBidirectional(viewModel.userProperty());
password.textProperty().bindBidirectional(viewModel.passwordProperty());
port.textProperty().bindBidirectional(viewModel.portProperty());
serverTimezone.textProperty().bindBidirectional(viewModel.serverTimezoneProperty());
databaseType.valueProperty().bindBidirectional(viewModel.selectedDbmstypeProperty());
folder.textProperty().bindBidirectional(viewModel.folderProperty());
browseButton.disableProperty().bind(viewModel.autosaveProperty().not());
folder.disableProperty().bind(viewModel.autosaveProperty().not());
autosave.selectedProperty().bindBidirectional(viewModel.autosaveProperty());
useSSL.selectedProperty().bindBidirectional(viewModel.useSSLProperty());
fileKeystore.textProperty().bindBidirectional(viewModel.keyStoreProperty());
browseKeystore.disableProperty().bind(viewModel.useSSLProperty().not());
passwordKeystore.disableProperty().bind(viewModel.useSSLProperty().not());
passwordKeystore.textProperty().bindBidirectional(viewModel.keyStorePasswordProperty());
rememberPassword.selectedProperty().bindBidirectional(viewModel.rememberPasswordProperty());
// Must be executed after the initialization of the view, otherwise it doesn't work
Platform.runLater(() -> {
visualizer.initVisualization(viewModel.dbValidation(), database, true);
visualizer.initVisualization(viewModel.hostValidation(), host, true);
visualizer.initVisualization(viewModel.portValidation(), port, true);
visualizer.initVisualization(viewModel.userValidation(), user, true);
EasyBind.subscribe(autosave.selectedProperty(), selected ->
visualizer.initVisualization(viewModel.folderValidation(), folder, true));
EasyBind.subscribe(useSSL.selectedProperty(), selected ->
visualizer.initVisualization(viewModel.keystoreValidation(), fileKeystore, true));
});
}
@FXML
private void showSaveDbToFileDialog(ActionEvent event) {
viewModel.showSaveDbToFileDialog();
}
@FXML
private void showOpenKeystoreFileDialog(ActionEvent event) {
viewModel.showOpenKeystoreFileDialog();
}
}
| 5,797
| 41.948148
| 170
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.