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/autocompleter/PersonNameSuggestionProvider.java
package org.jabref.gui.autocompleter; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Map; import java.util.Objects; import java.util.stream.Stream; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.Author; import org.jabref.model.entry.AuthorList; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.strings.StringUtil; import com.google.common.base.Equivalence; import org.controlsfx.control.textfield.AutoCompletionBinding; /** * Delivers possible completions as a list of {@link Author}s. */ public class PersonNameSuggestionProvider extends SuggestionProvider<Author> { private final Collection<Field> fields; private final BibDatabase database; PersonNameSuggestionProvider(Field field, BibDatabase database) { this(Collections.singletonList(Objects.requireNonNull(field)), database); } public PersonNameSuggestionProvider(Collection<Field> fields, BibDatabase database) { super(); this.fields = Objects.requireNonNull(fields); this.database = database; } public Stream<Author> getAuthors(BibEntry entry) { return entry.getFieldMap() .entrySet() .stream() .filter(fieldValuePair -> fields.contains(fieldValuePair.getKey())) .map(Map.Entry::getValue) .map(AuthorList::parse) .flatMap(authors -> authors.getAuthors().stream()); } @Override protected Equivalence<Author> getEquivalence() { return Equivalence.equals().onResultOf(Author::getLastOnly); } @Override protected Comparator<Author> getComparator() { return Comparator.comparing(Author::getNameForAlphabetization); } @Override protected boolean isMatch(Author candidate, AutoCompletionBinding.ISuggestionRequest request) { return StringUtil.containsIgnoreCase(candidate.getLastFirst(false), request.getUserText()); } @Override public Stream<Author> getSource() { return database.getEntries() .parallelStream() .flatMap(this::getAuthors); } }
2,275
31.056338
99
java
null
jabref-main/src/main/java/org/jabref/gui/autocompleter/ReplaceStrategy.java
package org.jabref.gui.autocompleter; public class ReplaceStrategy implements AutoCompletionStrategy { @Override public AutoCompletionInput analyze(String input) { return new AutoCompletionInput("", input); } }
233
22.4
64
java
null
jabref-main/src/main/java/org/jabref/gui/autocompleter/StringSuggestionProvider.java
package org.jabref.gui.autocompleter; import java.util.Comparator; import java.util.stream.Stream; import org.jabref.model.strings.StringUtil; import com.google.common.base.Equivalence; import org.controlsfx.control.textfield.AutoCompletionBinding; abstract class StringSuggestionProvider extends SuggestionProvider<String> { @Override protected Equivalence<String> getEquivalence() { return Equivalence.equals().onResultOf(value -> value); } @Override protected Comparator<String> getComparator() { return Comparator.naturalOrder(); } @Override protected boolean isMatch(String candidate, AutoCompletionBinding.ISuggestionRequest request) { return StringUtil.containsIgnoreCase(candidate, request.getUserText()); } @Override public abstract Stream<String> getSource(); }
848
26.387097
99
java
null
jabref-main/src/main/java/org/jabref/gui/autocompleter/SuggestionProvider.java
/** * Copyright (c) 2014, 2016 ControlsFX * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of ControlsFX, any associated website, nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CONTROLSFX BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jabref.gui.autocompleter; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.stream.Collectors; import java.util.stream.Stream; import com.google.common.base.Equivalence; import org.controlsfx.control.textfield.AutoCompletionBinding.ISuggestionRequest; /** * This is a simple implementation of a generic suggestion provider callback. * * @param <T> Type of suggestions */ public abstract class SuggestionProvider<T> { public final Collection<T> provideSuggestions(ISuggestionRequest request) { if (!request.getUserText().isEmpty()) { Comparator<T> comparator = getComparator(); Equivalence<T> equivalence = getEquivalence(); return getSource().filter(candidate -> isMatch(candidate, request)) .map(equivalence::wrap) // Need to do a bit of acrobatic as there is no distinctBy method .distinct() .limit(10) .map(Equivalence.Wrapper::get) .sorted(comparator) .collect(Collectors.toList()); } else { return Collections.emptyList(); } } protected abstract Equivalence<T> getEquivalence(); public Collection<T> getPossibleSuggestions() { Comparator<T> comparator = getComparator().reversed(); Equivalence<T> equivalence = getEquivalence(); return getSource().map(equivalence::wrap) // Need to do a bit of acrobatic as there is no distinctBy method .distinct() .map(Equivalence.Wrapper::get) .sorted(comparator) .collect(Collectors.toList()); } /** * Get the comparator to order the suggestions */ protected abstract Comparator<T> getComparator(); /** * Check the given candidate is a match (ie a valid suggestion) */ protected abstract boolean isMatch(T candidate, ISuggestionRequest request); public abstract Stream<T> getSource(); }
3,696
42.494118
119
java
null
jabref-main/src/main/java/org/jabref/gui/autocompleter/SuggestionProviders.java
package org.jabref.gui.autocompleter; import java.util.Set; import org.jabref.logic.journals.JournalAbbreviationRepository; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldProperty; import org.jabref.model.entry.field.StandardField; public class SuggestionProviders { private final boolean isEmpty; private BibDatabase database; private JournalAbbreviationRepository abbreviationRepository; private AutoCompletePreferences autoCompletePreferences; public SuggestionProviders(BibDatabase database, JournalAbbreviationRepository abbreviationRepository, AutoCompletePreferences autoCompletePreferences) { this.database = database; this.abbreviationRepository = abbreviationRepository; this.autoCompletePreferences = autoCompletePreferences; this.isEmpty = false; } public SuggestionProviders() { this.isEmpty = true; } public SuggestionProvider<?> getForField(Field field) { if (isEmpty || !autoCompletePreferences.getCompleteFields().contains(field)) { return new EmptySuggestionProvider(); } Set<FieldProperty> fieldProperties = field.getProperties(); if (fieldProperties.contains(FieldProperty.PERSON_NAMES)) { return new PersonNameSuggestionProvider(field, database); } else if (fieldProperties.contains(FieldProperty.SINGLE_ENTRY_LINK) || fieldProperties.contains(FieldProperty.MULTIPLE_ENTRY_LINK)) { return new BibEntrySuggestionProvider(database); } else if (fieldProperties.contains(FieldProperty.JOURNAL_NAME) || StandardField.PUBLISHER == field) { return new JournalsSuggestionProvider(field, database, abbreviationRepository); } else { return new WordSuggestionProvider(field, database); } } }
1,897
40.26087
157
java
null
jabref-main/src/main/java/org/jabref/gui/autocompleter/WordSuggestionProvider.java
package org.jabref.gui.autocompleter; import java.util.Objects; import java.util.stream.Stream; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.field.Field; /** * Stores all words in the given field. */ public class WordSuggestionProvider extends StringSuggestionProvider { private final Field field; private final BibDatabase database; public WordSuggestionProvider(Field field, BibDatabase database) { this.field = Objects.requireNonNull(field); this.database = database; } @Override public Stream<String> getSource() { return database.getEntries() .parallelStream() .flatMap(entry -> entry.getFieldAsWords(field).stream()); } }
765
25.413793
80
java
null
jabref-main/src/main/java/org/jabref/gui/auximport/AuxParserResultViewModel.java
package org.jabref.gui.auximport; import org.jabref.logic.auxparser.AuxParserResult; import org.jabref.logic.l10n.Localization; public class AuxParserResultViewModel { private AuxParserResult auxParserResult; public AuxParserResultViewModel(AuxParserResult auxParserResult) { this.auxParserResult = auxParserResult; } /** * Prints parsing statistics */ public String getInformation(boolean includeMissingEntries) { StringBuilder result = new StringBuilder(); result.append(Localization.lang("keys in library")).append(' ').append(this.auxParserResult.getMasterDatabase().getEntryCount()).append('\n') .append(Localization.lang("found in AUX file")).append(' ').append(this.auxParserResult.getFoundKeysInAux()).append('\n') .append(Localization.lang("resolved")).append(' ').append(this.auxParserResult.getResolvedKeysCount()).append('\n') .append(Localization.lang("not found")).append(' ').append(this.auxParserResult.getUnresolvedKeysCount()).append('\n') .append(Localization.lang("crossreferenced entries included")).append(' ').append(this.auxParserResult.getCrossRefEntriesCount()).append('\n') .append(Localization.lang("strings included")).append(' ').append(this.auxParserResult.getInsertedStrings()).append('\n'); if (includeMissingEntries && (this.auxParserResult.getUnresolvedKeysCount() > 0)) { for (String entry : this.auxParserResult.getUnresolvedKeys()) { result.append(entry).append('\n'); } } if (this.auxParserResult.getNestedAuxCount() > 0) { result.append(Localization.lang("nested AUX files")).append(' ').append(this.auxParserResult.getNestedAuxCount()); } return result.toString(); } }
1,837
47.368421
156
java
null
jabref-main/src/main/java/org/jabref/gui/auximport/FromAuxDialog.java
package org.jabref.gui.auximport; import java.nio.file.Path; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.ListView; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import org.jabref.gui.DialogService; import org.jabref.gui.JabRefFrame; import org.jabref.gui.LibraryTab; import org.jabref.gui.theme.ThemeManager; import org.jabref.gui.util.BaseDialog; import org.jabref.gui.util.FileDialogConfiguration; import org.jabref.logic.auxparser.AuxParser; import org.jabref.logic.auxparser.AuxParserResult; import org.jabref.logic.auxparser.DefaultAuxParser; import org.jabref.logic.l10n.Localization; import org.jabref.logic.util.StandardFileType; import org.jabref.model.database.BibDatabase; import org.jabref.model.database.BibDatabaseContext; import org.jabref.preferences.PreferencesService; import com.airhacks.afterburner.views.ViewLoader; import jakarta.inject.Inject; /** * A wizard dialog for generating a new sub database from existing TeX AUX file */ public class FromAuxDialog extends BaseDialog<Void> { private final LibraryTab libraryTab; @FXML private ButtonType generateButtonType; private final Button generateButton; @FXML private TextField auxFileField; @FXML private ListView<String> notFoundList; @FXML private TextArea statusInfos; private AuxParserResult auxParserResult; @Inject private PreferencesService preferences; @Inject private DialogService dialogService; @Inject private ThemeManager themeManager; public FromAuxDialog(JabRefFrame frame) { libraryTab = frame.getCurrentLibraryTab(); this.setTitle(Localization.lang("AUX file import")); ViewLoader.view(this) .load() .setAsDialogPane(this); generateButton = (Button) this.getDialogPane().lookupButton(generateButtonType); generateButton.setDisable(true); generateButton.defaultButtonProperty().bind(generateButton.disableProperty().not()); setResultConverter(button -> { if (button == generateButtonType) { BibDatabaseContext context = new BibDatabaseContext(auxParserResult.getGeneratedBibDatabase()); frame.addTab(context, true); } return null; }); themeManager.updateFontStyle(getDialogPane().getScene()); } @FXML private void parseActionPerformed() { notFoundList.getItems().clear(); statusInfos.setText(""); BibDatabase refBase = libraryTab.getDatabase(); String auxName = auxFileField.getText(); if ((auxName != null) && (refBase != null) && !auxName.isEmpty()) { AuxParser auxParser = new DefaultAuxParser(refBase); auxParserResult = auxParser.parse(Path.of(auxName)); notFoundList.getItems().setAll(auxParserResult.getUnresolvedKeys()); statusInfos.setText(new AuxParserResultViewModel(auxParserResult).getInformation(false)); if (!auxParserResult.getGeneratedBibDatabase().hasEntries()) { // The generated database contains no entries -> no active generate-button statusInfos.setText(statusInfos.getText() + "\n" + Localization.lang("empty library")); generateButton.setDisable(true); } else { generateButton.setDisable(false); } } else { generateButton.setDisable(true); } } @FXML private void browseButtonClicked() { FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() .addExtensionFilter(StandardFileType.AUX) .withDefaultExtension(StandardFileType.AUX) .withInitialDirectory(preferences.getFilePreferences().getWorkingDirectory()).build(); dialogService.showFileOpenDialog(fileDialogConfiguration).ifPresent(file -> auxFileField.setText(file.toAbsolutePath().toString())); } }
4,060
38.427184
140
java
null
jabref-main/src/main/java/org/jabref/gui/auximport/NewSubLibraryAction.java
package org.jabref.gui.auximport; import org.jabref.gui.DialogService; import org.jabref.gui.JabRefFrame; import org.jabref.gui.StateManager; import org.jabref.gui.actions.SimpleCommand; import com.airhacks.afterburner.injection.Injector; import static org.jabref.gui.actions.ActionHelper.needsDatabase; /** * The action concerned with generate a new (sub-)database from latex AUX file. */ public class NewSubLibraryAction extends SimpleCommand { private final JabRefFrame jabRefFrame; public NewSubLibraryAction(JabRefFrame jabRefFrame, StateManager stateManager) { this.jabRefFrame = jabRefFrame; this.executable.bind(needsDatabase(stateManager)); } @Override public void execute() { DialogService dialogService = Injector.instantiateModelOrService(DialogService.class); dialogService.showCustomDialogAndWait(new FromAuxDialog(jabRefFrame)); } }
914
28.516129
94
java
null
jabref-main/src/main/java/org/jabref/gui/backup/BackupResolverDialog.java
package org.jabref.gui.backup; import java.io.IOException; import java.nio.file.Path; import java.util.Optional; import javafx.scene.control.ButtonBar; import javafx.scene.control.ButtonType; import javafx.scene.control.Hyperlink; import org.jabref.gui.FXDialog; import org.jabref.gui.Globals; import org.jabref.gui.desktop.JabRefDesktop; import org.jabref.logic.l10n.Localization; import org.jabref.logic.util.BackupFileType; import org.jabref.logic.util.io.BackupFileUtil; import org.controlsfx.control.HyperlinkLabel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BackupResolverDialog extends FXDialog { public static final ButtonType RESTORE_FROM_BACKUP = new ButtonType(Localization.lang("Restore from backup"), ButtonBar.ButtonData.OK_DONE); public static final ButtonType REVIEW_BACKUP = new ButtonType(Localization.lang("Review backup"), ButtonBar.ButtonData.LEFT); public static final ButtonType IGNORE_BACKUP = new ButtonType(Localization.lang("Ignore backup"), ButtonBar.ButtonData.CANCEL_CLOSE); private static final Logger LOGGER = LoggerFactory.getLogger(BackupResolverDialog.class); public BackupResolverDialog(Path originalPath, Path backupDir) { super(AlertType.CONFIRMATION, Localization.lang("Backup found"), true); setHeaderText(null); getDialogPane().setMinHeight(180); getDialogPane().getButtonTypes().setAll(RESTORE_FROM_BACKUP, REVIEW_BACKUP, IGNORE_BACKUP); Optional<Path> backupPathOpt = BackupFileUtil.getPathOfLatestExistingBackupFile(originalPath, BackupFileType.BACKUP, backupDir); String backupFilename = backupPathOpt.map(Path::getFileName).map(Path::toString).orElse(Localization.lang("File not found")); String content = new StringBuilder() .append(Localization.lang("A backup file for '%0' was found at [%1]", originalPath.getFileName().toString(), backupFilename)) .append("\n") .append(Localization.lang("This could indicate that JabRef did not shut down cleanly last time the file was used.")) .append("\n\n") .append(Localization.lang("Do you want to recover the library from the backup file?")) .toString(); setContentText(content); HyperlinkLabel contentLabel = new HyperlinkLabel(content); contentLabel.setPrefWidth(360); contentLabel.setOnAction(e -> { if (backupPathOpt.isPresent()) { if (!(e.getSource() instanceof Hyperlink)) { return; } String clickedLinkText = ((Hyperlink) (e.getSource())).getText(); if (backupFilename.equals(clickedLinkText)) { try { JabRefDesktop.openFolderAndSelectFile(backupPathOpt.get(), Globals.prefs, null); } catch (IOException ex) { LOGGER.error("Could not open backup folder", ex); } } } }); getDialogPane().setContent(contentLabel); } }
3,153
45.382353
144
java
null
jabref-main/src/main/java/org/jabref/gui/bibtexextractor/BibtexExtractor.java
package org.jabref.gui.bibtexextractor; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.EntryType; import org.jabref.model.entry.types.StandardEntryType; public class BibtexExtractor { private static final String AUTHOR_TAG = "[author_tag]"; private static final String URL_TAG = "[url_tag]"; private static final String YEAR_TAG = "[year_tag]"; private static final String PAGES_TAG = "[pages_tag]"; private static final String INITIALS_GROUP = "INITIALS"; private static final String LASTNAME_GROUP = "LASTNAME"; private static final Pattern URL_PATTERN = Pattern.compile( "(?:^|[\\W])((ht|f)tp(s?):\\/\\/|www\\.)" + "(([\\w\\-]+\\.)+?([\\w\\-.~]+\\/?)*" + "[\\p{Alnum}.,%_=?&#\\-+()\\[\\]\\*$~@!:/{};']*)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); private static final Pattern YEAR_PATTERN = Pattern.compile( "\\d{4}", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); private static final Pattern AUTHOR_PATTERN = Pattern.compile( "(?<" + LASTNAME_GROUP + ">\\p{Lu}\\w+),?\\s(?<" + INITIALS_GROUP + ">(\\p{Lu}\\.\\s){1,2})" + "\\s*(and|,|\\.)*", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); private static final Pattern AUTHOR_PATTERN_2 = Pattern.compile( "(?<" + INITIALS_GROUP + ">(\\p{Lu}\\.\\s){1,2})(?<" + LASTNAME_GROUP + ">\\p{Lu}\\w+)" + "\\s*(and|,|\\.)*", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); private static final Pattern PAGES_PATTERN = Pattern.compile( "(p.)?\\s?\\d+(-\\d+)?", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); private final List<String> urls = new ArrayList<>(); private final List<String> authors = new ArrayList<>(); private String year = ""; private String pages = ""; private String title = ""; private boolean isArticle = true; private String journalOrPublisher = ""; public BibEntry extract(String input) { String inputWithoutUrls = findUrls(input); String inputWithoutAuthors = findAuthors(inputWithoutUrls); String inputWithoutYear = findYear(inputWithoutAuthors); String inputWithoutPages = findPages(inputWithoutYear); String nonParsed = findParts(inputWithoutPages); return generateEntity(nonParsed); } private BibEntry generateEntity(String input) { EntryType type = isArticle ? StandardEntryType.Article : StandardEntryType.Book; BibEntry extractedEntity = new BibEntry(type); extractedEntity.setField(StandardField.AUTHOR, String.join(" and ", authors)); extractedEntity.setField(StandardField.URL, String.join(", ", urls)); extractedEntity.setField(StandardField.YEAR, year); extractedEntity.setField(StandardField.PAGES, pages); extractedEntity.setField(StandardField.TITLE, title); if (isArticle) { extractedEntity.setField(StandardField.JOURNAL, journalOrPublisher); } else { extractedEntity.setField(StandardField.PUBLISHER, journalOrPublisher); } extractedEntity.setField(StandardField.COMMENT, input); return extractedEntity; } private String findUrls(String input) { Matcher matcher = URL_PATTERN.matcher(input); while (matcher.find()) { urls.add(input.substring(matcher.start(1), matcher.end())); } return fixSpaces(matcher.replaceAll(URL_TAG)); } private String findYear(String input) { Matcher matcher = YEAR_PATTERN.matcher(input); while (matcher.find()) { String yearCandidate = input.substring(matcher.start(), matcher.end()); int intYearCandidate = Integer.parseInt(yearCandidate); if ((intYearCandidate > 1700) && (intYearCandidate <= Calendar.getInstance().get(Calendar.YEAR))) { year = yearCandidate; return fixSpaces(input.replace(year, YEAR_TAG)); } } return input; } private String findAuthors(String input) { String currentInput = findAuthorsByPattern(input, AUTHOR_PATTERN); return findAuthorsByPattern(currentInput, AUTHOR_PATTERN_2); } private String findAuthorsByPattern(String input, Pattern pattern) { Matcher matcher = pattern.matcher(input); while (matcher.find()) { authors.add(GenerateAuthor(matcher.group(LASTNAME_GROUP), matcher.group(INITIALS_GROUP))); } return fixSpaces(matcher.replaceAll(AUTHOR_TAG)); } private String GenerateAuthor(String lastName, String initials) { return lastName + ", " + initials; } private String findPages(String input) { Matcher matcher = PAGES_PATTERN.matcher(input); if (matcher.find()) { pages = input.substring(matcher.start(), matcher.end()); } return fixSpaces(matcher.replaceFirst(PAGES_TAG)); } private String fixSpaces(String input) { return input.replaceAll("[,.!?;:]", "$0 ") .replaceAll("\\p{Lt}", " $0") .replaceAll("\\s+", " ").trim(); } private String findParts(String input) { ArrayList<String> lastParts = new ArrayList<>(); int afterAuthorsIndex = input.lastIndexOf(AUTHOR_TAG); if (afterAuthorsIndex == -1) { return input; } else { afterAuthorsIndex += AUTHOR_TAG.length(); } int delimiterIndex = input.lastIndexOf("//"); if (delimiterIndex != -1) { lastParts.add(input.substring(afterAuthorsIndex, delimiterIndex) .replace(YEAR_TAG, "") .replace(PAGES_TAG, "")); lastParts.addAll(Arrays.asList(input.substring(delimiterIndex + 2).split(",|\\."))); } else { lastParts.addAll(Arrays.asList(input.substring(afterAuthorsIndex).split(",|\\."))); } int nonDigitParts = 0; for (String part : lastParts) { if (part.matches(".*\\d.*")) { break; } nonDigitParts++; } if (nonDigitParts > 0) { title = lastParts.get(0); } if (nonDigitParts > 1) { journalOrPublisher = lastParts.get(1); } if (nonDigitParts > 2) { isArticle = false; } return fixSpaces(input); } }
6,846
39.040936
111
java
null
jabref-main/src/main/java/org/jabref/gui/bibtexextractor/BibtexExtractorViewModel.java
package org.jabref.gui.bibtexextractor; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.undo.UndoManager; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import org.jabref.gui.DialogService; import org.jabref.gui.Globals; import org.jabref.gui.StateManager; import org.jabref.gui.externalfiles.ImportHandler; import org.jabref.gui.util.BackgroundTask; import org.jabref.gui.util.TaskExecutor; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.fetcher.GrobidCitationFetcher; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.util.FileUpdateMonitor; import org.jabref.preferences.PreferencesService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BibtexExtractorViewModel { private static final Logger LOGGER = LoggerFactory.getLogger(BibtexExtractorViewModel.class); private final StringProperty inputTextProperty = new SimpleStringProperty(""); private final DialogService dialogService; private final PreferencesService preferencesService; private final TaskExecutor taskExecutor; private final ImportHandler importHandler; public BibtexExtractorViewModel(BibDatabaseContext bibdatabaseContext, DialogService dialogService, PreferencesService preferencesService, FileUpdateMonitor fileUpdateMonitor, TaskExecutor taskExecutor, UndoManager undoManager, StateManager stateManager) { this.dialogService = dialogService; this.preferencesService = preferencesService; this.taskExecutor = taskExecutor; this.importHandler = new ImportHandler( bibdatabaseContext, preferencesService, fileUpdateMonitor, undoManager, stateManager, dialogService, taskExecutor); } public StringProperty inputTextProperty() { return this.inputTextProperty; } public void startParsing() { if (preferencesService.getGrobidPreferences().isGrobidEnabled()) { parseUsingGrobid(); } else { parseUsingBibtexExtractor(); } } private void parseUsingBibtexExtractor() { BibEntry parsedEntry = new BibtexExtractor().extract(inputTextProperty.getValue()); importHandler.importEntries(List.of(parsedEntry)); trackNewEntry(parsedEntry, "ParseWithBibTeXExtractor"); } private void parseUsingGrobid() { GrobidCitationFetcher grobidCitationFetcher = new GrobidCitationFetcher(preferencesService.getGrobidPreferences(), preferencesService.getImportFormatPreferences()); BackgroundTask.wrap(() -> grobidCitationFetcher.performSearch(inputTextProperty.getValue())) .onRunning(() -> dialogService.notify(Localization.lang("Your text is being parsed..."))) .onFailure(e -> { if (e instanceof FetcherException) { String msg = Localization.lang("There are connection issues with a JabRef server. Detailed information: %0", e.getMessage()); dialogService.notify(msg); } else { LOGGER.warn("Missing exception handling.", e); } }) .onSuccess(parsedEntries -> { dialogService.notify(Localization.lang("%0 entries were parsed from your query.", String.valueOf(parsedEntries.size()))); importHandler.importEntries(parsedEntries); for (BibEntry bibEntry : parsedEntries) { trackNewEntry(bibEntry, "ParseWithGrobid"); } }).executeWith(taskExecutor); } private void trackNewEntry(BibEntry bibEntry, String eventMessage) { Map<String, String> properties = new HashMap<>(); properties.put("EntryType", bibEntry.typeProperty().getValue().getName()); Globals.getTelemetryClient().ifPresent(client -> client.trackEvent(eventMessage, properties, new HashMap<>())); } }
4,578
42.198113
172
java
null
jabref-main/src/main/java/org/jabref/gui/bibtexextractor/ExtractBibtexAction.java
package org.jabref.gui.bibtexextractor; import org.jabref.gui.DialogService; import org.jabref.gui.StateManager; import org.jabref.gui.actions.SimpleCommand; import org.jabref.gui.importer.GrobidOptInDialogHelper; import org.jabref.preferences.PreferencesService; import com.airhacks.afterburner.injection.Injector; import static org.jabref.gui.actions.ActionHelper.needsDatabase; public class ExtractBibtexAction extends SimpleCommand { PreferencesService preferencesService; DialogService dialogService; public ExtractBibtexAction(DialogService dialogService, PreferencesService preferencesService, StateManager stateManager) { this.preferencesService = preferencesService; this.dialogService = dialogService; this.executable.bind(needsDatabase(stateManager)); } @Override public void execute() { DialogService dialogService = Injector.instantiateModelOrService(DialogService.class); GrobidOptInDialogHelper.showAndWaitIfUserIsUndecided(dialogService, preferencesService.getGrobidPreferences()); dialogService.showCustomDialogAndWait(new ExtractBibtexDialog()); } }
1,151
36.16129
127
java
null
jabref-main/src/main/java/org/jabref/gui/bibtexextractor/ExtractBibtexDialog.java
package org.jabref.gui.bibtexextractor; import javax.swing.undo.UndoManager; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.TextArea; import javafx.scene.control.Tooltip; import org.jabref.gui.DialogService; import org.jabref.gui.StateManager; import org.jabref.gui.util.BaseDialog; import org.jabref.gui.util.TaskExecutor; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.util.FileUpdateMonitor; import org.jabref.preferences.PreferencesService; import com.airhacks.afterburner.views.ViewLoader; import jakarta.inject.Inject; /** * GUI Dialog for the feature "Extract BibTeX from plain text". */ public class ExtractBibtexDialog extends BaseDialog<Void> { private final Button buttonParse; @FXML private TextArea input; @FXML private ButtonType parseButtonType; private BibtexExtractorViewModel viewModel; @Inject private StateManager stateManager; @Inject private DialogService dialogService; @Inject private FileUpdateMonitor fileUpdateMonitor; @Inject private TaskExecutor taskExecutor; @Inject private UndoManager undoManager; @Inject private PreferencesService preferencesService; public ExtractBibtexDialog() { ViewLoader.view(this) .load() .setAsDialogPane(this); this.setTitle(Localization.lang("Plain References Parser")); input.setPromptText(Localization.lang("Please enter the plain references to extract from separated by double empty lines.")); input.selectAll(); buttonParse = (Button) getDialogPane().lookupButton(parseButtonType); buttonParse.setTooltip(new Tooltip((Localization.lang("Starts the extraction and adds the resulting entries to the currently opened database")))); buttonParse.setOnAction(event -> viewModel.startParsing()); buttonParse.disableProperty().bind(viewModel.inputTextProperty().isEmpty()); } @FXML private void initialize() { BibDatabaseContext database = stateManager.getActiveDatabase().orElseThrow(() -> new NullPointerException("Database null")); this.viewModel = new BibtexExtractorViewModel( database, dialogService, preferencesService, fileUpdateMonitor, taskExecutor, undoManager, stateManager); input.textProperty().bindBidirectional(viewModel.inputTextProperty()); } }
2,581
37.537313
154
java
null
jabref-main/src/main/java/org/jabref/gui/citationkeypattern/GenerateCitationKeyAction.java
package org.jabref.gui.citationkeypattern; import java.util.List; import java.util.function.Consumer; import org.jabref.gui.DialogService; import org.jabref.gui.JabRefFrame; import org.jabref.gui.StateManager; import org.jabref.gui.actions.ActionHelper; import org.jabref.gui.actions.SimpleCommand; import org.jabref.gui.undo.NamedCompound; import org.jabref.gui.undo.UndoableKeyChange; import org.jabref.gui.util.BackgroundTask; import org.jabref.gui.util.DefaultTaskExecutor; import org.jabref.gui.util.TaskExecutor; import org.jabref.logic.citationkeypattern.CitationKeyGenerator; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.BibEntry; import org.jabref.preferences.PreferencesService; public class GenerateCitationKeyAction extends SimpleCommand { private final JabRefFrame frame; private final DialogService dialogService; private final StateManager stateManager; private List<BibEntry> entries; private boolean isCanceled; private final TaskExecutor taskExecutor; private final PreferencesService preferencesService; public GenerateCitationKeyAction(JabRefFrame frame, DialogService dialogService, StateManager stateManager, TaskExecutor taskExecutor, PreferencesService preferencesService) { this.frame = frame; this.dialogService = dialogService; this.stateManager = stateManager; this.taskExecutor = taskExecutor; this.preferencesService = preferencesService; this.executable.bind(ActionHelper.needsEntriesSelected(stateManager)); } @Override public void execute() { entries = stateManager.getSelectedEntries(); if (entries.isEmpty()) { dialogService.showWarningDialogAndWait(Localization.lang("Autogenerate citation keys"), Localization.lang("First select the entries you want keys to be generated for.")); return; } dialogService.notify(formatOutputMessage(Localization.lang("Generating citation key for"), entries.size())); checkOverwriteKeysChosen(); if (!this.isCanceled) { BackgroundTask<Void> backgroundTask = this.generateKeysInBackground(); backgroundTask.showToUser(true); backgroundTask.titleProperty().set(Localization.lang("Autogenerate citation keys")); backgroundTask.messageProperty().set(Localization.lang("%0/%1 entries", 0, entries.size())); backgroundTask.executeWith(this.taskExecutor); } } public static boolean confirmOverwriteKeys(DialogService dialogService, PreferencesService preferencesService) { if (preferencesService.getCitationKeyPatternPreferences().shouldWarnBeforeOverwriteCiteKey()) { return dialogService.showConfirmationDialogWithOptOutAndWait( Localization.lang("Overwrite keys"), Localization.lang("One or more keys will be overwritten. Continue?"), Localization.lang("Overwrite keys"), Localization.lang("Cancel"), Localization.lang("Do not ask again"), optOut -> preferencesService.getCitationKeyPatternPreferences().setWarnBeforeOverwriteCiteKey(!optOut)); } else { // Always overwrite keys by default return true; } } private void checkOverwriteKeysChosen() { // We don't want to generate keys for entries which already have one thus remove the entries if (this.preferencesService.getCitationKeyPatternPreferences().shouldAvoidOverwriteCiteKey()) { entries.removeIf(BibEntry::hasCitationKey); // if we're going to override some citation keys warn the user about it } else if (entries.parallelStream().anyMatch(BibEntry::hasCitationKey)) { boolean overwriteKeys = confirmOverwriteKeys(dialogService, this.preferencesService); // The user doesn't want to override citation keys if (!overwriteKeys) { isCanceled = true; } } } private BackgroundTask<Void> generateKeysInBackground() { return new BackgroundTask<>() { private NamedCompound compound; @Override protected Void call() { if (isCanceled) { return null; } DefaultTaskExecutor.runInJavaFXThread(() -> { updateProgress(0, entries.size()); messageProperty().set(Localization.lang("%0/%1 entries", 0, entries.size())); }); stateManager.getActiveDatabase().ifPresent(databaseContext -> { // generate the new citation keys for each entry compound = new NamedCompound(Localization.lang("Autogenerate citation keys")); CitationKeyGenerator keyGenerator = new CitationKeyGenerator(databaseContext, preferencesService.getCitationKeyPatternPreferences()); int entriesDone = 0; for (BibEntry entry : entries) { keyGenerator.generateAndSetKey(entry) .ifPresent(fieldChange -> compound.addEdit(new UndoableKeyChange(fieldChange))); entriesDone++; int finalEntriesDone = entriesDone; DefaultTaskExecutor.runInJavaFXThread(() -> { updateProgress(finalEntriesDone, entries.size()); messageProperty().set(Localization.lang("%0/%1 entries", finalEntriesDone, entries.size())); }); } compound.end(); }); return null; } @Override public BackgroundTask<Void> onSuccess(Consumer<Void> onSuccess) { // register the undo event only if new citation keys were generated if (compound.hasEdits()) { frame.getUndoManager().addEdit(compound); } frame.getCurrentLibraryTab().markBaseChanged(); dialogService.notify(formatOutputMessage(Localization.lang("Generated citation key for"), entries.size())); return super.onSuccess(onSuccess); } }; } private String formatOutputMessage(String start, int count) { return String.format("%s %d %s.", start, count, (count > 1 ? Localization.lang("entries") : Localization.lang("entry"))); } }
6,742
44.255034
179
java
null
jabref-main/src/main/java/org/jabref/gui/citationkeypattern/GenerateCitationKeySingleAction.java
package org.jabref.gui.citationkeypattern; import javax.swing.undo.UndoManager; import org.jabref.gui.DialogService; import org.jabref.gui.actions.SimpleCommand; import org.jabref.gui.undo.UndoableKeyChange; import org.jabref.logic.citationkeypattern.CitationKeyGenerator; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.preferences.PreferencesService; public class GenerateCitationKeySingleAction extends SimpleCommand { private final DialogService dialogService; private final BibDatabaseContext databaseContext; private final PreferencesService preferencesService; private final BibEntry entry; private final UndoManager undoManager; public GenerateCitationKeySingleAction(BibEntry entry, BibDatabaseContext databaseContext, DialogService dialogService, PreferencesService preferencesService, UndoManager undoManager) { this.entry = entry; this.databaseContext = databaseContext; this.dialogService = dialogService; this.preferencesService = preferencesService; this.undoManager = undoManager; if (preferencesService.getCitationKeyPatternPreferences().shouldAvoidOverwriteCiteKey()) { this.executable.bind(entry.getCiteKeyBinding().isEmpty()); } } @Override public void execute() { if (!entry.hasCitationKey() || GenerateCitationKeyAction.confirmOverwriteKeys(dialogService, preferencesService)) { new CitationKeyGenerator(databaseContext, preferencesService.getCitationKeyPatternPreferences()) .generateAndSetKey(entry) .ifPresent(change -> undoManager.addEdit(new UndoableKeyChange(change))); } } }
1,750
40.690476
189
java
null
jabref-main/src/main/java/org/jabref/gui/cleanup/CleanupAction.java
package org.jabref.gui.cleanup; import java.util.List; import java.util.Optional; import org.jabref.gui.DialogService; import org.jabref.gui.Globals; import org.jabref.gui.JabRefFrame; import org.jabref.gui.StateManager; import org.jabref.gui.actions.ActionHelper; import org.jabref.gui.actions.SimpleCommand; import org.jabref.gui.undo.NamedCompound; import org.jabref.gui.undo.UndoableFieldChange; import org.jabref.gui.util.BackgroundTask; import org.jabref.logic.cleanup.CleanupWorker; import org.jabref.logic.l10n.Localization; import org.jabref.model.FieldChange; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.preferences.CleanupPreferences; import org.jabref.preferences.PreferencesService; public class CleanupAction extends SimpleCommand { private final JabRefFrame frame; private final PreferencesService preferences; private final DialogService dialogService; private final StateManager stateManager; private boolean isCanceled; private int modifiedEntriesCount; public CleanupAction(JabRefFrame frame, PreferencesService preferences, DialogService dialogService, StateManager stateManager) { this.frame = frame; this.preferences = preferences; this.dialogService = dialogService; this.stateManager = stateManager; this.executable.bind(ActionHelper.needsEntriesSelected(stateManager)); } @Override public void execute() { if (stateManager.getActiveDatabase().isEmpty()) { return; } if (stateManager.getSelectedEntries().isEmpty()) { // None selected. Inform the user to select entries first. dialogService.showInformationDialogAndWait(Localization.lang("Cleanup entry"), Localization.lang("First select entries to clean up.")); return; } dialogService.notify(Localization.lang("Doing a cleanup for %0 entries...", Integer.toString(stateManager.getSelectedEntries().size()))); isCanceled = false; modifiedEntriesCount = 0; CleanupDialog cleanupDialog = new CleanupDialog( stateManager.getActiveDatabase().get(), preferences.getCleanupPreferences(), preferences.getFilePreferences() ); Optional<CleanupPreferences> chosenPreset = dialogService.showCustomDialogAndWait(cleanupDialog); chosenPreset.ifPresent(preset -> { if (preset.isActive(CleanupPreferences.CleanupStep.RENAME_PDF) && preferences.getAutoLinkPreferences().shouldAskAutoNamingPdfs()) { boolean confirmed = dialogService.showConfirmationDialogWithOptOutAndWait(Localization.lang("Autogenerate PDF Names"), Localization.lang("Auto-generating PDF-Names does not support undo. Continue?"), Localization.lang("Autogenerate PDF Names"), Localization.lang("Cancel"), Localization.lang("Do not ask again"), optOut -> preferences.getAutoLinkPreferences().setAskAutoNamingPdfs(!optOut)); if (!confirmed) { isCanceled = true; return; } } preferences.getCleanupPreferences().setActiveJobs(preset.getActiveJobs()); preferences.getCleanupPreferences().setFieldFormatterCleanups(preset.getFieldFormatterCleanups()); BackgroundTask.wrap(() -> cleanup(stateManager.getActiveDatabase().get(), preset)) .onSuccess(result -> showResults()) .executeWith(Globals.TASK_EXECUTOR); }); } /** * Runs the cleanup on the entry and records the change. */ private void doCleanup(BibDatabaseContext databaseContext, CleanupPreferences preset, BibEntry entry, NamedCompound ce) { // Create and run cleaner CleanupWorker cleaner = new CleanupWorker( databaseContext, preferences.getFilePreferences(), preferences.getTimestampPreferences()); List<FieldChange> changes = cleaner.cleanup(preset, entry); // Register undo action for (FieldChange change : changes) { ce.addEdit(new UndoableFieldChange(change)); } } private void showResults() { if (isCanceled) { return; } if (modifiedEntriesCount > 0) { frame.getCurrentLibraryTab().updateEntryEditorIfShowing(); frame.getCurrentLibraryTab().markBaseChanged(); } if (modifiedEntriesCount == 0) { dialogService.notify(Localization.lang("No entry needed a clean up")); } else if (modifiedEntriesCount == 1) { dialogService.notify(Localization.lang("One entry needed a clean up")); } else { dialogService.notify(Localization.lang("%0 entries needed a clean up", Integer.toString(modifiedEntriesCount))); } } private void cleanup(BibDatabaseContext databaseContext, CleanupPreferences cleanupPreferences) { for (BibEntry entry : stateManager.getSelectedEntries()) { // undo granularity is on entry level NamedCompound ce = new NamedCompound(Localization.lang("Cleanup entry")); doCleanup(databaseContext, cleanupPreferences, entry, ce); ce.end(); if (ce.hasEdits()) { modifiedEntriesCount++; frame.getUndoManager().addEdit(ce); } } } }
5,611
38.521127
147
java
null
jabref-main/src/main/java/org/jabref/gui/cleanup/CleanupDialog.java
package org.jabref.gui.cleanup; import javafx.scene.control.ButtonType; import javafx.scene.control.ScrollPane; import org.jabref.gui.util.BaseDialog; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.preferences.CleanupPreferences; import org.jabref.preferences.FilePreferences; public class CleanupDialog extends BaseDialog<CleanupPreferences> { public CleanupDialog(BibDatabaseContext databaseContext, CleanupPreferences initialPreset, FilePreferences filePreferences) { setTitle(Localization.lang("Cleanup entries")); getDialogPane().setPrefSize(600, 650); getDialogPane().getButtonTypes().setAll(ButtonType.OK, ButtonType.CANCEL); CleanupPresetPanel presetPanel = new CleanupPresetPanel(databaseContext, initialPreset, filePreferences); // placing the content of the presetPanel in a scroll pane ScrollPane scrollPane = new ScrollPane(); scrollPane.setFitToWidth(true); scrollPane.setFitToHeight(true); scrollPane.setContent(presetPanel); getDialogPane().setContent(scrollPane); setResultConverter(button -> { if (button == ButtonType.OK) { return presetPanel.getCleanupPreset(); } else { return null; } }); } }
1,359
36.777778
129
java
null
jabref-main/src/main/java/org/jabref/gui/cleanup/CleanupPresetPanel.java
package org.jabref.gui.cleanup; import java.nio.file.Path; import java.util.EnumSet; import java.util.Objects; import java.util.Optional; import javafx.collections.FXCollections; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; import javafx.scene.layout.VBox; import org.jabref.gui.commonfxcontrols.FieldFormatterCleanupsPanel; import org.jabref.logic.cleanup.FieldFormatterCleanups; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.field.StandardField; import org.jabref.preferences.CleanupPreferences; import org.jabref.preferences.FilePreferences; import com.airhacks.afterburner.views.ViewLoader; public class CleanupPresetPanel extends VBox { private final BibDatabaseContext databaseContext; @FXML private Label cleanupRenamePDFLabel; @FXML private CheckBox cleanUpDOI; @FXML private CheckBox cleanUpEprint; @FXML private CheckBox cleanUpURL; @FXML private CheckBox cleanUpISSN; @FXML private CheckBox cleanUpMovePDF; @FXML private CheckBox cleanUpMakePathsRelative; @FXML private CheckBox cleanUpRenamePDF; @FXML private CheckBox cleanUpRenamePDFonlyRelativePaths; @FXML private CheckBox cleanUpUpgradeExternalLinks; @FXML private CheckBox cleanUpBiblatex; @FXML private CheckBox cleanUpBibtex; @FXML private CheckBox cleanUpTimestampToCreationDate; @FXML private CheckBox cleanUpTimestampToModificationDate; @FXML private FieldFormatterCleanupsPanel formatterCleanupsPanel; public CleanupPresetPanel(BibDatabaseContext databaseContext, CleanupPreferences cleanupPreferences, FilePreferences filePreferences) { this.databaseContext = Objects.requireNonNull(databaseContext); // Load FXML ViewLoader.view(this) .root(this) .load(); init(cleanupPreferences, filePreferences); } private void init(CleanupPreferences cleanupPreferences, FilePreferences filePreferences) { Optional<Path> firstExistingDir = databaseContext.getFirstExistingFileDir(filePreferences); if (firstExistingDir.isPresent()) { cleanUpMovePDF.setText(Localization.lang("Move linked files to default file directory %0", firstExistingDir.get().toString())); } else { cleanUpMovePDF.setText(Localization.lang("Move linked files to default file directory %0", "...")); // Since the directory does not exist, we cannot move it to there. So, this option is not checked - regardless of the presets stored in the preferences. cleanUpMovePDF.setDisable(true); cleanUpMovePDF.setSelected(false); } cleanUpRenamePDFonlyRelativePaths.disableProperty().bind(cleanUpRenamePDF.selectedProperty().not()); cleanUpUpgradeExternalLinks.setText(Localization.lang("Upgrade external PDF/PS links to use the '%0' field.", StandardField.FILE.getDisplayName())); String currentPattern = Localization.lang("Filename format pattern") .concat(": ") .concat(filePreferences.getFileNamePattern()); cleanupRenamePDFLabel.setText(currentPattern); cleanUpBibtex.selectedProperty().addListener( (observable, oldValue, newValue) -> { if (newValue) { cleanUpBiblatex.selectedProperty().setValue(false); } }); cleanUpBiblatex.selectedProperty().addListener( (observable, oldValue, newValue) -> { if (newValue) { cleanUpBibtex.selectedProperty().setValue(false); } }); cleanUpTimestampToCreationDate.selectedProperty().addListener( (observable, oldValue, newValue) -> { if (newValue) { cleanUpTimestampToModificationDate.selectedProperty().setValue(false); } }); cleanUpTimestampToModificationDate.selectedProperty().addListener( (observable, oldValue, newValue) -> { if (newValue) { cleanUpTimestampToCreationDate.selectedProperty().setValue(false); } }); updateDisplay(cleanupPreferences); } private void updateDisplay(CleanupPreferences preset) { cleanUpDOI.setSelected(preset.isActive(CleanupPreferences.CleanupStep.CLEAN_UP_DOI)); cleanUpEprint.setSelected(preset.isActive(CleanupPreferences.CleanupStep.CLEANUP_EPRINT)); cleanUpURL.setSelected(preset.isActive(CleanupPreferences.CleanupStep.CLEAN_UP_URL)); if (!cleanUpMovePDF.isDisabled()) { cleanUpMovePDF.setSelected(preset.isActive(CleanupPreferences.CleanupStep.MOVE_PDF)); } cleanUpMakePathsRelative.setSelected(preset.isActive(CleanupPreferences.CleanupStep.MAKE_PATHS_RELATIVE)); cleanUpRenamePDF.setSelected(preset.isActive(CleanupPreferences.CleanupStep.RENAME_PDF)); cleanUpRenamePDFonlyRelativePaths.setSelected(preset.isActive(CleanupPreferences.CleanupStep.RENAME_PDF_ONLY_RELATIVE_PATHS)); cleanUpUpgradeExternalLinks.setSelected(preset.isActive(CleanupPreferences.CleanupStep.CLEAN_UP_UPGRADE_EXTERNAL_LINKS)); cleanUpBiblatex.setSelected(preset.isActive(CleanupPreferences.CleanupStep.CONVERT_TO_BIBLATEX)); cleanUpBibtex.setSelected(preset.isActive(CleanupPreferences.CleanupStep.CONVERT_TO_BIBTEX)); cleanUpTimestampToCreationDate.setSelected(preset.isActive(CleanupPreferences.CleanupStep.CONVERT_TIMESTAMP_TO_CREATIONDATE)); cleanUpTimestampToModificationDate.setSelected(preset.isActive(CleanupPreferences.CleanupStep.CONVERT_TIMESTAMP_TO_MODIFICATIONDATE)); cleanUpTimestampToModificationDate.setSelected(preset.isActive(CleanupPreferences.CleanupStep.DO_NOT_CONVERT_TIMESTAMP)); cleanUpISSN.setSelected(preset.isActive(CleanupPreferences.CleanupStep.CLEAN_UP_ISSN)); formatterCleanupsPanel.cleanupsDisableProperty().setValue(!preset.getFieldFormatterCleanups().isEnabled()); formatterCleanupsPanel.cleanupsProperty().setValue(FXCollections.observableArrayList(preset.getFieldFormatterCleanups().getConfiguredActions())); } public CleanupPreferences getCleanupPreset() { EnumSet<CleanupPreferences.CleanupStep> activeJobs = EnumSet.noneOf(CleanupPreferences.CleanupStep.class); if (cleanUpMovePDF.isSelected()) { activeJobs.add(CleanupPreferences.CleanupStep.MOVE_PDF); } if (cleanUpDOI.isSelected()) { activeJobs.add(CleanupPreferences.CleanupStep.CLEAN_UP_DOI); } if (cleanUpEprint.isSelected()) { activeJobs.add(CleanupPreferences.CleanupStep.CLEANUP_EPRINT); } if (cleanUpURL.isSelected()) { activeJobs.add(CleanupPreferences.CleanupStep.CLEAN_UP_URL); } if (cleanUpISSN.isSelected()) { activeJobs.add(CleanupPreferences.CleanupStep.CLEAN_UP_ISSN); } if (cleanUpMakePathsRelative.isSelected()) { activeJobs.add(CleanupPreferences.CleanupStep.MAKE_PATHS_RELATIVE); } if (cleanUpRenamePDF.isSelected()) { if (cleanUpRenamePDFonlyRelativePaths.isSelected()) { activeJobs.add(CleanupPreferences.CleanupStep.RENAME_PDF_ONLY_RELATIVE_PATHS); } else { activeJobs.add(CleanupPreferences.CleanupStep.RENAME_PDF); } } if (cleanUpUpgradeExternalLinks.isSelected()) { activeJobs.add(CleanupPreferences.CleanupStep.CLEAN_UP_UPGRADE_EXTERNAL_LINKS); } if (cleanUpBiblatex.isSelected()) { activeJobs.add(CleanupPreferences.CleanupStep.CONVERT_TO_BIBLATEX); } if (cleanUpBibtex.isSelected()) { activeJobs.add(CleanupPreferences.CleanupStep.CONVERT_TO_BIBTEX); } if (cleanUpTimestampToCreationDate.isSelected()) { activeJobs.add(CleanupPreferences.CleanupStep.CONVERT_TIMESTAMP_TO_CREATIONDATE); } if (cleanUpTimestampToModificationDate.isSelected()) { activeJobs.add(CleanupPreferences.CleanupStep.CONVERT_TIMESTAMP_TO_MODIFICATIONDATE); } activeJobs.add(CleanupPreferences.CleanupStep.FIX_FILE_LINKS); return new CleanupPreferences(activeJobs, new FieldFormatterCleanups( !formatterCleanupsPanel.cleanupsDisableProperty().getValue(), formatterCleanupsPanel.cleanupsProperty())); } }
8,730
49.468208
164
java
null
jabref-main/src/main/java/org/jabref/gui/cleanup/CleanupSingleAction.java
package org.jabref.gui.cleanup; import java.util.List; import java.util.Optional; import javax.swing.undo.UndoManager; import org.jabref.gui.DialogService; import org.jabref.gui.StateManager; import org.jabref.gui.actions.ActionHelper; import org.jabref.gui.actions.SimpleCommand; import org.jabref.gui.undo.NamedCompound; import org.jabref.gui.undo.UndoableFieldChange; import org.jabref.logic.cleanup.CleanupWorker; import org.jabref.logic.l10n.Localization; import org.jabref.model.FieldChange; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.preferences.CleanupPreferences; import org.jabref.preferences.PreferencesService; public class CleanupSingleAction extends SimpleCommand { private final PreferencesService preferences; private final DialogService dialogService; private final StateManager stateManager; private final BibEntry entry; private final UndoManager undoManager; private boolean isCanceled; private int modifiedEntriesCount; public CleanupSingleAction(BibEntry entry, PreferencesService preferences, DialogService dialogService, StateManager stateManager, UndoManager undoManager) { this.entry = entry; this.preferences = preferences; this.dialogService = dialogService; this.stateManager = stateManager; this.undoManager = undoManager; this.executable.bind(ActionHelper.needsEntriesSelected(stateManager)); } @Override public void execute() { isCanceled = false; CleanupDialog cleanupDialog = new CleanupDialog( stateManager.getActiveDatabase().get(), preferences.getCleanupPreferences(), preferences.getFilePreferences() ); Optional<CleanupPreferences> chosenPreset = dialogService.showCustomDialogAndWait(cleanupDialog); chosenPreset.ifPresent(preset -> { if (preset.isActive(CleanupPreferences.CleanupStep.RENAME_PDF) && preferences.getAutoLinkPreferences().shouldAskAutoNamingPdfs()) { boolean confirmed = dialogService.showConfirmationDialogWithOptOutAndWait(Localization.lang("Autogenerate PDF Names"), Localization.lang("Auto-generating PDF-Names does not support undo. Continue?"), Localization.lang("Autogenerate PDF Names"), Localization.lang("Cancel"), Localization.lang("Do not ask again"), optOut -> preferences.getAutoLinkPreferences().setAskAutoNamingPdfs(!optOut)); if (!confirmed) { isCanceled = true; return; } } preferences.getCleanupPreferences().setActiveJobs(preset.getActiveJobs()); preferences.getCleanupPreferences().setFieldFormatterCleanups(preset.getFieldFormatterCleanups()); cleanup(stateManager.getActiveDatabase().get(), preset); }); } /** * Runs the cleanup on the entry and records the change. */ private void doCleanup(BibDatabaseContext databaseContext, CleanupPreferences preset, BibEntry entry, NamedCompound ce) { // Create and run cleaner CleanupWorker cleaner = new CleanupWorker( databaseContext, preferences.getFilePreferences(), preferences.getTimestampPreferences()); List<FieldChange> changes = cleaner.cleanup(preset, entry); // Register undo action for (FieldChange change : changes) { ce.addEdit(new UndoableFieldChange(change)); } } private void cleanup(BibDatabaseContext databaseContext, CleanupPreferences cleanupPreferences) { // undo granularity is on entry level NamedCompound ce = new NamedCompound(Localization.lang("Cleanup entry")); doCleanup(databaseContext, cleanupPreferences, entry, ce); ce.end(); if (ce.hasEdits()) { undoManager.addEdit(ce); } } }
4,105
37.735849
161
java
null
jabref-main/src/main/java/org/jabref/gui/collab/ChangeScanner.java
package org.jabref.gui.collab; import java.io.IOException; import java.util.Collections; import java.util.List; import org.jabref.gui.DialogService; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.OpenDatabase; import org.jabref.logic.importer.ParserResult; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.util.DummyFileUpdateMonitor; import org.jabref.preferences.PreferencesService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ChangeScanner { private static final Logger LOGGER = LoggerFactory.getLogger(ChangeScanner.class); private final BibDatabaseContext database; private final PreferencesService preferencesService; private final DatabaseChangeResolverFactory databaseChangeResolverFactory; public ChangeScanner(BibDatabaseContext database, DialogService dialogService, PreferencesService preferencesService) { this.database = database; this.preferencesService = preferencesService; this.databaseChangeResolverFactory = new DatabaseChangeResolverFactory(dialogService, database, preferencesService.getBibEntryPreferences()); } public List<DatabaseChange> scanForChanges() { if (database.getDatabasePath().isEmpty()) { return Collections.emptyList(); } try { // Parse the modified file // Important: apply all post-load actions ImportFormatPreferences importFormatPreferences = preferencesService.getImportFormatPreferences(); ParserResult result = OpenDatabase.loadDatabase(database.getDatabasePath().get(), importFormatPreferences, new DummyFileUpdateMonitor()); BibDatabaseContext databaseOnDisk = result.getDatabaseContext(); return DatabaseChangeList.compareAndGetChanges(database, databaseOnDisk, databaseChangeResolverFactory); } catch (IOException e) { LOGGER.warn("Error while parsing changed file.", e); return Collections.emptyList(); } } }
2,121
39.037736
149
java
null
jabref-main/src/main/java/org/jabref/gui/collab/DatabaseChange.java
package org.jabref.gui.collab; import java.util.Optional; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import org.jabref.gui.collab.entryadd.EntryAdd; import org.jabref.gui.collab.entrychange.EntryChange; import org.jabref.gui.collab.entrydelete.EntryDelete; import org.jabref.gui.collab.groupchange.GroupChange; import org.jabref.gui.collab.metedatachange.MetadataChange; import org.jabref.gui.collab.preamblechange.PreambleChange; import org.jabref.gui.collab.stringadd.BibTexStringAdd; import org.jabref.gui.collab.stringchange.BibTexStringChange; import org.jabref.gui.collab.stringdelete.BibTexStringDelete; import org.jabref.gui.collab.stringrename.BibTexStringRename; import org.jabref.gui.undo.NamedCompound; import org.jabref.gui.util.OptionalObjectProperty; import org.jabref.model.database.BibDatabaseContext; public sealed abstract class DatabaseChange permits EntryAdd, EntryChange, EntryDelete, GroupChange, MetadataChange, PreambleChange, BibTexStringAdd, BibTexStringChange, BibTexStringDelete, BibTexStringRename { protected final BibDatabaseContext databaseContext; protected final OptionalObjectProperty<DatabaseChangeResolver> externalChangeResolver = OptionalObjectProperty.empty(); private final BooleanProperty accepted = new SimpleBooleanProperty(); private final StringProperty name = new SimpleStringProperty(); protected DatabaseChange(BibDatabaseContext databaseContext, DatabaseChangeResolverFactory databaseChangeResolverFactory) { this.databaseContext = databaseContext; setChangeName("Unnamed Change!"); if (databaseChangeResolverFactory != null) { externalChangeResolver.set(databaseChangeResolverFactory.create(this)); } } public boolean isAccepted() { return accepted.get(); } public BooleanProperty acceptedProperty() { return accepted; } public void setAccepted(boolean accepted) { this.accepted.set(accepted); } /** * Convenience method for accepting changes * */ public void accept() { setAccepted(true); } public String getName() { return name.get(); } protected void setChangeName(String changeName) { name.set(changeName); } public Optional<DatabaseChangeResolver> getExternalChangeResolver() { return externalChangeResolver.get(); } public abstract void applyChange(NamedCompound undoEdit); }
2,597
35.083333
210
java
null
jabref-main/src/main/java/org/jabref/gui/collab/DatabaseChangeDetailsView.java
package org.jabref.gui.collab; import javafx.scene.layout.AnchorPane; import org.jabref.gui.collab.entrychange.EntryChangeDetailsView; import org.jabref.gui.collab.entrychange.EntryWithPreviewAndSourceDetailsView; import org.jabref.gui.collab.groupchange.GroupChangeDetailsView; import org.jabref.gui.collab.metedatachange.MetadataChangeDetailsView; import org.jabref.gui.collab.preamblechange.PreambleChangeDetailsView; import org.jabref.gui.collab.stringadd.BibTexStringAddDetailsView; import org.jabref.gui.collab.stringchange.BibTexStringChangeDetailsView; import org.jabref.gui.collab.stringdelete.BibTexStringDeleteDetailsView; import org.jabref.gui.collab.stringrename.BibTexStringRenameDetailsView; public sealed abstract class DatabaseChangeDetailsView extends AnchorPane permits EntryWithPreviewAndSourceDetailsView, GroupChangeDetailsView, MetadataChangeDetailsView, PreambleChangeDetailsView, BibTexStringAddDetailsView, BibTexStringChangeDetailsView, BibTexStringDeleteDetailsView, BibTexStringRenameDetailsView, EntryChangeDetailsView { }
1,056
61.176471
343
java
null
jabref-main/src/main/java/org/jabref/gui/collab/DatabaseChangeDetailsViewFactory.java
package org.jabref.gui.collab; import org.jabref.gui.DialogService; import org.jabref.gui.StateManager; import org.jabref.gui.collab.entryadd.EntryAdd; import org.jabref.gui.collab.entrychange.EntryChange; import org.jabref.gui.collab.entrychange.EntryChangeDetailsView; import org.jabref.gui.collab.entrychange.EntryWithPreviewAndSourceDetailsView; import org.jabref.gui.collab.entrydelete.EntryDelete; import org.jabref.gui.collab.groupchange.GroupChange; import org.jabref.gui.collab.groupchange.GroupChangeDetailsView; import org.jabref.gui.collab.metedatachange.MetadataChange; import org.jabref.gui.collab.metedatachange.MetadataChangeDetailsView; import org.jabref.gui.collab.preamblechange.PreambleChange; import org.jabref.gui.collab.preamblechange.PreambleChangeDetailsView; import org.jabref.gui.collab.stringadd.BibTexStringAdd; import org.jabref.gui.collab.stringadd.BibTexStringAddDetailsView; import org.jabref.gui.collab.stringchange.BibTexStringChange; import org.jabref.gui.collab.stringchange.BibTexStringChangeDetailsView; import org.jabref.gui.collab.stringdelete.BibTexStringDelete; import org.jabref.gui.collab.stringdelete.BibTexStringDeleteDetailsView; import org.jabref.gui.collab.stringrename.BibTexStringRename; import org.jabref.gui.collab.stringrename.BibTexStringRenameDetailsView; import org.jabref.gui.preview.PreviewViewer; import org.jabref.gui.theme.ThemeManager; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntryTypesManager; import org.jabref.preferences.PreferencesService; public class DatabaseChangeDetailsViewFactory { private final BibDatabaseContext databaseContext; private final DialogService dialogService; private final StateManager stateManager; private final ThemeManager themeManager; private final PreferencesService preferencesService; private final BibEntryTypesManager entryTypesManager; private final PreviewViewer previewViewer; public DatabaseChangeDetailsViewFactory(BibDatabaseContext databaseContext, DialogService dialogService, StateManager stateManager, ThemeManager themeManager, PreferencesService preferencesService, BibEntryTypesManager entryTypesManager, PreviewViewer previewViewer) { this.databaseContext = databaseContext; this.dialogService = dialogService; this.stateManager = stateManager; this.themeManager = themeManager; this.preferencesService = preferencesService; this.entryTypesManager = entryTypesManager; this.previewViewer = previewViewer; } public DatabaseChangeDetailsView create(DatabaseChange databaseChange) { // TODO: Use Pattern Matching for switch once it's out of preview if (databaseChange instanceof EntryChange entryChange) { return new EntryChangeDetailsView(entryChange.getOldEntry(), entryChange.getNewEntry(), databaseContext, dialogService, stateManager, themeManager, preferencesService, entryTypesManager, previewViewer); } else if (databaseChange instanceof EntryAdd entryAdd) { return new EntryWithPreviewAndSourceDetailsView(entryAdd.getAddedEntry(), databaseContext, preferencesService, entryTypesManager, previewViewer); } else if (databaseChange instanceof EntryDelete entryDelete) { return new EntryWithPreviewAndSourceDetailsView(entryDelete.getDeletedEntry(), databaseContext, preferencesService, entryTypesManager, previewViewer); } else if (databaseChange instanceof BibTexStringAdd stringAdd) { return new BibTexStringAddDetailsView(stringAdd); } else if (databaseChange instanceof BibTexStringDelete stringDelete) { return new BibTexStringDeleteDetailsView(stringDelete); } else if (databaseChange instanceof BibTexStringChange stringChange) { return new BibTexStringChangeDetailsView(stringChange); } else if (databaseChange instanceof BibTexStringRename stringRename) { return new BibTexStringRenameDetailsView(stringRename); } else if (databaseChange instanceof MetadataChange metadataChange) { return new MetadataChangeDetailsView(metadataChange, preferencesService); } else if (databaseChange instanceof GroupChange groupChange) { return new GroupChangeDetailsView(groupChange); } else if (databaseChange instanceof PreambleChange preambleChange) { return new PreambleChangeDetailsView(preambleChange); } throw new UnsupportedOperationException("Cannot preview the given change: " + databaseChange.getName()); } }
4,606
60.426667
272
java
null
jabref-main/src/main/java/org/jabref/gui/collab/DatabaseChangeList.java
package org.jabref.gui.collab; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.jabref.gui.collab.entryadd.EntryAdd; import org.jabref.gui.collab.entrychange.EntryChange; import org.jabref.gui.collab.entrydelete.EntryDelete; import org.jabref.gui.collab.groupchange.GroupChange; import org.jabref.gui.collab.metedatachange.MetadataChange; import org.jabref.gui.collab.preamblechange.PreambleChange; import org.jabref.gui.collab.stringadd.BibTexStringAdd; import org.jabref.gui.collab.stringchange.BibTexStringChange; import org.jabref.gui.collab.stringdelete.BibTexStringDelete; import org.jabref.gui.collab.stringrename.BibTexStringRename; import org.jabref.logic.bibtex.comparator.BibDatabaseDiff; import org.jabref.logic.bibtex.comparator.BibEntryDiff; import org.jabref.logic.bibtex.comparator.BibStringDiff; import org.jabref.model.database.BibDatabaseContext; public class DatabaseChangeList { private DatabaseChangeList() { } /** * Compares the given two databases, and returns the list of changes required to change the {@code originalDatabase} into the {@code otherDatabase} * * @param originalDatabase This is the original database * @param otherDatabase This is the other database. * @return an unmodifiable list of {@code DatabaseChange} required to change {@code originalDatabase} into {@code otherDatabase} */ public static List<DatabaseChange> compareAndGetChanges(BibDatabaseContext originalDatabase, BibDatabaseContext otherDatabase, DatabaseChangeResolverFactory databaseChangeResolverFactory) { List<DatabaseChange> changes = new ArrayList<>(); BibDatabaseDiff differences = BibDatabaseDiff.compare(originalDatabase, otherDatabase); differences.getMetaDataDifferences().ifPresent(diff -> { changes.add(new MetadataChange(diff, originalDatabase, databaseChangeResolverFactory)); diff.getGroupDifferences().ifPresent(groupDiff -> changes.add(new GroupChange( groupDiff, originalDatabase, databaseChangeResolverFactory ))); }); differences.getPreambleDifferences().ifPresent(diff -> changes.add(new PreambleChange(diff, originalDatabase, databaseChangeResolverFactory))); differences.getBibStringDifferences().forEach(diff -> changes.add(createBibStringDiff(originalDatabase, databaseChangeResolverFactory, diff))); differences.getEntryDifferences().forEach(diff -> changes.add(createBibEntryDiff(originalDatabase, databaseChangeResolverFactory, diff))); return Collections.unmodifiableList(changes); } private static DatabaseChange createBibStringDiff(BibDatabaseContext originalDatabase, DatabaseChangeResolverFactory databaseChangeResolverFactory, BibStringDiff diff) { if (diff.getOriginalString() == null) { return new BibTexStringAdd(diff.getNewString(), originalDatabase, databaseChangeResolverFactory); } if (diff.getNewString() == null) { return new BibTexStringDelete(diff.getOriginalString(), originalDatabase, databaseChangeResolverFactory); } if (diff.getOriginalString().getName().equals(diff.getNewString().getName())) { return new BibTexStringChange(diff.getOriginalString(), diff.getNewString(), originalDatabase, databaseChangeResolverFactory); } return new BibTexStringRename(diff.getOriginalString(), diff.getNewString(), originalDatabase, databaseChangeResolverFactory); } private static DatabaseChange createBibEntryDiff(BibDatabaseContext originalDatabase, DatabaseChangeResolverFactory databaseChangeResolverFactory, BibEntryDiff diff) { if (diff.getOriginalEntry() == null) { return new EntryAdd(diff.getNewEntry(), originalDatabase, databaseChangeResolverFactory); } if (diff.getNewEntry() == null) { return new EntryDelete(diff.getOriginalEntry(), originalDatabase, databaseChangeResolverFactory); } return new EntryChange(diff.getOriginalEntry(), diff.getNewEntry(), originalDatabase, databaseChangeResolverFactory); } }
4,167
51.759494
193
java
null
jabref-main/src/main/java/org/jabref/gui/collab/DatabaseChangeListener.java
package org.jabref.gui.collab; import java.util.List; public interface DatabaseChangeListener { void databaseChanged(List<DatabaseChange> changes); }
156
18.625
55
java
null
jabref-main/src/main/java/org/jabref/gui/collab/DatabaseChangeMonitor.java
package org.jabref.gui.collab; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javafx.util.Duration; import org.jabref.gui.DialogService; import org.jabref.gui.LibraryTab; import org.jabref.gui.icon.IconTheme; import org.jabref.gui.util.BackgroundTask; import org.jabref.gui.util.TaskExecutor; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.util.FileUpdateListener; import org.jabref.model.util.FileUpdateMonitor; import org.jabref.preferences.PreferencesService; import org.controlsfx.control.action.Action; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DatabaseChangeMonitor implements FileUpdateListener { private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseChangeMonitor.class); private final BibDatabaseContext database; private final FileUpdateMonitor fileMonitor; private final List<DatabaseChangeListener> listeners; private final TaskExecutor taskExecutor; private final DialogService dialogService; private final PreferencesService preferencesService; public DatabaseChangeMonitor(BibDatabaseContext database, FileUpdateMonitor fileMonitor, TaskExecutor taskExecutor, DialogService dialogService, PreferencesService preferencesService, LibraryTab.DatabaseNotification notificationPane) { this.database = database; this.fileMonitor = fileMonitor; this.taskExecutor = taskExecutor; this.dialogService = dialogService; this.preferencesService = preferencesService; this.listeners = new ArrayList<>(); this.database.getDatabasePath().ifPresent(path -> { try { fileMonitor.addListenerForFile(path, this); } catch (IOException e) { LOGGER.error("Error while trying to monitor {}", path, e); } }); addListener(changes -> notificationPane.notify( IconTheme.JabRefIcons.SAVE.getGraphicNode(), Localization.lang("The library has been modified by another program."), List.of(new Action(Localization.lang("Dismiss changes"), event -> notificationPane.hide()), new Action(Localization.lang("Review changes"), event -> { dialogService.showCustomDialogAndWait(new DatabaseChangesResolverDialog(changes, database, Localization.lang("External Changes Resolver"))); notificationPane.hide(); })), Duration.ZERO)); } @Override public void fileUpdated() { synchronized (database) { // File on disk has changed, thus look for notable changes and notify listeners in case there are such changes ChangeScanner scanner = new ChangeScanner(database, dialogService, preferencesService); BackgroundTask.wrap(scanner::scanForChanges) .onSuccess(changes -> { if (!changes.isEmpty()) { listeners.forEach(listener -> listener.databaseChanged(changes)); } }) .onFailure(e -> LOGGER.error("Error while watching for changes", e)) .executeWith(taskExecutor); } } public void addListener(DatabaseChangeListener listener) { listeners.add(listener); } public void unregister() { database.getDatabasePath().ifPresent(file -> fileMonitor.removeListener(file, this)); } }
3,809
40.413043
168
java
null
jabref-main/src/main/java/org/jabref/gui/collab/DatabaseChangeResolver.java
package org.jabref.gui.collab; import java.util.Optional; import org.jabref.gui.DialogService; import org.jabref.gui.collab.entrychange.EntryChangeResolver; public sealed abstract class DatabaseChangeResolver permits EntryChangeResolver { protected final DialogService dialogService; protected DatabaseChangeResolver(DialogService dialogService) { this.dialogService = dialogService; } public abstract Optional<DatabaseChange> askUserToResolveChange(); }
484
27.529412
81
java
null
jabref-main/src/main/java/org/jabref/gui/collab/DatabaseChangeResolverFactory.java
package org.jabref.gui.collab; import java.util.Optional; import org.jabref.gui.DialogService; import org.jabref.gui.collab.entrychange.EntryChange; import org.jabref.gui.collab.entrychange.EntryChangeResolver; import org.jabref.model.database.BibDatabaseContext; import org.jabref.preferences.BibEntryPreferences; public class DatabaseChangeResolverFactory { private final DialogService dialogService; private final BibDatabaseContext databaseContext; private final BibEntryPreferences bibEntryPreferences; public DatabaseChangeResolverFactory(DialogService dialogService, BibDatabaseContext databaseContext, BibEntryPreferences bibEntryPreferences) { this.dialogService = dialogService; this.databaseContext = databaseContext; this.bibEntryPreferences = bibEntryPreferences; } public Optional<DatabaseChangeResolver> create(DatabaseChange change) { if (change instanceof EntryChange entryChange) { return Optional.of(new EntryChangeResolver(entryChange, dialogService, databaseContext, bibEntryPreferences)); } return Optional.empty(); } }
1,136
36.9
148
java
null
jabref-main/src/main/java/org/jabref/gui/collab/DatabaseChangesResolverDialog.java
package org.jabref.gui.collab; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.undo.UndoManager; import javafx.beans.property.SimpleStringProperty; 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.layout.BorderPane; import org.jabref.gui.DialogService; import org.jabref.gui.StateManager; import org.jabref.gui.preview.PreviewViewer; import org.jabref.gui.theme.ThemeManager; import org.jabref.gui.util.BaseDialog; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntryTypesManager; import org.jabref.preferences.PreferencesService; import com.airhacks.afterburner.views.ViewLoader; import com.tobiasdiez.easybind.EasyBind; import jakarta.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DatabaseChangesResolverDialog extends BaseDialog<Boolean> { private final static Logger LOGGER = LoggerFactory.getLogger(DatabaseChangesResolverDialog.class); /** * Reconstructing the details view to preview an {@link DatabaseChange} every time it's selected is a heavy operation. * It is also useless because changes are static and if the change data is static then the view doesn't have to change * either. This cache is used to ensure that we only create the detail view instance once for each {@link DatabaseChange}. */ private final Map<DatabaseChange, DatabaseChangeDetailsView> DETAILS_VIEW_CACHE = new HashMap<>(); @FXML private TableView<DatabaseChange> changesTableView; @FXML private TableColumn<DatabaseChange, String> changeName; @FXML private Button askUserToResolveChangeButton; @FXML private BorderPane changeInfoPane; private final List<DatabaseChange> changes; private final BibDatabaseContext database; private ExternalChangesResolverViewModel viewModel; @Inject private UndoManager undoManager; @Inject private StateManager stateManager; @Inject private DialogService dialogService; @Inject private PreferencesService preferencesService; @Inject private ThemeManager themeManager; @Inject private BibEntryTypesManager entryTypesManager; /** * A dialog going through given <code>changes</code>, which are diffs to the provided <code>database</code>. * Each accepted change is written to the provided <code>database</code>. * * @param changes The list of changes * @param database The database to apply the changes to */ public DatabaseChangesResolverDialog(List<DatabaseChange> changes, BibDatabaseContext database, String dialogTitle) { this.changes = changes; this.database = database; this.setTitle(dialogTitle); ViewLoader.view(this) .load() .setAsDialogPane(this); this.setResultConverter(button -> { if (viewModel.areAllChangesResolved()) { LOGGER.info("External changes are resolved successfully"); return true; } else { LOGGER.info("External changes aren't resolved"); return false; } }); } @FXML private void initialize() { PreviewViewer previewViewer = new PreviewViewer(database, dialogService, stateManager, themeManager); DatabaseChangeDetailsViewFactory databaseChangeDetailsViewFactory = new DatabaseChangeDetailsViewFactory(database, dialogService, stateManager, themeManager, preferencesService, entryTypesManager, previewViewer); viewModel = new ExternalChangesResolverViewModel(changes, undoManager); changeName.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getName())); askUserToResolveChangeButton.disableProperty().bind(viewModel.canAskUserToResolveChangeProperty().not()); changesTableView.setItems(viewModel.getVisibleChanges()); // Think twice before setting this to MULTIPLE... changesTableView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE); changesTableView.getSelectionModel().selectFirst(); viewModel.selectedChangeProperty().bind(changesTableView.getSelectionModel().selectedItemProperty()); EasyBind.subscribe(viewModel.selectedChangeProperty(), selectedChange -> { if (selectedChange != null) { DatabaseChangeDetailsView detailsView = DETAILS_VIEW_CACHE.computeIfAbsent(selectedChange, databaseChangeDetailsViewFactory::create); changeInfoPane.setCenter(detailsView); } }); EasyBind.subscribe(viewModel.areAllChangesResolvedProperty(), isResolved -> { if (isResolved) { viewModel.applyChanges(); close(); } }); } @FXML public void denyChanges() { viewModel.denyChange(); } @FXML public void acceptChanges() { viewModel.acceptChange(); } @FXML public void askUserToResolveChange() { viewModel.getSelectedChange().flatMap(DatabaseChange::getExternalChangeResolver) .flatMap(DatabaseChangeResolver::askUserToResolveChange).ifPresent(viewModel::acceptMergedChange); } }
5,368
38.477941
220
java
null
jabref-main/src/main/java/org/jabref/gui/collab/ExternalChangesResolverViewModel.java
package org.jabref.gui.collab; import java.util.List; import java.util.Objects; import java.util.Optional; import javax.swing.undo.UndoManager; import javafx.beans.binding.Bindings; import javafx.beans.binding.BooleanBinding; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import org.jabref.gui.AbstractViewModel; import org.jabref.gui.undo.NamedCompound; import org.jabref.logic.l10n.Localization; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ExternalChangesResolverViewModel extends AbstractViewModel { private final static Logger LOGGER = LoggerFactory.getLogger(ExternalChangesResolverViewModel.class); private final NamedCompound ce = new NamedCompound(Localization.lang("Merged external changes")); private final ObservableList<DatabaseChange> visibleChanges = FXCollections.observableArrayList(); /** * Because visible changes list will be bound to the UI, certain changes can be removed. This list is used to keep * track of changes even when they're removed from the UI. */ private final ObservableList<DatabaseChange> changes = FXCollections.observableArrayList(); private final ObjectProperty<DatabaseChange> selectedChange = new SimpleObjectProperty<>(); private final BooleanBinding areAllChangesResolved; private final BooleanBinding canAskUserToResolveChange; private final UndoManager undoManager; public ExternalChangesResolverViewModel(List<DatabaseChange> externalChanges, UndoManager undoManager) { Objects.requireNonNull(externalChanges); assert !externalChanges.isEmpty(); this.visibleChanges.addAll(externalChanges); this.changes.addAll(externalChanges); this.undoManager = undoManager; areAllChangesResolved = Bindings.createBooleanBinding(visibleChanges::isEmpty, visibleChanges); canAskUserToResolveChange = Bindings.createBooleanBinding(() -> selectedChange.isNotNull().get() && selectedChange.get().getExternalChangeResolver().isPresent(), selectedChange); } public ObservableList<DatabaseChange> getVisibleChanges() { return visibleChanges; } public ObjectProperty<DatabaseChange> selectedChangeProperty() { return selectedChange; } public Optional<DatabaseChange> getSelectedChange() { return Optional.ofNullable(selectedChangeProperty().get()); } public BooleanBinding areAllChangesResolvedProperty() { return areAllChangesResolved; } public boolean areAllChangesResolved() { return areAllChangesResolvedProperty().get(); } public BooleanBinding canAskUserToResolveChangeProperty() { return canAskUserToResolveChange; } public void acceptChange() { getSelectedChange().ifPresent(selectedChange -> { selectedChange.accept(); getVisibleChanges().remove(selectedChange); }); } public void denyChange() { getSelectedChange().ifPresent(getVisibleChanges()::remove); } public void acceptMergedChange(DatabaseChange databaseChange) { Objects.requireNonNull(databaseChange); getSelectedChange().ifPresent(oldChange -> { changes.remove(oldChange); changes.add(databaseChange); databaseChange.accept(); getVisibleChanges().remove(oldChange); }); } public void applyChanges() { changes.stream().filter(DatabaseChange::isAccepted).forEach(change -> change.applyChange(ce)); ce.end(); undoManager.addEdit(ce); } }
3,703
33.296296
186
java
null
jabref-main/src/main/java/org/jabref/gui/collab/entryadd/EntryAdd.java
package org.jabref.gui.collab.entryadd; import org.jabref.gui.collab.DatabaseChange; import org.jabref.gui.collab.DatabaseChangeResolverFactory; import org.jabref.gui.undo.NamedCompound; import org.jabref.gui.undo.UndoableInsertEntries; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; public final class EntryAdd extends DatabaseChange { private final BibEntry addedEntry; public EntryAdd(BibEntry addedEntry, BibDatabaseContext databaseContext, DatabaseChangeResolverFactory databaseChangeResolverFactory) { super(databaseContext, databaseChangeResolverFactory); this.addedEntry = addedEntry; setChangeName(addedEntry.getCitationKey() .map(key -> Localization.lang("Added entry '%0'", key)) .orElse(Localization.lang("Added entry"))); } @Override public void applyChange(NamedCompound undoEdit) { databaseContext.getDatabase().insertEntry(addedEntry); undoEdit.addEdit(new UndoableInsertEntries(databaseContext.getDatabase(), addedEntry)); } public BibEntry getAddedEntry() { return addedEntry; } }
1,227
37.375
139
java
null
jabref-main/src/main/java/org/jabref/gui/collab/entrychange/EntryChange.java
package org.jabref.gui.collab.entrychange; import javax.swing.undo.CompoundEdit; import org.jabref.gui.collab.DatabaseChange; import org.jabref.gui.collab.DatabaseChangeResolverFactory; import org.jabref.gui.undo.NamedCompound; import org.jabref.gui.undo.UndoableInsertEntries; import org.jabref.gui.undo.UndoableRemoveEntries; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; public final class EntryChange extends DatabaseChange { private final BibEntry oldEntry; private final BibEntry newEntry; public EntryChange(BibEntry oldEntry, BibEntry newEntry, BibDatabaseContext databaseContext, DatabaseChangeResolverFactory databaseChangeResolverFactory) { super(databaseContext, databaseChangeResolverFactory); this.oldEntry = oldEntry; this.newEntry = newEntry; setChangeName(oldEntry.getCitationKey().map(key -> Localization.lang("Modified entry '%0'", key)) .orElse(Localization.lang("Modified entry"))); } public EntryChange(BibEntry oldEntry, BibEntry newEntry, BibDatabaseContext databaseContext) { this(oldEntry, newEntry, databaseContext, null); } public BibEntry getOldEntry() { return oldEntry; } public BibEntry getNewEntry() { return newEntry; } @Override public void applyChange(NamedCompound undoEdit) { databaseContext.getDatabase().removeEntry(oldEntry); databaseContext.getDatabase().insertEntry(newEntry); CompoundEdit changeEntryEdit = new CompoundEdit(); changeEntryEdit.addEdit(new UndoableRemoveEntries(databaseContext.getDatabase(), oldEntry)); changeEntryEdit.addEdit(new UndoableInsertEntries(databaseContext.getDatabase(), newEntry)); changeEntryEdit.end(); undoEdit.addEdit(changeEntryEdit); } }
1,909
37.2
159
java
null
jabref-main/src/main/java/org/jabref/gui/collab/entrychange/EntryChangeDetailsView.java
package org.jabref.gui.collab.entrychange; import javafx.geometry.Orientation; import javafx.scene.control.Label; import javafx.scene.control.SplitPane; import javafx.scene.control.TabPane; import javafx.scene.layout.VBox; import org.jabref.gui.DialogService; import org.jabref.gui.StateManager; import org.jabref.gui.collab.DatabaseChangeDetailsView; import org.jabref.gui.preview.PreviewViewer; import org.jabref.gui.theme.ThemeManager; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.BibEntryTypesManager; import org.jabref.preferences.PreferencesService; import com.tobiasdiez.easybind.EasyBind; public final class EntryChangeDetailsView extends DatabaseChangeDetailsView { private final PreviewWithSourceTab oldPreviewWithSourcesTab = new PreviewWithSourceTab(); private final PreviewWithSourceTab newPreviewWithSourcesTab = new PreviewWithSourceTab(); public EntryChangeDetailsView(BibEntry oldEntry, BibEntry newEntry, BibDatabaseContext databaseContext, DialogService dialogService, StateManager stateManager, ThemeManager themeManager, PreferencesService preferencesService, BibEntryTypesManager entryTypesManager, PreviewViewer previewViewer) { Label inJabRef = new Label(Localization.lang("In JabRef")); inJabRef.getStyleClass().add("lib-change-header"); Label onDisk = new Label(Localization.lang("On disk")); onDisk.getStyleClass().add("lib-change-header"); // we need a copy here as we otherwise would set the same entry twice PreviewViewer previewClone = new PreviewViewer(databaseContext, dialogService, stateManager, themeManager); TabPane oldEntryTabPane = oldPreviewWithSourcesTab.getPreviewWithSourceTab(oldEntry, databaseContext, preferencesService, entryTypesManager, previewClone, Localization.lang("Entry Preview")); TabPane newEntryTabPane = newPreviewWithSourcesTab.getPreviewWithSourceTab(newEntry, databaseContext, preferencesService, entryTypesManager, previewViewer, Localization.lang("Entry Preview")); EasyBind.subscribe(oldEntryTabPane.getSelectionModel().selectedIndexProperty(), selectedIndex -> { newEntryTabPane.getSelectionModel().select(selectedIndex.intValue()); }); EasyBind.subscribe(newEntryTabPane.getSelectionModel().selectedIndexProperty(), selectedIndex -> { if (oldEntryTabPane.getSelectionModel().getSelectedIndex() != selectedIndex.intValue()) { oldEntryTabPane.getSelectionModel().select(selectedIndex.intValue()); } }); VBox containerOld = new VBox(inJabRef, oldEntryTabPane); VBox containerNew = new VBox(onDisk, newEntryTabPane); SplitPane split = new SplitPane(containerOld, containerNew); split.setOrientation(Orientation.HORIZONTAL); setLeftAnchor(split, 8d); setTopAnchor(split, 8d); setRightAnchor(split, 8d); setBottomAnchor(split, 8d); this.getChildren().add(split); } }
3,099
49
300
java
null
jabref-main/src/main/java/org/jabref/gui/collab/entrychange/EntryChangeResolver.java
package org.jabref.gui.collab.entrychange; import java.util.Optional; import org.jabref.gui.DialogService; import org.jabref.gui.collab.DatabaseChange; import org.jabref.gui.collab.DatabaseChangeResolver; import org.jabref.gui.mergeentries.EntriesMergeResult; import org.jabref.gui.mergeentries.MergeEntriesDialog; import org.jabref.gui.mergeentries.newmergedialog.ShowDiffConfig; import org.jabref.gui.mergeentries.newmergedialog.diffhighlighter.DiffHighlighter.BasicDiffMethod; import org.jabref.gui.mergeentries.newmergedialog.toolbar.ThreeWayMergeToolbar; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.preferences.BibEntryPreferences; public final class EntryChangeResolver extends DatabaseChangeResolver { private final EntryChange entryChange; private final BibDatabaseContext databaseContext; private final BibEntryPreferences bibEntryPreferences; public EntryChangeResolver(EntryChange entryChange, DialogService dialogService, BibDatabaseContext databaseContext, BibEntryPreferences bibEntryPreferences) { super(dialogService); this.entryChange = entryChange; this.databaseContext = databaseContext; this.bibEntryPreferences = bibEntryPreferences; } @Override public Optional<DatabaseChange> askUserToResolveChange() { MergeEntriesDialog mergeEntriesDialog = new MergeEntriesDialog(entryChange.getOldEntry(), entryChange.getNewEntry(), bibEntryPreferences); mergeEntriesDialog.setLeftHeaderText(Localization.lang("In JabRef")); mergeEntriesDialog.setRightHeaderText(Localization.lang("On disk")); mergeEntriesDialog.configureDiff(new ShowDiffConfig(ThreeWayMergeToolbar.DiffView.SPLIT, BasicDiffMethod.WORDS)); return dialogService.showCustomDialogAndWait(mergeEntriesDialog) .map(this::mapMergeResultToExternalChange); } private EntryChange mapMergeResultToExternalChange(EntriesMergeResult entriesMergeResult) { return new EntryChange( entryChange.getOldEntry(), entriesMergeResult.mergedEntry(), databaseContext ); } }
2,211
44.142857
163
java
null
jabref-main/src/main/java/org/jabref/gui/collab/entrychange/EntryWithPreviewAndSourceDetailsView.java
package org.jabref.gui.collab.entrychange; import javafx.scene.control.TabPane; import org.jabref.gui.collab.DatabaseChangeDetailsView; import org.jabref.gui.preview.PreviewViewer; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.BibEntryTypesManager; import org.jabref.preferences.PreferencesService; public final class EntryWithPreviewAndSourceDetailsView extends DatabaseChangeDetailsView { private final PreviewWithSourceTab previewWithSourceTab = new PreviewWithSourceTab(); public EntryWithPreviewAndSourceDetailsView(BibEntry entry, BibDatabaseContext bibDatabaseContext, PreferencesService preferencesService, BibEntryTypesManager entryTypesManager, PreviewViewer previewViewer) { TabPane tabPanePreviewCode = previewWithSourceTab.getPreviewWithSourceTab(entry, bibDatabaseContext, preferencesService, entryTypesManager, previewViewer); setLeftAnchor(tabPanePreviewCode, 8d); setTopAnchor(tabPanePreviewCode, 8d); setRightAnchor(tabPanePreviewCode, 8d); setBottomAnchor(tabPanePreviewCode, 8d); getChildren().setAll(tabPanePreviewCode); } }
1,189
44.769231
212
java
null
jabref-main/src/main/java/org/jabref/gui/collab/entrychange/PreviewWithSourceTab.java
package org.jabref.gui.collab.entrychange; import java.io.IOException; import java.io.StringWriter; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import org.jabref.gui.preview.PreviewViewer; import org.jabref.logic.bibtex.BibEntryWriter; import org.jabref.logic.bibtex.FieldPreferences; import org.jabref.logic.bibtex.FieldWriter; import org.jabref.logic.exporter.BibWriter; import org.jabref.logic.l10n.Localization; import org.jabref.logic.util.OS; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.database.BibDatabaseMode; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.BibEntryTypesManager; import org.jabref.model.strings.StringUtil; import org.jabref.preferences.PreferencesService; import org.fxmisc.richtext.CodeArea; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PreviewWithSourceTab { private static final Logger LOGGER = LoggerFactory.getLogger(PreviewWithSourceTab.class); public TabPane getPreviewWithSourceTab(BibEntry entry, BibDatabaseContext bibDatabaseContext, PreferencesService preferencesService, BibEntryTypesManager entryTypesManager, PreviewViewer previewViewer) { return getPreviewWithSourceTab(entry, bibDatabaseContext, preferencesService, entryTypesManager, previewViewer, ""); } public TabPane getPreviewWithSourceTab(BibEntry entry, BibDatabaseContext bibDatabaseContext, PreferencesService preferencesService, BibEntryTypesManager entryTypesManager, PreviewViewer previewViewer, String label) { previewViewer.setLayout(preferencesService.getPreviewPreferences().getSelectedPreviewLayout()); previewViewer.setEntry(entry); CodeArea codeArea = new CodeArea(); codeArea.setId("bibtexcodearea"); codeArea.setWrapText(true); codeArea.setDisable(true); TabPane tabPanePreviewCode = new TabPane(); Tab previewTab = new Tab(); previewTab.setContent(previewViewer); if (StringUtil.isNullOrEmpty(label)) { previewTab.setText(Localization.lang("Entry preview")); } else { previewTab.setText(label); } try { codeArea.appendText(getSourceString(entry, bibDatabaseContext.getMode(), preferencesService.getFieldPreferences(), entryTypesManager)); } catch (IOException e) { LOGGER.error("Error getting Bibtex: {}", entry); } codeArea.setEditable(false); Tab codeTab = new Tab(Localization.lang("%0 source", bibDatabaseContext.getMode().getFormattedName()), codeArea); tabPanePreviewCode.getTabs().addAll(previewTab, codeTab); return tabPanePreviewCode; } private String getSourceString(BibEntry entry, BibDatabaseMode type, FieldPreferences fieldPreferences, BibEntryTypesManager entryTypesManager) throws IOException { StringWriter writer = new StringWriter(); BibWriter bibWriter = new BibWriter(writer, OS.NEWLINE); FieldWriter fieldWriter = FieldWriter.buildIgnoreHashes(fieldPreferences); new BibEntryWriter(fieldWriter, entryTypesManager).write(entry, bibWriter, type); return writer.toString(); } }
3,210
42.391892
221
java
null
jabref-main/src/main/java/org/jabref/gui/collab/entrydelete/EntryDelete.java
package org.jabref.gui.collab.entrydelete; import org.jabref.gui.collab.DatabaseChange; import org.jabref.gui.collab.DatabaseChangeResolverFactory; import org.jabref.gui.undo.NamedCompound; import org.jabref.gui.undo.UndoableRemoveEntries; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; public final class EntryDelete extends DatabaseChange { private final BibEntry deletedEntry; public EntryDelete(BibEntry deletedEntry, BibDatabaseContext databaseContext, DatabaseChangeResolverFactory databaseChangeResolverFactory) { super(databaseContext, databaseChangeResolverFactory); this.deletedEntry = deletedEntry; setChangeName(deletedEntry.getCitationKey() .map(key -> Localization.lang("Deleted entry '%0'", key)) .orElse(Localization.lang("Deleted entry"))); } @Override public void applyChange(NamedCompound undoEdit) { databaseContext.getDatabase().removeEntry(deletedEntry); undoEdit.addEdit(new UndoableRemoveEntries(databaseContext.getDatabase(), deletedEntry)); } public BibEntry getDeletedEntry() { return deletedEntry; } }
1,258
38.34375
144
java
null
jabref-main/src/main/java/org/jabref/gui/collab/groupchange/GroupChange.java
package org.jabref.gui.collab.groupchange; import org.jabref.gui.collab.DatabaseChange; import org.jabref.gui.collab.DatabaseChangeResolverFactory; import org.jabref.gui.groups.GroupTreeNodeViewModel; import org.jabref.gui.groups.UndoableModifySubtree; import org.jabref.gui.undo.NamedCompound; import org.jabref.logic.bibtex.comparator.GroupDiff; import org.jabref.logic.groups.DefaultGroupsFactory; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.groups.GroupTreeNode; public final class GroupChange extends DatabaseChange { private final GroupDiff groupDiff; public GroupChange(GroupDiff groupDiff, BibDatabaseContext databaseContext, DatabaseChangeResolverFactory databaseChangeResolverFactory) { super(databaseContext, databaseChangeResolverFactory); this.groupDiff = groupDiff; setChangeName(groupDiff.getOriginalGroupRoot() == null ? Localization.lang("Removed all groups") : Localization .lang("Modified groups tree")); } @Override public void applyChange(NamedCompound undoEdit) { GroupTreeNode oldRoot = groupDiff.getOriginalGroupRoot(); GroupTreeNode newRoot = groupDiff.getNewGroupRoot(); GroupTreeNode root = databaseContext.getMetaData().getGroups().orElseGet(() -> { GroupTreeNode groupTreeNode = new GroupTreeNode(DefaultGroupsFactory.getAllEntriesGroup()); databaseContext.getMetaData().setGroups(groupTreeNode); return groupTreeNode; }); final UndoableModifySubtree undo = new UndoableModifySubtree( new GroupTreeNodeViewModel(databaseContext.getMetaData().getGroups().orElse(null)), new GroupTreeNodeViewModel(root), Localization.lang("Modified groups")); root.removeAllChildren(); if (newRoot == null) { // I think setting root to null is not possible root.setGroup(DefaultGroupsFactory.getAllEntriesGroup(), false, false, null); } else { // change root group, even though it'll be AllEntries anyway root.setGroup(newRoot.getGroup(), false, false, null); for (GroupTreeNode child : newRoot.getChildren()) { child.copySubtree().moveTo(root); } } undoEdit.addEdit(undo); } public GroupDiff getGroupDiff() { return groupDiff; } }
2,443
41.877193
142
java
null
jabref-main/src/main/java/org/jabref/gui/collab/groupchange/GroupChangeDetailsView.java
package org.jabref.gui.collab.groupchange; import javafx.scene.control.Label; import org.jabref.gui.collab.DatabaseChangeDetailsView; import org.jabref.logic.l10n.Localization; public final class GroupChangeDetailsView extends DatabaseChangeDetailsView { public GroupChangeDetailsView(GroupChange groupChange) { String labelValue = ""; if (groupChange.getGroupDiff().getNewGroupRoot() == null) { labelValue = groupChange.getName() + '.'; } else { labelValue = Localization.lang("%0. Accepting the change replaces the complete groups tree with the externally modified groups tree.", groupChange.getName()); } Label label = new Label(labelValue); setLeftAnchor(label, 8d); setTopAnchor(label, 8d); setRightAnchor(label, 8d); setBottomAnchor(label, 8d); getChildren().setAll(label); } }
901
33.692308
170
java
null
jabref-main/src/main/java/org/jabref/gui/collab/metedatachange/MetadataChange.java
package org.jabref.gui.collab.metedatachange; import org.jabref.gui.collab.DatabaseChange; import org.jabref.gui.collab.DatabaseChangeResolverFactory; import org.jabref.gui.undo.NamedCompound; import org.jabref.logic.bibtex.comparator.MetaDataDiff; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; public final class MetadataChange extends DatabaseChange { private final MetaDataDiff metaDataDiff; public MetadataChange(MetaDataDiff metaDataDiff, BibDatabaseContext databaseContext, DatabaseChangeResolverFactory databaseChangeResolverFactory) { super(databaseContext, databaseChangeResolverFactory); this.metaDataDiff = metaDataDiff; setChangeName(Localization.lang("Metadata change")); } @Override public void applyChange(NamedCompound undoEdit) { // TODO: Metadata edit should be undoable databaseContext.setMetaData(metaDataDiff.getNewMetaData()); // group change is handled by GroupChange, so we set the groups root to the original value // to prevent any inconsistency metaDataDiff.getGroupDifferences() .ifPresent(groupDiff -> databaseContext.getMetaData().setGroups(groupDiff.getOriginalGroupRoot())); } public MetaDataDiff getMetaDataDiff() { return metaDataDiff; } }
1,353
40.030303
151
java
null
jabref-main/src/main/java/org/jabref/gui/collab/metedatachange/MetadataChangeDetailsView.java
package org.jabref.gui.collab.metedatachange; import javafx.scene.control.Label; import javafx.scene.layout.VBox; import org.jabref.gui.collab.DatabaseChangeDetailsView; import org.jabref.logic.bibtex.comparator.MetaDataDiff; import org.jabref.logic.l10n.Localization; import org.jabref.preferences.PreferencesService; public final class MetadataChangeDetailsView extends DatabaseChangeDetailsView { public MetadataChangeDetailsView(MetadataChange metadataChange, PreferencesService preferencesService) { VBox container = new VBox(15); Label header = new Label(Localization.lang("The following metadata changed:")); header.getStyleClass().add("sectionHeader"); container.getChildren().add(header); for (MetaDataDiff.Difference change : metadataChange.getMetaDataDiff().getDifferences(preferencesService)) { container.getChildren().add(new Label(getDifferenceString(change))); } setLeftAnchor(container, 8d); setTopAnchor(container, 8d); setRightAnchor(container, 8d); setBottomAnchor(container, 8d); getChildren().setAll(container); } private String getDifferenceString(MetaDataDiff.Difference change) { return switch (change) { case PROTECTED -> Localization.lang("Library protection"); case GROUPS_ALTERED -> Localization.lang("Modified groups tree"); case ENCODING -> Localization.lang("Library encoding"); case SAVE_SORT_ORDER -> Localization.lang("Save sort order"); case KEY_PATTERNS -> Localization.lang("Key patterns"); case USER_FILE_DIRECTORY -> Localization.lang("User-specific file directory"); case LATEX_FILE_DIRECTORY -> Localization.lang("LaTeX file directory"); case DEFAULT_KEY_PATTERN -> Localization.lang("Default pattern"); case SAVE_ACTIONS -> Localization.lang("Save actions"); case MODE -> Localization.lang("Library mode"); case GENERAL_FILE_DIRECTORY -> Localization.lang("General file directory"); case CONTENT_SELECTOR -> Localization.lang("Content selectors"); }; } }
2,422
38.721311
116
java
null
jabref-main/src/main/java/org/jabref/gui/collab/preamblechange/PreambleChange.java
package org.jabref.gui.collab.preamblechange; import org.jabref.gui.collab.DatabaseChange; import org.jabref.gui.collab.DatabaseChangeResolverFactory; import org.jabref.gui.undo.NamedCompound; import org.jabref.gui.undo.UndoablePreambleChange; import org.jabref.logic.bibtex.comparator.PreambleDiff; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class PreambleChange extends DatabaseChange { private static final Logger LOGGER = LoggerFactory.getLogger(PreambleChange.class); private final PreambleDiff preambleDiff; public PreambleChange(PreambleDiff preambleDiff, BibDatabaseContext databaseContext, DatabaseChangeResolverFactory databaseChangeResolverFactory) { super(databaseContext, databaseChangeResolverFactory); this.preambleDiff = preambleDiff; setChangeName(Localization.lang("Changed preamble")); } @Override public void applyChange(NamedCompound undoEdit) { databaseContext.getDatabase().setPreamble(preambleDiff.getNewPreamble()); undoEdit.addEdit(new UndoablePreambleChange(databaseContext.getDatabase(), preambleDiff.getOriginalPreamble(), preambleDiff.getNewPreamble())); } public PreambleDiff getPreambleDiff() { return preambleDiff; } }
1,367
37
151
java
null
jabref-main/src/main/java/org/jabref/gui/collab/preamblechange/PreambleChangeDetailsView.java
package org.jabref.gui.collab.preamblechange; import javafx.scene.control.Label; import javafx.scene.layout.VBox; import org.jabref.gui.collab.DatabaseChangeDetailsView; import org.jabref.logic.bibtex.comparator.PreambleDiff; import org.jabref.logic.l10n.Localization; import org.jabref.model.strings.StringUtil; public final class PreambleChangeDetailsView extends DatabaseChangeDetailsView { public PreambleChangeDetailsView(PreambleChange preambleChange) { PreambleDiff preambleDiff = preambleChange.getPreambleDiff(); VBox container = new VBox(); Label header = new Label(Localization.lang("Changed preamble")); header.getStyleClass().add("sectionHeader"); container.getChildren().add(header); if (StringUtil.isNotBlank(preambleDiff.getOriginalPreamble())) { container.getChildren().add(new Label(Localization.lang("Current value: %0", preambleDiff.getOriginalPreamble()))); } if (StringUtil.isNotBlank(preambleDiff.getNewPreamble())) { container.getChildren().add(new Label(Localization.lang("Value set externally: %0", preambleDiff.getNewPreamble()))); } else { container.getChildren().add(new Label(Localization.lang("Value cleared externally"))); } setLeftAnchor(container, 8d); setTopAnchor(container, 8d); setRightAnchor(container, 8d); setBottomAnchor(container, 8d); getChildren().setAll(container); } }
1,488
38.184211
129
java
null
jabref-main/src/main/java/org/jabref/gui/collab/stringadd/BibTexStringAdd.java
package org.jabref.gui.collab.stringadd; import org.jabref.gui.collab.DatabaseChange; import org.jabref.gui.collab.DatabaseChangeResolverFactory; import org.jabref.gui.undo.NamedCompound; import org.jabref.gui.undo.UndoableInsertString; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.database.KeyCollisionException; import org.jabref.model.entry.BibtexString; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class BibTexStringAdd extends DatabaseChange { private static final Logger LOGGER = LoggerFactory.getLogger(BibTexStringAdd.class); private final BibtexString addedString; public BibTexStringAdd(BibtexString addedString, BibDatabaseContext databaseContext, DatabaseChangeResolverFactory databaseChangeResolverFactory) { super(databaseContext, databaseChangeResolverFactory); this.addedString = addedString; setChangeName(Localization.lang("Added string: '%0'", addedString.getName())); } @Override public void applyChange(NamedCompound undoEdit) { try { databaseContext.getDatabase().addString(addedString); undoEdit.addEdit(new UndoableInsertString(databaseContext.getDatabase(), addedString)); } catch (KeyCollisionException ex) { LOGGER.warn("Error: could not add string '{}': {}", addedString.getName(), ex.getMessage(), ex); } } public BibtexString getAddedString() { return addedString; } }
1,535
37.4
151
java
null
jabref-main/src/main/java/org/jabref/gui/collab/stringadd/BibTexStringAddDetailsView.java
package org.jabref.gui.collab.stringadd; import javafx.scene.control.Label; import javafx.scene.layout.VBox; import org.jabref.gui.collab.DatabaseChangeDetailsView; import org.jabref.logic.l10n.Localization; public final class BibTexStringAddDetailsView extends DatabaseChangeDetailsView { public BibTexStringAddDetailsView(BibTexStringAdd stringAdd) { VBox container = new VBox(); Label header = new Label(Localization.lang("Added string")); header.getStyleClass().add("sectionHeader"); container.getChildren().addAll( header, new Label(Localization.lang("Label: %0", stringAdd.getAddedString().getName())), new Label(Localization.lang("Content: %0", stringAdd.getAddedString().getContent())) ); setLeftAnchor(container, 8d); setTopAnchor(container, 8d); setRightAnchor(container, 8d); setBottomAnchor(container, 8d); getChildren().setAll(container); } }
997
34.642857
100
java
null
jabref-main/src/main/java/org/jabref/gui/collab/stringchange/BibTexStringChange.java
package org.jabref.gui.collab.stringchange; import org.jabref.gui.collab.DatabaseChange; import org.jabref.gui.collab.DatabaseChangeResolverFactory; import org.jabref.gui.undo.NamedCompound; import org.jabref.gui.undo.UndoableStringChange; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibtexString; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class BibTexStringChange extends DatabaseChange { private static final Logger LOGGER = LoggerFactory.getLogger(BibTexStringChange.class); private final BibtexString oldString; private final BibtexString newString; public BibTexStringChange(BibtexString oldString, BibtexString newString, BibDatabaseContext databaseContext, DatabaseChangeResolverFactory databaseChangeResolverFactory) { super(databaseContext, databaseChangeResolverFactory); this.oldString = oldString; this.newString = newString; setChangeName(Localization.lang("Modified string: '%0'", oldString.getName())); } @Override public void applyChange(NamedCompound undoEdit) { String oldContent = oldString.getContent(); String newContent = newString.getContent(); oldString.setContent(newContent); undoEdit.addEdit(new UndoableStringChange(oldString, false, oldContent, newContent)); } public BibtexString getOldString() { return oldString; } public BibtexString getNewString() { return newString; } }
1,553
34.318182
176
java
null
jabref-main/src/main/java/org/jabref/gui/collab/stringchange/BibTexStringChangeDetailsView.java
package org.jabref.gui.collab.stringchange; import javafx.scene.control.Label; import javafx.scene.layout.VBox; import org.jabref.gui.collab.DatabaseChangeDetailsView; import org.jabref.logic.l10n.Localization; public final class BibTexStringChangeDetailsView extends DatabaseChangeDetailsView { public BibTexStringChangeDetailsView(BibTexStringChange stringChange) { VBox container = new VBox(); Label header = new Label(Localization.lang("Modified string")); header.getStyleClass().add("sectionHeader"); container.getChildren().addAll( header, new Label(Localization.lang("Label: %0", stringChange.getOldString().getName())), new Label(Localization.lang("Content: %0", stringChange.getNewString().getContent())) ); container.getChildren().add(new Label(Localization.lang("Current content: %0", stringChange.getOldString().getContent()))); setLeftAnchor(container, 8d); setTopAnchor(container, 8d); setRightAnchor(container, 8d); setBottomAnchor(container, 8d); getChildren().setAll(container); } }
1,150
37.366667
131
java
null
jabref-main/src/main/java/org/jabref/gui/collab/stringdelete/BibTexStringDelete.java
package org.jabref.gui.collab.stringdelete; import org.jabref.gui.collab.DatabaseChange; import org.jabref.gui.collab.DatabaseChangeResolverFactory; import org.jabref.gui.undo.NamedCompound; import org.jabref.gui.undo.UndoableRemoveString; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibtexString; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class BibTexStringDelete extends DatabaseChange { private static final Logger LOGGER = LoggerFactory.getLogger(BibTexStringDelete.class); private final BibtexString deletedString; public BibTexStringDelete(BibtexString deletedString, BibDatabaseContext databaseContext, DatabaseChangeResolverFactory databaseChangeResolverFactory) { super(databaseContext, databaseChangeResolverFactory); this.deletedString = deletedString; setChangeName(Localization.lang("Deleted string: '%0'", deletedString.getName())); } @Override public void applyChange(NamedCompound undoEdit) { try { databaseContext.getDatabase().removeString(deletedString.getId()); undoEdit.addEdit(new UndoableRemoveString(databaseContext.getDatabase(), deletedString)); } catch (Exception ex) { LOGGER.warn("Error: could not remove string '{}': {}", deletedString.getName(), ex.getMessage(), ex); } } public BibtexString getDeletedString() { return deletedString; } }
1,515
37.871795
156
java
null
jabref-main/src/main/java/org/jabref/gui/collab/stringdelete/BibTexStringDeleteDetailsView.java
package org.jabref.gui.collab.stringdelete; import javafx.scene.control.Label; import javafx.scene.layout.VBox; import org.jabref.gui.collab.DatabaseChangeDetailsView; import org.jabref.logic.l10n.Localization; public final class BibTexStringDeleteDetailsView extends DatabaseChangeDetailsView { public BibTexStringDeleteDetailsView(BibTexStringDelete stringDelete) { VBox container = new VBox(); Label header = new Label(Localization.lang("Deleted string")); header.getStyleClass().add("sectionHeader"); container.getChildren().addAll( header, new Label(Localization.lang("Label: %0", stringDelete.getDeletedString().getName())), new Label(Localization.lang("Content: %0", stringDelete.getDeletedString().getContent())) ); setLeftAnchor(container, 8d); setTopAnchor(container, 8d); setRightAnchor(container, 8d); setBottomAnchor(container, 8d); getChildren().setAll(container); } }
1,024
35.607143
105
java
null
jabref-main/src/main/java/org/jabref/gui/collab/stringrename/BibTexStringRename.java
package org.jabref.gui.collab.stringrename; import org.jabref.gui.collab.DatabaseChange; import org.jabref.gui.collab.DatabaseChangeResolverFactory; import org.jabref.gui.undo.NamedCompound; import org.jabref.gui.undo.UndoableStringChange; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibtexString; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class BibTexStringRename extends DatabaseChange { private static final Logger LOGGER = LoggerFactory.getLogger(BibTexStringRename.class); private final BibtexString oldString; private final BibtexString newString; public BibTexStringRename(BibtexString oldString, BibtexString newString, BibDatabaseContext databaseContext, DatabaseChangeResolverFactory databaseChangeResolverFactory) { super(databaseContext, databaseChangeResolverFactory); this.oldString = oldString; this.newString = newString; setChangeName(Localization.lang("Renamed string: '%0'", oldString.getName())); } @Override public void applyChange(NamedCompound undoEdit) { if (databaseContext.getDatabase().hasStringByName(newString.getName())) { // The name to change to is already in the database, so we can't comply. LOGGER.info("Cannot rename string '{}' to '{}' because the name is already in use", oldString.getName(), newString.getName()); } String currentName = oldString.getName(); String newName = newString.getName(); oldString.setName(newName); undoEdit.addEdit(new UndoableStringChange(oldString, true, currentName, newName)); } public BibtexString getOldString() { return oldString; } public BibtexString getNewString() { return newString; } }
1,852
36.816327
176
java
null
jabref-main/src/main/java/org/jabref/gui/collab/stringrename/BibTexStringRenameDetailsView.java
package org.jabref.gui.collab.stringrename; import javafx.scene.control.Label; import org.jabref.gui.collab.DatabaseChangeDetailsView; public final class BibTexStringRenameDetailsView extends DatabaseChangeDetailsView { public BibTexStringRenameDetailsView(BibTexStringRename stringRename) { Label label = new Label(stringRename.getNewString().getName() + " : " + stringRename.getOldString().getContent()); setLeftAnchor(label, 8d); setTopAnchor(label, 8d); setRightAnchor(label, 8d); setBottomAnchor(label, 8d); getChildren().setAll(label); } }
607
31
122
java
null
jabref-main/src/main/java/org/jabref/gui/commonfxcontrols/CitationKeyPatternPanel.java
package org.jabref.gui.commonfxcontrols; import java.util.Collection; import javafx.beans.property.ListProperty; import javafx.beans.property.ObjectProperty; import javafx.fxml.FXML; import javafx.scene.control.TableColumn; import javafx.scene.control.TableRow; import javafx.scene.control.TableView; import javafx.scene.control.cell.TextFieldTableCell; import javafx.scene.input.KeyEvent; import org.jabref.gui.icon.IconTheme; import org.jabref.gui.util.ValueTableCellFactory; import org.jabref.logic.citationkeypattern.AbstractCitationKeyPattern; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.BibEntryType; import org.jabref.model.entry.types.EntryType; import org.jabref.preferences.PreferencesService; import com.airhacks.afterburner.views.ViewLoader; import jakarta.inject.Inject; public class CitationKeyPatternPanel extends TableView<CitationKeyPatternPanelItemModel> { @FXML public TableColumn<CitationKeyPatternPanelItemModel, EntryType> entryTypeColumn; @FXML public TableColumn<CitationKeyPatternPanelItemModel, String> patternColumn; @FXML public TableColumn<CitationKeyPatternPanelItemModel, EntryType> actionsColumn; @Inject private PreferencesService preferences; private CitationKeyPatternPanelViewModel viewModel; private long lastKeyPressTime; private String tableSearchTerm; public CitationKeyPatternPanel() { super(); ViewLoader.view(this) .root(this) .load(); } @FXML private void initialize() { viewModel = new CitationKeyPatternPanelViewModel(preferences.getCitationKeyPatternPreferences()); this.setEditable(true); entryTypeColumn.setSortable(true); entryTypeColumn.setReorderable(false); entryTypeColumn.setCellValueFactory(cellData -> cellData.getValue().entryType()); new ValueTableCellFactory<CitationKeyPatternPanelItemModel, EntryType>() .withText(EntryType::getDisplayName) .install(entryTypeColumn); this.setOnSort(event -> viewModel.patternListProperty().sort(CitationKeyPatternPanelViewModel.defaultOnTopComparator)); patternColumn.setSortable(true); patternColumn.setReorderable(false); patternColumn.setCellValueFactory(cellData -> cellData.getValue().pattern()); patternColumn.setCellFactory(TextFieldTableCell.forTableColumn()); patternColumn.setEditable(true); patternColumn.setOnEditCommit( (TableColumn.CellEditEvent<CitationKeyPatternPanelItemModel, String> event) -> event.getRowValue().setPattern(event.getNewValue())); actionsColumn.setSortable(false); actionsColumn.setReorderable(false); actionsColumn.setCellValueFactory(cellData -> cellData.getValue().entryType()); new ValueTableCellFactory<CitationKeyPatternPanelItemModel, EntryType>() .withGraphic(entryType -> IconTheme.JabRefIcons.REFRESH.getGraphicNode()) .withTooltip(entryType -> String.format(Localization.lang("Reset %s to default value"), entryType.getDisplayName())) .withOnMouseClickedEvent(item -> evt -> viewModel.setItemToDefaultPattern(this.getFocusModel().getFocusedItem())) .install(actionsColumn); this.setRowFactory(item -> new HighlightTableRow()); this.setOnKeyTyped(this::jumpToSearchKey); this.itemsProperty().bindBidirectional(viewModel.patternListProperty()); } public void setValues(Collection<BibEntryType> entryTypeList, AbstractCitationKeyPattern keyPattern) { viewModel.setValues(entryTypeList, keyPattern); } public void resetAll() { viewModel.resetAll(); } public ListProperty<CitationKeyPatternPanelItemModel> patternListProperty() { return viewModel.patternListProperty(); } public ObjectProperty<CitationKeyPatternPanelItemModel> defaultKeyPatternProperty() { return viewModel.defaultKeyPatternProperty(); } private void jumpToSearchKey(KeyEvent keypressed) { if (keypressed.getCharacter() == null) { return; } if (System.currentTimeMillis() - lastKeyPressTime < 1000) { tableSearchTerm += keypressed.getCharacter().toLowerCase(); } else { tableSearchTerm = keypressed.getCharacter().toLowerCase(); } lastKeyPressTime = System.currentTimeMillis(); this.getItems().stream().filter(item -> item.getEntryType().getName().toLowerCase().startsWith(tableSearchTerm)) .findFirst().ifPresent(this::scrollTo); } private static class HighlightTableRow extends TableRow<CitationKeyPatternPanelItemModel> { @Override public void updateItem(CitationKeyPatternPanelItemModel item, boolean empty) { super.updateItem(item, empty); if (item == null || item.getEntryType() == null) { setStyle(""); } else if (isSelected()) { setStyle("-fx-background-color: -fx-selection-bar"); } else if (item.getEntryType().getName().equals(CitationKeyPatternPanelViewModel.ENTRY_TYPE_DEFAULT_NAME)) { setStyle("-fx-background-color: -fx-default-button"); } else { setStyle(""); } } } }
5,448
39.362963
120
java
null
jabref-main/src/main/java/org/jabref/gui/commonfxcontrols/CitationKeyPatternPanelItemModel.java
package org.jabref.gui.commonfxcontrols; import java.util.Objects; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import org.jabref.model.entry.types.EntryType; public class CitationKeyPatternPanelItemModel { private final ObjectProperty<EntryType> entryType = new SimpleObjectProperty<>(); private final StringProperty pattern = new SimpleStringProperty(""); public CitationKeyPatternPanelItemModel(EntryType entryType, String pattern) { Objects.requireNonNull(entryType); Objects.requireNonNull(pattern); this.entryType.setValue(entryType); this.pattern.setValue(pattern); } public EntryType getEntryType() { return entryType.getValue(); } public ObjectProperty<EntryType> entryType() { return entryType; } public void setPattern(String pattern) { this.pattern.setValue(pattern); } public String getPattern() { return pattern.getValue(); } public StringProperty pattern() { return pattern; } @Override public String toString() { return "[" + entryType.getValue().getName() + "," + pattern.getValue() + "]"; } }
1,317
26.458333
85
java
null
jabref-main/src/main/java/org/jabref/gui/commonfxcontrols/CitationKeyPatternPanelViewModel.java
package org.jabref.gui.commonfxcontrols; import java.util.Collection; import java.util.Comparator; import javafx.beans.property.ListProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleListProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.FXCollections; import org.jabref.logic.citationkeypattern.AbstractCitationKeyPattern; import org.jabref.logic.citationkeypattern.CitationKeyPatternPreferences; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.BibEntryType; import org.jabref.model.entry.types.EntryType; public class CitationKeyPatternPanelViewModel { public static final String ENTRY_TYPE_DEFAULT_NAME = "default"; public static Comparator<CitationKeyPatternPanelItemModel> defaultOnTopComparator = (o1, o2) -> { String itemOneName = o1.getEntryType().getName(); String itemTwoName = o2.getEntryType().getName(); if (itemOneName.equals(itemTwoName)) { return 0; } else if (itemOneName.equals(ENTRY_TYPE_DEFAULT_NAME)) { return -1; } else if (itemTwoName.equals(ENTRY_TYPE_DEFAULT_NAME)) { return 1; } return 0; }; private final ListProperty<CitationKeyPatternPanelItemModel> patternListProperty = new SimpleListProperty<>(); private final ObjectProperty<CitationKeyPatternPanelItemModel> defaultItemProperty = new SimpleObjectProperty<>(); private final CitationKeyPatternPreferences keyPatternPreferences; public CitationKeyPatternPanelViewModel(CitationKeyPatternPreferences keyPatternPreferences) { this.keyPatternPreferences = keyPatternPreferences; } public void setValues(Collection<BibEntryType> entryTypeList, AbstractCitationKeyPattern initialKeyPattern) { String defaultPattern; if ((initialKeyPattern.getDefaultValue() == null) || initialKeyPattern.getDefaultValue().isEmpty()) { defaultPattern = ""; } else { defaultPattern = initialKeyPattern.getDefaultValue().get(0); } defaultItemProperty.setValue(new CitationKeyPatternPanelItemModel(new DefaultEntryType(), defaultPattern)); patternListProperty.setValue(FXCollections.observableArrayList()); patternListProperty.add(defaultItemProperty.getValue()); entryTypeList.stream() .map(BibEntryType::getType) .forEach(entryType -> { String pattern; if (initialKeyPattern.isDefaultValue(entryType)) { pattern = ""; } else { pattern = initialKeyPattern.getPatterns().get(entryType).get(0); } patternListProperty.add(new CitationKeyPatternPanelItemModel(entryType, pattern)); }); } public void setItemToDefaultPattern(CitationKeyPatternPanelItemModel item) { item.setPattern(keyPatternPreferences.getDefaultPattern()); } public void resetAll() { patternListProperty.forEach(item -> item.setPattern("")); defaultItemProperty.getValue().setPattern(keyPatternPreferences.getDefaultPattern()); } public ListProperty<CitationKeyPatternPanelItemModel> patternListProperty() { return patternListProperty; } public ObjectProperty<CitationKeyPatternPanelItemModel> defaultKeyPatternProperty() { return defaultItemProperty; } public static class DefaultEntryType implements EntryType { @Override public String getName() { return ENTRY_TYPE_DEFAULT_NAME; } @Override public String getDisplayName() { return Localization.lang("Default pattern"); } } }
3,845
37.46
118
java
null
jabref-main/src/main/java/org/jabref/gui/commonfxcontrols/FieldFormatterCleanupsPanel.java
package org.jabref.gui.commonfxcontrols; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ListProperty; import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.SelectionMode; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.input.KeyCode; import javafx.scene.layout.VBox; import org.jabref.gui.icon.IconTheme; import org.jabref.gui.util.BindingsHelper; import org.jabref.gui.util.FieldsUtil; import org.jabref.gui.util.ValueTableCellFactory; import org.jabref.gui.util.ViewModelListCellFactory; import org.jabref.logic.cleanup.FieldFormatterCleanup; import org.jabref.logic.cleanup.Formatter; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.field.Field; import com.airhacks.afterburner.views.ViewLoader; public class FieldFormatterCleanupsPanel extends VBox { @FXML private CheckBox cleanupsEnabled; @FXML private TableView<FieldFormatterCleanup> cleanupsList; @FXML private TableColumn<FieldFormatterCleanup, Field> fieldColumn; @FXML private TableColumn<FieldFormatterCleanup, Formatter> formatterColumn; @FXML private TableColumn<FieldFormatterCleanup, Field> actionsColumn; @FXML private ComboBox<Field> addableFields; @FXML private ComboBox<Formatter> addableFormatters; private FieldFormatterCleanupsPanelViewModel viewModel; public FieldFormatterCleanupsPanel() { ViewLoader.view(this) .root(this) .load(); } @FXML private void initialize() { this.viewModel = new FieldFormatterCleanupsPanelViewModel(); setupTable(); setupCombos(); setupBindings(); } private void setupTable() { cleanupsList.getSelectionModel().setSelectionMode(SelectionMode.SINGLE); // ToDo: To be editable the list needs a view model wrapper for FieldFormatterCleanup fieldColumn.setCellValueFactory(cellData -> new ReadOnlyObjectWrapper<>(cellData.getValue().getField())); new ValueTableCellFactory<FieldFormatterCleanup, Field>() .withText(Field::getDisplayName) .install(fieldColumn); formatterColumn.setCellValueFactory(cellData -> new ReadOnlyObjectWrapper<>(cellData.getValue().getFormatter())); new ValueTableCellFactory<FieldFormatterCleanup, Formatter>() .withText(Formatter::getName) .install(formatterColumn); actionsColumn.setCellValueFactory(cellData -> new ReadOnlyObjectWrapper<>(cellData.getValue().getField())); new ValueTableCellFactory<FieldFormatterCleanup, Field>() .withGraphic(field -> IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode()) .withTooltip(field -> Localization.lang("Remove formatter for %0", field.getDisplayName())) .withOnMouseClickedEvent(item -> event -> viewModel.removeCleanup(cleanupsList.getSelectionModel().getSelectedItem())) .install(actionsColumn); viewModel.selectedCleanupProperty().setValue(cleanupsList.getSelectionModel()); cleanupsList.setOnKeyPressed(event -> { if (event.getCode() == KeyCode.DELETE) { viewModel.removeCleanup(cleanupsList.getSelectionModel().getSelectedItem()); } }); } private void setupCombos() { new ViewModelListCellFactory<Field>() .withText(Field::getDisplayName) .install(addableFields); addableFields.setConverter(FieldsUtil.FIELD_STRING_CONVERTER); addableFields.setOnKeyPressed(event -> { if (event.getCode() == KeyCode.TAB || event.getCode() == KeyCode.ENTER) { addableFormatters.requestFocus(); event.consume(); } }); new ViewModelListCellFactory<Formatter>() .withText(Formatter::getName) .withStringTooltip(Formatter::getDescription) .install(addableFormatters); addableFormatters.setOnKeyPressed(event -> { if (event.getCode() == KeyCode.ENTER) { viewModel.addCleanup(); event.consume(); } }); } private void setupBindings() { BindingsHelper.bindBidirectional((ObservableValue<Boolean>) cleanupsEnabled.selectedProperty(), viewModel.cleanupsDisableProperty(), disabled -> cleanupsEnabled.selectedProperty().setValue(!disabled), selected -> viewModel.cleanupsDisableProperty().setValue(!selected)); cleanupsList.itemsProperty().bind(viewModel.cleanupsListProperty()); addableFields.itemsProperty().bind(viewModel.availableFieldsProperty()); addableFields.valueProperty().bindBidirectional(viewModel.selectedFieldProperty()); addableFormatters.itemsProperty().bind(viewModel.availableFormattersProperty()); addableFormatters.valueProperty().bindBidirectional(viewModel.selectedFormatterProperty()); } @FXML private void resetToRecommended() { viewModel.resetToRecommended(); } @FXML private void clearAll() { viewModel.clearAll(); } @FXML private void addCleanup() { viewModel.addCleanup(); } public BooleanProperty cleanupsDisableProperty() { return viewModel.cleanupsDisableProperty(); } public ListProperty<FieldFormatterCleanup> cleanupsProperty() { return viewModel.cleanupsListProperty(); } }
5,703
38.068493
134
java
null
jabref-main/src/main/java/org/jabref/gui/commonfxcontrols/FieldFormatterCleanupsPanelViewModel.java
package org.jabref.gui.commonfxcontrols; 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 javafx.collections.transformation.SortedList; import javafx.scene.control.SelectionModel; import org.jabref.gui.Globals; import org.jabref.gui.util.NoSelectionModel; import org.jabref.logic.cleanup.FieldFormatterCleanup; import org.jabref.logic.cleanup.FieldFormatterCleanups; import org.jabref.logic.cleanup.Formatter; import org.jabref.logic.formatter.Formatters; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldFactory; public class FieldFormatterCleanupsPanelViewModel { private final BooleanProperty cleanupsDisableProperty = new SimpleBooleanProperty(); private final ListProperty<FieldFormatterCleanup> cleanupsListProperty = new SimpleListProperty<>(FXCollections.observableArrayList()); private final ObjectProperty<SelectionModel<FieldFormatterCleanup>> selectedCleanupProperty = new SimpleObjectProperty<>(new NoSelectionModel<>()); private final ListProperty<Field> availableFieldsProperty = new SimpleListProperty<>(new SortedList<>(FXCollections.observableArrayList(FieldFactory.getCommonFields()), Comparator.comparing(Field::getDisplayName))); private final ObjectProperty<Field> selectedFieldProperty = new SimpleObjectProperty<>(); private final ListProperty<Formatter> availableFormattersProperty = new SimpleListProperty<>(new SortedList<>(FXCollections.observableArrayList(Formatters.getAll()), Comparator.comparing(Formatter::getName))); private final ObjectProperty<Formatter> selectedFormatterProperty = new SimpleObjectProperty<>(); public FieldFormatterCleanupsPanelViewModel() { } public void resetToRecommended() { Globals.stateManager.getActiveDatabase().ifPresent(databaseContext -> { if (databaseContext.isBiblatexMode()) { cleanupsListProperty.setAll(FieldFormatterCleanups.RECOMMEND_BIBLATEX_ACTIONS); } else { cleanupsListProperty.setAll(FieldFormatterCleanups.RECOMMEND_BIBTEX_ACTIONS); } }); } public void clearAll() { cleanupsListProperty.clear(); } public void addCleanup() { if (selectedFieldProperty.getValue() == null || selectedFormatterProperty.getValue() == null) { return; } FieldFormatterCleanup cleanup = new FieldFormatterCleanup( selectedFieldProperty.getValue(), selectedFormatterProperty.getValue()); if (cleanupsListProperty.stream().noneMatch(item -> item.equals(cleanup))) { cleanupsListProperty.add(cleanup); } } public void removeCleanup(FieldFormatterCleanup cleanup) { cleanupsListProperty.remove(cleanup); } public BooleanProperty cleanupsDisableProperty() { return cleanupsDisableProperty; } public ListProperty<FieldFormatterCleanup> cleanupsListProperty() { return cleanupsListProperty; } public ObjectProperty<SelectionModel<FieldFormatterCleanup>> selectedCleanupProperty() { return selectedCleanupProperty; } public ListProperty<Field> availableFieldsProperty() { return availableFieldsProperty; } public ObjectProperty<Field> selectedFieldProperty() { return selectedFieldProperty; } public ListProperty<Formatter> availableFormattersProperty() { return availableFormattersProperty; } public ObjectProperty<Formatter> selectedFormatterProperty() { return selectedFormatterProperty; } }
3,887
39.082474
219
java
null
jabref-main/src/main/java/org/jabref/gui/commonfxcontrols/SaveOrderConfigPanel.java
package org.jabref.gui.commonfxcontrols; import java.util.List; import java.util.stream.Collectors; import javafx.beans.binding.Bindings; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ListProperty; import javafx.collections.ListChangeListener; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.RadioButton; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import org.jabref.gui.icon.IconTheme; import org.jabref.gui.icon.JabRefIconView; import org.jabref.gui.util.FieldsUtil; 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; public class SaveOrderConfigPanel extends VBox { @FXML private RadioButton exportInSpecifiedOrder; @FXML private RadioButton exportInTableOrder; @FXML private RadioButton exportInOriginalOrder; @FXML private GridPane sortCriterionList; @FXML private Button addButton; private SaveOrderConfigPanelViewModel viewModel; public SaveOrderConfigPanel() { ViewLoader.view(this) .root(this) .load(); } @FXML private void initialize() { viewModel = new SaveOrderConfigPanelViewModel(); exportInOriginalOrder.selectedProperty().bindBidirectional(viewModel.saveInOriginalProperty()); exportInTableOrder.selectedProperty().bindBidirectional(viewModel.saveInTableOrderProperty()); exportInSpecifiedOrder.selectedProperty().bindBidirectional(viewModel.saveInSpecifiedOrderProperty()); viewModel.sortCriteriaProperty().addListener((ListChangeListener<SortCriterionViewModel>) change -> { while (change.next()) { if (change.wasReplaced()) { clearCriterionRow(change.getFrom()); createCriterionRow(change.getAddedSubList().get(0), change.getFrom()); } else if (change.wasAdded()) { for (SortCriterionViewModel criterionViewModel : change.getAddedSubList()) { int row = change.getFrom() + change.getAddedSubList().indexOf(criterionViewModel); createCriterionRow(criterionViewModel, row); } } else if (change.wasRemoved()) { for (SortCriterionViewModel criterionViewModel : change.getRemoved()) { clearCriterionRow(change.getFrom()); } } } }); } private void createCriterionRow(SortCriterionViewModel criterionViewModel, int row) { sortCriterionList.getChildren().stream() .filter(item -> GridPane.getRowIndex(item) >= row) .forEach(item -> { GridPane.setRowIndex(item, GridPane.getRowIndex(item) + 1); if (item instanceof Label label) { label.setText(String.valueOf(GridPane.getRowIndex(item) + 1)); } }); Label label = new Label(String.valueOf(row + 1)); sortCriterionList.add(label, 0, row); ComboBox<Field> field = new ComboBox<>(viewModel.sortableFieldsProperty()); field.setMaxWidth(Double.MAX_VALUE); new ViewModelListCellFactory<Field>() .withText(FieldsUtil::getNameWithType) .install(field); field.setConverter(FieldsUtil.FIELD_STRING_CONVERTER); field.itemsProperty().bindBidirectional(viewModel.sortableFieldsProperty()); field.valueProperty().bindBidirectional(criterionViewModel.fieldProperty()); sortCriterionList.add(field, 1, row); GridPane.getHgrow(field); CheckBox descending = new CheckBox(Localization.lang("Descending")); descending.selectedProperty().bindBidirectional(criterionViewModel.descendingProperty()); sortCriterionList.add(descending, 2, row); HBox hBox = new HBox(); hBox.getChildren().addAll(createRowButtons(criterionViewModel)); sortCriterionList.add(hBox, 3, row); } private List<Node> createRowButtons(SortCriterionViewModel criterionViewModel) { Button remove = new Button("", new JabRefIconView(IconTheme.JabRefIcons.REMOVE_NOBOX)); remove.getStyleClass().addAll("icon-button", "narrow"); remove.setPrefHeight(20.0); remove.setPrefWidth(20.0); remove.setOnAction(event -> removeCriterion(criterionViewModel)); Button moveUp = new Button("", new JabRefIconView(IconTheme.JabRefIcons.LIST_MOVE_UP)); moveUp.getStyleClass().addAll("icon-button", "narrow"); moveUp.setPrefHeight(20.0); moveUp.setPrefWidth(20.0); moveUp.setOnAction(event -> moveCriterionUp(criterionViewModel)); Button moveDown = new Button("", new JabRefIconView(IconTheme.JabRefIcons.LIST_MOVE_DOWN)); moveDown.getStyleClass().addAll("icon-button", "narrow"); moveDown.setPrefHeight(20.0); moveDown.setPrefWidth(20.0); moveDown.setOnAction(event -> moveCriterionDown(criterionViewModel)); return List.of(moveUp, moveDown, remove); } private void clearCriterionRow(int row) { List<Node> criterionRow = sortCriterionList.getChildren().stream() .filter(item -> GridPane.getRowIndex(item) == row) .collect(Collectors.toList()); sortCriterionList.getChildren().removeAll(criterionRow); sortCriterionList.getChildren().stream() .filter(item -> GridPane.getRowIndex(item) > row) .forEach(item -> { GridPane.setRowIndex(item, GridPane.getRowIndex(item) - 1); if (item instanceof Label label) { label.setText(String.valueOf(GridPane.getRowIndex(item) + 1)); } }); } public void setCriteriaLimit(int limit) { addButton.disableProperty().unbind(); addButton.disableProperty().bind( Bindings.createBooleanBinding( () -> viewModel.sortCriteriaProperty().size() >= limit || !exportInSpecifiedOrder.selectedProperty().get(), viewModel.sortCriteriaProperty().sizeProperty(), exportInSpecifiedOrder.selectedProperty())); } @FXML public void addCriterion() { viewModel.addCriterion(); } @FXML public void moveCriterionUp(SortCriterionViewModel criterionViewModel) { viewModel.moveCriterionUp(criterionViewModel); } @FXML public void moveCriterionDown(SortCriterionViewModel criterionViewModel) { viewModel.moveCriterionDown(criterionViewModel); } @FXML public void removeCriterion(SortCriterionViewModel criterionViewModel) { viewModel.removeCriterion(criterionViewModel); } public BooleanProperty saveInOriginalProperty() { return viewModel.saveInOriginalProperty(); } public BooleanProperty saveInTableOrderProperty() { return viewModel.saveInTableOrderProperty(); } public BooleanProperty saveInSpecifiedOrderProperty() { return viewModel.saveInSpecifiedOrderProperty(); } public ListProperty<Field> sortableFieldsProperty() { return viewModel.sortableFieldsProperty(); } public ListProperty<SortCriterionViewModel> sortCriteriaProperty() { return viewModel.sortCriteriaProperty(); } }
7,946
40.176166
131
java
null
jabref-main/src/main/java/org/jabref/gui/commonfxcontrols/SaveOrderConfigPanelViewModel.java
package org.jabref.gui.commonfxcontrols; import java.util.Collections; 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.model.entry.field.Field; import org.jabref.model.metadata.SaveOrder; public class SaveOrderConfigPanelViewModel { private final BooleanProperty saveInOriginalProperty = new SimpleBooleanProperty(); private final BooleanProperty saveInTableOrderProperty = new SimpleBooleanProperty(); private final BooleanProperty saveInSpecifiedOrderProperty = new SimpleBooleanProperty(); private final ListProperty<Field> sortableFieldsProperty = new SimpleListProperty<>(FXCollections.observableArrayList()); private final ListProperty<SortCriterionViewModel> selectedSortCriteriaProperty = new SimpleListProperty<>(FXCollections.observableArrayList()); public SaveOrderConfigPanelViewModel() { } public void addCriterion() { selectedSortCriteriaProperty.add(new SortCriterionViewModel(new SaveOrder.SortCriterion())); } public void removeCriterion(SortCriterionViewModel sortCriterionViewModel) { selectedSortCriteriaProperty.remove(sortCriterionViewModel); } public void moveCriterionUp(SortCriterionViewModel sortCriterionViewModel) { if (selectedSortCriteriaProperty.contains(sortCriterionViewModel)) { int index = selectedSortCriteriaProperty.indexOf(sortCriterionViewModel); if (index > 0) { Collections.swap(selectedSortCriteriaProperty, index - 1, index); } } } public void moveCriterionDown(SortCriterionViewModel sortCriterionViewModel) { if (selectedSortCriteriaProperty.contains(sortCriterionViewModel)) { int index = selectedSortCriteriaProperty.indexOf(sortCriterionViewModel); if (index >= 0 && index < selectedSortCriteriaProperty.size() - 1) { Collections.swap(selectedSortCriteriaProperty, index + 1, index); } } } public BooleanProperty saveInOriginalProperty() { return saveInOriginalProperty; } public BooleanProperty saveInTableOrderProperty() { return saveInTableOrderProperty; } public BooleanProperty saveInSpecifiedOrderProperty() { return saveInSpecifiedOrderProperty; } public ListProperty<Field> sortableFieldsProperty() { return sortableFieldsProperty; } public ListProperty<SortCriterionViewModel> sortCriteriaProperty() { return selectedSortCriteriaProperty; } }
2,710
36.652778
148
java
null
jabref-main/src/main/java/org/jabref/gui/commonfxcontrols/SortCriterionViewModel.java
package org.jabref.gui.commonfxcontrols; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleObjectProperty; import org.jabref.model.entry.field.Field; import org.jabref.model.metadata.SaveOrder; public class SortCriterionViewModel { private final ObjectProperty<Field> fieldProperty = new SimpleObjectProperty<>(); private final BooleanProperty descendingProperty = new SimpleBooleanProperty(); public SortCriterionViewModel(SaveOrder.SortCriterion criterion) { this.fieldProperty.setValue(criterion.field); this.descendingProperty.setValue(criterion.descending); } public ObjectProperty<Field> fieldProperty() { return fieldProperty; } public BooleanProperty descendingProperty() { return descendingProperty; } public SaveOrder.SortCriterion getCriterion() { return new SaveOrder.SortCriterion(fieldProperty.getValue(), descendingProperty.getValue()); } }
1,072
31.515152
100
java
null
jabref-main/src/main/java/org/jabref/gui/copyfiles/CopyFilesAction.java
package org.jabref.gui.copyfiles; import java.nio.file.Path; import java.util.List; import java.util.Optional; import javafx.concurrent.Task; import org.jabref.gui.DialogService; import org.jabref.gui.Globals; import org.jabref.gui.StateManager; import org.jabref.gui.actions.SimpleCommand; import org.jabref.gui.util.DirectoryDialogConfiguration; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.preferences.PreferencesService; import static org.jabref.gui.actions.ActionHelper.needsDatabase; import static org.jabref.gui.actions.ActionHelper.needsEntriesSelected; public class CopyFilesAction extends SimpleCommand { private final DialogService dialogService; private final PreferencesService preferencesService; private final StateManager stateManager; public CopyFilesAction(DialogService dialogService, PreferencesService preferencesService, StateManager stateManager) { this.dialogService = dialogService; this.preferencesService = preferencesService; this.stateManager = stateManager; this.executable.bind(needsDatabase(stateManager).and(needsEntriesSelected(stateManager))); } private void showDialog(List<CopyFilesResultItemViewModel> data) { if (data.isEmpty()) { dialogService.showInformationDialogAndWait(Localization.lang("Copy linked files to folder..."), Localization.lang("No linked files found for export.")); return; } dialogService.showCustomDialogAndWait(new CopyFilesDialogView(new CopyFilesResultListDependency(data))); } @Override public void execute() { BibDatabaseContext database = stateManager.getActiveDatabase().orElseThrow(() -> new NullPointerException("Database null")); List<BibEntry> entries = stateManager.getSelectedEntries(); DirectoryDialogConfiguration dirDialogConfiguration = new DirectoryDialogConfiguration.Builder() .withInitialDirectory(preferencesService.getExportPreferences().getExportWorkingDirectory()) .build(); Optional<Path> exportPath = dialogService.showDirectorySelectionDialog(dirDialogConfiguration); exportPath.ifPresent(path -> { Task<List<CopyFilesResultItemViewModel>> exportTask = new CopyFilesTask(database, entries, path, preferencesService); dialogService.showProgressDialog( Localization.lang("Copy linked files to folder..."), Localization.lang("Copy linked files to folder..."), exportTask); Globals.TASK_EXECUTOR.execute(exportTask); exportTask.setOnSucceeded(e -> showDialog(exportTask.getValue())); }); } }
2,803
42.8125
164
java
null
jabref-main/src/main/java/org/jabref/gui/copyfiles/CopyFilesDialogView.java
package org.jabref.gui.copyfiles; import javafx.fxml.FXML; import javafx.scene.control.ButtonType; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.paint.Color; import org.jabref.gui.icon.IconTheme; import org.jabref.gui.icon.JabRefIcon; import org.jabref.gui.util.BaseDialog; import org.jabref.gui.util.ValueTableCellFactory; import org.jabref.logic.l10n.Localization; import com.airhacks.afterburner.views.ViewLoader; public class CopyFilesDialogView extends BaseDialog<Void> { @FXML private TableView<CopyFilesResultItemViewModel> tvResult; @FXML private TableColumn<CopyFilesResultItemViewModel, JabRefIcon> colStatus; @FXML private TableColumn<CopyFilesResultItemViewModel, String> colMessage; @FXML private TableColumn<CopyFilesResultItemViewModel, String> colFile; private final CopyFilesDialogViewModel viewModel; public CopyFilesDialogView(CopyFilesResultListDependency results) { this.setTitle(Localization.lang("Result")); this.getDialogPane().getButtonTypes().addAll(ButtonType.OK); viewModel = new CopyFilesDialogViewModel(results); ViewLoader.view(this) .load() .setAsContent(this.getDialogPane()); } @FXML private void initialize() { setupTable(); } private void setupTable() { colFile.setCellValueFactory(cellData -> cellData.getValue().getFile()); colMessage.setCellValueFactory(cellData -> cellData.getValue().getMessage()); colStatus.setCellValueFactory(cellData -> cellData.getValue().getIcon()); colFile.setCellFactory(new ValueTableCellFactory<CopyFilesResultItemViewModel, String>().withText(item -> item).withTooltip(item -> item)); colStatus.setCellFactory(new ValueTableCellFactory<CopyFilesResultItemViewModel, JabRefIcon>().withGraphic(item -> { if (item == IconTheme.JabRefIcons.CHECK) { item = item.withColor(Color.GREEN); } if (item == IconTheme.JabRefIcons.WARNING) { item = item.withColor(Color.RED); } return item.getGraphicNode(); })); tvResult.setItems(viewModel.copyFilesResultListProperty()); tvResult.setColumnResizePolicy(param -> true); } }
2,326
36.532258
147
java
null
jabref-main/src/main/java/org/jabref/gui/copyfiles/CopyFilesDialogViewModel.java
package org.jabref.gui.copyfiles; import javafx.beans.property.SimpleListProperty; import javafx.collections.FXCollections; import org.jabref.gui.AbstractViewModel; public class CopyFilesDialogViewModel extends AbstractViewModel { private final SimpleListProperty<CopyFilesResultItemViewModel> copyFilesResultItems = new SimpleListProperty<>( FXCollections.observableArrayList()); public CopyFilesDialogViewModel(CopyFilesResultListDependency results) { copyFilesResultItems.addAll(results.getResults()); } public SimpleListProperty<CopyFilesResultItemViewModel> copyFilesResultListProperty() { return this.copyFilesResultItems; } }
687
31.761905
115
java
null
jabref-main/src/main/java/org/jabref/gui/copyfiles/CopyFilesResultItemViewModel.java
package org.jabref.gui.copyfiles; import java.nio.file.Path; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import org.jabref.gui.icon.IconTheme; import org.jabref.gui.icon.JabRefIcon; public class CopyFilesResultItemViewModel { private final StringProperty file = new SimpleStringProperty(""); private final ObjectProperty<JabRefIcon> icon = new SimpleObjectProperty<>(IconTheme.JabRefIcons.WARNING); private final StringProperty message = new SimpleStringProperty(""); public CopyFilesResultItemViewModel(Path file, boolean success, String message) { this.file.setValue(file.toString()); this.message.setValue(message); if (success) { this.icon.setValue(IconTheme.JabRefIcons.CHECK); } } public StringProperty getFile() { return file; } public StringProperty getMessage() { return message; } public ObjectProperty<JabRefIcon> getIcon() { return icon; } @Override public String toString() { return "CopyFilesResultItemViewModel [file=" + file.get() + ", message=" + message.get() + "]"; } }
1,279
28.090909
110
java
null
jabref-main/src/main/java/org/jabref/gui/copyfiles/CopyFilesResultListDependency.java
package org.jabref.gui.copyfiles; import java.util.ArrayList; import java.util.List; /** * This class is a wrapper class for the containing list as it is currently not possible to inject complex object types into FXML controller */ public class CopyFilesResultListDependency { private List<CopyFilesResultItemViewModel> results = new ArrayList<>(); public CopyFilesResultListDependency() { // empty, workaround for injection into FXML controller } public CopyFilesResultListDependency(List<CopyFilesResultItemViewModel> results) { this.results = results; } public List<CopyFilesResultItemViewModel> getResults() { return results; } @Override public String toString() { return "CopyFilesResultListDependency [results=" + results + "]"; } }
820
26.366667
140
java
null
jabref-main/src/main/java/org/jabref/gui/copyfiles/CopyFilesTask.java
package org.jabref.gui.copyfiles; import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.function.BiFunction; import javafx.concurrent.Task; import org.jabref.logic.l10n.Localization; import org.jabref.logic.util.OS; import org.jabref.logic.util.io.FileUtil; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.LinkedFile; import org.jabref.model.util.OptionalUtil; import org.jabref.preferences.PreferencesService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CopyFilesTask extends Task<List<CopyFilesResultItemViewModel>> { private static final Logger LOGGER = LoggerFactory.getLogger(CopyFilesAction.class); private static final String LOGFILE_PREFIX = "copyFileslog_"; private static final String LOGFILE_EXT = ".log"; private final BibDatabaseContext databaseContext; private final PreferencesService preferencesService; private final Path exportPath; private final String localizedSuccessMessage = Localization.lang("Copied file successfully"); private final String localizedErrorMessage = Localization.lang("Could not copy file") + ": " + Localization.lang("File exists"); private final long totalFilesCount; private final List<BibEntry> entries; private final List<CopyFilesResultItemViewModel> results = new ArrayList<>(); private Optional<Path> newPath = Optional.empty(); private int numberSuccessful; private int totalFilesCounter; private final BiFunction<Path, Path, Path> resolvePathFilename = (path, file) -> path.resolve(file.getFileName()); public CopyFilesTask(BibDatabaseContext databaseContext, List<BibEntry> entries, Path path, PreferencesService preferencesService) { this.databaseContext = databaseContext; this.preferencesService = preferencesService; this.entries = entries; this.exportPath = path; totalFilesCount = entries.stream().mapToLong(entry -> entry.getFiles().size()).sum(); } @Override protected List<CopyFilesResultItemViewModel> call() throws InterruptedException, IOException { updateMessage(Localization.lang("Copying files...")); updateProgress(0, totalFilesCount); LocalDateTime currentTime = LocalDateTime.now(); String currentDate = currentTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss")); try (BufferedWriter bw = Files.newBufferedWriter(exportPath.resolve(LOGFILE_PREFIX + currentDate + LOGFILE_EXT), StandardCharsets.UTF_8)) { for (int i = 0; i < entries.size(); i++) { if (isCancelled()) { break; } List<LinkedFile> files = entries.get(i).getFiles(); for (int j = 0; j < files.size(); j++) { if (isCancelled()) { break; } updateMessage(Localization.lang("Copying file %0 of entry %1", Integer.toString(j + 1), Integer.toString(i + 1))); LinkedFile fileName = files.get(j); Optional<Path> fileToExport = fileName.findIn(databaseContext, preferencesService.getFilePreferences()); newPath = OptionalUtil.combine(Optional.of(exportPath), fileToExport, resolvePathFilename); if (newPath.isPresent()) { Path newFile = newPath.get(); boolean success = FileUtil.copyFile(fileToExport.get(), newFile, false); updateProgress(totalFilesCounter++, totalFilesCount); try { Thread.sleep(300); } catch (InterruptedException e) { if (isCancelled()) { updateMessage("Cancelled"); break; } } if (success) { updateMessage(localizedSuccessMessage); numberSuccessful++; writeLogMessage(newFile, bw, localizedSuccessMessage); addResultToList(newFile, success, localizedSuccessMessage); } else { updateMessage(localizedErrorMessage); writeLogMessage(newFile, bw, localizedErrorMessage); addResultToList(newFile, success, localizedErrorMessage); } } } } updateMessage(Localization.lang("Finished copying")); String successMessage = Localization.lang("Copied %0 files of %1 successfully to %2", Integer.toString(numberSuccessful), Integer.toString(totalFilesCounter), newPath.map(Path::getParent).map(Path::toString).orElse("")); updateMessage(successMessage); bw.write(successMessage); return results; } } private void writeLogMessage(Path newFile, BufferedWriter bw, String logMessage) { try { bw.write(logMessage + ": " + newFile); bw.write(OS.NEWLINE); } catch (IOException e) { LOGGER.error("error writing log file", e); } } private void addResultToList(Path newFile, boolean success, String logMessage) { CopyFilesResultItemViewModel result = new CopyFilesResultItemViewModel(newFile, success, logMessage); results.add(result); } }
5,915
42.182482
147
java
null
jabref-main/src/main/java/org/jabref/gui/copyfiles/CopySingleFileAction.java
package org.jabref.gui.copyfiles; import java.nio.file.Path; import java.util.Optional; import java.util.function.BiFunction; import javafx.beans.binding.Bindings; import org.jabref.gui.DialogService; import org.jabref.gui.actions.SimpleCommand; import org.jabref.gui.util.DirectoryDialogConfiguration; import org.jabref.logic.l10n.Localization; import org.jabref.logic.util.io.FileUtil; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.LinkedFile; import org.jabref.model.util.OptionalUtil; import org.jabref.preferences.FilePreferences; public class CopySingleFileAction extends SimpleCommand { private final LinkedFile linkedFile; private final DialogService dialogService; private final BibDatabaseContext databaseContext; private final FilePreferences filePreferences; private final BiFunction<Path, Path, Path> resolvePathFilename = (path, file) -> path.resolve(file.getFileName()); public CopySingleFileAction(LinkedFile linkedFile, DialogService dialogService, BibDatabaseContext databaseContext, FilePreferences filePreferences) { this.linkedFile = linkedFile; this.dialogService = dialogService; this.databaseContext = databaseContext; this.filePreferences = filePreferences; this.executable.bind(Bindings.createBooleanBinding( () -> !linkedFile.isOnlineLink() && linkedFile.findIn(databaseContext, this.filePreferences).isPresent(), linkedFile.linkProperty())); } @Override public void execute() { DirectoryDialogConfiguration dirDialogConfiguration = new DirectoryDialogConfiguration.Builder() .withInitialDirectory(filePreferences.getWorkingDirectory()) .build(); Optional<Path> exportPath = dialogService.showDirectorySelectionDialog(dirDialogConfiguration); exportPath.ifPresent(this::copyFileToDestination); } private void copyFileToDestination(Path exportPath) { Optional<Path> fileToExport = linkedFile.findIn(databaseContext, filePreferences); Optional<Path> newPath = OptionalUtil.combine(Optional.of(exportPath), fileToExport, resolvePathFilename); if (newPath.isPresent()) { Path newFile = newPath.get(); boolean success = fileToExport.isPresent() && FileUtil.copyFile(fileToExport.get(), newFile, false); if (success) { dialogService.showInformationDialogAndWait(Localization.lang("Copy linked file"), Localization.lang("Successfully copied file to %0.", newPath.map(Path::getParent).map(Path::toString).orElse(""))); } else { dialogService.showErrorDialogAndWait(Localization.lang("Copy linked file"), Localization.lang("Could not copy file to %0, maybe the file is already existing?", newPath.map(Path::getParent).map(Path::toString).orElse(""))); } } else { dialogService.showErrorDialogAndWait(Localization.lang("Could not resolve the file %0", fileToExport.map(Path::getParent).map(Path::toString).orElse(""))); } } }
3,135
46.515152
238
java
null
jabref-main/src/main/java/org/jabref/gui/desktop/JabRefDesktop.java
package org.jabref.gui.desktop; import java.io.IOException; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.Optional; import java.util.regex.Pattern; import org.jabref.gui.DialogService; import org.jabref.gui.Globals; import org.jabref.gui.desktop.os.NativeDesktop; import org.jabref.gui.externalfiletype.ExternalFileType; import org.jabref.gui.externalfiletype.ExternalFileTypes; import org.jabref.logic.importer.util.IdentifierParser; import org.jabref.logic.l10n.Localization; import org.jabref.logic.util.OS; import org.jabref.logic.util.io.FileUtil; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.identifier.DOI; import org.jabref.model.entry.identifier.Identifier; import org.jabref.preferences.PreferencesService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * See http://stackoverflow.com/questions/18004150/desktop-api-is-not-supported-on-the-current-platform for more implementation hints. * http://docs.oracle.com/javase/7/docs/api/java/awt/Desktop.html cannot be used as we don't want to rely on AWT */ public class JabRefDesktop { private static final Logger LOGGER = LoggerFactory.getLogger(JabRefDesktop.class); private static final NativeDesktop NATIVE_DESKTOP = OS.getNativeDesktop(); private static final Pattern REMOTE_LINK_PATTERN = Pattern.compile("[a-z]+://.*"); private JabRefDesktop() { } /** * Open a http/pdf/ps viewer for the given link string. * * Opening a PDF file at the file field is done at {@link org.jabref.gui.fieldeditors.LinkedFileViewModel#open} */ public static void openExternalViewer(BibDatabaseContext databaseContext, PreferencesService preferencesService, String initialLink, Field initialField, DialogService dialogService, BibEntry entry) throws IOException { String link = initialLink; Field field = initialField; if ((StandardField.PS == field) || (StandardField.PDF == field)) { // Find the default directory for this field type: List<Path> directories = databaseContext.getFileDirectories(preferencesService.getFilePreferences()); Optional<Path> file = FileUtil.find(link, directories); // Check that the file exists: if (file.isEmpty() || !Files.exists(file.get())) { throw new IOException("File not found (" + field + "): '" + link + "'."); } link = file.get().toAbsolutePath().toString(); // Use the correct viewer even if pdf and ps are mixed up: String[] split = file.get().getFileName().toString().split("\\."); if (split.length >= 2) { if ("pdf".equalsIgnoreCase(split[split.length - 1])) { field = StandardField.PDF; } else if ("ps".equalsIgnoreCase(split[split.length - 1]) || ((split.length >= 3) && "ps".equalsIgnoreCase(split[split.length - 2]))) { field = StandardField.PS; } } } else if (StandardField.DOI == field) { openDoi(link); return; } else if (StandardField.ISBN == field) { openIsbn(link); return; } else if (StandardField.EPRINT == field) { IdentifierParser identifierParser = new IdentifierParser(entry); link = identifierParser.parse(StandardField.EPRINT) .flatMap(Identifier::getExternalURI) .map(URI::toASCIIString) .orElse(link); if (Objects.equals(link, initialLink)) { Optional<String> eprintTypeOpt = entry.getField(StandardField.EPRINTTYPE); if (eprintTypeOpt.isEmpty()) { dialogService.showErrorDialogAndWait(Localization.lang("Unable to open linked eprint. Please set the eprinttype field")); } else { dialogService.showErrorDialogAndWait(Localization.lang("Unable to open linked eprint. Please verify that the eprint field has a valid '%0' id", eprintTypeOpt.get())); } } // should be opened in browser field = StandardField.URL; } if (StandardField.URL == field) { openBrowser(link); } else if (StandardField.PS == field) { try { NATIVE_DESKTOP.openFile(link, StandardField.PS.getName()); } catch (IOException e) { LOGGER.error("An error occurred on the command: " + link, e); } } else if (StandardField.PDF == field) { try { NATIVE_DESKTOP.openFile(link, StandardField.PDF.getName()); } catch (IOException e) { LOGGER.error("An error occurred on the command: " + link, e); } } else { LOGGER.info("Message: currently only PDF, PS and HTML files can be opened by double clicking"); } } private static void openDoi(String doi) throws IOException { String link = DOI.parse(doi).map(DOI::getURIAsASCIIString).orElse(doi); openBrowser(link); } public static void openCustomDoi(String link, PreferencesService preferences, DialogService dialogService) { DOI.parse(link) .flatMap(doi -> doi.getExternalURIWithCustomBase(preferences.getDOIPreferences().getDefaultBaseURI())) .ifPresent(uri -> { try { JabRefDesktop.openBrowser(uri); } catch (IOException e) { dialogService.showErrorDialogAndWait(Localization.lang("Unable to open link."), e); } }); } private static void openIsbn(String isbn) throws IOException { String link = "https://openlibrary.org/isbn/" + isbn; openBrowser(link); } /** * Open an external file, attempting to use the correct viewer for it. * * @param databaseContext The database this file belongs to. * @param link The filename. * @return false if the link couldn't be resolved, true otherwise. */ public static boolean openExternalFileAnyFormat(final BibDatabaseContext databaseContext, PreferencesService preferencesService, String link, final Optional<ExternalFileType> type) throws IOException { if (REMOTE_LINK_PATTERN.matcher(link.toLowerCase(Locale.ROOT)).matches()) { openExternalFilePlatformIndependent(type, link); return true; } Optional<Path> file = FileUtil.find(databaseContext, link, preferencesService.getFilePreferences()); if (file.isPresent() && Files.exists(file.get())) { // Open the file: String filePath = file.get().toString(); openExternalFilePlatformIndependent(type, filePath); return true; } // No file matched the name, try to open it directly using the given app openExternalFilePlatformIndependent(type, link); return true; } private static void openExternalFilePlatformIndependent(Optional<ExternalFileType> fileType, String filePath) throws IOException { if (fileType.isPresent()) { String application = fileType.get().getOpenWithApplication(); if (application.isEmpty()) { NATIVE_DESKTOP.openFile(filePath, fileType.get().getExtension()); } else { NATIVE_DESKTOP.openFileWithApplication(filePath, application); } } else { // File type is not given and therefore no application specified // Let the OS handle the opening of the file NATIVE_DESKTOP.openFile(filePath, ""); } } /** * Opens a file browser of the folder of the given file. If possible, the file is selected * * @param fileLink the location of the file * @throws IOException if the default file browser cannot be opened */ public static void openFolderAndSelectFile(Path fileLink, PreferencesService preferencesService, DialogService dialogService) throws IOException { if (fileLink == null) { return; } boolean useCustomFileBrowser = preferencesService.getExternalApplicationsPreferences().useCustomFileBrowser(); if (!useCustomFileBrowser) { NATIVE_DESKTOP.openFolderAndSelectFile(fileLink); return; } String absolutePath = fileLink.toAbsolutePath().getParent().toString(); String command = preferencesService.getExternalApplicationsPreferences().getCustomFileBrowserCommand(); if (command.isEmpty()) { LOGGER.info("No custom file browser command defined"); NATIVE_DESKTOP.openFolderAndSelectFile(fileLink); return; } executeCommand(command, absolutePath, dialogService); } /** * Opens a new console starting on the given file location * <p> * If no command is specified in {@link Globals}, the default system console will be executed. * * @param file Location the console should be opened at. * */ public static void openConsole(Path file, PreferencesService preferencesService, DialogService dialogService) throws IOException { if (file == null) { return; } String absolutePath = file.toAbsolutePath().getParent().toString(); boolean useCustomTerminal = preferencesService.getExternalApplicationsPreferences().useCustomTerminal(); if (!useCustomTerminal) { NATIVE_DESKTOP.openConsole(absolutePath, dialogService); return; } String command = preferencesService.getExternalApplicationsPreferences().getCustomTerminalCommand(); command = command.trim(); if (command.isEmpty()) { NATIVE_DESKTOP.openConsole(absolutePath, dialogService); LOGGER.info("Preference for custom terminal is empty. Using default terminal."); return; } executeCommand(command, absolutePath, dialogService); } private static void executeCommand(String command, String absolutePath, DialogService dialogService) { // normalize white spaces command = command.replaceAll("\\s+", " "); // replace the placeholder if used command = command.replace("%DIR", absolutePath); LOGGER.info("Executing command \"{}\"...", command); dialogService.notify(Localization.lang("Executing command \"%0\"...", command)); String[] subcommands = command.split(" "); try { new ProcessBuilder(subcommands).start(); } catch (IOException exception) { LOGGER.error("Error during command execution", exception); dialogService.notify(Localization.lang("Error occurred while executing the command \"%0\".", command)); } } /** * Opens the given URL using the system browser * * @param url the URL to open */ public static void openBrowser(String url) throws IOException { Optional<ExternalFileType> fileType = ExternalFileTypes.getExternalFileTypeByExt("html", Globals.prefs.getFilePreferences()); openExternalFilePlatformIndependent(fileType, url); } public static void openBrowser(URI url) throws IOException { openBrowser(url.toASCIIString()); } /** * Opens the url with the users standard Browser. If that fails a popup will be shown to instruct the user to open the link manually and the link gets copied to the clipboard * * @param url the URL to open */ public static void openBrowserShowPopup(String url, DialogService dialogService) { try { openBrowser(url); } catch (IOException exception) { Globals.getClipboardManager().setContent(url); LOGGER.error("Could not open browser", exception); String couldNotOpenBrowser = Localization.lang("Could not open browser."); String openManually = Localization.lang("Please open %0 manually.", url); String copiedToClipboard = Localization.lang("The link has been copied to the clipboard."); dialogService.notify(couldNotOpenBrowser); dialogService.showErrorDialogAndWait(couldNotOpenBrowser, couldNotOpenBrowser + "\n" + openManually + "\n" + copiedToClipboard); } } }
13,140
42.513245
186
java
null
jabref-main/src/main/java/org/jabref/gui/desktop/os/DefaultDesktop.java
package org.jabref.gui.desktop.os; import java.awt.Desktop; import java.io.File; import java.io.IOException; import java.nio.file.Path; import org.jabref.architecture.AllowedToUseAwt; import org.jabref.cli.Launcher; import org.jabref.gui.DialogService; import org.slf4j.LoggerFactory; /** * This class contains some default implementations (if OS is neither linux, windows or osx) file directories and file/application open handling methods <br> * We cannot use a static logger instance here in this class as the Logger first needs to be configured in the {@link Launcher#addLogToDisk} * The configuration of tinylog will become immutable as soon as the first log entry is issued. * https://tinylog.org/v2/configuration/ **/ @AllowedToUseAwt("Requires AWT to open a file") public class DefaultDesktop extends NativeDesktop { @Override public void openFile(String filePath, String fileType) throws IOException { Desktop.getDesktop().open(new File(filePath)); } @Override public void openFileWithApplication(String filePath, String application) throws IOException { Desktop.getDesktop().open(new File(filePath)); } @Override public void openFolderAndSelectFile(Path filePath) throws IOException { File file = filePath.toAbsolutePath().getParent().toFile(); Desktop.getDesktop().open(file); } @Override public void openConsole(String absolutePath, DialogService dialogService) throws IOException { LoggerFactory.getLogger(DefaultDesktop.class).error("This feature is not supported by your Operating System."); } @Override public String detectProgramPath(String programName, String directoryName) { return programName; } @Override public Path getApplicationDirectory() { return getUserDirectory(); } }
1,841
33.111111
157
java
null
jabref-main/src/main/java/org/jabref/gui/desktop/os/Linux.java
package org.jabref.gui.desktop.os; import java.awt.Desktop; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Locale; import java.util.Optional; import org.jabref.architecture.AllowedToUseAwt; import org.jabref.cli.Launcher; import org.jabref.gui.DialogService; import org.jabref.gui.Globals; import org.jabref.gui.JabRefExecutorService; import org.jabref.gui.externalfiletype.ExternalFileType; import org.jabref.gui.externalfiletype.ExternalFileTypes; import org.jabref.gui.util.StreamGobbler; import org.jabref.logic.l10n.Localization; import org.slf4j.LoggerFactory; /** * This class contains Linux specific implementations for file directories and file/application open handling methods <br> * We cannot use a static logger instance here in this class as the Logger first needs to be configured in the {@link Launcher#addLogToDisk} * The configuration of tinylog will become immutable as soon as the first log entry is issued. * https://tinylog.org/v2/configuration/ **/ @AllowedToUseAwt("Requires AWT to open a file with the native method") public class Linux extends NativeDesktop { private static final String ETC_ALTERNATIVES_X_TERMINAL_EMULATOR = "/etc/alternatives/x-terminal-emulator"; private void nativeOpenFile(String filePath) { JabRefExecutorService.INSTANCE.execute(() -> { try { File file = new File(filePath); Desktop.getDesktop().open(file); LoggerFactory.getLogger(Linux.class).debug("Open file in default application with Desktop integration"); } catch (IllegalArgumentException e) { LoggerFactory.getLogger(Linux.class).debug("Fail back to xdg-open"); try { String[] cmd = {"xdg-open", filePath}; Runtime.getRuntime().exec(cmd); } catch (Exception e2) { LoggerFactory.getLogger(Linux.class).warn("Open operation not successful: ", e2); } } catch (IOException e) { LoggerFactory.getLogger(Linux.class).warn("Native open operation not successful: ", e); } }); } @Override public void openFile(String filePath, String fileType) throws IOException { Optional<ExternalFileType> type = ExternalFileTypes.getExternalFileTypeByExt(fileType, Globals.prefs.getFilePreferences()); String viewer; if (type.isPresent() && !type.get().getOpenWithApplication().isEmpty()) { viewer = type.get().getOpenWithApplication(); ProcessBuilder processBuilder = new ProcessBuilder(viewer, filePath); Process process = processBuilder.start(); StreamGobbler streamGobblerInput = new StreamGobbler(process.getInputStream(), LoggerFactory.getLogger(Linux.class)::debug); StreamGobbler streamGobblerError = new StreamGobbler(process.getErrorStream(), LoggerFactory.getLogger(Linux.class)::debug); JabRefExecutorService.INSTANCE.execute(streamGobblerInput); JabRefExecutorService.INSTANCE.execute(streamGobblerError); } else { nativeOpenFile(filePath); } } @Override public void openFileWithApplication(String filePath, String application) throws IOException { // Use the given app if specified, and the universal "xdg-open" otherwise: String[] openWith; if ((application != null) && !application.isEmpty()) { openWith = application.split(" "); String[] cmdArray = new String[openWith.length + 1]; System.arraycopy(openWith, 0, cmdArray, 0, openWith.length); cmdArray[cmdArray.length - 1] = filePath; ProcessBuilder processBuilder = new ProcessBuilder(cmdArray); Process process = processBuilder.start(); StreamGobbler streamGobblerInput = new StreamGobbler(process.getInputStream(), LoggerFactory.getLogger(Linux.class)::debug); StreamGobbler streamGobblerError = new StreamGobbler(process.getErrorStream(), LoggerFactory.getLogger(Linux.class)::debug); JabRefExecutorService.INSTANCE.execute(streamGobblerInput); JabRefExecutorService.INSTANCE.execute(streamGobblerError); } else { nativeOpenFile(filePath); } } @Override public void openFolderAndSelectFile(Path filePath) throws IOException { String desktopSession = System.getenv("DESKTOP_SESSION"); String absoluteFilePath = filePath.toAbsolutePath().toString(); String[] cmd = {"xdg-open", filePath.getParent().toString()}; // default is the folder of the file if (desktopSession != null) { desktopSession = desktopSession.toLowerCase(Locale.ROOT); if (desktopSession.contains("gnome")) { cmd = new String[] {"nautilus", "--select", absoluteFilePath}; } else if (desktopSession.contains("kde") || desktopSession.contains("plasma")) { cmd = new String[] {"dolphin", "--select", absoluteFilePath}; } else if (desktopSession.contains("mate")) { cmd = new String[] {"caja", "--select", absoluteFilePath}; } else if (desktopSession.contains("cinnamon")) { cmd = new String[] {"nemo", absoluteFilePath}; // Although nemo is based on nautilus it does not support --select, it directly highlights the file } else if (desktopSession.contains("xfce")) { cmd = new String[] {"thunar", absoluteFilePath}; } } LoggerFactory.getLogger(Linux.class).debug("Opening folder and selecting file using {}", String.join(" ", cmd)); ProcessBuilder processBuilder = new ProcessBuilder(cmd); Process process = processBuilder.start(); StreamGobbler streamGobblerInput = new StreamGobbler(process.getInputStream(), LoggerFactory.getLogger(Linux.class)::debug); StreamGobbler streamGobblerError = new StreamGobbler(process.getErrorStream(), LoggerFactory.getLogger(Linux.class)::debug); JabRefExecutorService.INSTANCE.execute(streamGobblerInput); JabRefExecutorService.INSTANCE.execute(streamGobblerError); } @Override public void openConsole(String absolutePath, DialogService dialogService) throws IOException { if (!Files.exists(Path.of(ETC_ALTERNATIVES_X_TERMINAL_EMULATOR))) { dialogService.showErrorDialogAndWait(Localization.lang("Could not detect terminal automatically using '%0'. Please define a custom terminal in the preferences.", ETC_ALTERNATIVES_X_TERMINAL_EMULATOR)); return; } ProcessBuilder processBuilder = new ProcessBuilder("readlink", ETC_ALTERNATIVES_X_TERMINAL_EMULATOR); Process process = processBuilder.start(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { String emulatorName = reader.readLine(); if (emulatorName != null) { emulatorName = emulatorName.substring(emulatorName.lastIndexOf(File.separator) + 1); String[] cmd; if (emulatorName.contains("gnome")) { cmd = new String[] {"gnome-terminal", "--working-directory", absolutePath}; } else if (emulatorName.contains("xfce4")) { // xfce4-terminal requires "--working-directory=<directory>" format (one arg) cmd = new String[] {"xfce4-terminal", "--working-directory=" + absolutePath}; } else if (emulatorName.contains("konsole")) { cmd = new String[] {"konsole", "--workdir", absolutePath}; } else { cmd = new String[] {emulatorName, absolutePath}; } LoggerFactory.getLogger(Linux.class).debug("Opening terminal using {}", String.join(" ", cmd)); ProcessBuilder builder = new ProcessBuilder(cmd); builder.directory(new File(absolutePath)); Process processTerminal = builder.start(); StreamGobbler streamGobblerInput = new StreamGobbler(processTerminal.getInputStream(), LoggerFactory.getLogger(Linux.class)::debug); StreamGobbler streamGobblerError = new StreamGobbler(processTerminal.getErrorStream(), LoggerFactory.getLogger(Linux.class)::debug); JabRefExecutorService.INSTANCE.execute(streamGobblerInput); JabRefExecutorService.INSTANCE.execute(streamGobblerError); } } } @Override public String detectProgramPath(String programName, String directoryName) { return programName; } @Override public Path getApplicationDirectory() { return Path.of("/usr/lib/"); } @Override public Path getDefaultFileChooserDirectory() { String xdgDocumentsDir = System.getenv("XDG_DOCUMENTS_DIR"); if (xdgDocumentsDir != null) { return Path.of(xdgDocumentsDir); } // Make use of xdg-user-dirs // See https://www.freedesktop.org/wiki/Software/xdg-user-dirs/ for details try { Process process = new ProcessBuilder("xdg-user-dir", "DOCUMENTS").start(); // Package name with 's', command without List<String> strings = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8)) .lines().toList(); if (strings.isEmpty()) { LoggerFactory.getLogger(Linux.class).error("xdg-user-dir returned nothing"); return getUserDirectory(); } String documentsDirectory = strings.get(0); Path documentsPath = Path.of(documentsDirectory); if (!Files.exists(documentsPath)) { LoggerFactory.getLogger(Linux.class).error("xdg-user-dir returned non-existant directory {}", documentsDirectory); return getUserDirectory(); } LoggerFactory.getLogger(Linux.class).debug("Got documents path {}", documentsPath); return documentsPath; } catch (IOException e) { LoggerFactory.getLogger(Linux.class).error("Error while executing xdg-user-dir", e); } // Fallback return getUserDirectory(); } }
10,559
47.440367
213
java
null
jabref-main/src/main/java/org/jabref/gui/desktop/os/NativeDesktop.java
package org.jabref.gui.desktop.os; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.file.Files; import java.nio.file.Path; import org.jabref.cli.Launcher; import org.jabref.gui.DialogService; import org.jabref.logic.util.BuildInfo; import org.jabref.logic.util.OS; import org.jabref.model.pdf.search.SearchFieldConstants; import org.jabref.model.strings.StringUtil; import net.harawata.appdirs.AppDirsFactory; import org.slf4j.LoggerFactory; /** * This class contains bundles OS specific implementations for file directories and file/application open handling methods. * In case the default does not work, subclasses provide the correct behavior. * * <p> * We cannot use a static logger instance here in this class as the Logger first needs to be configured in the {@link Launcher#addLogToDisk} * The configuration of tinylog will become immutable as soon as the first log entry is issued. * https://tinylog.org/v2/configuration/ * </p> */ public abstract class NativeDesktop { public abstract void openFile(String filePath, String fileType) throws IOException; /** * Opens a file on an Operating System, using the given application. * * @param filePath The filename. * @param application Link to the app that opens the file. */ public abstract void openFileWithApplication(String filePath, String application) throws IOException; public abstract void openFolderAndSelectFile(Path file) throws IOException; public abstract void openConsole(String absolutePath, DialogService dialogService) throws IOException; public abstract String detectProgramPath(String programName, String directoryName); /** * Returns the path to the system's applications folder. * * @return the path to the applications folder. */ public abstract Path getApplicationDirectory(); /** * Get the user's default file chooser directory * * @return The path to the directory */ public Path getDefaultFileChooserDirectory() { Path userDirectory = getUserDirectory(); Path documents = userDirectory.resolve("Documents"); if (!Files.exists(documents)) { return userDirectory; } return documents; } /** * Returns the path to the system's user directory. * * @return the path to the user directory. */ public Path getUserDirectory() { return Path.of(System.getProperty("user.home")); } public Path getLogDirectory() { return Path.of(AppDirsFactory.getInstance() .getUserDataDir( OS.APP_DIR_APP_NAME, "logs", OS.APP_DIR_APP_AUTHOR)) .resolve(new BuildInfo().version.toString()); } public Path getBackupDirectory() { return Path.of(AppDirsFactory.getInstance() .getUserDataDir( OS.APP_DIR_APP_NAME, "backups", OS.APP_DIR_APP_AUTHOR)); } public Path getFulltextIndexBaseDirectory() { return Path.of(AppDirsFactory.getInstance() .getUserDataDir(OS.APP_DIR_APP_NAME, "lucene" + File.separator + SearchFieldConstants.VERSION, OS.APP_DIR_APP_AUTHOR)); } public Path getSslDirectory() { return Path.of(AppDirsFactory.getInstance() .getUserDataDir(OS.APP_DIR_APP_NAME, "ssl", OS.APP_DIR_APP_AUTHOR)); } public String getHostName() { String hostName; // Following code inspired by https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/SystemUtils.html#getHostName-- // See also https://stackoverflow.com/a/20793241/873282 hostName = System.getenv("HOSTNAME"); if (StringUtil.isBlank(hostName)) { hostName = System.getenv("COMPUTERNAME"); } if (StringUtil.isBlank(hostName)) { try { hostName = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { LoggerFactory.getLogger(OS.class).info("Hostname not found. Using \"localhost\" as fallback.", e); hostName = "localhost"; } } return hostName; } }
4,775
36.3125
148
java
null
jabref-main/src/main/java/org/jabref/gui/desktop/os/OSX.java
package org.jabref.gui.desktop.os; import java.io.IOException; import java.nio.file.Path; import java.util.Optional; import org.jabref.architecture.AllowedToUseAwt; import org.jabref.cli.Launcher; import org.jabref.gui.DialogService; import org.jabref.gui.Globals; import org.jabref.gui.externalfiletype.ExternalFileType; import org.jabref.gui.externalfiletype.ExternalFileTypes; /** * This class contains macOS (OSX) specific implementations for file directories and file/application open handling methods <br> * We cannot use a static logger instance here in this class as the Logger first needs to be configured in the {@link Launcher#addLogToDisk} * The configuration of tinylog will become immutable as soon as the first log entry is issued. * https://tinylog.org/v2/configuration/ **/ @AllowedToUseAwt("Requires AWT to open a file") public class OSX extends NativeDesktop { @Override public void openFile(String filePath, String fileType) throws IOException { Optional<ExternalFileType> type = ExternalFileTypes.getExternalFileTypeByExt(fileType, Globals.prefs.getFilePreferences()); if (type.isPresent() && !type.get().getOpenWithApplication().isEmpty()) { openFileWithApplication(filePath, type.get().getOpenWithApplication()); } else { String[] cmd = {"/usr/bin/open", filePath}; Runtime.getRuntime().exec(cmd); } } @Override public void openFileWithApplication(String filePath, String application) throws IOException { // Use "-a <application>" if the app is specified, and just "open <filename>" otherwise: String[] cmd = (application != null) && !application.isEmpty() ? new String[] {"/usr/bin/open", "-a", application, filePath} : new String[] {"/usr/bin/open", filePath}; new ProcessBuilder(cmd).start(); } @Override public void openFolderAndSelectFile(Path file) throws IOException { String[] cmd = {"/usr/bin/open", "-R", file.toString()}; Runtime.getRuntime().exec(cmd); } @Override public void openConsole(String absolutePath, DialogService dialogService) throws IOException { new ProcessBuilder("open", "-a", "Terminal", absolutePath).start(); } @Override public String detectProgramPath(String programName, String directoryName) { return programName; } @Override public Path getApplicationDirectory() { return Path.of("/Applications"); } }
2,496
38.634921
140
java
null
jabref-main/src/main/java/org/jabref/gui/desktop/os/Windows.java
package org.jabref.gui.desktop.os; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Optional; import org.jabref.cli.Launcher; import org.jabref.gui.DialogService; import org.jabref.gui.Globals; import org.jabref.gui.externalfiletype.ExternalFileType; import org.jabref.gui.externalfiletype.ExternalFileTypes; import com.sun.jna.platform.win32.KnownFolders; import com.sun.jna.platform.win32.Shell32Util; import com.sun.jna.platform.win32.ShlObj; import com.sun.jna.platform.win32.Win32Exception; import org.slf4j.LoggerFactory; /** * This class contains Windows specific implementations for file directories and file/application open handling methods <br> * We cannot use a static logger instance here in this class as the Logger first needs to be configured in the {@link Launcher#addLogToDisk} * The configuration of tinylog will become immutable as soon as the first log entry is issued. * https://tinylog.org/v2/configuration/ **/ public class Windows extends NativeDesktop { private static final String DEFAULT_EXECUTABLE_EXTENSION = ".exe"; @Override public void openFile(String filePath, String fileType) throws IOException { Optional<ExternalFileType> type = ExternalFileTypes.getExternalFileTypeByExt(fileType, Globals.prefs.getFilePreferences()); if (type.isPresent() && !type.get().getOpenWithApplication().isEmpty()) { openFileWithApplication(filePath, type.get().getOpenWithApplication()); } else { // quote String so explorer handles URL query strings correctly String quotePath = "\"" + filePath + "\""; new ProcessBuilder("explorer.exe", quotePath).start(); } } @Override public String detectProgramPath(String programName, String directoryName) { String progFiles = System.getenv("ProgramFiles(x86)"); String programPath; if (progFiles != null) { programPath = getProgramPath(programName, directoryName, progFiles); if (programPath != null) { return programPath; } } progFiles = System.getenv("ProgramFiles"); programPath = getProgramPath(programName, directoryName, progFiles); if (programPath != null) { return programPath; } return ""; } private String getProgramPath(String programName, String directoryName, String progFiles) { Path programPath; if ((directoryName != null) && !directoryName.isEmpty()) { programPath = Path.of(progFiles, directoryName, programName + DEFAULT_EXECUTABLE_EXTENSION); } else { programPath = Path.of(progFiles, programName + DEFAULT_EXECUTABLE_EXTENSION); } if (Files.exists(programPath)) { return programPath.toString(); } return null; } @Override public Path getApplicationDirectory() { String programDir = System.getenv("ProgramFiles"); if (programDir != null) { return Path.of(programDir); } return getUserDirectory(); } @Override public Path getDefaultFileChooserDirectory() { try { try { return Path.of(Shell32Util.getKnownFolderPath(KnownFolders.FOLDERID_Documents)); } catch (UnsatisfiedLinkError e) { // Windows Vista or earlier return Path.of(Shell32Util.getFolderPath(ShlObj.CSIDL_MYDOCUMENTS)); } } catch (Win32Exception e) { // needs to be non-static because of org.jabref.cli.Launcher.addLogToDisk LoggerFactory.getLogger(Windows.class).error("Error accessing folder", e); return Path.of(System.getProperty("user.home")); } } @Override public void openFileWithApplication(String filePath, String application) throws IOException { new ProcessBuilder(Path.of(application).toString(), Path.of(filePath).toString()).start(); } @Override public void openFolderAndSelectFile(Path filePath) throws IOException { new ProcessBuilder("explorer.exe", "/select,", filePath.toString()).start(); } @Override public void openConsole(String absolutePath, DialogService dialogService) throws IOException { ProcessBuilder process = new ProcessBuilder("cmd.exe", "/c", "start"); process.directory(new File(absolutePath)); process.start(); } }
4,515
36.633333
140
java
null
jabref-main/src/main/java/org/jabref/gui/dialogs/AutosaveUiManager.java
package org.jabref.gui.dialogs; import org.jabref.gui.Globals; import org.jabref.gui.LibraryTab; import org.jabref.gui.exporter.SaveDatabaseAction; import org.jabref.model.database.event.AutosaveEvent; import com.google.common.eventbus.Subscribe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class has an abstract UI role as it listens for an {@link AutosaveEvent} and saves the bib file associated with * the given {@link LibraryTab}. */ public class AutosaveUiManager { private static final Logger LOGGER = LoggerFactory.getLogger(AutosaveUiManager.class); private SaveDatabaseAction saveDatabaseAction; public AutosaveUiManager(LibraryTab libraryTab) { this.saveDatabaseAction = new SaveDatabaseAction(libraryTab, Globals.prefs, Globals.entryTypesManager); } @Subscribe public void listen(AutosaveEvent event) { try { this.saveDatabaseAction.save(SaveDatabaseAction.SaveDatabaseMode.SILENT); } catch (Throwable e) { LOGGER.error("Problem occurred while saving.", e); } } }
1,092
31.147059
119
java
null
jabref-main/src/main/java/org/jabref/gui/dialogs/BackupUIManager.java
package org.jabref.gui.dialogs; import java.io.IOException; import java.nio.file.Path; import java.util.List; import java.util.Optional; import javafx.scene.control.ButtonType; import org.jabref.gui.DialogService; import org.jabref.gui.backup.BackupResolverDialog; import org.jabref.gui.collab.DatabaseChange; import org.jabref.gui.collab.DatabaseChangeList; import org.jabref.gui.collab.DatabaseChangeResolverFactory; import org.jabref.gui.collab.DatabaseChangesResolverDialog; import org.jabref.gui.util.DefaultTaskExecutor; import org.jabref.logic.autosaveandbackup.BackupManager; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.OpenDatabase; import org.jabref.logic.importer.ParserResult; import org.jabref.logic.util.BackupFileType; import org.jabref.logic.util.io.BackupFileUtil; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.util.DummyFileUpdateMonitor; import org.jabref.model.util.FileUpdateMonitor; import org.jabref.preferences.PreferencesService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Stores all user dialogs related to {@link BackupManager}. */ public class BackupUIManager { private static final Logger LOGGER = LoggerFactory.getLogger(BackupUIManager.class); private BackupUIManager() { } public static Optional<ParserResult> showRestoreBackupDialog(DialogService dialogService, Path originalPath, PreferencesService preferencesService, FileUpdateMonitor fileUpdateMonitor) { var actionOpt = showBackupResolverDialog(dialogService, originalPath, preferencesService.getFilePreferences().getBackupDirectory()); return actionOpt.flatMap(action -> { if (action == BackupResolverDialog.RESTORE_FROM_BACKUP) { BackupManager.restoreBackup(originalPath, preferencesService.getFilePreferences().getBackupDirectory()); return Optional.empty(); } else if (action == BackupResolverDialog.REVIEW_BACKUP) { return showReviewBackupDialog(dialogService, originalPath, preferencesService, fileUpdateMonitor); } return Optional.empty(); }); } private static Optional<ButtonType> showBackupResolverDialog(DialogService dialogService, Path originalPath, Path backupDir) { return DefaultTaskExecutor.runInJavaFXThread(() -> dialogService.showCustomDialogAndWait(new BackupResolverDialog(originalPath, backupDir))); } private static Optional<ParserResult> showReviewBackupDialog( DialogService dialogService, Path originalPath, PreferencesService preferencesService, FileUpdateMonitor fileUpdateMonitor) { try { ImportFormatPreferences importFormatPreferences = preferencesService.getImportFormatPreferences(); // The database of the originalParserResult will be modified ParserResult originalParserResult = OpenDatabase.loadDatabase(originalPath, importFormatPreferences, fileUpdateMonitor); // This will be modified by using the `DatabaseChangesResolverDialog`. BibDatabaseContext originalDatabase = originalParserResult.getDatabaseContext(); Path backupPath = BackupFileUtil.getPathOfLatestExistingBackupFile(originalPath, BackupFileType.BACKUP, preferencesService.getFilePreferences().getBackupDirectory()).orElseThrow(); BibDatabaseContext backupDatabase = OpenDatabase.loadDatabase(backupPath, importFormatPreferences, new DummyFileUpdateMonitor()).getDatabaseContext(); DatabaseChangeResolverFactory changeResolverFactory = new DatabaseChangeResolverFactory(dialogService, originalDatabase, preferencesService.getBibEntryPreferences()); return DefaultTaskExecutor.runInJavaFXThread(() -> { List<DatabaseChange> changes = DatabaseChangeList.compareAndGetChanges(originalDatabase, backupDatabase, changeResolverFactory); DatabaseChangesResolverDialog reviewBackupDialog = new DatabaseChangesResolverDialog( changes, originalDatabase, "Review Backup" ); var allChangesResolved = dialogService.showCustomDialogAndWait(reviewBackupDialog); if (allChangesResolved.isEmpty() || !allChangesResolved.get()) { // In case not all changes are resolved, start from scratch return showRestoreBackupDialog(dialogService, originalPath, preferencesService, fileUpdateMonitor); } // This does NOT return the original ParserResult, but a modified version with all changes accepted or rejected return Optional.of(originalParserResult); }); } catch (IOException e) { LOGGER.error("Error while loading backup or current database", e); return Optional.empty(); } } }
5,150
51.030303
192
java
null
jabref-main/src/main/java/org/jabref/gui/documentviewer/DocumentPageViewModel.java
package org.jabref.gui.documentviewer; import javafx.scene.image.Image; /** * Represents the view model for a page in the document viewer. */ public abstract class DocumentPageViewModel { /** * Renders this page and returns an image representation of itself. */ public abstract Image render(int width, int height); /** * Get the page number of the current page in the document. */ public abstract int getPageNumber(); /** * Calculates the aspect ratio (width / height) of the page. */ public abstract double getAspectRatio(); }
589
22.6
71
java
null
jabref-main/src/main/java/org/jabref/gui/documentviewer/DocumentViewModel.java
package org.jabref.gui.documentviewer; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.collections.ObservableList; public abstract class DocumentViewModel { private IntegerProperty maxPages = new SimpleIntegerProperty(); public abstract ObservableList<DocumentPageViewModel> getPages(); public int getMaxPages() { return maxPages.get(); } public IntegerProperty maxPagesProperty() { return maxPages; } }
513
24.7
69
java
null
jabref-main/src/main/java/org/jabref/gui/documentviewer/DocumentViewerControl.java
package org.jabref.gui.documentviewer; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Optional; import javafx.animation.FadeTransition; import javafx.beans.property.DoubleProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.scene.control.ProgressIndicator; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.StackPane; import javafx.scene.shape.Rectangle; import javafx.util.Duration; import org.jabref.gui.util.BackgroundTask; import org.jabref.gui.util.TaskExecutor; import com.tobiasdiez.easybind.EasyBind; import org.fxmisc.flowless.Cell; import org.fxmisc.flowless.VirtualFlow; import org.fxmisc.flowless.VirtualFlowHit; public class DocumentViewerControl extends StackPane { private final TaskExecutor taskExecutor; private final ObjectProperty<Integer> currentPage = new SimpleObjectProperty<>(1); private final DoubleProperty scrollY = new SimpleDoubleProperty(); private final DoubleProperty scrollYMax = new SimpleDoubleProperty(); private VirtualFlow<DocumentPageViewModel, DocumentViewerPage> flow; private PageDimension desiredPageDimension = PageDimension.ofFixedWidth(600); public DocumentViewerControl(TaskExecutor taskExecutor) { this.taskExecutor = Objects.requireNonNull(taskExecutor); this.getStyleClass().add("document-viewer"); // External changes to currentPage should result in scrolling to this page EasyBind.subscribe(currentPage, this::showPage); } public DoubleProperty scrollYMaxProperty() { return scrollYMax; } public DoubleProperty scrollYProperty() { return scrollY; } public int getCurrentPage() { return currentPage.get(); } public ObjectProperty<Integer> currentPageProperty() { return currentPage; } private void showPage(int pageNumber) { if (flow != null) { flow.show(pageNumber - 1); } } public void show(DocumentViewModel document) { flow = VirtualFlow.createVertical(document.getPages(), DocumentViewerPage::new); getChildren().setAll(flow); flow.visibleCells().addListener((ListChangeListener<? super DocumentViewerPage>) c -> updateCurrentPage(flow.visibleCells())); // (Bidirectional) binding does not work, so use listeners instead flow.estimatedScrollYProperty().addListener((observable, oldValue, newValue) -> scrollY.setValue(newValue)); scrollY.addListener((observable, oldValue, newValue) -> flow.estimatedScrollYProperty().setValue((double) newValue)); flow.totalLengthEstimateProperty().addListener((observable, oldValue, newValue) -> scrollYMax.setValue(newValue)); } private void updateCurrentPage(ObservableList<DocumentViewerPage> visiblePages) { if (flow == null) { return; } // We try to find the page that is displayed in the center of the viewport Optional<DocumentViewerPage> inMiddleOfViewport = Optional.empty(); try { VirtualFlowHit<DocumentViewerPage> hit = flow.hit(0, flow.getHeight() / 2); if (hit.isCellHit()) { // Successful hit inMiddleOfViewport = Optional.of(hit.getCell()); } } catch (NoSuchElementException exception) { // Sometimes throws exception if no page is found -> ignore } if (inMiddleOfViewport.isPresent()) { // Successful hit currentPage.set(inMiddleOfViewport.get().getPageNumber()); } else { // Heuristic missed, so try to get page number from first shown page currentPage.set( visiblePages.stream().findFirst().map(DocumentViewerPage::getPageNumber).orElse(1)); } } public void setPageWidth(double width) { desiredPageDimension = PageDimension.ofFixedWidth(width); updateSizeOfDisplayedPages(); } public void setPageHeight(double height) { desiredPageDimension = PageDimension.ofFixedHeight(height); updateSizeOfDisplayedPages(); } private void updateSizeOfDisplayedPages() { if (flow != null) { for (DocumentViewerPage page : flow.visibleCells()) { page.updateSize(); } flow.requestLayout(); } } public void changePageWidth(int delta) { // Assuming the current page is A4 (or has same aspect ratio) setPageWidth(desiredPageDimension.getWidth(Math.sqrt(2)) + delta); } /** * Represents the viewport for a page. Note: the instances of {@link DocumentViewerPage} are reused, i.e., not every * page is rendered in a new instance but instead {@link DocumentViewerPage#updateItem(Object)} is called. */ private class DocumentViewerPage implements Cell<DocumentPageViewModel, StackPane> { private final ImageView imageView; private final StackPane imageHolder; private final Rectangle background; private DocumentPageViewModel page; public DocumentViewerPage(DocumentPageViewModel initialPage) { page = initialPage; imageView = new ImageView(); imageHolder = new StackPane(); imageHolder.getStyleClass().add("page"); // Show progress indicator ProgressIndicator progress = new ProgressIndicator(); progress.setMaxSize(50, 50); // Set empty background and create proper rendering in background (for smoother loading) background = new Rectangle(getDesiredWidth(), getDesiredHeight()); background.setStyle("-fx-fill: WHITE"); // imageView.setImage(new WritableImage(getDesiredWidth(), getDesiredHeight())); BackgroundTask<Image> generateImage = BackgroundTask .wrap(() -> renderPage(initialPage)) .onSuccess(image -> { imageView.setImage(image); progress.setVisible(false); background.setVisible(false); }); taskExecutor.execute(generateImage); imageHolder.getChildren().setAll(background, progress, imageView); } private int getDesiredHeight() { return desiredPageDimension.getHeight(page.getAspectRatio()); } private int getDesiredWidth() { return desiredPageDimension.getWidth(page.getAspectRatio()); } @Override public StackPane getNode() { return imageHolder; } @Override public boolean isReusable() { return true; } @Override public void updateItem(DocumentPageViewModel page) { this.page = page; // First hide old page and show background instead (recalculate size of background to make sure its correct) background.setWidth(getDesiredWidth()); background.setHeight(getDesiredHeight()); background.setVisible(true); imageView.setOpacity(0); BackgroundTask<Image> generateImage = BackgroundTask .wrap(() -> renderPage(page)) .onSuccess(image -> { imageView.setImage(image); // Fade new page in for smoother transition FadeTransition fadeIn = new FadeTransition(Duration.millis(100), imageView); fadeIn.setFromValue(0); fadeIn.setToValue(1); fadeIn.play(); }); taskExecutor.execute(generateImage); } private Image renderPage(DocumentPageViewModel page) { return page.render(getDesiredWidth(), getDesiredHeight()); } public int getPageNumber() { return page.getPageNumber(); } public void updateSize() { background.setWidth(getDesiredWidth()); background.setHeight(getDesiredWidth()); updateItem(page); imageHolder.requestLayout(); } } }
8,427
35.803493
134
java
null
jabref-main/src/main/java/org/jabref/gui/documentviewer/DocumentViewerView.java
package org.jabref.gui.documentviewer; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.ButtonBar; import javafx.scene.control.ButtonType; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.ScrollBar; import javafx.scene.control.TextField; import javafx.scene.control.ToggleButton; import javafx.scene.layout.BorderPane; import javafx.stage.Modality; import org.jabref.gui.StateManager; import org.jabref.gui.util.BaseDialog; import org.jabref.gui.util.OnlyIntegerFormatter; import org.jabref.gui.util.TaskExecutor; import org.jabref.gui.util.ViewModelListCellFactory; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.LinkedFile; import org.jabref.preferences.PreferencesService; import com.airhacks.afterburner.views.ViewLoader; import jakarta.inject.Inject; public class DocumentViewerView extends BaseDialog<Void> { @FXML private ScrollBar scrollBar; @FXML private ComboBox<LinkedFile> fileChoice; @FXML private BorderPane mainPane; @FXML private ToggleButton modeLive; @FXML private ToggleButton modeLock; @FXML private TextField currentPage; @FXML private Label maxPages; @Inject private StateManager stateManager; @Inject private TaskExecutor taskExecutor; @Inject private PreferencesService preferencesService; private DocumentViewerControl viewer; private DocumentViewerViewModel viewModel; public DocumentViewerView() { this.setTitle(Localization.lang("Document viewer")); this.initModality(Modality.NONE); ViewLoader.view(this) .load() .setAsContent(this.getDialogPane()); // Remove button bar at bottom, but add close button to keep the dialog closable by clicking the "x" window symbol getDialogPane().getButtonTypes().add(ButtonType.CLOSE); getDialogPane().getChildren().removeIf(ButtonBar.class::isInstance); } @FXML private void initialize() { viewModel = new DocumentViewerViewModel(stateManager, preferencesService); setupViewer(); setupScrollbar(); setupFileChoice(); setupPageControls(); setupModeButtons(); } private void setupModeButtons() { viewModel.liveModeProperty().bind(modeLive.selectedProperty()); modeLock.selectedProperty().bind(modeLive.selectedProperty().not()); } private void setupScrollbar() { scrollBar.valueProperty().bindBidirectional(viewer.scrollYProperty()); scrollBar.maxProperty().bind(viewer.scrollYMaxProperty()); } private void setupPageControls() { OnlyIntegerFormatter integerFormatter = new OnlyIntegerFormatter(1); viewModel.currentPageProperty().bindBidirectional(integerFormatter.valueProperty()); currentPage.setTextFormatter(integerFormatter); maxPages.textProperty().bind(viewModel.maxPagesProperty().asString()); } private void setupFileChoice() { ViewModelListCellFactory<LinkedFile> cellFactory = new ViewModelListCellFactory<LinkedFile>() .withText(LinkedFile::getLink); fileChoice.setButtonCell(cellFactory.call(null)); fileChoice.setCellFactory(cellFactory); fileChoice.getSelectionModel().selectedItemProperty().addListener( (observable, oldValue, newValue) -> viewModel.switchToFile(newValue)); // We always want that the first item is selected after a change // This also automatically selects the first file on the initial load fileChoice.itemsProperty().addListener( (observable, oldValue, newValue) -> fileChoice.getSelectionModel().selectFirst()); fileChoice.itemsProperty().bind(viewModel.filesProperty()); } private void setupViewer() { viewer = new DocumentViewerControl(taskExecutor); viewModel.currentDocumentProperty().addListener((observable, oldDocument, newDocument) -> { if (newDocument != null) { viewer.show(newDocument); } }); viewModel.currentPageProperty().bindBidirectional(viewer.currentPageProperty()); mainPane.setCenter(viewer); } public void setLiveMode(boolean liveMode) { modeLive.setSelected(liveMode); } public void gotoPage(int pageNumber) { viewModel.showPage(pageNumber); } public void nextPage(ActionEvent actionEvent) { viewModel.showNextPage(); } public void previousPage(ActionEvent actionEvent) { viewModel.showPreviousPage(); } public void fitWidth(ActionEvent actionEvent) { viewer.setPageWidth(viewer.getWidth()); } public void zoomIn(ActionEvent actionEvent) { viewer.changePageWidth(100); } public void zoomOut(ActionEvent actionEvent) { viewer.changePageWidth(-100); } public void fitSinglePage(ActionEvent actionEvent) { viewer.setPageHeight(viewer.getHeight()); } }
5,036
34.471831
122
java
null
jabref-main/src/main/java/org/jabref/gui/documentviewer/DocumentViewerViewModel.java
package org.jabref.gui.documentviewer; import java.io.IOException; import java.nio.file.Path; import java.util.List; import java.util.Objects; import javafx.application.Platform; import javafx.beans.property.BooleanProperty; import javafx.beans.property.IntegerProperty; import javafx.beans.property.ListProperty; import javafx.beans.property.ObjectProperty; 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.AbstractViewModel; import org.jabref.gui.StateManager; import org.jabref.logic.util.io.FileUtil; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.LinkedFile; import org.jabref.preferences.PreferencesService; import com.tobiasdiez.easybind.EasyBind; import org.apache.pdfbox.Loader; import org.apache.pdfbox.pdmodel.PDDocument; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DocumentViewerViewModel extends AbstractViewModel { private static final Logger LOGGER = LoggerFactory.getLogger(DocumentViewerViewModel.class); private final StateManager stateManager; private final PreferencesService preferencesService; private final ObjectProperty<DocumentViewModel> currentDocument = new SimpleObjectProperty<>(); private final ListProperty<LinkedFile> files = new SimpleListProperty<>(); private final BooleanProperty liveMode = new SimpleBooleanProperty(); private final ObjectProperty<Integer> currentPage = new SimpleObjectProperty<>(); private final IntegerProperty maxPages = new SimpleIntegerProperty(); public DocumentViewerViewModel(StateManager stateManager, PreferencesService preferencesService) { this.stateManager = Objects.requireNonNull(stateManager); this.preferencesService = Objects.requireNonNull(preferencesService); this.stateManager.getSelectedEntries().addListener((ListChangeListener<? super BibEntry>) c -> { // Switch to currently selected entry in live mode if (isLiveMode()) { setCurrentEntries(this.stateManager.getSelectedEntries()); } }); this.liveMode.addListener((observable, oldValue, newValue) -> { // Switch to currently selected entry if mode is changed to live if ((oldValue != newValue) && newValue) { setCurrentEntries(this.stateManager.getSelectedEntries()); } }); // we need to wrap this in run later so that the max pages number is correctly shown Platform.runLater(() -> maxPages.bindBidirectional( EasyBind.wrapNullable(currentDocument).selectProperty(DocumentViewModel::maxPagesProperty))); setCurrentEntries(this.stateManager.getSelectedEntries()); } private int getCurrentPage() { return currentPage.get(); } public ObjectProperty<Integer> currentPageProperty() { return currentPage; } public IntegerProperty maxPagesProperty() { return maxPages; } private boolean isLiveMode() { return liveMode.get(); } public ObjectProperty<DocumentViewModel> currentDocumentProperty() { return currentDocument; } public ListProperty<LinkedFile> filesProperty() { return files; } private void setCurrentEntries(List<BibEntry> entries) { if (!entries.isEmpty()) { BibEntry firstSelectedEntry = entries.get(0); setCurrentEntry(firstSelectedEntry); } } private void setCurrentEntry(BibEntry entry) { stateManager.getActiveDatabase().ifPresent(database -> { List<LinkedFile> linkedFiles = entry.getFiles(); // We don't need to switch to the first file, this is done automatically in the UI part files.setValue(FXCollections.observableArrayList(linkedFiles)); }); } private void setCurrentDocument(Path path) { try { if (FileUtil.isPDFFile(path)) { PDDocument document = Loader.loadPDF(path.toFile()); currentDocument.set(new PdfDocumentViewModel(document)); } } catch (IOException e) { LOGGER.error("Could not set Document Viewer for path {}", path, e); } } public void switchToFile(LinkedFile file) { if (file != null) { stateManager.getActiveDatabase() .flatMap(database -> file.findIn(database, preferencesService.getFilePreferences())) .ifPresent(this::setCurrentDocument); } } public BooleanProperty liveModeProperty() { return liveMode; } public void showPage(int pageNumber) { currentPage.set(pageNumber); } public void showNextPage() { currentPage.set(getCurrentPage() + 1); } public void showPreviousPage() { currentPage.set(getCurrentPage() - 1); } }
5,108
34.727273
108
java
null
jabref-main/src/main/java/org/jabref/gui/documentviewer/PageDimension.java
package org.jabref.gui.documentviewer; public abstract class PageDimension { public static PageDimension ofFixedWidth(int width) { return new FixedWidthPageDimension(width); } public static PageDimension ofFixedHeight(int height) { return new FixedHeightPageDimension(height); } public static PageDimension ofFixedWidth(double width) { return ofFixedWidth((int) width); } public static PageDimension ofFixedHeight(double height) { return ofFixedHeight((int) height); } public abstract int getWidth(double aspectRatio); public abstract int getHeight(double aspectRatio); private static class FixedWidthPageDimension extends PageDimension { private final int width; public FixedWidthPageDimension(int width) { this.width = width; } @Override public int getWidth(double aspectRatio) { return width; } @Override public int getHeight(double aspectRatio) { return (int) (width / aspectRatio); } } private static class FixedHeightPageDimension extends PageDimension { private final int height; public FixedHeightPageDimension(int height) { this.height = height; } @Override public int getWidth(double aspectRatio) { return (int) (aspectRatio * height); } @Override public int getHeight(double aspectRatio) { return height; } } }
1,541
24.278689
73
java
null
jabref-main/src/main/java/org/jabref/gui/documentviewer/PdfDocumentPageViewModel.java
package org.jabref.gui.documentviewer; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Objects; import javafx.scene.image.Image; import javafx.scene.image.PixelWriter; import javafx.scene.image.WritableImage; import org.jabref.architecture.AllowedToUseAwt; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.rendering.ImageType; import org.apache.pdfbox.rendering.PDFRenderer; /** * Represents the view model of a pdf page backed by a {@link PDPage}. */ @AllowedToUseAwt("Requires AWT due to PDFBox") public class PdfDocumentPageViewModel extends DocumentPageViewModel { private final PDPage page; private final int pageNumber; private final PDDocument document; public PdfDocumentPageViewModel(PDPage page, int pageNumber, PDDocument document) { this.page = Objects.requireNonNull(page); this.pageNumber = pageNumber; this.document = document; } // Taken from http://stackoverflow.com/a/9417836/873661 private static BufferedImage resize(BufferedImage img, int newWidth, int newHeight) { java.awt.Image tmp = img.getScaledInstance(newWidth, newHeight, java.awt.Image.SCALE_SMOOTH); BufferedImage dimg = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = dimg.createGraphics(); g2d.drawImage(tmp, 0, 0, null); g2d.dispose(); return dimg; } @Override // Taken from https://stackoverflow.com/questions/23326562/apache-pdfbox-convert-pdf-to-images public Image render(int width, int height) { PDFRenderer renderer = new PDFRenderer(document); try { int resolution = 96; BufferedImage image = renderer.renderImageWithDPI(pageNumber, 2 * resolution, ImageType.RGB); return convertToFxImage(resize(image, width, height)); } catch (IOException e) { // TODO: LOG return null; } } @Override public int getPageNumber() { return pageNumber + 1; } @Override public double getAspectRatio() { PDRectangle mediaBox = page.getMediaBox(); return mediaBox.getWidth() / mediaBox.getHeight(); } // See https://stackoverflow.com/a/57552025/3450689 private static Image convertToFxImage(BufferedImage image) { WritableImage wr = null; if (image != null) { wr = new WritableImage(image.getWidth(), image.getHeight()); PixelWriter pw = wr.getPixelWriter(); for (int x = 0; x < image.getWidth(); x++) { for (int y = 0; y < image.getHeight(); y++) { pw.setArgb(x, y, image.getRGB(x, y)); } } } return wr; } }
2,913
32.113636
105
java
null
jabref-main/src/main/java/org/jabref/gui/documentviewer/PdfDocumentViewModel.java
package org.jabref.gui.documentviewer; import java.util.ArrayList; import java.util.List; import java.util.Objects; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPageTree; public class PdfDocumentViewModel extends DocumentViewModel { private final PDDocument document; public PdfDocumentViewModel(PDDocument document) { this.document = Objects.requireNonNull(document); this.maxPagesProperty().set(document.getNumberOfPages()); } @Override public ObservableList<DocumentPageViewModel> getPages() { PDPageTree pages = document.getDocumentCatalog().getPages(); List<PdfDocumentPageViewModel> pdfPages = new ArrayList<>(); // There is apparently no neat way to get the page number from a PDPage...thus this old-style for loop for (int i = 0; i < pages.getCount(); i++) { pdfPages.add(new PdfDocumentPageViewModel(pages.get(i), i, document)); } return FXCollections.observableArrayList(pdfPages); } }
1,122
32.029412
110
java
null
jabref-main/src/main/java/org/jabref/gui/documentviewer/ShowDocumentViewerAction.java
package org.jabref.gui.documentviewer; import org.jabref.gui.DialogService; import org.jabref.gui.StateManager; import org.jabref.gui.actions.ActionHelper; import org.jabref.gui.actions.SimpleCommand; import org.jabref.preferences.PreferencesService; import com.airhacks.afterburner.injection.Injector; import static org.jabref.gui.actions.ActionHelper.needsEntriesSelected; public class ShowDocumentViewerAction extends SimpleCommand { public ShowDocumentViewerAction(StateManager stateManager, PreferencesService preferences) { this.executable.bind(needsEntriesSelected(stateManager).and(ActionHelper.isFilePresentForSelectedEntry(stateManager, preferences))); } @Override public void execute() { DialogService dialogService = Injector.instantiateModelOrService(DialogService.class); dialogService.showCustomDialog(new DocumentViewerView()); } }
898
34.96
140
java
null
jabref-main/src/main/java/org/jabref/gui/duplicationFinder/DuplicateResolverDialog.java
package org.jabref.gui.duplicationFinder; import javafx.scene.control.Button; import javafx.scene.control.ButtonBar; import javafx.scene.control.ButtonBar.ButtonData; import javafx.scene.control.ButtonType; import javafx.scene.layout.BorderPane; import org.jabref.gui.DialogService; import org.jabref.gui.StateManager; import org.jabref.gui.actions.ActionFactory; import org.jabref.gui.actions.StandardActions; import org.jabref.gui.duplicationFinder.DuplicateResolverDialog.DuplicateResolverResult; import org.jabref.gui.help.HelpAction; import org.jabref.gui.mergeentries.newmergedialog.ThreeWayMergeView; import org.jabref.gui.util.BaseDialog; import org.jabref.gui.util.DialogWindowState; import org.jabref.logic.help.HelpFile; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.preferences.PreferencesService; public class DuplicateResolverDialog extends BaseDialog<DuplicateResolverResult> { private final BibDatabaseContext database; private final StateManager stateManager; public enum DuplicateResolverType { DUPLICATE_SEARCH, IMPORT_CHECK, DUPLICATE_SEARCH_WITH_EXACT } public enum DuplicateResolverResult { KEEP_BOTH, KEEP_LEFT, KEEP_RIGHT, AUTOREMOVE_EXACT, KEEP_MERGE, BREAK } private ThreeWayMergeView threeWayMerge; private final DialogService dialogService; private final ActionFactory actionFactory; private final PreferencesService preferencesService; public DuplicateResolverDialog(BibEntry one, BibEntry two, DuplicateResolverType type, BibDatabaseContext database, StateManager stateManager, DialogService dialogService, PreferencesService preferencesService) { this.setTitle(Localization.lang("Possible duplicate entries")); this.database = database; this.stateManager = stateManager; this.dialogService = dialogService; this.preferencesService = preferencesService; this.actionFactory = new ActionFactory(preferencesService.getKeyBindingRepository()); init(one, two, type); } private void init(BibEntry one, BibEntry two, DuplicateResolverType type) { ButtonType cancel = ButtonType.CANCEL; ButtonType merge = new ButtonType(Localization.lang("Keep merged"), ButtonData.OK_DONE); ButtonType both; ButtonType second; ButtonType first; ButtonType removeExact = new ButtonType(Localization.lang("Automatically remove exact duplicates"), ButtonData.LEFT); boolean removeExactVisible = false; switch (type) { case DUPLICATE_SEARCH -> { first = new ButtonType(Localization.lang("Keep left"), ButtonData.LEFT); second = new ButtonType(Localization.lang("Keep right"), ButtonData.LEFT); both = new ButtonType(Localization.lang("Keep both"), ButtonData.LEFT); threeWayMerge = new ThreeWayMergeView(one, two, preferencesService.getBibEntryPreferences()); } case DUPLICATE_SEARCH_WITH_EXACT -> { first = new ButtonType(Localization.lang("Keep left"), ButtonData.LEFT); second = new ButtonType(Localization.lang("Keep right"), ButtonData.LEFT); both = new ButtonType(Localization.lang("Keep both"), ButtonData.LEFT); removeExactVisible = true; threeWayMerge = new ThreeWayMergeView(one, two, preferencesService.getBibEntryPreferences()); } case IMPORT_CHECK -> { first = new ButtonType(Localization.lang("Keep old entry"), ButtonData.LEFT); second = new ButtonType(Localization.lang("Keep from import"), ButtonData.LEFT); both = new ButtonType(Localization.lang("Keep both"), ButtonData.LEFT); threeWayMerge = new ThreeWayMergeView(one, two, Localization.lang("Old entry"), Localization.lang("From import"), preferencesService.getBibEntryPreferences()); } default -> throw new IllegalStateException("Switch expression should be exhaustive"); } this.getDialogPane().getButtonTypes().addAll(first, second, both, merge, cancel); this.getDialogPane().setFocusTraversable(false); if (removeExactVisible) { this.getDialogPane().getButtonTypes().add(removeExact); // This will prevent all dialog buttons from having the same size // Read more: https://stackoverflow.com/questions/45866249/javafx-8-alert-different-button-sizes getDialogPane().getButtonTypes().stream() .map(getDialogPane()::lookupButton) .forEach(btn -> ButtonBar.setButtonUniformSize(btn, false)); } // Retrieves the previous window state and sets the new dialog window size and position to match it DialogWindowState state = stateManager.getDialogWindowState(getClass().getSimpleName()); if (state != null) { this.getDialogPane().setPrefSize(state.getWidth(), state.getHeight()); this.setX(state.getX()); this.setY(state.getY()); } BorderPane borderPane = new BorderPane(threeWayMerge); this.setResultConverter(button -> { // Updates the window state on button press stateManager.setDialogWindowState(getClass().getSimpleName(), new DialogWindowState(this.getX(), this.getY(), this.getDialogPane().getHeight(), this.getDialogPane().getWidth())); threeWayMerge.saveConfiguration(); if (button.equals(first)) { return DuplicateResolverResult.KEEP_LEFT; } else if (button.equals(second)) { return DuplicateResolverResult.KEEP_RIGHT; } else if (button.equals(both)) { return DuplicateResolverResult.KEEP_BOTH; } else if (button.equals(merge)) { return DuplicateResolverResult.KEEP_MERGE; } else if (button.equals(removeExact)) { return DuplicateResolverResult.AUTOREMOVE_EXACT; } return null; }); HelpAction helpCommand = new HelpAction(HelpFile.FIND_DUPLICATES, dialogService); Button helpButton = actionFactory.createIconButton(StandardActions.HELP, helpCommand); borderPane.setRight(helpButton); getDialogPane().setContent(borderPane); } public BibEntry getMergedEntry() { return threeWayMerge.getMergedEntry(); } public BibEntry getNewLeftEntry() { return threeWayMerge.getLeftEntry(); } public BibEntry getNewRightEntry() { return threeWayMerge.getRightEntry(); } }
7,054
43.09375
190
java
null
jabref-main/src/main/java/org/jabref/gui/duplicationFinder/DuplicateSearch.java
package org.jabref.gui.duplicationFinder; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import javafx.beans.binding.Bindings; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleStringProperty; import org.jabref.gui.DialogService; import org.jabref.gui.Globals; import org.jabref.gui.JabRefExecutorService; import org.jabref.gui.JabRefFrame; import org.jabref.gui.LibraryTab; import org.jabref.gui.StateManager; import org.jabref.gui.actions.SimpleCommand; import org.jabref.gui.duplicationFinder.DuplicateResolverDialog.DuplicateResolverResult; import org.jabref.gui.duplicationFinder.DuplicateResolverDialog.DuplicateResolverType; import org.jabref.gui.undo.NamedCompound; import org.jabref.gui.undo.UndoableInsertEntries; import org.jabref.gui.undo.UndoableRemoveEntries; import org.jabref.gui.util.BackgroundTask; import org.jabref.gui.util.DefaultTaskExecutor; import org.jabref.logic.database.DuplicateCheck; import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.database.BibDatabaseMode; import org.jabref.model.entry.BibEntry; import org.jabref.preferences.PreferencesService; import static org.jabref.gui.actions.ActionHelper.needsDatabase; public class DuplicateSearch extends SimpleCommand { private final JabRefFrame frame; private final BlockingQueue<List<BibEntry>> duplicates = new LinkedBlockingQueue<>(); private final AtomicBoolean libraryAnalyzed = new AtomicBoolean(); private final AtomicBoolean autoRemoveExactDuplicates = new AtomicBoolean(); private final AtomicInteger duplicateCount = new AtomicInteger(); private final SimpleStringProperty duplicateCountObservable = new SimpleStringProperty(); private final SimpleStringProperty duplicateTotal = new SimpleStringProperty(); private final SimpleIntegerProperty duplicateProgress = new SimpleIntegerProperty(0); private final DialogService dialogService; private final StateManager stateManager; private final PreferencesService prefs; public DuplicateSearch(JabRefFrame frame, DialogService dialogService, StateManager stateManager, PreferencesService prefs) { this.frame = frame; this.dialogService = dialogService; this.stateManager = stateManager; this.prefs = prefs; this.executable.bind(needsDatabase(stateManager)); } @Override public void execute() { BibDatabaseContext database = stateManager.getActiveDatabase().orElseThrow(() -> new NullPointerException("Database null")); dialogService.notify(Localization.lang("Searching for duplicates...")); List<BibEntry> entries = database.getEntries(); duplicates.clear(); libraryAnalyzed.set(false); autoRemoveExactDuplicates.set(false); duplicateCount.set(0); if (entries.size() < 2) { return; } duplicateCountObservable.addListener((obj, oldValue, newValue) -> DefaultTaskExecutor.runAndWaitInJavaFXThread(() -> duplicateTotal.set(newValue))); JabRefExecutorService.INSTANCE.executeInterruptableTask(() -> searchPossibleDuplicates(entries, database.getMode()), "DuplicateSearcher"); BackgroundTask.wrap(this::verifyDuplicates) .onSuccess(this::handleDuplicates) .executeWith(Globals.TASK_EXECUTOR); } private void searchPossibleDuplicates(List<BibEntry> entries, BibDatabaseMode databaseMode) { for (int i = 0; i < (entries.size() - 1); i++) { for (int j = i + 1; j < entries.size(); j++) { if (Thread.interrupted()) { return; } BibEntry first = entries.get(i); BibEntry second = entries.get(j); if (new DuplicateCheck(Globals.entryTypesManager).isDuplicate(first, second, databaseMode)) { duplicates.add(Arrays.asList(first, second)); duplicateCountObservable.set(String.valueOf(duplicateCount.incrementAndGet())); } } } libraryAnalyzed.set(true); } private DuplicateSearchResult verifyDuplicates() { DuplicateSearchResult result = new DuplicateSearchResult(); while (!libraryAnalyzed.get() || !duplicates.isEmpty()) { duplicateProgress.set(duplicateProgress.getValue() + 1); List<BibEntry> dups; try { // poll with timeout in case the library is not analyzed completely, but contains no more duplicates dups = this.duplicates.poll(100, TimeUnit.MILLISECONDS); if (dups == null) { continue; } } catch (InterruptedException e) { return null; } BibEntry first = dups.get(0); BibEntry second = dups.get(1); if (!result.isToRemove(first) && !result.isToRemove(second)) { // Check if they are exact duplicates: boolean askAboutExact = false; if (DuplicateCheck.compareEntriesStrictly(first, second) > 1) { if (autoRemoveExactDuplicates.get()) { result.remove(second); continue; } askAboutExact = true; } DuplicateResolverType resolverType = askAboutExact ? DuplicateResolverType.DUPLICATE_SEARCH_WITH_EXACT : DuplicateResolverType.DUPLICATE_SEARCH; DefaultTaskExecutor.runAndWaitInJavaFXThread(() -> askResolveStrategy(result, first, second, resolverType)); } } return result; } private void askResolveStrategy(DuplicateSearchResult result, BibEntry first, BibEntry second, DuplicateResolverType resolverType) { DuplicateResolverDialog dialog = new DuplicateResolverDialog(first, second, resolverType, frame.getCurrentLibraryTab().getBibDatabaseContext(), stateManager, dialogService, prefs); dialog.titleProperty().bind(Bindings.concat(dialog.getTitle()).concat(" (").concat(duplicateProgress.getValue()).concat("/").concat(duplicateTotal).concat(")")); DuplicateResolverResult resolverResult = dialogService.showCustomDialogAndWait(dialog) .orElse(DuplicateResolverResult.BREAK); if ((resolverResult == DuplicateResolverResult.KEEP_LEFT) || (resolverResult == DuplicateResolverResult.AUTOREMOVE_EXACT)) { result.remove(second); result.replace(first, dialog.getNewLeftEntry()); if (resolverResult == DuplicateResolverResult.AUTOREMOVE_EXACT) { autoRemoveExactDuplicates.set(true); // Remember choice } } else if (resolverResult == DuplicateResolverResult.KEEP_RIGHT) { result.remove(first); result.replace(second, dialog.getNewRightEntry()); } else if (resolverResult == DuplicateResolverResult.BREAK) { libraryAnalyzed.set(true); duplicates.clear(); } else if (resolverResult == DuplicateResolverResult.KEEP_MERGE) { result.replace(first, second, dialog.getMergedEntry()); } else if (resolverResult == DuplicateResolverResult.KEEP_BOTH) { result.replace(first, dialog.getNewLeftEntry()); result.replace(second, dialog.getNewRightEntry()); } } private void handleDuplicates(DuplicateSearchResult result) { if (result == null) { return; } LibraryTab libraryTab = frame.getCurrentLibraryTab(); final NamedCompound compoundEdit = new NamedCompound(Localization.lang("duplicate removal")); // Now, do the actual removal: if (!result.getToRemove().isEmpty()) { compoundEdit.addEdit(new UndoableRemoveEntries(libraryTab.getDatabase(), result.getToRemove())); libraryTab.getDatabase().removeEntries(result.getToRemove()); libraryTab.markBaseChanged(); } // and adding merged entries: if (!result.getToAdd().isEmpty()) { compoundEdit.addEdit(new UndoableInsertEntries(libraryTab.getDatabase(), result.getToAdd())); libraryTab.getDatabase().insertEntries(result.getToAdd()); libraryTab.markBaseChanged(); } duplicateProgress.set(0); dialogService.notify(Localization.lang("Duplicates found") + ": " + duplicateCount.get() + ' ' + Localization.lang("pairs processed") + ": " + result.getDuplicateCount()); compoundEdit.end(); libraryTab.getUndoManager().addEdit(compoundEdit); } /** * Result of a duplicate search. * Uses {@link System#identityHashCode(Object)} for identifying objects for removal, as completely identical * {@link BibEntry BibEntries} are equal to each other. */ static class DuplicateSearchResult { private final Map<Integer, BibEntry> toRemove = new HashMap<>(); private final List<BibEntry> toAdd = new ArrayList<>(); private int duplicates = 0; public synchronized List<BibEntry> getToRemove() { return new ArrayList<>(toRemove.values()); } public synchronized List<BibEntry> getToAdd() { return toAdd; } public synchronized void remove(BibEntry entry) { toRemove.put(System.identityHashCode(entry), entry); duplicates++; } public synchronized void replace(BibEntry first, BibEntry second, BibEntry replacement) { remove(first); remove(second); toAdd.add(replacement); duplicates++; } public synchronized void replace(BibEntry entry, BibEntry replacement) { remove(entry); getToAdd().add(replacement); } public synchronized boolean isToRemove(BibEntry entry) { return toRemove.containsKey(System.identityHashCode(entry)); } public synchronized int getDuplicateCount() { return duplicates; } } }
10,545
41.015936
188
java
null
jabref-main/src/main/java/org/jabref/gui/edit/CopyDoiUrlAction.java
package org.jabref.gui.edit; import java.util.Optional; import javafx.scene.control.TextArea; import org.jabref.gui.Globals; import org.jabref.gui.JabRefGUI; import org.jabref.gui.actions.SimpleCommand; import org.jabref.gui.actions.StandardActions; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.identifier.DOI; /** * Copies the doi url to the clipboard */ public class CopyDoiUrlAction extends SimpleCommand { private TextArea component; private StandardActions action; public CopyDoiUrlAction(TextArea component, StandardActions action) { this.component = component; this.action = action; } @Override public void execute() { String identifier = component.getText(); if (action == StandardActions.COPY_DOI_URL) { copy(DOI.parse(identifier).map(DOI::getURIAsASCIIString), identifier); } else { copy(DOI.parse(identifier).map(DOI::getDOI), identifier); } } private void copy(Optional<String> urlOptional, String identifier) { if (urlOptional.isPresent()) { Globals.getClipboardManager().setContent(urlOptional.get()); JabRefGUI.getMainFrame().getDialogService().notify(Localization.lang("The link has been copied to the clipboard.")); } else { JabRefGUI.getMainFrame().getDialogService().notify(Localization.lang("Invalid DOI: '%0'.", identifier)); } } }
1,460
30.085106
128
java
null
jabref-main/src/main/java/org/jabref/gui/edit/CopyMoreAction.java
package org.jabref.gui.edit; import java.io.IOException; import java.io.StringReader; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.jabref.gui.ClipBoardManager; import org.jabref.gui.DialogService; import org.jabref.gui.JabRefDialogService; import org.jabref.gui.StateManager; import org.jabref.gui.actions.ActionHelper; import org.jabref.gui.actions.SimpleCommand; import org.jabref.gui.actions.StandardActions; import org.jabref.logic.journals.JournalAbbreviationRepository; import org.jabref.logic.l10n.Localization; import org.jabref.logic.layout.Layout; import org.jabref.logic.layout.LayoutHelper; import org.jabref.logic.util.OS; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.preferences.PreferencesService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CopyMoreAction extends SimpleCommand { private static final Logger LOGGER = LoggerFactory.getLogger(CopyMoreAction.class); private final StandardActions action; private final DialogService dialogService; private final StateManager stateManager; private final ClipBoardManager clipBoardManager; private final PreferencesService preferencesService; private final JournalAbbreviationRepository abbreviationRepository; public CopyMoreAction(StandardActions action, DialogService dialogService, StateManager stateManager, ClipBoardManager clipBoardManager, PreferencesService preferencesService, JournalAbbreviationRepository abbreviationRepository) { this.action = action; this.dialogService = dialogService; this.stateManager = stateManager; this.clipBoardManager = clipBoardManager; this.preferencesService = preferencesService; this.abbreviationRepository = abbreviationRepository; this.executable.bind(ActionHelper.needsEntriesSelected(stateManager)); } @Override public void execute() { if (stateManager.getActiveDatabase().isEmpty() || stateManager.getSelectedEntries().isEmpty()) { return; } switch (action) { case COPY_TITLE -> copyTitle(); case COPY_KEY -> copyKey(); case COPY_CITE_KEY -> copyCiteKey(); case COPY_KEY_AND_TITLE -> copyKeyAndTitle(); case COPY_KEY_AND_LINK -> copyKeyAndLink(); case COPY_DOI, COPY_DOI_URL -> copyDoi(); default -> LOGGER.info("Unknown copy command."); } } private void copyTitle() { List<BibEntry> selectedBibEntries = stateManager.getSelectedEntries(); List<String> titles = selectedBibEntries.stream() .filter(bibEntry -> bibEntry.getTitle().isPresent()) .map(bibEntry -> bibEntry.getTitle().get()) .collect(Collectors.toList()); if (titles.isEmpty()) { dialogService.notify(Localization.lang("None of the selected entries have titles.")); return; } final String copiedTitles = String.join("\n", titles); clipBoardManager.setContent(copiedTitles); if (titles.size() == selectedBibEntries.size()) { // All entries had titles. dialogService.notify(Localization.lang("Copied '%0' to clipboard.", JabRefDialogService.shortenDialogMessage(copiedTitles))); } else { dialogService.notify(Localization.lang("Warning: %0 out of %1 entries have undefined title.", Integer.toString(selectedBibEntries.size() - titles.size()), Integer.toString(selectedBibEntries.size()))); } } private void copyKey() { List<BibEntry> entries = stateManager.getSelectedEntries(); // Collect all non-null keys. List<String> keys = entries.stream() .filter(entry -> entry.getCitationKey().isPresent()) .map(entry -> entry.getCitationKey().get()) .collect(Collectors.toList()); if (keys.isEmpty()) { dialogService.notify(Localization.lang("None of the selected entries have citation keys.")); return; } final String copiedKeys = String.join(",", keys); clipBoardManager.setContent(copiedKeys); if (keys.size() == entries.size()) { // All entries had keys. dialogService.notify(Localization.lang("Copied '%0' to clipboard.", JabRefDialogService.shortenDialogMessage(copiedKeys))); } else { dialogService.notify(Localization.lang("Warning: %0 out of %1 entries have undefined citation key.", Integer.toString(entries.size() - keys.size()), Integer.toString(entries.size()))); } } private void copyDoi() { List<BibEntry> entries = stateManager.getSelectedEntries(); // Collect all non-null DOI or DOI urls if (action == StandardActions.COPY_DOI_URL) { copyDoiList(entries.stream() .filter(entry -> entry.getDOI().isPresent()) .map(entry -> entry.getDOI().get().getURIAsASCIIString()) .collect(Collectors.toList()), entries.size()); } else { copyDoiList(entries.stream() .filter(entry -> entry.getDOI().isPresent()) .map(entry -> entry.getDOI().get().getDOI()) .collect(Collectors.toList()), entries.size()); } } private void copyDoiList(List<String> dois, int size) { if (dois.isEmpty()) { dialogService.notify(Localization.lang("None of the selected entries have DOIs.")); return; } final String copiedDois = String.join(",", dois); clipBoardManager.setContent(copiedDois); if (dois.size() == size) { // All entries had DOIs. dialogService.notify(Localization.lang("Copied '%0' to clipboard.", JabRefDialogService.shortenDialogMessage(copiedDois))); } else { dialogService.notify(Localization.lang("Warning: %0 out of %1 entries have undefined DOIs.", Integer.toString(size - dois.size()), Integer.toString(size))); } } private void copyCiteKey() { List<BibEntry> entries = stateManager.getSelectedEntries(); // Collect all non-null keys. List<String> keys = entries.stream() .filter(entry -> entry.getCitationKey().isPresent()) .map(entry -> entry.getCitationKey().get()) .collect(Collectors.toList()); if (keys.isEmpty()) { dialogService.notify(Localization.lang("None of the selected entries have citation keys.")); return; } String citeCommand = Optional.ofNullable(preferencesService.getExternalApplicationsPreferences().getCiteCommand()) .filter(cite -> cite.contains("\\")) // must contain \ .orElse("\\cite"); final String copiedCiteCommand = citeCommand + "{" + String.join(",", keys) + '}'; clipBoardManager.setContent(copiedCiteCommand); if (keys.size() == entries.size()) { // All entries had keys. dialogService.notify(Localization.lang("Copied '%0' to clipboard.", JabRefDialogService.shortenDialogMessage(copiedCiteCommand))); } else { dialogService.notify(Localization.lang("Warning: %0 out of %1 entries have undefined citation key.", Integer.toString(entries.size() - keys.size()), Integer.toString(entries.size()))); } } private void copyKeyAndTitle() { List<BibEntry> entries = stateManager.getSelectedEntries(); // ToDo: this string should be configurable to allow arbitrary exports StringReader layoutString = new StringReader("\\citationkey - \\begin{title}\\format[RemoveBrackets]{\\title}\\end{title}\n"); Layout layout; try { layout = new LayoutHelper(layoutString, preferencesService.getLayoutFormatterPreferences(), abbreviationRepository).getLayoutFromText(); } catch (IOException e) { LOGGER.info("Could not get layout.", e); return; } StringBuilder keyAndTitle = new StringBuilder(); int entriesWithKeys = 0; // Collect all non-null keys. for (BibEntry entry : entries) { if (entry.hasCitationKey()) { entriesWithKeys++; keyAndTitle.append(layout.doLayout(entry, stateManager.getActiveDatabase().get().getDatabase())); } } if (entriesWithKeys == 0) { dialogService.notify(Localization.lang("None of the selected entries have citation keys.")); return; } clipBoardManager.setContent(keyAndTitle.toString()); if (entriesWithKeys == entries.size()) { // All entries had keys. dialogService.notify(Localization.lang("Copied '%0' to clipboard.", JabRefDialogService.shortenDialogMessage(keyAndTitle.toString()))); } else { dialogService.notify(Localization.lang("Warning: %0 out of %1 entries have undefined citation key.", Integer.toString(entries.size() - entriesWithKeys), Integer.toString(entries.size()))); } } /** * This method will copy each selected entry's citation key as a hyperlink to its url to the clipboard. In case an * entry doesn't have a citation key it will not be copied. In case an entry doesn't have an url this will only copy * the citation key. */ private void copyKeyAndLink() { List<BibEntry> entries = stateManager.getSelectedEntries(); StringBuilder keyAndLink = new StringBuilder(); StringBuilder fallbackString = new StringBuilder(); List<BibEntry> entriesWithKey = entries.stream() .filter(BibEntry::hasCitationKey) .collect(Collectors.toList()); if (entriesWithKey.isEmpty()) { dialogService.notify(Localization.lang("None of the selected entries have citation keys.")); return; } for (BibEntry entry : entriesWithKey) { String key = entry.getCitationKey().get(); String url = entry.getField(StandardField.URL).orElse(""); keyAndLink.append(url.isEmpty() ? key : String.format("<a href=\"%s\">%s</a>", url, key)); keyAndLink.append(OS.NEWLINE); fallbackString.append(url.isEmpty() ? key : String.format("%s - %s", key, url)); fallbackString.append(OS.NEWLINE); } clipBoardManager.setHtmlContent(keyAndLink.toString(), fallbackString.toString()); if (entriesWithKey.size() == entries.size()) { // All entries had keys. dialogService.notify(Localization.lang("Copied '%0' to clipboard.", JabRefDialogService.shortenDialogMessage(keyAndLink.toString()))); } else { dialogService.notify(Localization.lang("Warning: %0 out of %1 entries have undefined citation key.", Long.toString(entries.size() - entriesWithKey.size()), Integer.toString(entries.size()))); } } }
11,817
42.289377
148
java
null
jabref-main/src/main/java/org/jabref/gui/edit/EditAction.java
package org.jabref.gui.edit; import javafx.scene.control.TextInputControl; import javafx.scene.web.WebView; import org.jabref.gui.JabRefFrame; import org.jabref.gui.StateManager; import org.jabref.gui.actions.ActionHelper; import org.jabref.gui.actions.SimpleCommand; import org.jabref.gui.actions.StandardActions; import org.fxmisc.richtext.CodeArea; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Class for handling general actions; cut, copy and paste. The focused component is kept track of by * Globals.focusListener, and we call the action stored under the relevant name in its action map. */ public class EditAction extends SimpleCommand { private static final Logger LOGGER = LoggerFactory.getLogger(EditAction.class); private final JabRefFrame frame; private final StandardActions action; private final StateManager stateManager; public EditAction(StandardActions action, JabRefFrame frame, StateManager stateManager) { this.action = action; this.frame = frame; this.stateManager = stateManager; if (action == StandardActions.PASTE) { this.executable.bind(ActionHelper.needsDatabase(stateManager)); } else { this.executable.bind(ActionHelper.needsEntriesSelected(stateManager)); } } @Override public String toString() { return this.action.toString(); } @Override public void execute() { stateManager.getFocusOwner().ifPresent(focusOwner -> { LOGGER.debug("focusOwner: {}; Action: {}", focusOwner, action.getText()); if (focusOwner instanceof TextInputControl textInput) { // Focus is on text field -> copy/paste/cut selected text // DELETE_ENTRY in text field should do forward delete switch (action) { case SELECT_ALL -> textInput.selectAll(); case COPY -> textInput.copy(); case CUT -> textInput.cut(); case PASTE -> textInput.paste(); case DELETE -> textInput.clear(); case DELETE_ENTRY -> textInput.deleteNextChar(); case UNDO -> textInput.undo(); case REDO -> textInput.redo(); default -> { String message = "Only cut/copy/paste supported in TextInputControl but got " + action; LOGGER.error(message); throw new IllegalStateException(message); } } } else if ((focusOwner instanceof CodeArea) || (focusOwner instanceof WebView)) { LOGGER.debug("Ignoring request in CodeArea or WebView"); return; } else { LOGGER.debug("Else: {}", focusOwner.getClass().getSimpleName()); // Not sure what is selected -> copy/paste/cut selected entries except for Preview and CodeArea switch (action) { case COPY -> frame.getCurrentLibraryTab().copy(); case CUT -> frame.getCurrentLibraryTab().cut(); case PASTE -> frame.getCurrentLibraryTab().paste(); case DELETE_ENTRY -> frame.getCurrentLibraryTab().delete(false); case UNDO -> { if (frame.getUndoManager().canUndo()) { frame.getUndoManager().undo(); } } case REDO -> { if (frame.getUndoManager().canRedo()) { frame.getUndoManager().redo(); } } default -> LOGGER.debug("Only cut/copy/paste/deleteEntry supported but got: {} and focus owner {}", action, focusOwner); } } }); } }
3,923
40.305263
140
java
null
jabref-main/src/main/java/org/jabref/gui/edit/ManageKeywordsAction.java
package org.jabref.gui.edit; import org.jabref.gui.DialogService; import org.jabref.gui.StateManager; import org.jabref.gui.actions.SimpleCommand; import org.jabref.gui.util.BindingsHelper; import org.jabref.logic.l10n.Localization; import com.airhacks.afterburner.injection.Injector; import static org.jabref.gui.actions.ActionHelper.needsDatabase; import static org.jabref.gui.actions.ActionHelper.needsEntriesSelected; /** * An Action for launching keyword managing dialog */ public class ManageKeywordsAction extends SimpleCommand { private final StateManager stateManager; public ManageKeywordsAction(StateManager stateManager) { this.stateManager = stateManager; this.executable.bind(needsDatabase(stateManager).and(needsEntriesSelected(stateManager))); this.statusMessage.bind(BindingsHelper.ifThenElse(this.executable, "", Localization.lang("Select at least one entry to manage keywords."))); } @Override public void execute() { DialogService dialogService = Injector.instantiateModelOrService(DialogService.class); dialogService.showCustomDialogAndWait(new ManageKeywordsDialog(stateManager.getSelectedEntries())); } }
1,202
34.382353
148
java
null
jabref-main/src/main/java/org/jabref/gui/edit/ManageKeywordsDialog.java
package org.jabref.gui.edit; import java.util.List; import javafx.fxml.FXML; import javafx.scene.control.ButtonType; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.ToggleGroup; import javafx.scene.control.cell.TextFieldTableCell; import org.jabref.gui.icon.IconTheme; import org.jabref.gui.util.BaseDialog; import org.jabref.gui.util.BindingsHelper; import org.jabref.gui.util.ValueTableCellFactory; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.BibEntry; import org.jabref.preferences.PreferencesService; import com.airhacks.afterburner.views.ViewLoader; import com.tobiasdiez.easybind.EasyBind; import jakarta.inject.Inject; public class ManageKeywordsDialog extends BaseDialog<Void> { private final List<BibEntry> entries; @FXML private TableColumn<String, String> keywordsTableMainColumn; @FXML private TableColumn<String, Boolean> keywordsTableEditColumn; @FXML private TableColumn<String, Boolean> keywordsTableDeleteColumn; @FXML private TableView<String> keywordsTable; @FXML private ToggleGroup displayType; @Inject private PreferencesService preferences; private ManageKeywordsViewModel viewModel; public ManageKeywordsDialog(List<BibEntry> entries) { this.entries = entries; this.setTitle(Localization.lang("Manage keywords")); ViewLoader.view(this) .load() .setAsDialogPane(this); setResultConverter(button -> { if (button == ButtonType.APPLY) { viewModel.saveChanges(); } return null; }); } @FXML public void initialize() { viewModel = new ManageKeywordsViewModel(preferences.getBibEntryPreferences(), entries); viewModel.displayTypeProperty().bind( EasyBind.map(displayType.selectedToggleProperty(), toggle -> { if (toggle != null) { return (ManageKeywordsDisplayType) toggle.getUserData(); } else { return ManageKeywordsDisplayType.CONTAINED_IN_ALL_ENTRIES; } }) ); keywordsTable.setItems(viewModel.getKeywords()); keywordsTableMainColumn.setCellValueFactory(data -> BindingsHelper.constantOf(data.getValue())); keywordsTableMainColumn.setOnEditCommit(event -> { // Poor mans reverse databinding (necessary because we use a constant value above) viewModel.getKeywords().set(event.getTablePosition().getRow(), event.getNewValue()); }); keywordsTableMainColumn.setCellFactory(TextFieldTableCell.forTableColumn()); keywordsTableEditColumn.setCellValueFactory(data -> BindingsHelper.constantOf(true)); keywordsTableDeleteColumn.setCellValueFactory(data -> BindingsHelper.constantOf(true)); new ValueTableCellFactory<String, Boolean>() .withGraphic(none -> IconTheme.JabRefIcons.EDIT.getGraphicNode()) .withOnMouseClickedEvent(none -> event -> keywordsTable.edit(keywordsTable.getFocusModel().getFocusedIndex(), keywordsTableMainColumn)) .install(keywordsTableEditColumn); new ValueTableCellFactory<String, Boolean>() .withGraphic(none -> IconTheme.JabRefIcons.REMOVE.getGraphicNode()) .withOnMouseClickedEvent((keyword, none) -> event -> viewModel.removeKeyword(keyword)) .install(keywordsTableDeleteColumn); } }
3,559
41.891566
151
java
null
jabref-main/src/main/java/org/jabref/gui/edit/ManageKeywordsDisplayType.java
package org.jabref.gui.edit; public enum ManageKeywordsDisplayType { CONTAINED_IN_ALL_ENTRIES, CONTAINED_IN_ANY_ENTRY, }
130
17.714286
39
java
null
jabref-main/src/main/java/org/jabref/gui/edit/ManageKeywordsViewModel.java
package org.jabref.gui.edit; 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 org.jabref.gui.undo.NamedCompound; import org.jabref.gui.undo.UndoableFieldChange; import org.jabref.logic.l10n.Localization; import org.jabref.model.FieldChange; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.Keyword; import org.jabref.model.entry.KeywordList; import org.jabref.preferences.BibEntryPreferences; import com.tobiasdiez.easybind.EasyBind; public class ManageKeywordsViewModel { private final List<BibEntry> entries; private final KeywordList sortedKeywordsOfAllEntriesBeforeUpdateByUser = new KeywordList(); private final BibEntryPreferences bibEntryPreferences; private final ObjectProperty<ManageKeywordsDisplayType> displayType = new SimpleObjectProperty<>(ManageKeywordsDisplayType.CONTAINED_IN_ALL_ENTRIES); private final ObservableList<String> keywords; public ManageKeywordsViewModel(BibEntryPreferences bibEntryPreferences, List<BibEntry> entries) { this.bibEntryPreferences = bibEntryPreferences; this.entries = entries; this.keywords = FXCollections.observableArrayList(); EasyBind.subscribe(displayType, this::fillKeywordsList); } public ManageKeywordsDisplayType getDisplayType() { return displayType.get(); } public ObjectProperty<ManageKeywordsDisplayType> displayTypeProperty() { return displayType; } private void fillKeywordsList(ManageKeywordsDisplayType type) { keywords.clear(); sortedKeywordsOfAllEntriesBeforeUpdateByUser.clear(); Character keywordSeparator = bibEntryPreferences.getKeywordSeparator(); if (type == ManageKeywordsDisplayType.CONTAINED_IN_ALL_ENTRIES) { for (BibEntry entry : entries) { KeywordList separatedKeywords = entry.getKeywords(keywordSeparator); sortedKeywordsOfAllEntriesBeforeUpdateByUser.addAll(separatedKeywords); } } else if (type == ManageKeywordsDisplayType.CONTAINED_IN_ANY_ENTRY) { // all keywords from first entry have to be added BibEntry firstEntry = entries.get(0); KeywordList separatedKeywords = firstEntry.getKeywords(keywordSeparator); sortedKeywordsOfAllEntriesBeforeUpdateByUser.addAll(separatedKeywords); // for the remaining entries, intersection has to be used // this approach ensures that one empty keyword list leads to an empty set of common keywords for (BibEntry entry : entries) { separatedKeywords = entry.getKeywords(keywordSeparator); sortedKeywordsOfAllEntriesBeforeUpdateByUser.retainAll(separatedKeywords); } } else { throw new IllegalStateException("DisplayType " + type + " not handled"); } for (Keyword keyword : sortedKeywordsOfAllEntriesBeforeUpdateByUser) { keywords.add(keyword.get()); } } public ObservableList<String> getKeywords() { return keywords; } public void removeKeyword(String keyword) { keywords.remove(keyword); } public void saveChanges() { KeywordList keywordsToAdd = new KeywordList(); KeywordList userSelectedKeywords = new KeywordList(); // build keywordsToAdd and userSelectedKeywords in parallel for (String keyword : keywords) { userSelectedKeywords.add(keyword); if (!sortedKeywordsOfAllEntriesBeforeUpdateByUser.contains(keyword)) { keywordsToAdd.add(keyword); } } KeywordList keywordsToRemove = new KeywordList(); for (Keyword kword : sortedKeywordsOfAllEntriesBeforeUpdateByUser) { if (!userSelectedKeywords.contains(kword)) { keywordsToRemove.add(kword); } } if (keywordsToAdd.isEmpty() && keywordsToRemove.isEmpty()) { // nothing to be done if nothing is new and nothing is obsolete return; } NamedCompound ce = updateKeywords(entries, keywordsToAdd, keywordsToRemove); // TODO: bp.getUndoManager().addEdit(ce); } private NamedCompound updateKeywords(List<BibEntry> entries, KeywordList keywordsToAdd, KeywordList keywordsToRemove) { Character keywordSeparator = bibEntryPreferences.getKeywordSeparator(); NamedCompound ce = new NamedCompound(Localization.lang("Update keywords")); for (BibEntry entry : entries) { KeywordList keywords = entry.getKeywords(keywordSeparator); // update keywords keywords.removeAll(keywordsToRemove); keywords.addAll(keywordsToAdd); // put keywords back Optional<FieldChange> change = entry.putKeywords(keywords, keywordSeparator); change.ifPresent(fieldChange -> ce.addEdit(new UndoableFieldChange(fieldChange))); } ce.end(); return ce; } }
5,228
38.916031
153
java
null
jabref-main/src/main/java/org/jabref/gui/edit/OpenBrowserAction.java
package org.jabref.gui.edit; import org.jabref.gui.DialogService; import org.jabref.gui.actions.SimpleCommand; import org.jabref.gui.desktop.JabRefDesktop; public class OpenBrowserAction extends SimpleCommand { private final String urlToOpen; private final DialogService dialogService; public OpenBrowserAction(String urlToOpen, DialogService dialogService) { this.urlToOpen = urlToOpen; this.dialogService = dialogService; } @Override public void execute() { JabRefDesktop.openBrowserShowPopup(urlToOpen, dialogService); } }
583
25.545455
77
java
null
jabref-main/src/main/java/org/jabref/gui/edit/ReplaceStringAction.java
package org.jabref.gui.edit; import org.jabref.gui.DialogService; import org.jabref.gui.JabRefFrame; import org.jabref.gui.StateManager; import org.jabref.gui.actions.ActionHelper; import org.jabref.gui.actions.SimpleCommand; import com.airhacks.afterburner.injection.Injector; public class ReplaceStringAction extends SimpleCommand { private final JabRefFrame frame; public ReplaceStringAction(JabRefFrame frame, StateManager stateManager) { this.frame = frame; this.executable.bind(ActionHelper.needsDatabase(stateManager)); } @Override public void execute() { DialogService dialogService = Injector.instantiateModelOrService(DialogService.class); dialogService.showCustomDialogAndWait(new ReplaceStringView(frame.getCurrentLibraryTab())); } }
808
30.115385
99
java
null
jabref-main/src/main/java/org/jabref/gui/edit/ReplaceStringView.java
package org.jabref.gui.edit; import javafx.fxml.FXML; import javafx.scene.control.ButtonType; import javafx.scene.control.CheckBox; import javafx.scene.control.RadioButton; import javafx.scene.control.TextField; import org.jabref.gui.LibraryTab; 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 com.airhacks.afterburner.views.ViewLoader; import de.saxsys.mvvmfx.utils.validation.visualization.ControlsFxVisualizer; public class ReplaceStringView extends BaseDialog<Void> { @FXML private RadioButton allReplace; @FXML private CheckBox selectFieldOnly; @FXML private ButtonType replaceButton; @FXML private TextField limitFieldInput; @FXML private TextField findField; @FXML private TextField replaceField; private ReplaceStringViewModel viewModel; private final ControlsFxVisualizer visualizer = new ControlsFxVisualizer(); public ReplaceStringView(LibraryTab libraryTab) { this.setTitle(Localization.lang("Replace String")); viewModel = new ReplaceStringViewModel(libraryTab); ViewLoader.view(this) .load() .setAsDialogPane(this); ControlHelper.setAction(replaceButton, getDialogPane(), event -> buttonReplace()); } @FXML public void initialize() { visualizer.setDecoration(new IconValidationDecorator()); viewModel.findStringProperty().bind(findField.textProperty()); viewModel.replaceStringProperty().bind(replaceField.textProperty()); viewModel.fieldStringProperty().bind(limitFieldInput.textProperty()); viewModel.selectOnlyProperty().bind(selectFieldOnly.selectedProperty()); viewModel.allFieldReplaceProperty().bind(allReplace.selectedProperty()); } @FXML private void buttonReplace() { String findString = findField.getText(); if ("".equals(findString)) { this.close(); return; } viewModel.replace(); this.close(); } }
2,118
31.6
90
java
null
jabref-main/src/main/java/org/jabref/gui/edit/ReplaceStringViewModel.java
package org.jabref.gui.edit; import java.util.Objects; 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.AbstractViewModel; import org.jabref.gui.LibraryTab; import org.jabref.gui.undo.NamedCompound; import org.jabref.gui.undo.UndoableFieldChange; import org.jabref.logic.l10n.Localization; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldFactory; public class ReplaceStringViewModel extends AbstractViewModel { private boolean allFieldReplace; private String findString; private String replaceString; private Set<Field> fields; private LibraryTab panel; private StringProperty findStringProperty = new SimpleStringProperty(); private StringProperty replaceStringProperty = new SimpleStringProperty(); private StringProperty fieldStringProperty = new SimpleStringProperty(); private BooleanProperty allFieldReplaceProperty = new SimpleBooleanProperty(); private BooleanProperty selectOnlyProperty = new SimpleBooleanProperty(); public ReplaceStringViewModel(LibraryTab libraryTab) { Objects.requireNonNull(libraryTab); this.panel = libraryTab; } public int replace() { findString = findStringProperty.getValue(); replaceString = replaceStringProperty.getValue(); fields = FieldFactory.parseFieldList(fieldStringProperty.getValue()); boolean selOnly = selectOnlyProperty.getValue(); allFieldReplace = allFieldReplaceProperty.getValue(); final NamedCompound compound = new NamedCompound(Localization.lang("Replace string")); int counter = 0; if (selOnly) { for (BibEntry bibEntry : this.panel.getSelectedEntries()) { counter += replaceItem(bibEntry, compound); } } else { for (BibEntry bibEntry : this.panel.getDatabase().getEntries()) { counter += replaceItem(bibEntry, compound); } } return counter; } /** * Does the actual operation on a Bibtex entry based on the settings specified in this same dialog. Returns the * number of occurrences replaced. */ private int replaceItem(BibEntry entry, NamedCompound compound) { int counter = 0; if (this.allFieldReplace) { for (Field field : entry.getFields()) { counter += replaceField(entry, field, compound); } } else { for (Field espField : fields) { counter += replaceField(entry, espField, compound); } } return counter; } private int replaceField(BibEntry entry, Field field, NamedCompound compound) { if (!entry.hasField(field)) { return 0; } String txt = entry.getField(field).get(); StringBuilder stringBuilder = new StringBuilder(); int ind; int piv = 0; int counter = 0; int len1 = this.findString.length(); while ((ind = txt.indexOf(this.findString, piv)) >= 0) { counter++; stringBuilder.append(txt, piv, ind); // Text leading up to s1 stringBuilder.append(this.replaceString); // Insert s2 piv = ind + len1; } stringBuilder.append(txt.substring(piv)); String newStr = stringBuilder.toString(); entry.setField(field, newStr); compound.addEdit(new UndoableFieldChange(entry, field, txt, newStr)); return counter; } public BooleanProperty allFieldReplaceProperty() { return allFieldReplaceProperty; } public BooleanProperty selectOnlyProperty() { return selectOnlyProperty; } public StringProperty fieldStringProperty() { return fieldStringProperty; } public StringProperty findStringProperty() { return findStringProperty; } public StringProperty replaceStringProperty() { return replaceStringProperty; } }
4,196
33.975
115
java
null
jabref-main/src/main/java/org/jabref/gui/edit/automaticfiededitor/AbstractAutomaticFieldEditorTabView.java
package org.jabref.gui.edit.automaticfiededitor; import javafx.scene.layout.AnchorPane; public abstract class AbstractAutomaticFieldEditorTabView extends AnchorPane implements AutomaticFieldEditorTab { @Override public AnchorPane getContent() { return this; } }
285
22.833333
113
java
null
jabref-main/src/main/java/org/jabref/gui/edit/automaticfiededitor/AbstractAutomaticFieldEditorTabViewModel.java
package org.jabref.gui.edit.automaticfiededitor; import java.util.Collection; import java.util.Comparator; import java.util.EnumSet; import java.util.HashSet; import java.util.Objects; import java.util.Set; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import org.jabref.gui.AbstractViewModel; import org.jabref.gui.StateManager; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.StandardField; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class AbstractAutomaticFieldEditorTabViewModel extends AbstractViewModel { public static final Logger LOGGER = LoggerFactory.getLogger(AbstractAutomaticFieldEditorTabViewModel.class); protected final StateManager stateManager; private final ObservableList<Field> allFields = FXCollections.observableArrayList(); public AbstractAutomaticFieldEditorTabViewModel(BibDatabase bibDatabase, StateManager stateManager) { Objects.requireNonNull(bibDatabase); Objects.requireNonNull(stateManager); this.stateManager = stateManager; addFields(EnumSet.allOf(StandardField.class)); addFields(bibDatabase.getAllVisibleFields()); allFields.sort(Comparator.comparing(Field::getName)); } public ObservableList<Field> getAllFields() { return allFields; } private void addFields(Collection<? extends Field> fields) { Set<Field> fieldsSet = new HashSet<>(allFields); fieldsSet.addAll(fields); allFields.setAll(fieldsSet); } }
1,614
31.959184
112
java
null
jabref-main/src/main/java/org/jabref/gui/edit/automaticfiededitor/AutomaticFieldEditorAction.java
package org.jabref.gui.edit.automaticfiededitor; import org.jabref.gui.DialogService; import org.jabref.gui.StateManager; import org.jabref.gui.actions.SimpleCommand; import static org.jabref.gui.actions.ActionHelper.needsDatabase; import static org.jabref.gui.actions.ActionHelper.needsEntriesSelected; public class AutomaticFieldEditorAction extends SimpleCommand { private final StateManager stateManager; private final DialogService dialogService; public AutomaticFieldEditorAction(StateManager stateManager, DialogService dialogService) { this.stateManager = stateManager; this.dialogService = dialogService; this.executable.bind(needsDatabase(stateManager).and(needsEntriesSelected(stateManager))); } @Override public void execute() { dialogService.showCustomDialogAndWait(new AutomaticFieldEditorDialog(stateManager)); } }
896
33.5
98
java