From 5b3c78522e2c0a789156fe700d7d40c9a52b71c0 Mon Sep 17 00:00:00 2001 From: Oliver Kopp Date: Sat, 18 Nov 2023 12:28:53 +0100 Subject: [PATCH] Reformat to 100 line length --- .../org/jabref/gui/JabRefDialogService.java | 184 +--- .../org/jabref/gui/JabRefExecutorService.java | 53 +- src/main/java/org/jabref/gui/JabRefFrame.java | 455 +++------ src/main/java/org/jabref/gui/JabRefGUI.java | 60 +- src/main/java/org/jabref/gui/LibraryTab.java | 244 +---- .../java/org/jabref/gui/MainApplication.java | 8 +- src/main/java/org/jabref/gui/MainMenu.java | 33 +- src/main/java/org/jabref/gui/MainToolBar.java | 110 +- .../org/jabref/gui/OpenConsoleAction.java | 10 +- .../org/jabref/gui/SendAsEMailAction.java | 21 +- .../jabref/gui/SendAsKindleEmailAction.java | 10 +- .../jabref/gui/SendAsStandardEmailAction.java | 18 +- .../java/org/jabref/gui/StateManager.java | 104 +- src/main/java/org/jabref/gui/Telemetry.java | 5 +- .../java/org/jabref/gui/TelemetryClient.java | 6 +- .../jabref/gui/UpdateTimestampListener.java | 7 +- .../jabref/gui/WaitForSaveFinishedDialog.java | 7 +- .../jabref/gui/groups/GroupNodeViewModel.java | 93 +- .../gui/groups/GroupTreeNodeViewModel.java | 59 +- .../org/jabref/gui/groups/GroupTreeView.java | 194 +--- .../jabref/gui/groups/GroupTreeViewModel.java | 271 ++--- .../jabref/gui/groups/GroupsPreferences.java | 17 +- .../gui/groups/UndoableAddOrRemoveGroup.java | 19 +- .../gui/groups/UndoableModifySubtree.java | 8 +- .../jabref/gui/groups/UndoableMoveGroup.java | 25 +- .../java/org/jabref/gui/help/AboutAction.java | 4 +- .../jabref/gui/help/AboutDialogViewModel.java | 26 +- .../jabref/gui/help/ErrorConsoleAction.java | 4 +- .../java/org/jabref/gui/help/HelpAction.java | 6 +- .../org/jabref/gui/help/NewVersionDialog.java | 17 +- .../gui/help/SearchForUpdateAction.java | 11 +- .../org/jabref/gui/help/VersionWorker.java | 27 +- .../java/org/jabref/gui/icon/IconTheme.java | 26 +- .../gui/icon/InternalMaterialDesignIcon.java | 11 +- .../org/jabref/gui/icon/JabRefIconView.java | 10 +- .../gui/icon/JabRefMaterialDesignIcon.java | 8 +- .../jabref/gui/icon/JabrefIconProvider.java | 3 +- .../BibEntryTypePrefsAndFileViewModel.java | 4 +- .../importer/GenerateEntryFromIdAction.java | 30 +- .../importer/GenerateEntryFromIdDialog.java | 25 +- .../gui/importer/GrobidOptInDialogHelper.java | 17 +- .../jabref/gui/importer/ImportCommand.java | 84 +- .../ImportCustomEntryTypesDialog.java | 42 +- ...ImportCustomEntryTypesDialogViewModel.java | 39 +- .../gui/importer/ImportEntriesDialog.java | 66 +- .../gui/importer/ImportEntriesViewModel.java | 121 +-- .../gui/importer/NewDatabaseAction.java | 9 +- .../jabref/gui/importer/NewEntryAction.java | 20 +- .../importer/ParserResultWarningDialog.java | 4 +- .../actions/CheckForNewEntryTypesAction.java | 33 +- .../actions/MergeReviewIntoCommentAction.java | 15 +- ...geReviewIntoCommentConfirmationDialog.java | 8 +- .../importer/actions/OpenDatabaseAction.java | 78 +- .../fetcher/LookupIdentifierAction.java | 31 +- .../importer/fetcher/WebSearchPaneView.java | 33 +- .../fetcher/WebSearchPaneViewModel.java | 51 +- .../gui/integrity/IntegrityCheckAction.java | 18 +- .../gui/integrity/IntegrityCheckDialog.java | 27 +- .../jabref/gui/journals/AbbreviateAction.java | 48 +- .../gui/journals/UndoableAbbreviator.java | 18 +- .../gui/journals/UndoableUnabbreviator.java | 21 +- .../gui/keyboard/CodeAreaKeyBindings.java | 82 +- .../org/jabref/gui/keyboard/KeyBinding.java | 98 +- .../gui/keyboard/KeyBindingRepository.java | 29 +- .../gui/keyboard/TextInputKeyBindings.java | 30 +- .../AbstractPropertiesTabView.java | 4 +- .../LibraryPropertiesAction.java | 12 +- .../LibraryPropertiesView.java | 7 +- .../constants/ConstantsItemModel.java | 37 +- .../constants/ConstantsPropertiesView.java | 53 +- .../ConstantsPropertiesViewModel.java | 39 +- .../contentselectors/ContentSelectorView.java | 35 +- .../ContentSelectorViewModel.java | 43 +- .../general/GeneralPropertiesView.java | 31 +- .../general/GeneralPropertiesViewModel.java | 91 +- .../keypattern/KeyPatternPropertiesView.java | 16 +- .../KeyPatternPropertiesViewModel.java | 52 +- .../preamble/PreamblePropertiesView.java | 6 +- .../preamble/PreamblePropertiesViewModel.java | 21 +- .../saving/SavingPropertiesView.java | 11 +- .../saving/SavingPropertiesViewModel.java | 73 +- .../gui/linkedfile/AttachFileAction.java | 35 +- .../linkedfile/AttachFileFromURLAction.java | 21 +- .../gui/linkedfile/DeleteFileAction.java | 57 +- .../linkedfile/LinkedFileEditDialogView.java | 16 +- .../LinkedFilesEditDialogViewModel.java | 77 +- .../gui/maintable/BibEntryTableViewModel.java | 76 +- .../org/jabref/gui/maintable/CellFactory.java | 5 +- .../gui/maintable/ColumnPreferences.java | 3 +- .../org/jabref/gui/maintable/MainTable.java | 72 +- .../gui/maintable/MainTableColumnFactory.java | 77 +- .../gui/maintable/MainTableColumnModel.java | 27 +- .../gui/maintable/MainTableDataModel.java | 51 +- .../MainTableFieldValueFormatter.java | 26 +- .../maintable/MainTableHeaderContextMenu.java | 93 +- .../gui/maintable/MainTablePreferences.java | 6 +- .../gui/maintable/NameDisplayPreferences.java | 8 +- .../gui/maintable/OpenExternalFileAction.java | 53 +- .../gui/maintable/OpenFolderAction.java | 48 +- .../jabref/gui/maintable/OpenUrlAction.java | 29 +- .../PersistenceVisualStateTable.java | 13 +- .../jabref/gui/maintable/RightClickMenu.java | 50 +- .../maintable/SearchShortScienceAction.java | 11 +- .../SmartConstrainedResizePolicy.java | 19 +- .../gui/maintable/columns/FieldColumn.java | 9 +- .../gui/maintable/columns/FileColumn.java | 55 +- .../gui/maintable/columns/LibraryColumn.java | 4 +- .../columns/LinkedIdentifierColumn.java | 29 +- .../maintable/columns/SpecialFieldColumn.java | 50 +- .../gui/menus/ChangeEntryTypeAction.java | 19 +- .../jabref/gui/menus/ChangeEntryTypeMenu.java | 31 +- .../org/jabref/gui/menus/FileHistoryMenu.java | 8 +- .../gui/mergeentries/DiffHighlighting.java | 36 +- .../DiffHighlightingEllipsingTextFlow.java | 53 +- .../gui/mergeentries/FetchAndMergeEntry.java | 117 +-- .../gui/mergeentries/MergeEntriesAction.java | 26 +- .../gui/mergeentries/MergeEntriesDialog.java | 10 +- .../jabref/gui/mergeentries/MergeResult.java | 6 +- .../mergeentries/MergeTwoEntriesAction.java | 14 +- .../MergeWithFetchedEntryAction.java | 10 +- .../mergeentries/MultiMergeEntriesView.java | 150 +-- .../MultiMergeEntriesViewModel.java | 46 +- .../newmergedialog/FieldRowView.java | 111 +- .../newmergedialog/FieldRowViewModel.java | 40 +- .../PersonsNameFieldRowView.java | 5 +- .../newmergedialog/ShowDiffConfig.java | 5 +- .../ThreeWayMergeHeaderView.java | 13 +- .../newmergedialog/ThreeWayMergeView.java | 76 +- .../ThreeWayMergeViewModel.java | 17 +- .../cell/CopyFieldValueCommand.java | 5 +- .../newmergedialog/cell/FieldValueCell.java | 33 +- .../cell/FieldValueCellViewModel.java | 3 +- .../newmergedialog/cell/HeaderCell.java | 7 +- .../newmergedialog/cell/MergedFieldCell.java | 4 +- .../cell/OpenExternalLinkAction.java | 21 +- .../cell/ThreeWayMergeCell.java | 10 +- .../cell/ThreeWayMergeCellViewModel.java | 10 +- .../cell/sidebuttons/InfoButton.java | 9 +- .../sidebuttons/ToggleMergeUnmergeButton.java | 23 +- .../diffhighlighter/DiffHighlighter.java | 13 +- .../diffhighlighter/SplitDiffHighlighter.java | 29 +- .../UnifiedDiffHighlighter.java | 66 +- .../fieldsmerger/FieldMergerFactory.java | 3 +- .../fieldsmerger/GroupMerger.java | 10 +- .../fieldsmerger/KeywordMerger.java | 4 +- .../toolbar/ThreeWayMergeToolbar.java | 51 +- .../openoffice/AdvancedCiteDialogView.java | 11 +- .../org/jabref/gui/openoffice/Bootstrap.java | 124 +-- .../openoffice/CitationEntryViewModel.java | 16 +- .../DetectOpenOfficeInstallation.java | 39 +- .../openoffice/ManageCitationsDialogView.java | 23 +- .../ManageCitationsDialogViewModel.java | 16 +- .../org/jabref/gui/openoffice/OOBibBase.java | 362 ++----- .../gui/openoffice/OOBibBaseConnect.java | 51 +- .../org/jabref/gui/openoffice/OOError.java | 29 +- .../gui/openoffice/OpenOfficePanel.java | 319 ++---- .../gui/openoffice/StyleSelectDialogView.java | 36 +- .../StyleSelectDialogViewModel.java | 52 +- .../openoffice/StyleSelectItemViewModel.java | 7 +- .../AbstractPreferenceTabView.java | 4 +- .../preferences/PreferencesDialogView.java | 30 +- .../PreferencesDialogViewModel.java | 89 +- .../preferences/PreferencesFilterDialog.java | 38 +- .../preferences/PreferencesSearchHandler.java | 31 +- .../preferences/ShowPreferencesAction.java | 9 +- .../autocompletion/AutoCompletionTab.java | 13 +- .../AutoCompletionTabViewModel.java | 93 +- .../CitationKeyPatternTab.java | 40 +- .../CitationKeyPatternTabViewModel.java | 125 +-- .../CustomEntryTypeViewModel.java | 5 +- .../customentrytypes/CustomEntryTypesTab.java | 92 +- .../CustomEntryTypesTabViewModel.java | 68 +- .../customentrytypes/EntryTypeViewModel.java | 21 +- .../customentrytypes/FieldViewModel.java | 3 +- .../customexporter/CustomExporterTab.java | 15 +- .../CustomExporterTabViewModel.java | 29 +- .../customimporter/CustomImporterTab.java | 23 +- .../CustomImporterTabViewModel.java | 93 +- .../gui/preferences/entry/EntryTab.java | 42 +- .../preferences/entry/EntryTabViewModel.java | 82 +- .../entryeditor/EntryEditorTab.java | 27 +- .../entryeditor/EntryEditorTabViewModel.java | 96 +- .../gui/preferences/export/ExportTab.java | 11 +- .../export/ExportTabViewModel.java | 33 +- .../gui/preferences/external/ExternalTab.java | 26 +- .../external/ExternalTabViewModel.java | 107 +- .../EditExternalFileTypeEntryDialog.java | 21 +- .../EditExternalFileTypeViewModel.java | 44 +- .../ExternalFileTypeItemViewModel.java | 14 +- .../ExternalFileTypesTab.java | 61 +- .../ExternalFileTypesTabViewModel.java | 16 +- .../gui/preferences/general/GeneralTab.java | 98 +- .../general/GeneralTabViewModel.java | 218 ++-- .../gui/preferences/groups/GroupsTab.java | 11 +- .../groups/GroupsTabViewModel.java | 28 +- .../journals/AbbreviationViewModel.java | 31 +- .../journals/AbbreviationsFileViewModel.java | 9 +- .../journals/JournalAbbreviationsTab.java | 99 +- .../JournalAbbreviationsTabViewModel.java | 166 +-- .../keybindings/KeyBindingViewModel.java | 29 +- .../keybindings/KeyBindingsTab.java | 47 +- .../keybindings/KeyBindingsTabViewModel.java | 48 +- .../linkedfiles/LinkedFilesTab.java | 42 +- .../linkedfiles/LinkedFilesTabViewModel.java | 90 +- .../nameformatter/NameFormatterTab.java | 63 +- .../NameFormatterTabViewModel.java | 18 +- .../network/CustomCertificateViewModel.java | 24 +- .../gui/preferences/network/NetworkTab.java | 113 +- .../network/NetworkTabViewModel.java | 147 +-- .../gui/preferences/preview/PreviewTab.java | 135 +-- .../preview/PreviewTabViewModel.java | 235 ++--- .../NewProtectedTermsFileDialog.java | 37 +- .../protectedterms/ProtectedTermsTab.java | 96 +- .../ProtectedTermsTabViewModel.java | 83 +- .../gui/preferences/table/TableTab.java | 70 +- .../preferences/table/TableTabViewModel.java | 180 +--- .../preferences/websearch/WebSearchTab.java | 70 +- .../websearch/WebSearchTabViewModel.java | 101 +- .../gui/preferences/xmp/XmpPrivacyTab.java | 54 +- .../xmp/XmpPrivacyTabViewModel.java | 45 +- .../gui/preview/CopyCitationAction.java | 55 +- .../org/jabref/gui/preview/PreviewPanel.java | 47 +- .../org/jabref/gui/preview/PreviewViewer.java | 67 +- .../gui/push/AbstractPushToApplication.java | 61 +- .../jabref/gui/push/PushToApplication.java | 6 +- .../gui/push/PushToApplicationCommand.java | 49 +- .../gui/push/PushToApplicationSettings.java | 20 +- .../jabref/gui/push/PushToApplications.java | 7 +- .../java/org/jabref/gui/push/PushToEmacs.java | 32 +- .../jabref/gui/push/PushToEmacsSettings.java | 6 +- .../java/org/jabref/gui/push/PushToLyx.java | 16 +- .../jabref/gui/push/PushToSublimeText.java | 30 +- .../org/jabref/gui/push/PushToTeXstudio.java | 12 +- .../org/jabref/gui/push/PushToTexShop.java | 34 +- .../org/jabref/gui/push/PushToTexmaker.java | 5 +- .../java/org/jabref/gui/push/PushToVim.java | 19 +- .../jabref/gui/push/PushToVimSettings.java | 6 +- .../org/jabref/gui/push/PushToWinEdt.java | 5 +- .../jabref/gui/remote/CLIMessageHandler.java | 4 +- .../jabref/gui/search/GlobalSearchBar.java | 212 ++-- .../gui/search/GlobalSearchResultDialog.java | 28 +- .../GlobalSearchResultDialogViewModel.java | 15 +- .../RebuildFulltextSearchIndexAction.java | 21 +- .../jabref/gui/search/SearchDisplayMode.java | 15 +- .../gui/search/SearchFieldRightClickMenu.java | 26 +- .../jabref/gui/search/SearchResultsTable.java | 37 +- .../search/SearchResultsTableDataModel.java | 37 +- .../jabref/gui/search/SearchTextField.java | 3 +- ...tainsAndRegexBasedSearchRuleDescriber.java | 14 +- .../GrammarBasedSearchRuleDescriber.java | 136 +-- .../rules/describer/SearchDescribers.java | 17 +- .../ConnectToSharedDatabaseCommand.java | 8 +- .../shared/PullChangesFromSharedAction.java | 3 +- .../shared/SharedDatabaseLoginDialogView.java | 82 +- .../SharedDatabaseLoginDialogViewModel.java | 254 ++--- .../gui/shared/SharedDatabaseUIManager.java | 133 +-- .../gui/sidepane/GroupsSidePaneComponent.java | 28 +- .../org/jabref/gui/sidepane/SidePane.java | 3 +- .../gui/sidepane/SidePaneComponent.java | 11 +- .../gui/sidepane/SidePaneContentFactory.java | 6 +- .../gui/sidepane/SidePaneViewModel.java | 34 +- .../jabref/gui/sidepane/TogglePaneAction.java | 6 +- .../gui/slr/EditExistingStudyAction.java | 26 +- .../gui/slr/ExistingStudySearchAction.java | 27 +- .../gui/slr/ManageStudyDefinitionView.java | 66 +- .../slr/ManageStudyDefinitionViewModel.java | 75 +- .../jabref/gui/slr/StartNewStudyAction.java | 31 +- .../org/jabref/gui/slr/StudyCatalogItem.java | 9 +- .../gui/specialfields/SpecialFieldAction.java | 41 +- .../SpecialFieldMenuItemFactory.java | 33 +- .../SpecialFieldValueViewModel.java | 4 +- .../specialfields/SpecialFieldViewModel.java | 9 +- .../SpecialFieldsPreferences.java | 3 +- .../gui/texparser/CitationsDisplay.java | 26 +- .../gui/texparser/ParseLatexAction.java | 8 +- .../gui/texparser/ParseLatexDialogView.java | 33 +- .../texparser/ParseLatexDialogViewModel.java | 58 +- .../gui/texparser/ParseLatexResultView.java | 10 +- .../texparser/ParseLatexResultViewModel.java | 18 +- .../java/org/jabref/gui/theme/StyleSheet.java | 12 +- .../org/jabref/gui/theme/StyleSheetFile.java | 17 +- .../org/jabref/gui/theme/ThemeManager.java | 93 +- .../gui/undo/AbstractUndoableJabRefEdit.java | 16 +- .../org/jabref/gui/undo/UndoRedoAction.java | 12 +- .../jabref/gui/undo/UndoableChangeType.java | 15 +- .../jabref/gui/undo/UndoableFieldChange.java | 22 +- .../gui/undo/UndoableInsertEntries.java | 20 +- .../jabref/gui/undo/UndoableInsertString.java | 9 +- .../gui/undo/UndoablePreambleChange.java | 6 +- .../gui/undo/UndoableRemoveEntries.java | 20 +- .../jabref/gui/undo/UndoableRemoveString.java | 9 +- .../org/jabref/gui/util/BackgroundTask.java | 54 +- .../java/org/jabref/gui/util/BaseDialog.java | 18 +- .../org/jabref/gui/util/BindingsHelper.java | 77 +- .../org/jabref/gui/util/ControlHelper.java | 33 +- .../gui/util/CurrentThreadTaskExecutor.java | 13 +- .../jabref/gui/util/CustomLocalDragboard.java | 11 +- .../jabref/gui/util/CustomTitledPaneSkin.java | 61 +- .../gui/util/DefaultFileUpdateMonitor.java | 22 +- .../jabref/gui/util/DefaultTaskExecutor.java | 36 +- .../java/org/jabref/gui/util/FieldsUtil.java | 51 +- .../gui/util/FileDialogConfiguration.java | 39 +- .../jabref/gui/util/FileFilterConverter.java | 50 +- .../jabref/gui/util/FileNodeViewModel.java | 16 +- .../gui/util/IconValidationDecorator.java | 16 +- .../gui/util/JabRefResourceLocator.java | 4 +- .../gui/util/OptionalObjectProperty.java | 3 +- .../util/OptionalValueTableCellFactory.java | 7 +- .../jabref/gui/util/RecursiveTreeItem.java | 17 +- .../org/jabref/gui/util/StreamGobbler.java | 15 +- .../org/jabref/gui/util/TooltipTextUtil.java | 64 +- .../org/jabref/gui/util/UiThreadList.java | 8 +- .../gui/util/ValueTableCellFactory.java | 58 +- .../gui/util/ViewModelListCellFactory.java | 80 +- .../gui/util/ViewModelTableRowFactory.java | 56 +- ...extFieldTableCellVisualizationFactory.java | 27 +- .../gui/util/ViewModelTreeCellFactory.java | 38 +- .../util/ViewModelTreeTableCellFactory.java | 24 +- .../util/ViewModelTreeTableRowFactory.java | 106 +- .../org/jabref/gui/util/ZipFileChooser.java | 39 +- .../comparator/NumericFieldComparator.java | 5 +- .../comparator/RankingFieldComparator.java | 8 +- .../comparator/SpecialFieldComparator.java | 3 +- .../component/TemporalAccessorPicker.java | 68 +- .../uithreadaware/UiThreadChangeListener.java | 6 +- .../UiThreadInvalidationListener.java | 4 +- .../java/org/jabref/http/JabrefMediaType.java | 3 +- .../java/org/jabref/http/dto/BibEntryDTO.java | 11 +- .../org/jabref/http/server/Application.java | 10 +- .../org/jabref/http/server/CORSFilter.java | 22 +- .../jabref/http/server/LibrariesResource.java | 4 +- .../jabref/http/server/LibraryResource.java | 29 +- .../java/org/jabref/http/server/Server.java | 22 +- .../org/jabref/logic/JabRefException.java | 14 +- .../java/org/jabref/logic/TypedBibEntry.java | 14 +- .../logic/auxparser/DefaultAuxParser.java | 33 +- .../jabref/logic/bibtex/BibEntryWriter.java | 58 +- .../jabref/logic/bibtex/FieldPreferences.java | 6 +- .../org/jabref/logic/bibtex/FieldWriter.java | 37 +- .../jabref/logic/bibtex/FileFieldWriter.java | 11 +- .../bibtex/comparator/BibDatabaseDiff.java | 56 +- .../bibtex/comparator/BibStringDiff.java | 16 +- .../bibtex/comparator/EntryComparator.java | 18 +- .../bibtex/comparator/FieldComparator.java | 6 +- .../comparator/FieldComparatorStack.java | 4 +- .../logic/bibtex/comparator/GroupDiff.java | 15 +- .../logic/bibtex/comparator/MetaDataDiff.java | 9 +- .../logic/bibtex/comparator/PreambleDiff.java | 9 +- .../org/jabref/logic/bst/BstFunctions.java | 143 +-- .../jabref/logic/bst/BstPreviewLayout.java | 15 +- src/main/java/org/jabref/logic/bst/BstVM.java | 24 +- .../org/jabref/logic/bst/BstVMContext.java | 6 +- .../org/jabref/logic/bst/BstVMVisitor.java | 56 +- .../jabref/logic/bst/util/BstCaseChanger.java | 33 +- .../logic/bst/util/BstNameFormatter.java | 60 +- .../jabref/logic/bst/util/BstPurifier.java | 17 +- .../logic/bst/util/BstTextPrefixer.java | 9 +- .../logic/bst/util/BstWidthCalculator.java | 20 +- .../AbstractCitationKeyPattern.java | 10 +- .../citationkeypattern/BracketedPattern.java | 281 ++--- .../CitationKeyGenerator.java | 59 +- .../CitationKeyPatternPreferences.java | 42 +- .../DatabaseCitationKeyPattern.java | 4 +- .../logic/citationstyle/CSLAdapter.java | 14 +- .../logic/citationstyle/CitationStyle.java | 70 +- .../citationstyle/CitationStyleCache.java | 9 +- .../citationstyle/CitationStyleGenerator.java | 16 +- .../CitationStylePreviewLayout.java | 5 +- .../citationstyle/JabRefItemDataProvider.java | 62 +- .../citationstyle/JabRefLocaleProvider.java | 14 +- .../jabref/logic/cleanup/CleanupWorker.java | 29 +- .../cleanup/ConvertToBiblatexCleanup.java | 29 +- .../logic/cleanup/ConvertToBibtexCleanup.java | 22 +- .../org/jabref/logic/cleanup/DoiCleanup.java | 22 +- .../jabref/logic/cleanup/EprintCleanup.java | 13 +- .../logic/cleanup/FieldFormatterCleanup.java | 23 +- .../logic/cleanup/FieldFormatterCleanups.java | 83 +- .../logic/cleanup/MoveFilesCleanup.java | 15 +- .../logic/cleanup/RenamePdfCleanup.java | 10 +- .../cleanup/TimeStampToCreationDate.java | 24 +- .../cleanup/TimeStampToModificationDate.java | 28 +- .../org/jabref/logic/cleanup/URLCleanup.java | 55 +- .../cleanup/UpgradePdfPsToFileCleanup.java | 18 +- .../org/jabref/logic/crawler/Crawler.java | 3 +- .../StudyCatalogToFetcherConverter.java | 17 +- .../jabref/logic/crawler/StudyFetcher.java | 30 +- .../jabref/logic/crawler/StudyRepository.java | 160 +-- .../jabref/logic/crawler/StudyYamlParser.java | 9 +- .../jabref/logic/database/DatabaseMerger.java | 26 +- .../jabref/logic/database/DuplicateCheck.java | 121 +-- .../exporter/AtomicFileOutputStream.java | 36 +- .../logic/exporter/AtomicFileWriter.java | 3 +- .../logic/exporter/BibDatabaseWriter.java | 127 +-- .../logic/exporter/BibtexDatabaseWriter.java | 54 +- .../exporter/EmbeddedBibFilePdfExporter.java | 49 +- .../org/jabref/logic/exporter/Exporter.java | 5 +- .../logic/exporter/ExporterFactory.java | 13 +- .../logic/exporter/GroupSerializer.java | 32 +- .../jabref/logic/exporter/MSBibExporter.java | 20 +- .../logic/exporter/MetaDataSerializer.java | 78 +- .../jabref/logic/exporter/ModsExporter.java | 135 +-- .../jabref/logic/exporter/OOCalcDatabase.java | 31 +- .../exporter/OpenDocumentRepresentation.java | 79 +- .../OpenDocumentSpreadsheetCreator.java | 45 +- .../exporter/OpenOfficeDocumentCreator.java | 36 +- .../logic/exporter/SaveConfiguration.java | 4 +- .../jabref/logic/exporter/SaveException.java | 11 +- .../logic/exporter/TemplateExporter.java | 84 +- .../jabref/logic/exporter/XmpExporter.java | 18 +- .../jabref/logic/exporter/XmpPdfExporter.java | 29 +- .../ExternalFilesContentImporter.java | 19 +- .../externalfiles/LinkedFileHandler.java | 58 +- .../jabref/logic/formatter/Formatters.java | 9 +- .../bibtexfields/AddBracesFormatter.java | 4 +- .../bibtexfields/CleanupUrlFormatter.java | 8 +- .../EscapeAmpersandsFormatter.java | 8 +- .../EscapeDollarSignFormatter.java | 5 +- .../bibtexfields/HtmlToLatexFormatter.java | 66 +- .../bibtexfields/HtmlToUnicodeFormatter.java | 8 +- .../bibtexfields/LatexCleanupFormatter.java | 29 +- .../bibtexfields/NormalizeMonthFormatter.java | 4 +- .../bibtexfields/NormalizeNamesFormatter.java | 4 +- .../bibtexfields/NormalizePagesFormatter.java | 11 +- .../OrdinalsToSuperscriptFormatter.java | 3 +- .../bibtexfields/RegexFormatter.java | 51 +- .../bibtexfields/RemoveBracesFormatter.java | 4 +- .../RemoveHyphenatedNewlinesFormatter.java | 4 +- .../bibtexfields/RemoveNewlinesFormatter.java | 4 +- .../ReplaceTabsBySpaceFormater.java | 4 +- .../bibtexfields/ShortenDOIFormatter.java | 4 +- .../bibtexfields/TrimWhitespaceFormatter.java | 4 +- .../bibtexfields/UnicodeToLatexFormatter.java | 29 +- .../bibtexfields/UnitsToLatexFormatter.java | 20 +- .../casechanger/SentenceCaseFormatter.java | 4 +- .../logic/formatter/casechanger/Title.java | 5 +- .../casechanger/TitleCaseFormatter.java | 6 +- .../formatter/casechanger/TitleParser.java | 8 +- .../casechanger/UnprotectTermsFormatter.java | 4 +- .../logic/formatter/casechanger/Word.java | 16 +- .../minifier/MinifyNameListFormatter.java | 5 +- .../java/org/jabref/logic/git/GitHandler.java | 49 +- .../org/jabref/logic/git/SlrGitHandler.java | 47 +- .../logic/groups/DefaultGroupsFactory.java | 7 +- .../java/org/jabref/logic/help/HelpFile.java | 32 +- .../logic/importer/AuthorListParser.java | 115 +-- .../logic/importer/CompositeIdFetcher.java | 15 +- .../importer/EntryBasedParserFetcher.java | 9 +- .../importer/FetcherClientException.java | 12 +- .../logic/importer/FetcherException.java | 6 +- .../importer/FetcherServerException.java | 12 +- .../logic/importer/FulltextFetcher.java | 3 +- .../logic/importer/FulltextFetchers.java | 51 +- .../jabref/logic/importer/IdBasedFetcher.java | 3 +- .../logic/importer/IdBasedParserFetcher.java | 8 +- .../logic/importer/IdParserFetcher.java | 12 +- .../logic/importer/ImportCleanupBibtex.java | 3 +- .../logic/importer/ImportFormatReader.java | 46 +- .../org/jabref/logic/importer/Importer.java | 55 +- .../logic/importer/ImporterPreferences.java | 13 +- .../jabref/logic/importer/OpenDatabase.java | 5 +- .../importer/PagedSearchBasedFetcher.java | 13 +- .../PagedSearchBasedParserFetcher.java | 21 +- .../org/jabref/logic/importer/Parser.java | 9 +- .../jabref/logic/importer/ParserResult.java | 9 +- .../jabref/logic/importer/QueryParser.java | 10 +- .../logic/importer/SearchBasedFetcher.java | 7 +- .../importer/SearchBasedParserFetcher.java | 13 +- .../jabref/logic/importer/WebFetchers.java | 63 +- .../importer/fetcher/ACMPortalFetcher.java | 7 +- .../jabref/logic/importer/fetcher/ACS.java | 4 +- .../importer/fetcher/AbstractIsbnFetcher.java | 11 +- .../logic/importer/fetcher/ApsFetcher.java | 8 +- .../logic/importer/fetcher/ArXivFetcher.java | 344 ++----- .../fetcher/AstrophysicsDataSystem.java | 99 +- .../importer/fetcher/BibsonomyScraper.java | 12 +- .../importer/fetcher/BiodiversityLibrary.java | 100 +- .../logic/importer/fetcher/BvbFetcher.java | 6 +- .../logic/importer/fetcher/CiteSeer.java | 13 +- ...fComputerScienceBibliographiesFetcher.java | 36 +- ...OfComputerScienceBibliographiesParser.java | 29 +- .../importer/fetcher/ComplexSearchQuery.java | 78 +- .../fetcher/CompositeSearchBasedFetcher.java | 24 +- .../logic/importer/fetcher/CrossRef.java | 76 +- .../logic/importer/fetcher/DBLPFetcher.java | 16 +- .../logic/importer/fetcher/DOABFetcher.java | 68 +- .../logic/importer/fetcher/DOAJFetcher.java | 58 +- .../jabref/logic/importer/fetcher/DiVA.java | 4 +- .../logic/importer/fetcher/DoiFetcher.java | 91 +- .../logic/importer/fetcher/DoiResolution.java | 31 +- .../logic/importer/fetcher/GoogleScholar.java | 98 +- .../fetcher/GrobidCitationFetcher.java | 17 +- .../importer/fetcher/GrobidPreferences.java | 6 +- .../logic/importer/fetcher/GvkFetcher.java | 26 +- .../jabref/logic/importer/fetcher/IEEE.java | 122 +-- .../importer/fetcher/INSPIREFetcher.java | 44 +- .../importer/fetcher/IacrEprintFetcher.java | 85 +- .../logic/importer/fetcher/IssnFetcher.java | 15 +- .../fetcher/JournalInformationFetcher.java | 92 +- .../logic/importer/fetcher/JstorFetcher.java | 25 +- .../logic/importer/fetcher/LOBIDFetcher.java | 57 +- .../importer/fetcher/LibraryOfCongress.java | 4 +- .../logic/importer/fetcher/MathSciNet.java | 68 +- .../importer/fetcher/MedlineFetcher.java | 69 +- .../jabref/logic/importer/fetcher/Medra.java | 19 +- .../logic/importer/fetcher/MrDLibFetcher.java | 34 +- .../logic/importer/fetcher/OpenAccessDoi.java | 13 +- .../logic/importer/fetcher/ResearchGate.java | 67 +- .../logic/importer/fetcher/RfcFetcher.java | 4 +- .../fetcher/ScholarArchiveFetcher.java | 52 +- .../logic/importer/fetcher/ScienceDirect.java | 45 +- .../importer/fetcher/SemanticScholar.java | 67 +- .../importer/fetcher/SpringerFetcher.java | 92 +- .../logic/importer/fetcher/SpringerLink.java | 26 +- .../logic/importer/fetcher/TitleFetcher.java | 7 +- .../jabref/logic/importer/fetcher/ZbMATH.java | 50 +- .../DoiToBibtexConverterComIsbnFetcher.java | 52 +- .../isbntobibtex/EbookDeIsbnFetcher.java | 23 +- .../fetcher/isbntobibtex/IsbnFetcher.java | 36 +- .../isbntobibtex/OpenLibraryIsbnFetcher.java | 30 +- .../AbstractQueryTransformer.java | 23 +- .../transformers/ArXivQueryTransformer.java | 3 +- .../CiteSeerQueryTransformer.java | 5 +- .../transformers/DBLPQueryTransformer.java | 7 +- .../transformers/DefaultQueryTransformer.java | 3 +- .../transformers/GVKQueryTransformer.java | 13 +- .../transformers/IEEEQueryTransformer.java | 21 +- .../transformers/MedlineQueryTransformer.java | 7 +- .../transformers/ScholarQueryTransformer.java | 3 +- .../YearRangeByFilteringQueryTransformer.java | 11 +- .../importer/fileformat/ACMPortalParser.java | 114 +-- .../fileformat/BiblioscapeImporter.java | 77 +- .../importer/fileformat/BibtexImporter.java | 53 +- .../importer/fileformat/BibtexParser.java | 117 +-- .../importer/fileformat/CffImporter.java | 20 +- .../fileformat/CitaviXmlImporter.java | 183 +--- .../importer/fileformat/CiteSeerParser.java | 17 +- .../importer/fileformat/CoinsParser.java | 10 +- .../importer/fileformat/CopacImporter.java | 18 +- .../importer/fileformat/CustomImporter.java | 10 +- .../importer/fileformat/EndnoteImporter.java | 17 +- .../fileformat/EndnoteXmlImporter.java | 218 +--- .../importer/fileformat/InspecImporter.java | 13 +- .../importer/fileformat/IsiImporter.java | 45 +- .../importer/fileformat/MarcXmlParser.java | 118 +-- .../importer/fileformat/MedlineImporter.java | 501 ++------- .../fileformat/MedlinePlainImporter.java | 74 +- .../importer/fileformat/ModsImporter.java | 322 ++---- .../importer/fileformat/MrDLibImporter.java | 41 +- .../importer/fileformat/MsBibImporter.java | 35 +- .../importer/fileformat/OvidImporter.java | 58 +- .../fileformat/PdfContentImporter.java | 65 +- .../PdfEmbeddedBibFileImporter.java | 64 +- .../fileformat/PdfGrobidImporter.java | 22 +- .../fileformat/PdfMergeMetadataImporter.java | 51 +- .../PdfVerbatimBibTextImporter.java | 22 +- .../importer/fileformat/PdfXmpImporter.java | 10 +- .../importer/fileformat/PicaXmlParser.java | 27 +- .../importer/fileformat/RepecNepImporter.java | 57 +- .../importer/fileformat/RisImporter.java | 93 +- .../fileformat/SilverPlatterImporter.java | 47 +- .../fileformat/medline/Investigator.java | 6 +- .../logic/importer/util/FileFieldParser.java | 23 +- .../logic/importer/util/GrobidService.java | 35 +- .../logic/importer/util/GroupsParser.java | 169 +-- .../logic/importer/util/IdentifierParser.java | 8 +- .../logic/importer/util/JsonReader.java | 16 +- .../logic/importer/util/MathMLParser.java | 14 +- .../logic/importer/util/MediaTypes.java | 3 +- .../logic/importer/util/MetaDataParser.java | 126 +-- .../logic/importer/util/ShortDOIService.java | 4 +- .../util/ShortDOIServiceException.java | 6 +- .../logic/importer/util/StaxParser.java | 16 +- .../integrity/ASCIICharacterChecker.java | 4 +- .../logic/integrity/AbbreviationChecker.java | 4 +- .../logic/integrity/AmpersandChecker.java | 13 +- .../logic/integrity/BibStringChecker.java | 4 +- .../logic/integrity/BooktitleChecker.java | 4 +- .../logic/integrity/BracketChecker.java | 8 +- .../logic/integrity/CitationKeyChecker.java | 4 +- .../CitationKeyDeviationChecker.java | 7 +- .../CitationKeyDuplicationChecker.java | 4 +- .../integrity/DoiDuplicationChecker.java | 8 +- .../logic/integrity/EditionChecker.java | 40 +- .../logic/integrity/EntryLinkChecker.java | 16 +- .../jabref/logic/integrity/FieldCheckers.java | 38 +- .../jabref/logic/integrity/FileChecker.java | 11 +- .../logic/integrity/HTMLCharacterChecker.java | 12 +- .../logic/integrity/HowPublishedChecker.java | 9 +- .../logic/integrity/IntegrityCheck.java | 9 +- .../JournalInAbbreviationListChecker.java | 3 +- .../integrity/LatexIntegrityChecker.java | 64 +- .../jabref/logic/integrity/MonthChecker.java | 19 +- .../logic/integrity/NoBibtexFieldChecker.java | 7 +- .../jabref/logic/integrity/NoteChecker.java | 7 +- .../jabref/logic/integrity/PagesChecker.java | 7 +- .../logic/integrity/PersonNamesChecker.java | 6 +- .../jabref/logic/integrity/TitleChecker.java | 16 +- .../jabref/logic/integrity/TypeChecker.java | 4 +- .../jabref/logic/integrity/UTF8Checker.java | 4 +- .../jabref/logic/integrity/YearChecker.java | 12 +- .../jabref/logic/journals/Abbreviation.java | 24 +- .../logic/journals/AbbreviationParser.java | 18 +- .../logic/journals/AbbreviationWriter.java | 11 +- .../journals/JournalAbbreviationLoader.java | 26 +- .../JournalAbbreviationPreferences.java | 3 +- .../JournalAbbreviationRepository.java | 72 +- .../org/jabref/logic/l10n/Localization.java | 50 +- .../logic/l10n/LocalizationKeyParams.java | 10 +- .../layout/AbstractParamLayoutFormatter.java | 8 +- .../java/org/jabref/logic/layout/Layout.java | 14 +- .../org/jabref/logic/layout/LayoutEntry.java | 122 +-- .../layout/LayoutFormatterPreferences.java | 12 +- .../org/jabref/logic/layout/LayoutHelper.java | 53 +- .../logic/layout/TextBasedPreviewLayout.java | 15 +- .../layout/format/AuthorFirstFirstCommas.java | 6 +- .../layout/format/AuthorFirstLastCommas.java | 6 +- .../jabref/logic/layout/format/Authors.java | 42 +- .../layout/format/CreateBibORDFAuthors.java | 11 +- .../layout/format/CreateDocBook4Authors.java | 7 +- .../layout/format/CreateDocBook4Editors.java | 7 +- .../layout/format/CreateDocBook5Authors.java | 7 +- .../layout/format/CreateDocBook5Editors.java | 7 +- .../logic/layout/format/DateFormatter.java | 5 +- .../jabref/logic/layout/format/Default.java | 4 +- .../layout/format/DocBookAuthorFormatter.java | 21 +- .../jabref/logic/layout/format/FileLink.java | 5 +- .../jabref/logic/layout/format/HTMLChars.java | 16 +- .../logic/layout/format/HTMLParagraphs.java | 8 +- .../jabref/logic/layout/format/IfPlural.java | 4 +- .../format/LatexToUnicodeFormatter.java | 8 +- .../logic/layout/format/NameFormatter.java | 26 +- .../format/NameFormatterPreferences.java | 6 +- .../layout/format/NotFoundFormatter.java | 7 +- .../jabref/logic/layout/format/RTFChars.java | 71 +- .../format/RemoveLatexCommandsFormatter.java | 25 +- .../ReplaceUnicodeLigaturesFormatter.java | 8 +- .../jabref/logic/layout/format/RisMonth.java | 4 +- .../logic/layout/format/WrapFileLinks.java | 19 +- .../jabref/logic/layout/format/XMLChars.java | 3 +- .../org/jabref/logic/logging/LogMessages.java | 3 +- .../jabref/logic/msbib/BibTeXConverter.java | 104 +- .../jabref/logic/msbib/MSBibConverter.java | 71 +- .../org/jabref/logic/msbib/MSBibDatabase.java | 34 +- .../org/jabref/logic/msbib/MSBibEntry.java | 62 +- .../org/jabref/logic/msbib/MSBibMapping.java | 206 +--- .../org/jabref/logic/msbib/PageNumbers.java | 8 +- .../jabref/logic/net/ProxyPreferences.java | 10 +- .../org/jabref/logic/net/ProxyRegisterer.java | 10 +- .../org/jabref/logic/net/URLDownload.java | 107 +- .../jabref/logic/net/ssl/SSLCertificate.java | 11 +- .../logic/net/ssl/TrustStoreManager.java | 90 +- .../openoffice/OpenOfficeFileSearch.java | 31 +- .../openoffice/OpenOfficePreferences.java | 9 +- .../logic/openoffice/action/EditInsert.java | 10 +- .../logic/openoffice/action/EditMerge.java | 111 +- .../logic/openoffice/action/EditSeparate.java | 11 +- .../logic/openoffice/action/ExportCited.java | 13 +- .../openoffice/action/ManageCitations.java | 5 +- .../logic/openoffice/action/Update.java | 18 +- .../logic/openoffice/backend/Backend52.java | 109 +- .../logic/openoffice/backend/Codec52.java | 26 +- .../logic/openoffice/backend/GetContext.java | 10 +- .../NamedRangeManagerReferenceMark.java | 13 +- .../backend/NamedRangeReferenceMark.java | 116 +-- .../logic/openoffice/frontend/OOFrontend.java | 174 +--- .../frontend/RangeForOverlapCheck.java | 7 +- .../frontend/UpdateBibliography.java | 29 +- .../frontend/UpdateCitationMarkers.java | 32 +- .../logic/openoffice/style/OOBibStyle.java | 118 +-- .../style/OOBibStyleGetCitationMarker.java | 118 +-- .../style/OOBibStyleGetNumCitationMarker.java | 56 +- .../style/OOFormatBibliography.java | 55 +- .../openoffice/style/OOPreFormatter.java | 26 +- .../logic/openoffice/style/OOProcess.java | 19 +- .../style/OOProcessAuthorYearMarkers.java | 35 +- .../style/OOProcessCitationKeyMarkers.java | 10 +- .../style/OOProcessNumericMarkers.java | 5 +- .../logic/openoffice/style/StyleLoader.java | 36 +- .../logic/pdf/EntryAnnotationImporter.java | 8 +- .../jabref/logic/pdf/FileAnnotationCache.java | 29 +- .../logic/pdf/PdfAnnotationImporter.java | 60 +- .../org/jabref/logic/pdf/TextExtractor.java | 14 +- .../pdf/search/indexing/DocumentReader.java | 71 +- .../search/indexing/IndexingTaskManager.java | 26 +- .../logic/pdf/search/indexing/PdfIndexer.java | 44 +- .../pdf/search/retrieval/PdfSearcher.java | 40 +- .../logic/preferences/OwnerPreferences.java | 6 +- .../protectedterms/ProtectedTermsList.java | 10 +- .../protectedterms/ProtectedTermsLoader.java | 46 +- .../protectedterms/ProtectedTermsParser.java | 14 +- .../ProtectedTermsPreferences.java | 6 +- .../org/jabref/logic/remote/Protocol.java | 18 +- .../logic/remote/client/RemoteClient.java | 14 +- .../remote/server/RemoteListenerServer.java | 26 +- .../server/RemoteListenerServerManager.java | 14 +- .../server/RemoteListenerServerThread.java | 10 +- .../jabref/logic/search/DatabaseSearcher.java | 4 +- .../org/jabref/logic/search/SearchQuery.java | 22 +- .../jabref/logic/shared/DBMSConnection.java | 11 +- .../shared/DBMSConnectionProperties.java | 39 +- .../DBMSConnectionPropertiesBuilder.java | 4 +- .../jabref/logic/shared/DBMSProcessor.java | 163 +-- .../jabref/logic/shared/DBMSSynchronizer.java | 104 +- .../org/jabref/logic/shared/DBMSType.java | 21 +- .../logic/shared/DatabaseSynchronizer.java | 3 +- .../jabref/logic/shared/MySQLProcessor.java | 17 +- .../jabref/logic/shared/OracleProcessor.java | 70 +- .../logic/shared/PostgreSQLProcessor.java | 67 +- .../exception/OfflineLockException.java | 5 +- .../PostgresSQLNotificationListener.java | 14 +- .../prefs/SharedDatabasePreferences.java | 50 +- .../logic/shared/security/Password.java | 12 +- .../logic/texparser/DefaultLatexParser.java | 27 +- .../texparser/TexBibEntriesResolver.java | 36 +- .../java/org/jabref/logic/util/BuildInfo.java | 32 +- .../jabref/logic/util/CoarseChangeFilter.java | 6 +- .../jabref/logic/util/DelayTaskThrottler.java | 10 +- .../MetadataSerializationConfiguration.java | 6 +- src/main/java/org/jabref/logic/util/OS.java | 18 +- .../jabref/logic/util/StandardFileType.java | 4 +- .../java/org/jabref/logic/util/TestEntry.java | 15 +- .../jabref/logic/util/UnknownFileType.java | 3 +- .../org/jabref/logic/util/UpdateField.java | 29 +- .../java/org/jabref/logic/util/Version.java | 58 +- .../org/jabref/logic/util/WebViewStore.java | 9 +- .../logic/util/io/AutoLinkPreferences.java | 14 +- .../jabref/logic/util/io/BackupFileUtil.java | 13 +- .../util/io/CitationKeyBasedFileFinder.java | 20 +- .../logic/util/io/DatabaseFileLookup.java | 8 +- .../org/jabref/logic/util/io/FileFinder.java | 7 +- .../org/jabref/logic/util/io/FileFinders.java | 4 +- .../logic/util/io/FileNameUniqueness.java | 50 +- .../org/jabref/logic/util/io/FileUtil.java | 80 +- .../logic/util/io/RegExpBasedFileFinder.java | 60 +- .../org/jabref/logic/util/io/XMLUtil.java | 13 +- .../strings/HTMLUnicodeConversionMaps.java | 50 +- .../util/strings/QuotedStringTokenizer.java | 10 +- .../logic/util/strings/StringManipulator.java | 71 +- .../xmp/DocumentInformationExtractor.java | 4 +- .../jabref/logic/xmp/DublinCoreExtractor.java | 67 +- .../org/jabref/logic/xmp/XmpPreferences.java | 3 +- .../org/jabref/logic/xmp/XmpUtilReader.java | 53 +- .../org/jabref/logic/xmp/XmpUtilShared.java | 20 +- .../org/jabref/logic/xmp/XmpUtilWriter.java | 90 +- .../ConvertLegacyExplicitGroups.java | 8 +- .../migrations/ConvertMarkingToGroups.java | 46 +- .../CustomEntryTypePreferenceMigration.java | 29 +- .../MergeReviewIntoCommentMigration.java | 26 +- .../migrations/PreferencesMigrations.java | 249 ++--- .../SpecialFieldsToSeparateFields.java | 12 +- .../java/org/jabref/model/FieldChange.java | 7 +- src/main/java/org/jabref/model/TreeNode.java | 14 +- .../jabref/model/database/BibDatabase.java | 115 +-- .../model/database/BibDatabaseContext.java | 71 +- .../database/BibDatabaseModeDetection.java | 5 +- .../jabref/model/database/BibDatabases.java | 4 +- .../model/database/KeyChangeListener.java | 18 +- .../database/event/EntriesAddedEvent.java | 5 +- .../database/event/EntriesRemovedEvent.java | 5 +- .../java/org/jabref/model/entry/Author.java | 43 +- .../org/jabref/model/entry/AuthorList.java | 53 +- .../java/org/jabref/model/entry/BibEntry.java | 188 +--- .../org/jabref/model/entry/BibEntryType.java | 22 +- .../model/entry/BibEntryTypeBuilder.java | 38 +- .../model/entry/BibEntryTypesManager.java | 67 +- .../org/jabref/model/entry/BibtexString.java | 13 +- .../jabref/model/entry/CanonicalBibEntry.java | 16 +- .../java/org/jabref/model/entry/Date.java | 80 +- .../jabref/model/entry/EntryConverter.java | 4 +- .../org/jabref/model/entry/EntryLinkList.java | 10 +- .../java/org/jabref/model/entry/Keyword.java | 13 +- .../org/jabref/model/entry/KeywordList.java | 39 +- .../org/jabref/model/entry/LinkedFile.java | 12 +- .../jabref/model/entry/ParsedEntryLink.java | 5 +- .../model/entry/event/EntriesEvent.java | 5 +- .../entry/event/FieldAddedOrRemovedEvent.java | 5 +- .../model/entry/event/FieldChangedEvent.java | 26 +- .../jabref/model/entry/field/AMSField.java | 7 +- .../jabref/model/entry/field/BibField.java | 12 +- .../model/entry/field/BiblatexApaField.java | 7 +- .../entry/field/BiblatexSoftwareField.java | 11 +- .../model/entry/field/FieldFactory.java | 43 +- .../jabref/model/entry/field/OrFields.java | 4 +- .../model/entry/field/SpecialField.java | 4 +- .../model/entry/field/SpecialFieldValue.java | 8 +- .../model/entry/field/StandardField.java | 14 +- .../model/entry/field/UnknownField.java | 11 +- .../jabref/model/entry/identifier/ARK.java | 4 +- .../entry/identifier/ArXivIdentifier.java | 15 +- .../jabref/model/entry/identifier/DOI.java | 28 +- .../jabref/model/entry/identifier/ISBN.java | 11 +- .../jabref/model/entry/identifier/ISSN.java | 8 +- .../model/entry/identifier/IacrEprint.java | 18 +- .../model/entry/identifier/MathSciNetId.java | 11 +- .../BiblatexAPAEntryTypeDefinitions.java | 31 +- .../types/BiblatexEntryTypeDefinitions.java | 36 +- .../BiblatexSoftwareEntryTypeDefinitions.java | 117 ++- .../types/BibtexEntryTypeDefinitions.java | 6 +- .../model/entry/types/EntryTypeFactory.java | 29 +- ...tematicLiteratureReviewStudyEntryType.java | 4 +- ...ratureReviewStudyEntryTypeDefinitions.java | 16 +- .../jabref/model/groups/AllEntriesGroup.java | 5 +- .../jabref/model/groups/AutomaticGroup.java | 4 +- .../model/groups/AutomaticKeywordGroup.java | 10 +- .../model/groups/AutomaticPersonsGroup.java | 19 +- .../jabref/model/groups/ExplicitGroup.java | 21 +- .../jabref/model/groups/GroupTreeNode.java | 23 +- .../jabref/model/groups/LastNameGroup.java | 13 +- .../model/groups/RegexKeywordGroup.java | 14 +- .../org/jabref/model/groups/SearchGroup.java | 14 +- .../org/jabref/model/groups/TexGroup.java | 27 +- .../jabref/model/groups/WordKeywordGroup.java | 41 +- .../model/metadata/ContentSelector.java | 5 +- .../org/jabref/model/metadata/MetaData.java | 69 +- .../org/jabref/model/metadata/SaveOrder.java | 20 +- .../metadata/SelfContainedSaveOrder.java | 23 +- .../model/openoffice/CitationEntry.java | 6 +- .../model/openoffice/backend/NamedRange.java | 6 +- .../openoffice/backend/NamedRangeManager.java | 6 +- .../model/openoffice/ootext/OOFormat.java | 13 +- .../model/openoffice/ootext/OOTextIntoOO.java | 195 +--- .../rangesort/FunctionalTextViewCursor.java | 33 +- .../openoffice/rangesort/RangeOverlap.java | 5 +- .../rangesort/RangeOverlapBetween.java | 36 +- .../rangesort/RangeOverlapWithin.java | 39 +- .../model/openoffice/rangesort/RangeSort.java | 23 +- .../openoffice/rangesort/RangeSortVisual.java | 27 +- .../model/openoffice/style/Citation.java | 29 +- .../model/openoffice/style/CitationGroup.java | 15 +- .../openoffice/style/CitationGroups.java | 37 +- .../style/CitationLookupResult.java | 3 +- .../model/openoffice/style/CitedKey.java | 35 +- .../openoffice/style/CompareCitation.java | 8 +- .../openoffice/style/CompareCitedKey.java | 5 +- .../model/openoffice/style/OODataModel.java | 9 +- .../model/openoffice/style/PageInfo.java | 4 +- .../model/openoffice/uno/UnoBookmark.java | 34 +- .../jabref/model/openoffice/uno/UnoCast.java | 4 +- .../model/openoffice/uno/UnoCrossRef.java | 24 +- .../model/openoffice/uno/UnoCursor.java | 8 +- .../model/openoffice/uno/UnoNameAccess.java | 6 +- .../jabref/model/openoffice/uno/UnoNamed.java | 12 +- .../model/openoffice/uno/UnoProperties.java | 31 +- .../model/openoffice/uno/UnoRedlines.java | 7 +- .../openoffice/uno/UnoReferenceMark.java | 43 +- .../model/openoffice/uno/UnoSelection.java | 21 +- .../jabref/model/openoffice/uno/UnoStyle.java | 42 +- .../model/openoffice/uno/UnoTextDocument.java | 20 +- .../model/openoffice/uno/UnoTextRange.java | 35 +- .../model/openoffice/uno/UnoTextSection.java | 35 +- .../jabref/model/openoffice/uno/UnoUndo.java | 7 +- .../uno/UnoUserDefinedProperty.java | 55 +- .../model/openoffice/util/OOListUtil.java | 10 +- .../org/jabref/model/pdf/FileAnnotation.java | 17 +- .../jabref/model/pdf/FileAnnotationType.java | 12 +- .../jabref/model/pdf/search/SearchResult.java | 40 +- .../model/schema/DublinCoreSchemaCustom.java | 18 +- .../search/rules/ContainsBasedSearchRule.java | 10 +- .../search/rules/FullTextSearchRule.java | 14 +- .../search/rules/GrammarBasedSearchRule.java | 99 +- .../search/rules/RegexBasedSearchRule.java | 4 +- .../model/search/rules/SearchRules.java | 9 +- .../model/strings/LatexToUnicodeAdapter.java | 18 +- .../org/jabref/model/strings/StringUtil.java | 111 +- .../java/org/jabref/model/study/Study.java | 4 +- .../org/jabref/model/study/StudyDatabase.java | 14 +- .../org/jabref/model/study/StudyQuery.java | 4 +- .../org/jabref/model/texparser/Citation.java | 16 +- .../LatexBibEntriesResolverResult.java | 3 +- .../model/texparser/LatexParserResult.java | 14 +- .../jabref/model/util/FileUpdateMonitor.java | 3 +- .../java/org/jabref/model/util/ListUtil.java | 10 +- .../org/jabref/model/util/OptionalUtil.java | 13 +- .../org/jabref/model/util/TreeCollector.java | 8 +- .../preferences/CleanupPreferences.java | 11 +- .../jabref/preferences/ExportPreferences.java | 6 +- .../ExternalApplicationsPreferences.java | 17 +- .../jabref/preferences/FilePreferences.java | 36 +- .../jabref/preferences/GuiPreferences.java | 26 +- .../jabref/preferences/JabRefPreferences.java | 962 +++++------------- .../preferences/LibraryPreferences.java | 10 +- .../jabref/preferences/MrDlibPreferences.java | 3 +- .../jabref/preferences/PreferencesFilter.java | 26 +- .../preferences/PreferencesService.java | 4 +- .../preferences/PreviewPreferences.java | 20 +- .../PushToApplicationPreferences.java | 6 +- .../jabref/preferences/SearchPreferences.java | 6 +- .../preferences/SidePanePreferences.java | 6 +- .../preferences/TelemetryPreferences.java | 6 +- .../preferences/WorkspacePreferences.java | 11 +- .../java/org/jabref/IconsPropertiesTest.java | 15 +- .../architecture/MainArchitectureTest.java | 45 +- .../architecture/TestArchitectureTest.java | 49 +- .../org/jabref/cli/ArgumentProcessorTest.java | 45 +- .../org/jabref/cli/AuxCommandLineTest.java | 13 +- .../java/org/jabref/cli/JabRefCLITest.java | 45 +- .../gui/UpdateTimestampListenerTest.java | 9 +- .../AppendPersonNamesStrategyTest.java | 4 +- .../gui/autocompleter/AutoCompleterUtil.java | 4 +- .../BibEntrySuggestionProviderTest.java | 32 +- ...ContentSelectorSuggestionProviderTest.java | 82 +- .../DefaultAutoCompleterTest.java | 52 +- .../FieldValueSuggestionProviderTest.java | 63 +- .../PersonNameStringConverterTest.java | 4 +- .../PersonNameSuggestionProviderTest.java | 77 +- .../SuggestionProvidersTest.java | 39 +- .../BackupManagerDiscardedTest.java | 17 +- .../autosaveandbackup/BackupManagerTest.java | 73 +- .../SaveOrderPanelViewModelTest.java | 8 +- .../PdfDocumentViewModelTest.java | 4 +- .../jabref/gui/edit/CopyMoreActionTest.java | 105 +- ...opyOrMoveFieldContentTabViewModelTest.java | 76 +- .../EditFieldContentTabViewModelTest.java | 34 +- .../gui/edit/ManageKeywordsViewModelTest.java | 35 +- .../gui/edit/RenameFieldViewModelTest.java | 60 +- .../gui/edit/ReplaceStringViewModelTest.java | 30 +- .../gui/entryeditor/CommentsTabTest.java | 19 +- .../jabref/gui/entryeditor/SciteTabTest.java | 3 +- .../entryeditor/SciteTabViewModelTest.java | 3 +- .../jabref/gui/entryeditor/SourceTabTest.java | 16 +- .../FileAnnotationViewModelTest.java | 5 +- .../exporter/ExportToClipboardActionTest.java | 51 +- .../gui/exporter/SaveDatabaseActionTest.java | 50 +- .../AutoSetFileLinksUtilTest.java | 14 +- .../externalfiles/FileFilterUtilsTest.java | 50 +- .../GitIgnoreFileFilterTest.java | 6 +- .../gui/externalfiles/ImportHandlerTest.java | 47 +- .../UnlinkedFilesCrawlerTest.java | 25 +- .../ExternalFileTypesTest.java | 33 +- .../fieldeditors/LinkedFileViewModelTest.java | 62 +- .../LinkedFilesEditorViewModelTest.java | 19 +- .../gui/groups/GroupDialogViewModelTest.java | 35 +- .../gui/groups/GroupNodeViewModelTest.java | 38 +- .../gui/groups/GroupTreeViewModelTest.java | 16 +- .../gui/importer/NewEntryActionTest.java | 25 +- .../fetcher/WebSearchPaneViewModelTest.java | 74 +- .../gui/keyboard/KeyBindingsTabModelTest.java | 69 +- .../ConstantsPropertiesViewModelTest.java | 21 +- .../ContentSelectorViewModelTest.java | 8 +- .../maintable/MainTableColumnModelTest.java | 27 +- .../gui/maintable/MainTableDataModelTest.java | 65 +- .../jabref/gui/menus/FileHistoryMenuTest.java | 10 +- .../mergeentries/DiffHighlightingTest.java | 10 +- .../mergeentries/FieldRowViewModelTest.java | 98 +- .../gui/mergeentries/GroupMergerTest.java | 6 +- .../ThreeWayMergeCellViewModelTest.java | 11 +- .../ThreeWayMergeViewModelTest.java | 31 +- .../journals/AbbreviationViewModelTest.java | 39 +- .../JournalAbbreviationsViewModelTabTest.java | 297 ++---- .../keybindings/KeyBindingViewModelTest.java | 15 +- .../org/jabref/gui/push/PushToEmacsTest.java | 16 +- .../gui/search/GlobalSearchBarTest.java | 26 +- .../GrammarBasedSearchRuleDescriberTest.java | 59 +- .../gui/search/TextFlowEqualityHelper.java | 16 +- .../gui/sidepane/SidePaneViewModelTest.java | 37 +- .../ManageStudyDefinitionViewModelTest.java | 32 +- .../jabref/gui/theme/ThemeManagerTest.java | 122 +-- .../java/org/jabref/gui/theme/ThemeTest.java | 14 +- .../gui/util/FileDialogConfigurationTest.java | 67 +- .../gui/util/OpenConsoleActionTest.java | 13 +- .../gui/util/RecursiveTreeItemTest.java | 23 +- .../jabref/gui/util/TooltipTextUtilTest.java | 118 +-- .../NumericFieldComparatorTest.java | 3 +- .../http/server/LibrariesResourceTest.java | 9 +- .../org/jabref/http/server/ServerTest.java | 41 +- .../org/jabref/http/server/TestBibFile.java | 7 +- .../jabref/logic/auxparser/AuxParserTest.java | 104 +- .../jabref/logic/bibtex/BibEntryAssert.java | 72 +- .../logic/bibtex/BibEntryWriterTest.java | 83 +- .../bibtex/FieldContentFormatterTest.java | 37 +- .../jabref/logic/bibtex/FieldWriterTest.java | 47 +- .../logic/bibtex/FileFieldWriterTest.java | 31 +- .../comparator/BibDatabaseDiffTest.java | 71 +- .../bibtex/comparator/BibStringDiffTest.java | 68 +- .../BibtexStringComparatorTest.java | 44 +- .../comparator/EntryComparatorTest.java | 141 +-- .../comparator/FieldComparatorTest.java | 101 +- .../bibtex/comparator/GroupDiffTest.java | 56 +- .../bibtex/comparator/MetaDataDiffTest.java | 11 +- .../bibtex/comparator/PreambleDiffTest.java | 20 +- .../jabref/logic/bst/BstFunctionsTest.java | 29 +- .../logic/bst/BstPreviewLayoutTest.java | 24 +- .../java/org/jabref/logic/bst/BstVMTest.java | 18 +- .../jabref/logic/bst/BstVMVisitorTest.java | 39 +- .../logic/bst/util/BstCaseChangersTest.java | 45 +- .../logic/bst/util/BstNameFormatterTest.java | 69 +- .../logic/bst/util/BstTextPrefixerTest.java | 10 +- .../bst/util/BstWidthCalculatorTest.java | 5 +- .../BracketedPatternTest.java | 495 ++------- .../CitationKeyGeneratorTest.java | 660 +++--------- .../MakeLabelWithDatabaseTest.java | 209 ++-- .../MakeLabelWithoutDatabaseTest.java | 35 +- .../CitationStyleGeneratorTest.java | 87 +- .../JabRefItemDataProviderTest.java | 28 +- .../cleanup/BibtexBiblatexRoundtripTest.java | 10 +- .../logic/cleanup/CleanupWorkerTest.java | 184 +--- .../cleanup/ConvertToBiblatexCleanupTest.java | 28 +- .../cleanup/ConvertToBibtexCleanupTest.java | 24 +- .../jabref/logic/cleanup/DoiCleanupTest.java | 48 +- .../logic/cleanup/DoiDecodeCleanupTest.java | 34 +- .../cleanup/FieldFormatterCleanupTest.java | 35 +- .../cleanup/FieldFormatterCleanupsTest.java | 420 +++----- .../jabref/logic/cleanup/ISSNCleanupTest.java | 10 +- .../logic/cleanup/MoveFilesCleanupTest.java | 43 +- .../logic/cleanup/RenamePdfCleanupTest.java | 56 +- .../cleanup/TimeStampToCreationDateTest.java | 153 +-- .../TimeStampToModificationDateTest.java | 54 +- .../jabref/logic/cleanup/URLCleanupTest.java | 94 +- .../org/jabref/logic/crawler/CrawlerTest.java | 45 +- .../StudyCatalogToFetcherConverterTest.java | 34 +- .../logic/crawler/StudyRepositoryTest.java | 116 +-- .../logic/crawler/StudyYamlParserTest.java | 38 +- .../logic/database/DatabaseMergerTest.java | 99 +- .../logic/database/DuplicateCheckTest.java | 286 +----- .../exporter/AtomicFileOutputStreamTest.java | 28 +- .../exporter/BibtexDatabaseWriterTest.java | 505 ++------- .../logic/exporter/CsvExportFormatTest.java | 23 +- .../logic/exporter/DocBook5ExporterTest.java | 19 +- .../logic/exporter/DocbookExporterTest.java | 11 +- .../EmbeddedBibFilePdfExporterTest.java | 82 +- .../logic/exporter/GroupSerializerTest.java | 69 +- .../exporter/HayagrivaYamlExporterTest.java | 62 +- .../logic/exporter/HtmlExportFormatTest.java | 5 +- .../exporter/MSBibExportFormatFilesTest.java | 8 +- .../exporter/MetaDataSerializerTest.java | 59 +- .../exporter/ModsExportFormatFilesTest.java | 45 +- .../logic/exporter/ModsExportFormatTest.java | 14 +- .../OpenOfficeDocumentCreatorTest.java | 30 +- .../logic/exporter/XmpExporterTest.java | 59 +- .../logic/exporter/XmpPdfExporterTest.java | 118 +-- .../logic/exporter/YamlExporterTest.java | 38 +- .../jabref/logic/formatter/FormatterTest.java | 7 +- .../bibtexfields/AddBracesFormatterTest.java | 5 +- .../bibtexfields/CleanupUrlFormatterTest.java | 15 +- .../EscapeAmpersandsFormatterTest.java | 16 +- .../EscapeDollarSignFormatterTest.java | 8 +- .../EscapeUnderscoresFormatterTest.java | 5 +- .../HtmlToLatexFormatterTest.java | 5 +- .../LatexCleanupFormatterTest.java | 14 +- .../NormalizeDateFormatterTest.java | 5 +- .../NormalizeEnDashesFormatterTest.java | 20 +- .../NormalizeNamesFormatterTest.java | 41 +- .../NormalizePagesFormatterTest.java | 5 +- .../OrdinalsToSuperscriptFormatterTest.java | 5 +- .../bibtexfields/RegexFormatterTest.java | 22 +- .../ReplaceWithEscapedDoubleQuotesTest.java | 10 +- .../TrimWhitespaceFormatterTest.java | 5 +- .../UnicodeToLatexFormatterTest.java | 5 +- .../casechanger/CapitalizeFormatterTest.java | 5 +- .../casechanger/LowerCaseFormatterTest.java | 5 +- .../ProtectTermsFormatterTest.java | 5 +- .../SentenceCaseFormatterTest.java | 5 +- .../casechanger/TitleCaseFormatterTest.java | 10 +- .../UnprotectTermsFormatterTest.java | 5 +- .../casechanger/UpperCaseFormatterTest.java | 5 +- .../minifier/MinifyNameListFormatterTest.java | 20 +- .../jabref/logic/git/SlrGitHandlerTest.java | 22 +- .../org/jabref/logic/help/HelpFileTest.java | 6 +- .../logic/importer/AuthorListParserTest.java | 34 +- .../logic/importer/BibDatabaseFilesTest.java | 16 +- .../logic/importer/FulltextFetchersTest.java | 20 +- .../jabref/logic/importer/ImportDataTest.java | 15 +- .../ImportFormatReaderIntegrationTest.java | 91 +- .../ImportFormatReaderParameterlessTest.java | 27 +- .../jabref/logic/importer/ImporterTest.java | 35 +- .../logic/importer/OpenDatabaseTest.java | 36 +- .../logic/importer/QueryParserTest.java | 18 +- .../logic/importer/WebFetchersTest.java | 65 +- .../fetcher/ACMPortalFetcherTest.java | 22 +- .../logic/importer/fetcher/ACSTest.java | 6 +- .../fetcher/AbstractIsbnFetcherTest.java | 22 +- .../importer/fetcher/ApsFetcherTest.java | 12 +- .../importer/fetcher/ArXivFetcherTest.java | 318 ++---- .../fetcher/AstrophysicsDataSystemTest.java | 99 +- .../fetcher/BiodiversityLibraryTest.java | 61 +- .../importer/fetcher/BvbFetcherTest.java | 23 +- .../logic/importer/fetcher/CiteSeerTest.java | 35 +- ...puterScienceBibliographiesFetcherTest.java | 58 +- ...mputerScienceBibliographiesParserTest.java | 29 +- .../fetcher/CompositeIdFetcherTest.java | 34 +- .../CompositeSearchBasedFetcherTest.java | 48 +- .../logic/importer/fetcher/CrossRefTest.java | 69 +- .../importer/fetcher/DBLPFetcherTest.java | 4 +- .../importer/fetcher/DOABFetcherTest.java | 38 +- .../importer/fetcher/DOAJFetcherTest.java | 50 +- .../logic/importer/fetcher/DiVATest.java | 20 +- .../importer/fetcher/DoiFetcherTest.java | 60 +- .../importer/fetcher/DoiResolutionTest.java | 20 +- .../importer/fetcher/FulltextFetcherTest.java | 8 +- .../importer/fetcher/GoogleScholarTest.java | 12 +- .../fetcher/GrobidCitationFetcherTest.java | 69 +- .../importer/fetcher/GvkFetcherTest.java | 37 +- .../logic/importer/fetcher/IEEETest.java | 57 +- .../importer/fetcher/INSPIREFetcherTest.java | 28 +- .../fetcher/IacrEprintFetcherTest.java | 167 +-- .../importer/fetcher/IssnFetcherTest.java | 9 +- .../importer/fetcher/JstorFetcherTest.java | 21 +- .../importer/fetcher/LOBIDFetcherTest.java | 36 +- .../fetcher/LibraryOfCongressTest.java | 24 +- .../importer/fetcher/MathSciNetTest.java | 27 +- .../importer/fetcher/MedlineFetcherTest.java | 22 +- .../logic/importer/fetcher/MedraTest.java | 31 +- .../importer/fetcher/MrDLibFetcherTest.java | 17 +- .../fetcher/PagedSearchFetcherTest.java | 6 +- .../importer/fetcher/PicaXmlParserTest.java | 46 +- .../importer/fetcher/ResearchGateTest.java | 37 +- .../importer/fetcher/RfcFetcherTest.java | 49 +- .../fetcher/ScholarArchiveFetcherTest.java | 8 +- .../importer/fetcher/ScienceDirectTest.java | 12 +- .../SearchBasedFetcherCapabilityTest.java | 31 +- .../importer/fetcher/SemanticScholarTest.java | 48 +- .../importer/fetcher/SpringerFetcherTest.java | 83 +- .../importer/fetcher/SpringerLinkTest.java | 16 +- .../importer/fetcher/TitleFetcherTest.java | 5 +- .../logic/importer/fetcher/ZbMATHTest.java | 19 +- ...oiToBibtexConverterComIsbnFetcherTest.java | 22 +- .../isbntobibtex/EbookDeIsbnFetcherTest.java | 26 +- .../isbntobibtex/GVKIsbnFetcherTest.java | 44 +- .../fetcher/isbntobibtex/IsbnFetcherTest.java | 38 +- .../OpenLibraryIsbnFetcherTest.java | 20 +- .../CiteSeerQueryTransformerTest.java | 66 +- ...nceBibliographiesQueryTransformerTest.java | 15 +- .../DBLPQueryTransformerTest.java | 9 +- .../DefaultQueryTransformerTest.java | 4 +- .../transformers/GVKQueryTransformerTest.java | 6 +- .../IEEEQueryTransformerTest.java | 9 +- .../transformers/InfixTransformerTest.java | 39 +- .../JstorQueryTransformerTest.java | 9 +- .../ScholarQueryTransformerTest.java | 4 +- .../SpringerQueryTransformerTest.java | 9 +- .../transformers/SuffixTransformerTest.java | 43 +- ...rRangeByFilteringQueryTransformerTest.java | 3 +- .../ZbMathQueryTransformerTest.java | 9 +- .../fileformat/ACMPortalParserTest.java | 63 +- .../BiblioscapeImporterFilesTest.java | 11 +- .../fileformat/BiblioscapeImporterTest.java | 5 +- .../BiblioscapeImporterTypesTest.java | 6 +- .../fileformat/BibtexImporterTest.java | 142 +-- .../importer/fileformat/BibtexParserTest.java | 782 ++++---------- .../importer/fileformat/CffImporterTest.java | 113 +- .../CitaviXmlImporterFilesTest.java | 17 +- .../fileformat/CopacImporterFilesTest.java | 19 +- .../fileformat/CopacImporterTest.java | 9 +- .../fileformat/CustomImporterTest.java | 17 +- .../fileformat/EndnoteImporterTest.java | 146 +-- .../EndnoteXmlImporterFilesTest.java | 14 +- .../fileformat/ImporterTestEngine.java | 34 +- .../fileformat/InspecImporterTest.java | 42 +- .../importer/fileformat/IsiImporterTest.java | 225 +--- .../fileformat/MarcXmlParserTest.java | 12 +- .../fileformat/MedlineImporterFilesTest.java | 24 +- .../fileformat/MedlineImporterTest.java | 5 +- .../fileformat/MedlinePlainImporterTest.java | 101 +- .../fileformat/ModsImporterFilesTest.java | 11 +- .../fileformat/MrDLibImporterTest.java | 5 +- .../fileformat/MsBibImporterFilesTest.java | 19 +- .../fileformat/MsBibImporterTest.java | 21 +- .../importer/fileformat/OvidImporterTest.java | 114 +-- .../PdfContentImporterFilesTest.java | 11 +- .../fileformat/PdfContentImporterTest.java | 37 +- .../PdfEmbeddedBibFileImporterTest.java | 18 +- .../fileformat/PdfGrobidImporterTest.java | 45 +- .../PdfMergeMetadataImporterTest.java | 30 +- .../PdfVerbatimBibTextImporterTest.java | 22 +- .../fileformat/PdfXmpImporterTest.java | 39 +- .../fileformat/RISImporterFilesTest.java | 6 +- .../importer/fileformat/RISImporterTest.java | 13 +- .../fileformat/RepecNepImporterTest.java | 11 +- .../fileformat/SilverPlatterImporterTest.java | 22 +- .../importer/util/FileFieldParserTest.java | 73 +- .../importer/util/GrobidServiceTest.java | 36 +- .../logic/importer/util/GroupsParserTest.java | 33 +- .../logic/importer/util/JsonReaderTest.java | 16 +- .../logic/importer/util/MathMLParserTest.java | 7 +- .../importer/util/MetaDataParserTest.java | 5 +- .../importer/util/ShortDOIServiceTest.java | 8 +- .../logic/importer/util/StaxParserTest.java | 7 +- .../integrity/AbbreviationCheckerTest.java | 11 +- .../logic/integrity/AmpersandCheckerTest.java | 38 +- .../logic/integrity/BibStringCheckerTest.java | 30 +- .../logic/integrity/BracesCorrectorTest.java | 5 +- .../integrity/CitationKeyCheckerTest.java | 4 +- .../CitationKeyDeviationCheckerTest.java | 27 +- .../CitationKeyDuplicationCheckerTest.java | 6 +- .../integrity/DoiDuplicationCheckerTest.java | 15 +- .../integrity/DoiValidityCheckerTest.java | 9 +- .../logic/integrity/EditionCheckerTest.java | 70 +- .../logic/integrity/EntryLinkCheckerTest.java | 5 +- .../integrity/HTMLCharacterCheckerTest.java | 27 +- .../integrity/HowPublishedCheckerTest.java | 10 +- .../logic/integrity/ISBNCheckerTest.java | 10 +- .../logic/integrity/ISSNCheckerTest.java | 5 +- .../logic/integrity/IntegrityCheckTest.java | 92 +- .../JournalInAbbreviationListCheckerTest.java | 12 +- .../integrity/LatexIntegrityCheckerTest.java | 163 +-- .../logic/integrity/MonthCheckerTest.java | 5 +- .../integrity/NoBibTexFieldCheckerTest.java | 6 +- .../logic/integrity/NoteCheckerTest.java | 10 +- .../integrity/PersonNamesCheckerTest.java | 6 +- .../logic/integrity/TitleCheckerTest.java | 55 +- .../logic/integrity/UTF8CheckerTest.java | 12 +- .../logic/integrity/UrlCheckerTest.java | 10 +- .../ValidCitationKeyCheckerTest.java | 13 +- .../logic/integrity/YearCheckerTest.java | 10 +- .../journals/AbbreviationParserTest.java | 20 +- .../logic/journals/AbbreviationTest.java | 62 +- .../journals/AbbreviationWriterTest.java | 8 +- .../logic/journals/AbbreviationsTest.java | 10 +- .../JournalAbbreviationRepositoryTest.java | 369 ++----- .../JournalInformationFetcherTest.java | 474 +++++---- .../l10n/JavaLocalizationEntryParser.java | 25 +- .../l10n/JavaLocalizationEntryParserTest.java | 63 +- .../org/jabref/logic/l10n/LanguageTest.java | 5 +- .../l10n/LocalizationConsistencyTest.java | 49 +- .../logic/l10n/LocalizationKeyParamsTest.java | 20 +- .../logic/l10n/LocalizationKeyTest.java | 19 +- .../jabref/logic/l10n/LocalizationParser.java | 38 +- .../jabref/logic/l10n/LocalizationTest.java | 5 +- .../jabref/logic/layout/LayoutEntryTest.java | 85 +- .../jabref/logic/layout/LayoutHelperTest.java | 8 +- .../org/jabref/logic/layout/LayoutTest.java | 34 +- .../layout/format/AuthorAbbreviatorTest.java | 9 +- .../AuthorAndToSemicolonReplacerTest.java | 5 +- .../format/AuthorAndsCommaReplacerTest.java | 5 +- .../layout/format/AuthorAndsReplacerTest.java | 5 +- .../format/AuthorFirstFirstCommasTest.java | 4 +- .../layout/format/AuthorFirstFirstTest.java | 4 +- .../AuthorFirstLastOxfordCommasTest.java | 5 +- .../layout/format/AuthorLF_FFAbbrTest.java | 4 +- .../logic/layout/format/AuthorLF_FFTest.java | 5 +- .../AuthorLastFirstAbbreviatorTest.java | 13 +- .../format/AuthorLastFirstCommasTest.java | 5 +- .../AuthorLastFirstOxfordCommasTest.java | 5 +- .../layout/format/AuthorLastFirstTest.java | 5 +- .../logic/layout/format/AuthorNatBibTest.java | 5 +- .../logic/layout/format/AuthorOrgSciTest.java | 20 +- .../logic/layout/format/AuthorsTest.java | 40 +- .../layout/format/CompositeFormatTest.java | 6 +- .../logic/layout/format/DOICheckTest.java | 15 +- .../logic/layout/format/DOIStripTest.java | 10 +- .../layout/format/DateFormatterTest.java | 6 +- .../logic/layout/format/DefaultTest.java | 6 +- .../logic/layout/format/FileLinkTest.java | 29 +- .../logic/layout/format/FirstPageTest.java | 5 +- .../logic/layout/format/HTMLCharsTest.java | 10 +- .../logic/layout/format/LastPageTest.java | 5 +- .../format/LatexToUnicodeFormatterTest.java | 14 +- .../layout/format/MarkdownFormatterTest.java | 5 +- .../layout/format/NameFormatterTest.java | 20 +- .../NoSpaceBetweenAbbreviationsTest.java | 18 +- .../logic/layout/format/RTFCharsTest.java | 13 +- .../layout/format/RemoveBracketsTest.java | 3 +- .../layout/format/RemoveWhitespaceTest.java | 5 +- .../logic/layout/format/ReplaceTest.java | 10 +- .../format/ShortMonthFormatterTest.java | 5 +- .../logic/layout/format/ToLowerCaseTest.java | 5 +- .../logic/layout/format/WrapContentTest.java | 32 +- .../layout/format/WrapFileLinksTest.java | 32 +- .../logic/msbib/MSBibConverterTest.java | 9 +- .../jabref/logic/msbib/MsBibAuthorTest.java | 24 +- .../org/jabref/logic/net/URLDownloadTest.java | 49 +- .../org/jabref/logic/net/URLUtilTest.java | 21 +- .../openoffice/style/OOBibStyleTest.java | 318 +----- .../style/OOBibStyleTestHelper.java | 78 +- .../openoffice/style/OOPreFormatterTest.java | 35 +- .../openoffice/style/StyleLoaderTest.java | 198 +--- .../pdf/EntryAnnotationImporterTest.java | 11 +- .../logic/pdf/PdfAnnotationImporterTest.java | 50 +- .../search/indexing/DocumentReaderTest.java | 29 +- .../pdf/search/indexing/PdfIndexerTest.java | 16 +- .../pdf/search/retrieval/PdfSearcherTest.java | 21 +- .../ProtectedTermsLoaderTest.java | 35 +- .../logic/remote/RemoteCommunicationTest.java | 5 +- .../jabref/logic/remote/RemoteSetupTest.java | 38 +- .../jabref/logic/remote/RemoteUtilTest.java | 10 +- .../logic/search/DatabaseSearcherTest.java | 34 +- .../jabref/logic/search/SearchQueryTest.java | 69 +- .../jabref/logic/shared/ConnectorTest.java | 11 +- .../shared/DBMSConnectionPropertiesTest.java | 54 +- .../logic/shared/DBMSConnectionTest.java | 4 +- .../logic/shared/DBMSProcessorTest.java | 197 +--- .../logic/shared/DBMSSynchronizerTest.java | 62 +- .../org/jabref/logic/shared/DBMSTypeTest.java | 25 +- .../shared/SynchronizationSimulatorTest.java | 28 +- .../org/jabref/logic/shared/TestManager.java | 7 +- .../logic/shared/security/PasswordTest.java | 6 +- .../logic/texparser/DefaultTexParserTest.java | 241 +---- .../logic/texparser/LatexParserTest.java | 182 ++-- .../texparser/TexBibEntriesResolverTest.java | 185 ++-- .../org/jabref/logic/util/BuildInfoTest.java | 4 +- .../logic/util/DevelopmentStageTest.java | 41 +- .../logic/util/FileNameCleanerTest.java | 20 +- .../jabref/logic/util/UpdateFieldTest.java | 125 +-- .../org/jabref/logic/util/VersionTest.java | 15 +- .../logic/util/io/BackupFileUtilTest.java | 27 +- .../io/CitationKeyBasedFileFinderTest.java | 53 +- .../logic/util/io/FileNameUniquenessTest.java | 15 +- .../jabref/logic/util/io/FileUtilTest.java | 130 +-- .../util/io/RegExpBasedFileFinderTest.java | 50 +- .../strings/StringLengthComparatorTest.java | 6 +- .../util/strings/StringManipulatorTest.java | 113 +- .../util/strings/StringSimilarityTest.java | 11 +- .../jabref/logic/xmp/XmpUtilReaderTest.java | 85 +- .../jabref/logic/xmp/XmpUtilWriterTest.java | 48 +- .../ConvertLegacyExplicitGroupsTest.java | 32 +- .../ConvertMarkingToGroupsTest.java | 21 +- ...eReviewIntoCommentActionMigrationTest.java | 54 +- .../migrations/PreferencesMigrationsTest.java | 173 +--- .../SpecialFieldsToSeparateFieldsTest.java | 18 +- .../org/jabref/model/FieldChangeTest.java | 52 +- .../java/org/jabref/model/TreeNodeTest.java | 448 +++----- .../database/BibDatabaseContextTest.java | 22 +- .../BibDatabaseModeDetectionTest.java | 13 +- .../model/database/BibDatabaseTest.java | 80 +- .../model/database/KeyChangeListenerTest.java | 35 +- .../jabref/model/entry/AuthorListTest.java | 820 ++++----------- .../org/jabref/model/entry/BibEntryTest.java | 292 +----- .../model/entry/BibEntryTypesManagerTest.java | 159 +-- .../jabref/model/entry/BibtexStringTest.java | 10 +- .../model/entry/CanonicalBibEntryTest.java | 6 +- .../org/jabref/model/entry/CrossrefTest.java | 161 +-- .../java/org/jabref/model/entry/DateTest.java | 50 +- .../jabref/model/entry/EntryLinkListTest.java | 8 +- .../jabref/model/entry/KeywordListTest.java | 53 +- .../org/jabref/model/entry/KeywordTest.java | 5 +- .../org/jabref/model/entry/MonthTest.java | 10 +- .../model/entry/field/FieldFactoryTest.java | 25 +- .../model/entry/field/SpecialFieldTest.java | 5 +- .../entry/identifier/ArXivIdentifierTest.java | 135 +-- .../model/entry/identifier/DOITest.java | 315 ++---- .../entry/identifier/IacrEprintTest.java | 40 +- .../groups/AutomaticKeywordGroupTest.java | 6 +- .../groups/AutomaticPersonsGroupTest.java | 10 +- .../model/groups/ExplicitGroupTest.java | 24 +- .../model/groups/GroupTreeNodeTest.java | 143 +-- .../org/jabref/model/groups/TexGroupTest.java | 12 +- .../model/groups/WordKeywordGroupTest.java | 53 +- .../model/openoffice/CitationEntryTest.java | 54 +- .../jabref/model/pdf/FileAnnotationTest.java | 5 +- .../rules/ContainsBasedSearchRuleTest.java | 40 +- .../rules/GrammarBasedSearchRuleTest.java | 29 +- .../jabref/model/strings/StringUtilTest.java | 105 +- .../jabref/model/texparser/CitationTest.java | 23 +- .../org/jabref/support/CIServerCondition.java | 15 +- .../styletester/StyleTesterMain.java | 3 +- 1345 files changed, 13606 insertions(+), 42347 deletions(-) diff --git a/src/main/java/org/jabref/gui/JabRefDialogService.java b/src/main/java/org/jabref/gui/JabRefDialogService.java index c91e4a9fe9e..822187c145f 100644 --- a/src/main/java/org/jabref/gui/JabRefDialogService.java +++ b/src/main/java/org/jabref/gui/JabRefDialogService.java @@ -65,12 +65,8 @@ public class JabRefDialogService implements DialogService { // Snackbar dialog maximum size public static final int DIALOG_SIZE_LIMIT = 300; - private static final Duration TOAST_MESSAGE_DISPLAY_TIME = Duration.millis( - 3000 - ); - private static final Logger LOGGER = LoggerFactory.getLogger( - JabRefDialogService.class - ); + private static final Duration TOAST_MESSAGE_DISPLAY_TIME = Duration.millis(3000); + private static final Logger LOGGER = LoggerFactory.getLogger(JabRefDialogService.class); private final Window mainWindow; @@ -78,11 +74,7 @@ public JabRefDialogService(Window mainWindow) { this.mainWindow = mainWindow; } - private FXDialog createDialog( - AlertType type, - String title, - String content - ) { + private FXDialog createDialog(AlertType type, String title, String content) { FXDialog alert = new FXDialog(type, title, true); alert.setHeaderText(null); alert.setContentText(content); @@ -111,9 +103,7 @@ private FXDialog createDialogWithOptOut( protected Node createDetailsButton() { CheckBox optOut = new CheckBox(); optOut.setText(optOutMessage); - optOut.setOnAction(e -> - optOutAction.accept(optOut.isSelected()) - ); + optOut.setOnAction(e -> optOutAction.accept(optOut.isSelected())); return optOut; } } @@ -139,10 +129,7 @@ public static String shortenDialogMessage(String dialogMessage) { return ( dialogMessage.substring( 0, - Math.min( - dialogMessage.length(), - JabRefDialogService.DIALOG_SIZE_LIMIT - ) + Math.min(dialogMessage.length(), JabRefDialogService.DIALOG_SIZE_LIMIT) ) + "..." ).trim(); @@ -156,20 +143,11 @@ public Optional showChoiceDialogAndWait( T defaultChoice, Collection choices ) { - ChoiceDialog choiceDialog = new ChoiceDialog<>( - defaultChoice, - choices - ); + ChoiceDialog choiceDialog = new ChoiceDialog<>(defaultChoice, choices); ((Stage) choiceDialog.getDialogPane().getScene().getWindow()).getIcons() .add(IconTheme.getJabRefImage()); - ButtonType okButtonType = new ButtonType( - okButtonLabel, - ButtonBar.ButtonData.OK_DONE - ); - choiceDialog - .getDialogPane() - .getButtonTypes() - .setAll(ButtonType.CANCEL, okButtonType); + ButtonType okButtonType = new ButtonType(okButtonLabel, ButtonBar.ButtonData.OK_DONE); + choiceDialog.getDialogPane().getButtonTypes().setAll(ButtonType.CANCEL, okButtonType); choiceDialog.setHeaderText(title); choiceDialog.setTitle(title); choiceDialog.setContentText(content); @@ -178,10 +156,7 @@ public Optional showChoiceDialogAndWait( } @Override - public Optional showInputDialogAndWait( - String title, - String content - ) { + public Optional showInputDialogAndWait(String title, String content) { TextInputDialog inputDialog = new TextInputDialog(); inputDialog.setHeaderText(title); inputDialog.setContentText(content); @@ -230,11 +205,7 @@ public void showErrorDialogAndWait(String message, Throwable exception) { } @Override - public void showErrorDialogAndWait( - String title, - String content, - Throwable exception - ) { + public void showErrorDialogAndWait(String title, String content, Throwable exception) { ExceptionDialog exceptionDialog = new ExceptionDialog(exception); exceptionDialog.setHeaderText(title); exceptionDialog.setContentText(content); @@ -255,10 +226,7 @@ public void showErrorDialogAndWait(String message) { @Override public boolean showConfirmationDialogAndWait(String title, String content) { FXDialog alert = createDialog(AlertType.CONFIRMATION, title, content); - return alert - .showAndWait() - .filter(buttonType -> buttonType == ButtonType.OK) - .isPresent(); + return alert.showAndWait().filter(buttonType -> buttonType == ButtonType.OK).isPresent(); } @Override @@ -268,15 +236,9 @@ public boolean showConfirmationDialogAndWait( String okButtonLabel ) { FXDialog alert = createDialog(AlertType.CONFIRMATION, title, content); - ButtonType okButtonType = new ButtonType( - okButtonLabel, - ButtonBar.ButtonData.OK_DONE - ); + ButtonType okButtonType = new ButtonType(okButtonLabel, ButtonBar.ButtonData.OK_DONE); alert.getButtonTypes().setAll(ButtonType.CANCEL, okButtonType); - return alert - .showAndWait() - .filter(buttonType -> buttonType == okButtonType) - .isPresent(); + return alert.showAndWait().filter(buttonType -> buttonType == okButtonType).isPresent(); } @Override @@ -287,19 +249,10 @@ public boolean showConfirmationDialogAndWait( String cancelButtonLabel ) { FXDialog alert = createDialog(AlertType.CONFIRMATION, title, content); - ButtonType okButtonType = new ButtonType( - okButtonLabel, - ButtonBar.ButtonData.OK_DONE - ); - ButtonType cancelButtonType = new ButtonType( - cancelButtonLabel, - ButtonBar.ButtonData.NO - ); + ButtonType okButtonType = new ButtonType(okButtonLabel, ButtonBar.ButtonData.OK_DONE); + ButtonType cancelButtonType = new ButtonType(cancelButtonLabel, ButtonBar.ButtonData.NO); alert.getButtonTypes().setAll(okButtonType, cancelButtonType); - return alert - .showAndWait() - .filter(buttonType -> buttonType == okButtonType) - .isPresent(); + return alert.showAndWait().filter(buttonType -> buttonType == okButtonType).isPresent(); } @Override @@ -317,10 +270,7 @@ public boolean showConfirmationDialogWithOptOutAndWait( optOutAction ); alert.getButtonTypes().setAll(ButtonType.YES, ButtonType.NO); - return alert - .showAndWait() - .filter(buttonType -> buttonType == ButtonType.YES) - .isPresent(); + return alert.showAndWait().filter(buttonType -> buttonType == ButtonType.YES).isPresent(); } @Override @@ -339,19 +289,10 @@ public boolean showConfirmationDialogWithOptOutAndWait( optOutMessage, optOutAction ); - ButtonType okButtonType = new ButtonType( - okButtonLabel, - ButtonBar.ButtonData.YES - ); - ButtonType cancelButtonType = new ButtonType( - cancelButtonLabel, - ButtonBar.ButtonData.NO - ); + ButtonType okButtonType = new ButtonType(okButtonLabel, ButtonBar.ButtonData.YES); + ButtonType cancelButtonType = new ButtonType(cancelButtonLabel, ButtonBar.ButtonData.NO); alert.getButtonTypes().setAll(okButtonType, cancelButtonType); - return alert - .showAndWait() - .filter(buttonType -> buttonType == okButtonType) - .isPresent(); + return alert.showAndWait().filter(buttonType -> buttonType == okButtonType).isPresent(); } @Override @@ -382,9 +323,7 @@ public Optional showCustomDialogAndWait( } @Override - public Optional showCustomDialogAndWait( - javafx.scene.control.Dialog dialog - ) { + public Optional showCustomDialogAndWait(javafx.scene.control.Dialog dialog) { if (dialog.getOwner() == null) { dialog.initOwner(mainWindow); } @@ -392,13 +331,8 @@ public Optional showCustomDialogAndWait( } @Override - public Optional showPasswordDialogAndWait( - String title, - String header, - String content - ) { - javafx.scene.control.Dialog dialog = - new javafx.scene.control.Dialog<>(); + public Optional showPasswordDialogAndWait(String title, String header, String content) { + javafx.scene.control.Dialog dialog = new javafx.scene.control.Dialog<>(); dialog.setTitle(title); dialog.setHeaderText(header); @@ -410,10 +344,7 @@ public Optional showPasswordDialogAndWait( dialog.setTitle(title); dialog.getDialogPane().setContent(box); - dialog - .getDialogPane() - .getButtonTypes() - .addAll(ButtonType.CANCEL, ButtonType.OK); + dialog.getDialogPane().getButtonTypes().addAll(ButtonType.CANCEL, ButtonType.OK); dialog.setResultConverter(dialogButton -> { if (dialogButton == ButtonType.OK) { return passwordField.getText(); @@ -424,27 +355,18 @@ public Optional showPasswordDialogAndWait( } @Override - public void showProgressDialog( - String title, - String content, - Task task - ) { + public void showProgressDialog(String title, String content, Task task) { ProgressDialog progressDialog = new ProgressDialog(task); progressDialog.setHeaderText(null); progressDialog.setTitle(title); progressDialog.setContentText(content); progressDialog.setGraphic(null); - ((Stage) progressDialog - .getDialogPane() - .getScene() - .getWindow()).getIcons() + ((Stage) progressDialog.getDialogPane().getScene().getWindow()).getIcons() .add(IconTheme.getJabRefImage()); progressDialog.setOnCloseRequest(evt -> task.cancel()); DialogPane dialogPane = progressDialog.getDialogPane(); dialogPane.getButtonTypes().add(ButtonType.CANCEL); - Button cancelButton = (Button) dialogPane.lookupButton( - ButtonType.CANCEL - ); + Button cancelButton = (Button) dialogPane.lookupButton(ButtonType.CANCEL); cancelButton.setOnAction(evt -> { task.cancel(); progressDialog.close(); @@ -460,10 +382,7 @@ public Optional showBackgroundProgressDialogAndWait( StateManager stateManager ) { TaskProgressView> taskProgressView = new TaskProgressView<>(); - EasyBind.bindContent( - taskProgressView.getTasks(), - stateManager.getBackgroundTasks() - ); + EasyBind.bindContent(taskProgressView.getTasks(), stateManager.getBackgroundTasks()); taskProgressView.setRetainTasks(false); taskProgressView.setGraphicFactory(BackgroundTask::getIcon); @@ -512,9 +431,7 @@ public void notify(String message) { // TODO: Change to a notification overview instead of event log when that is available. The event log is not that user friendly (different purpose). .text( "(" + - Localization.lang( - "Check the event log to see all notifications" - ) + + Localization.lang("Check the event log to see all notifications") + ")" + "\n\n" + message @@ -530,9 +447,7 @@ public void notify(String message) { } @Override - public Optional showFileSaveDialog( - FileDialogConfiguration fileDialogConfiguration - ) { + public Optional showFileSaveDialog(FileDialogConfiguration fileDialogConfiguration) { FileChooser chooser = getConfiguredFileChooser(fileDialogConfiguration); File file = chooser.showSaveDialog(mainWindow); Optional @@ -542,9 +457,7 @@ public Optional showFileSaveDialog( } @Override - public Optional showFileOpenDialog( - FileDialogConfiguration fileDialogConfiguration - ) { + public Optional showFileOpenDialog(FileDialogConfiguration fileDialogConfiguration) { FileChooser chooser = getConfiguredFileChooser(fileDialogConfiguration); File file = chooser.showOpenDialog(mainWindow); Optional @@ -557,9 +470,7 @@ public Optional showFileOpenDialog( public Optional showDirectorySelectionDialog( DirectoryDialogConfiguration directoryDialogConfiguration ) { - DirectoryChooser chooser = getConfiguredDirectoryChooser( - directoryDialogConfiguration - ); + DirectoryChooser chooser = getConfiguredDirectoryChooser(directoryDialogConfiguration); File file = chooser.showDialog(mainWindow); return Optional.ofNullable(file).map(File::toPath); } @@ -586,19 +497,11 @@ private DirectoryChooser getConfiguredDirectoryChooser( return chooser; } - private FileChooser getConfiguredFileChooser( - FileDialogConfiguration fileDialogConfiguration - ) { + private FileChooser getConfiguredFileChooser(FileDialogConfiguration fileDialogConfiguration) { FileChooser chooser = new FileChooser(); - chooser - .getExtensionFilters() - .addAll(fileDialogConfiguration.getExtensionFilters()); - chooser.setSelectedExtensionFilter( - fileDialogConfiguration.getDefaultExtension() - ); - chooser.setInitialFileName( - fileDialogConfiguration.getInitialFileName() - ); + chooser.getExtensionFilters().addAll(fileDialogConfiguration.getExtensionFilters()); + chooser.setSelectedExtensionFilter(fileDialogConfiguration.getDefaultExtension()); + chooser.setInitialFileName(fileDialogConfiguration.getInitialFileName()); fileDialogConfiguration .getInitialDirectory() .map(Path::toFile) @@ -612,20 +515,11 @@ public boolean showPrintDialog(PrinterJob job) { } @Override - public Optional showFileOpenFromArchiveDialog(Path archivePath) - throws IOException { - try ( - FileSystem zipFile = FileSystems.newFileSystem( - archivePath, - (ClassLoader) null - ) - ) { + public Optional showFileOpenFromArchiveDialog(Path archivePath) throws IOException { + try (FileSystem zipFile = FileSystems.newFileSystem(archivePath, (ClassLoader) null)) { return new ZipFileChooser(zipFile).showAndWait(); } catch (NoClassDefFoundError exc) { - throw new IOException( - "Could not instantiate ZIP-archive reader.", - exc - ); + throw new IOException("Could not instantiate ZIP-archive reader.", exc); } } diff --git a/src/main/java/org/jabref/gui/JabRefExecutorService.java b/src/main/java/org/jabref/gui/JabRefExecutorService.java index 95471278642..1f32ddf26bd 100644 --- a/src/main/java/org/jabref/gui/JabRefExecutorService.java +++ b/src/main/java/org/jabref/gui/JabRefExecutorService.java @@ -20,28 +20,23 @@ */ public class JabRefExecutorService { - public static final JabRefExecutorService INSTANCE = - new JabRefExecutorService(); - - private static final Logger LOGGER = LoggerFactory.getLogger( - JabRefExecutorService.class - ); - - private final ExecutorService executorService = - Executors.newCachedThreadPool(r -> { - Thread thread = new Thread(r); - thread.setName("JabRef CachedThreadPool"); - thread.setUncaughtExceptionHandler(new FallbackExceptionHandler()); - return thread; - }); - - private final ExecutorService lowPriorityExecutorService = - Executors.newCachedThreadPool(r -> { - Thread thread = new Thread(r); - thread.setName("JabRef LowPriorityCachedThreadPool"); - thread.setUncaughtExceptionHandler(new FallbackExceptionHandler()); - return thread; - }); + public static final JabRefExecutorService INSTANCE = new JabRefExecutorService(); + + private static final Logger LOGGER = LoggerFactory.getLogger(JabRefExecutorService.class); + + private final ExecutorService executorService = Executors.newCachedThreadPool(r -> { + Thread thread = new Thread(r); + thread.setName("JabRef CachedThreadPool"); + thread.setUncaughtExceptionHandler(new FallbackExceptionHandler()); + return thread; + }); + + private final ExecutorService lowPriorityExecutorService = Executors.newCachedThreadPool(r -> { + Thread thread = new Thread(r); + thread.setName("JabRef LowPriorityCachedThreadPool"); + thread.setUncaughtExceptionHandler(new FallbackExceptionHandler()); + return thread; + }); private final Timer timer = new Timer("timer", true); @@ -107,13 +102,8 @@ public List> executeAll( } } - public void executeInterruptableTask( - final Runnable runnable, - String taskName - ) { - this.lowPriorityExecutorService.execute( - new NamedRunnable(taskName, runnable) - ); + public void executeInterruptableTask(final Runnable runnable, String taskName) { + this.lowPriorityExecutorService.execute(new NamedRunnable(taskName, runnable)); } public void executeInterruptableTaskAndWait(Runnable runnable) { @@ -205,10 +195,7 @@ public static void gracefullyShutdown(ExecutorService executorService) { executorService.toString() ); } else { - LOGGER.error( - "{} did not terminate", - executorService.toString() - ); + LOGGER.error("{} did not terminate", executorService.toString()); } } } catch (InterruptedException ie) { diff --git a/src/main/java/org/jabref/gui/JabRefFrame.java b/src/main/java/org/jabref/gui/JabRefFrame.java index 64ebf9f6f94..56a37ac26c7 100644 --- a/src/main/java/org/jabref/gui/JabRefFrame.java +++ b/src/main/java/org/jabref/gui/JabRefFrame.java @@ -88,9 +88,7 @@ public class JabRefFrame extends BorderPane implements LibraryTabContainer { public static final String FRAME_TITLE = "JabRef"; - private static final Logger LOGGER = LoggerFactory.getLogger( - JabRefFrame.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(JabRefFrame.class); private final SplitPane splitPane = new SplitPane(); private final PreferencesService prefs = Globals.prefs; @@ -123,21 +121,10 @@ public JabRefFrame(Stage mainStage) { this.fileUpdateMonitor = Globals.getFileUpdateMonitor(); this.entryTypesManager = Globals.entryTypesManager; this.globalSearchBar = - new GlobalSearchBar( - this, - stateManager, - prefs, - undoManager, - dialogService - ); + new GlobalSearchBar(this, stateManager, prefs, undoManager, dialogService); this.taskExecutor = Globals.TASK_EXECUTOR; this.pushToApplicationCommand = - new PushToApplicationCommand( - stateManager, - dialogService, - prefs, - taskExecutor - ); + new PushToApplicationCommand(stateManager, dialogService, prefs, taskExecutor); this.fileHistory = new FileHistoryMenu( prefs.getGuiPreferences().getFileHistory(), @@ -166,9 +153,7 @@ private void initDragAndDrop() { // Add drag and drop listeners to JabRefFrame this.getScene() .setOnDragOver(event -> { - if ( - DragAndDropHelper.hasBibFiles(event.getDragboard()) - ) { + if (DragAndDropHelper.hasBibFiles(event.getDragboard())) { event.acceptTransferModes(TransferMode.ANY); if (!tabbedPane.getTabs().contains(dndIndicator)) { tabbedPane.getTabs().add(dndIndicator); @@ -178,11 +163,7 @@ private void initDragAndDrop() { tabbedPane.getTabs().remove(dndIndicator); } // Accept drag entries from MainTable - if ( - event - .getDragboard() - .hasContent(DragAndDropDataFormats.ENTRIES) - ) { + if (event.getDragboard().hasContent(DragAndDropDataFormats.ENTRIES)) { event.acceptTransferModes(TransferMode.COPY); event.consume(); } @@ -196,157 +177,107 @@ private void initDragAndDrop() { .lookupAll(".tab") .forEach(destinationTabNode -> { destinationTabNode.setOnDragOver(tabDragEvent -> { - if ( - DragAndDropHelper.hasBibFiles( - tabDragEvent.getDragboard() - ) || - DragAndDropHelper.hasGroups( - tabDragEvent.getDragboard() - ) - ) { - tabDragEvent.acceptTransferModes( - TransferMode.ANY - ); - if ( - !tabbedPane - .getTabs() - .contains(dndIndicator) - ) { - tabbedPane - .getTabs() - .add(dndIndicator); - } - event.consume(); - } else { - tabbedPane - .getTabs() - .remove(dndIndicator); + if ( + DragAndDropHelper.hasBibFiles( + tabDragEvent.getDragboard() + ) || + DragAndDropHelper.hasGroups(tabDragEvent.getDragboard()) + ) { + tabDragEvent.acceptTransferModes(TransferMode.ANY); + if (!tabbedPane.getTabs().contains(dndIndicator)) { + tabbedPane.getTabs().add(dndIndicator); } + event.consume(); + } else { + tabbedPane.getTabs().remove(dndIndicator); + } - if ( - tabDragEvent - .getDragboard() - .hasContent( - DragAndDropDataFormats.ENTRIES - ) - ) { - tabDragEvent.acceptTransferModes( - TransferMode.COPY - ); - tabDragEvent.consume(); - } + if ( + tabDragEvent + .getDragboard() + .hasContent(DragAndDropDataFormats.ENTRIES) + ) { + tabDragEvent.acceptTransferModes(TransferMode.COPY); + tabDragEvent.consume(); } - ); + }); destinationTabNode.setOnDragExited(event1 -> tabbedPane.getTabs().remove(dndIndicator) ); destinationTabNode.setOnDragDropped(tabDragEvent -> { - Dragboard dragboard = - tabDragEvent.getDragboard(); - - if ( - DragAndDropHelper.hasBibFiles( - dragboard - ) - ) { - tabbedPane - .getTabs() - .remove(dndIndicator); - List bibFiles = - DragAndDropHelper.getBibFiles( - dragboard - ); - OpenDatabaseAction openDatabaseAction = - this.getOpenDatabaseAction(); - openDatabaseAction.openFiles( - bibFiles - ); - tabDragEvent.setDropCompleted(true); - tabDragEvent.consume(); - } else { - for (Tab libraryTab : tabbedPane.getTabs()) { - if ( - libraryTab - .getId() - .equals( - destinationTabNode.getId() - ) && - !tabbedPane - .getSelectionModel() - .getSelectedItem() - .equals(libraryTab) - ) { - LibraryTab destinationLibraryTab = - (LibraryTab) libraryTab; - if ( - DragAndDropHelper.hasGroups( - dragboard - ) - ) { - List< - String - > groupPathToSources = - DragAndDropHelper.getGroups( - dragboard - ); - - copyRootNode( - destinationLibraryTab - ); - - GroupTreeNode destinationLibraryGroupRoot = - destinationLibraryTab + Dragboard dragboard = tabDragEvent.getDragboard(); + + if (DragAndDropHelper.hasBibFiles(dragboard)) { + tabbedPane.getTabs().remove(dndIndicator); + List bibFiles = DragAndDropHelper.getBibFiles( + dragboard + ); + OpenDatabaseAction openDatabaseAction = + this.getOpenDatabaseAction(); + openDatabaseAction.openFiles(bibFiles); + tabDragEvent.setDropCompleted(true); + tabDragEvent.consume(); + } else { + for (Tab libraryTab : tabbedPane.getTabs()) { + if ( + libraryTab + .getId() + .equals(destinationTabNode.getId()) && + !tabbedPane + .getSelectionModel() + .getSelectedItem() + .equals(libraryTab) + ) { + LibraryTab destinationLibraryTab = + (LibraryTab) libraryTab; + if (DragAndDropHelper.hasGroups(dragboard)) { + List groupPathToSources = + DragAndDropHelper.getGroups(dragboard); + + copyRootNode(destinationLibraryTab); + + GroupTreeNode destinationLibraryGroupRoot = + destinationLibraryTab + .getBibDatabaseContext() + .getMetaData() + .getGroups() + .get(); + + for (String pathToSource : groupPathToSources) { + GroupTreeNode groupTreeNodeToCopy = + getCurrentLibraryTab() .getBibDatabaseContext() .getMetaData() .getGroups() + .get() + .getChildByPath(pathToSource) .get(); - - for (String pathToSource : groupPathToSources) { - GroupTreeNode groupTreeNodeToCopy = - getCurrentLibraryTab() - .getBibDatabaseContext() - .getMetaData() - .getGroups() - .get() - .getChildByPath( - pathToSource - ) - .get(); - copyGroupTreeNode( - (LibraryTab) libraryTab, - destinationLibraryGroupRoot, - groupTreeNodeToCopy - ); - } - return; + copyGroupTreeNode( + (LibraryTab) libraryTab, + destinationLibraryGroupRoot, + groupTreeNodeToCopy + ); } - destinationLibraryTab.dropEntry( - stateManager - .getLocalDragboard() - .getBibEntries() - ); + return; } + destinationLibraryTab.dropEntry( + stateManager.getLocalDragboard().getBibEntries() + ); } - tabDragEvent.consume(); } + tabDragEvent.consume(); } - ); + }); }); event.consume(); }); - this.getScene() - .setOnDragExited(event -> - tabbedPane.getTabs().remove(dndIndicator) - ); + this.getScene().setOnDragExited(event -> tabbedPane.getTabs().remove(dndIndicator)); this.getScene() .setOnDragDropped(event -> { tabbedPane.getTabs().remove(dndIndicator); - List bibFiles = DragAndDropHelper.getBibFiles( - event.getDragboard() - ); - OpenDatabaseAction openDatabaseAction = - this.getOpenDatabaseAction(); + List bibFiles = DragAndDropHelper.getBibFiles(event.getDragboard()); + OpenDatabaseAction openDatabaseAction = this.getOpenDatabaseAction(); openDatabaseAction.openFiles(bibFiles); event.setDropCompleted(true); event.consume(); @@ -359,21 +290,15 @@ private void initKeyBindings() { addEventFilter( KeyEvent.KEY_PRESSED, event -> { - Optional keyBinding = Globals - .getKeyPrefs() - .mapToKeyBinding(event); + Optional keyBinding = Globals.getKeyPrefs().mapToKeyBinding(event); if (keyBinding.isPresent()) { switch (keyBinding.get()) { case FOCUS_ENTRY_TABLE: - getCurrentLibraryTab() - .getMainTable() - .requestFocus(); + getCurrentLibraryTab().getMainTable().requestFocus(); event.consume(); break; case FOCUS_GROUP_LIST: - sidePane - .getSidePaneComponent(SidePaneType.GROUPS) - .requestFocus(); + sidePane.getSidePaneComponent(SidePaneType.GROUPS).requestFocus(); event.consume(); break; case NEXT_LIBRARY: @@ -481,13 +406,8 @@ private void initKeyBindings() { if (OS.OS_X) { // Workaround for a jdk issue that executes paste twice when using cmd+v in a TextField // Extra workaround for CodeArea, which does not inherit from TextInputControl if ( - !(stateManager - .getFocusOwner() - .isPresent() && - (stateManager - .getFocusOwner() - .get() instanceof - CodeArea)) + !(stateManager.getFocusOwner().isPresent() && + (stateManager.getFocusOwner().get() instanceof CodeArea)) ) { event.consume(); break; @@ -519,8 +439,7 @@ public void run() { } private void showTrackingNotification() { - TelemetryPreferences telemetryPreferences = - prefs.getTelemetryPreferences(); + TelemetryPreferences telemetryPreferences = prefs.getTelemetryPreferences(); boolean shouldCollect = telemetryPreferences.shouldCollectTelemetry(); if (!telemetryPreferences.shouldCollectTelemetry()) { @@ -551,12 +470,7 @@ public void openAction(String filePath) { * The MacAdapter calls this method when "About" is selected from the application menu. */ public void about() { - new HelpAction( - HelpFile.CONTENTS, - dialogService, - prefs.getFilePreferences() - ) - .execute(); + new HelpAction(HelpFile.CONTENTS, dialogService, prefs.getFilePreferences()).execute(); } /** @@ -603,21 +517,13 @@ public boolean quit() { It is important to wait for unfinished background tasks before checking if a save-operation is needed, because the background tasks may make changes themselves that need saving. */ - if ( - stateManager.getAnyTasksThatWillNotBeRecoveredRunning().getValue() - ) { - Optional shouldClose = - dialogService.showBackgroundProgressDialogAndWait( - Localization.lang("Please wait..."), - Localization.lang( - "Waiting for background tasks to finish. Quit anyway?" - ), - stateManager - ); - if ( - !(shouldClose.isPresent() && - (shouldClose.get() == ButtonType.YES)) - ) { + if (stateManager.getAnyTasksThatWillNotBeRecoveredRunning().getValue()) { + Optional shouldClose = dialogService.showBackgroundProgressDialogAndWait( + Localization.lang("Please wait..."), + Localization.lang("Waiting for background tasks to finish. Quit anyway?"), + stateManager + ); + if (!(shouldClose.isPresent() && (shouldClose.get() == ButtonType.YES))) { return false; } } @@ -626,12 +532,8 @@ public boolean quit() { List filenames = new ArrayList<>(); for (int i = 0; i < tabbedPane.getTabs().size(); i++) { LibraryTab libraryTab = getLibraryTabAt(i); - final BibDatabaseContext context = - libraryTab.getBibDatabaseContext(); - if ( - libraryTab.isModified() && - (context.getLocation() == DatabaseLocation.LOCAL) - ) { + final BibDatabaseContext context = libraryTab.getBibDatabaseContext(); + if (libraryTab.isModified() && (context.getLocation() == DatabaseLocation.LOCAL)) { tabbedPane.getSelectionModel().select(i); if (!confirmClose(libraryTab)) { return false; @@ -654,8 +556,9 @@ public boolean quit() { .ifPresent(filenames::add); } - WaitForSaveFinishedDialog waitForSaveFinishedDialog = - new WaitForSaveFinishedDialog(dialogService); + WaitForSaveFinishedDialog waitForSaveFinishedDialog = new WaitForSaveFinishedDialog( + dialogService + ); waitForSaveFinishedDialog.showAndWait(getLibraryTabs()); // We call saveWindow state here again because under Mac the windowClose listener on the stage isn't triggered when using cmd + q @@ -743,9 +646,7 @@ private void initLayout() { splitPane.getItems().addAll(tabbedPane); SplitPane.setResizableWithParent(sidePane, false); - sidePane - .getChildren() - .addListener((InvalidationListener) c -> updateSidePane()); + sidePane.getChildren().addListener((InvalidationListener) c -> updateSidePane()); updateSidePane(); // We need to wait with setting the divider since it gets reset a few times during the initial set-up @@ -785,16 +686,12 @@ private void updateSidePane() { private void setDividerPosition() { if (mainStage.isShowing() && !sidePane.getChildren().isEmpty()) { splitPane.setDividerPositions( - prefs.getGuiPreferences().getSidePaneWidth() / - splitPane.getWidth() + prefs.getGuiPreferences().getSidePaneWidth() / splitPane.getWidth() ); dividerSubscription = EasyBind.subscribe( sidePane.widthProperty(), - width -> - prefs - .getGuiPreferences() - .setSidePaneWidth(width.doubleValue()) + width -> prefs.getGuiPreferences().setSidePaneWidth(width.doubleValue()) ); } } @@ -849,17 +746,12 @@ public void init() { initDragAndDrop(); // Bind global state - FilteredList filteredTabs = new FilteredList<>( - tabbedPane.getTabs() - ); + FilteredList filteredTabs = new FilteredList<>(tabbedPane.getTabs()); filteredTabs.setPredicate(LibraryTab.class::isInstance); // This variable cannot be inlined, since otherwise the list created by EasyBind is being garbage collected openDatabaseList = - EasyBind.map( - filteredTabs, - tab -> ((LibraryTab) tab).getBibDatabaseContext() - ); + EasyBind.map(filteredTabs, tab -> ((LibraryTab) tab).getBibDatabaseContext()); EasyBind.bindContent(stateManager.getOpenDatabases(), openDatabaseList); // the binding for stateManager.activeDatabaseProperty() is at org.jabref.gui.LibraryTab.onDatabaseLoadingSucceed @@ -884,21 +776,14 @@ public void init() { Platform.runLater(() -> stateManager .focusOwnerProperty() - .bind( - EasyBind.map( - mainStage.getScene().focusOwnerProperty(), - Optional::ofNullable - ) - ) + .bind(EasyBind.map(mainStage.getScene().focusOwnerProperty(), Optional::ofNullable)) ); EasyBind.subscribe( tabbedPane.getSelectionModel().selectedItemProperty(), selectedTab -> { if (selectedTab instanceof LibraryTab libraryTab) { - stateManager.setActiveDatabase( - libraryTab.getBibDatabaseContext() - ); + stateManager.setActiveDatabase(libraryTab.getBibDatabaseContext()); } else if (selectedTab == null) { // All databases are closed stateManager.setActiveDatabase(null); @@ -922,9 +807,7 @@ public void init() { } // Poor-mans binding to global state - stateManager.setSelectedEntries( - libraryTab.getSelectedEntries() - ); + stateManager.setSelectedEntries(libraryTab.getSelectedEntries()); // Update active search query when switching between databases if ( @@ -950,10 +833,7 @@ public void init() { // Set window title - copy tab title StringBinding windowTitle = Bindings.createStringBinding( - () -> - libraryTab.textProperty().getValue() + - " \u2013 " + - FRAME_TITLE, + () -> libraryTab.textProperty().getValue() + " \u2013 " + FRAME_TITLE, libraryTab.textProperty() ); mainStage.titleProperty().bind(windowTitle); @@ -966,10 +846,7 @@ public void init() { * Returns the currently viewed BasePanel. */ public LibraryTab getCurrentLibraryTab() { - if ( - (tabbedPane == null) || - (tabbedPane.getSelectionModel().getSelectedItem() == null) - ) { + if ((tabbedPane == null) || (tabbedPane.getSelectionModel().getSelectedItem() == null)) { return null; } return (LibraryTab) tabbedPane.getSelectionModel().getSelectedItem(); @@ -999,13 +876,8 @@ public void setupAllTables() { tabbedPane .getTabs() .forEach(tab -> { - if ( - tab instanceof LibraryTab libraryTab && - (libraryTab.getDatabase() != null) - ) { - DefaultTaskExecutor.runInJavaFXThread( - libraryTab::setupMainPanel - ); + if (tab instanceof LibraryTab libraryTab && (libraryTab.getDatabase() != null)) { + DefaultTaskExecutor.runInJavaFXThread(libraryTab::setupMainPanel); } }); } @@ -1022,10 +894,7 @@ private ContextMenu createTabContextMenuFor( .addAll( factory.createMenuItem( StandardActions.LIBRARY_PROPERTIES, - new LibraryPropertiesAction( - tab::getBibDatabaseContext, - stateManager - ) + new LibraryPropertiesAction(tab::getBibDatabaseContext, stateManager) ), factory.createMenuItem( StandardActions.OPEN_DATABASE_FOLDER, @@ -1071,13 +940,9 @@ public void addTab(LibraryTab libraryTab, boolean raisePanel) { event.consume(); }); - libraryTab.setContextMenu( - createTabContextMenuFor(libraryTab, Globals.getKeyPrefs()) - ); + libraryTab.setContextMenu(createTabContextMenuFor(libraryTab, Globals.getKeyPrefs())); - libraryTab - .getUndoManager() - .registerListener(new UndoRedoEventManager()); + libraryTab.getUndoManager().registerListener(new UndoRedoEventManager()); } /** @@ -1122,10 +987,7 @@ public void addTab(ParserResult parserResult, boolean raisePanel) { Optional libraryTab = getLibraryTabs() .stream() .filter(p -> - p - .getBibDatabaseContext() - .getDatabasePath() - .equals(parserResult.getPath()) + p.getBibDatabaseContext().getDatabasePath().equals(parserResult.getPath()) ) .findFirst(); @@ -1143,21 +1005,11 @@ public void addTab(ParserResult parserResult, boolean raisePanel) { * @param panel The BasePanel to add to. * @param parserResult The entries to add. */ - private void addImportedEntries( - final LibraryTab panel, - final ParserResult parserResult - ) { - BackgroundTask task = BackgroundTask.wrap(() -> - parserResult - ); - ImportCleanup cleanup = ImportCleanup.targeting( - panel.getBibDatabaseContext().getMode() - ); + private void addImportedEntries(final LibraryTab panel, final ParserResult parserResult) { + BackgroundTask task = BackgroundTask.wrap(() -> parserResult); + ImportCleanup cleanup = ImportCleanup.targeting(panel.getBibDatabaseContext().getMode()); cleanup.doPostCleanup(parserResult.getDatabase().getEntries()); - ImportEntriesDialog dialog = new ImportEntriesDialog( - panel.getBibDatabaseContext(), - task - ); + ImportEntriesDialog dialog = new ImportEntriesDialog(panel.getBibDatabaseContext(), task); dialog.setTitle(Localization.lang("Import")); dialogService.showCustomDialogAndWait(dialog); } @@ -1193,15 +1045,14 @@ private boolean confirmClose(LibraryTab libraryTab) { ButtonBar.ButtonData.CANCEL_CLOSE ); - Optional response = - dialogService.showCustomButtonDialogAndWait( - Alert.AlertType.CONFIRMATION, - Localization.lang("Save before closing"), - Localization.lang("Library '%0' has changed.", filename), - saveChanges, - discardChanges, - returnToLibrary - ); + Optional response = dialogService.showCustomButtonDialogAndWait( + Alert.AlertType.CONFIRMATION, + Localization.lang("Save before closing"), + Localization.lang("Library '%0' has changed.", filename), + saveChanges, + discardChanges, + returnToLibrary + ); if (response.isEmpty()) { return true; @@ -1225,14 +1076,9 @@ private boolean confirmClose(LibraryTab libraryTab) { return true; } // The action was either canceled or unsuccessful. - dialogService.notify( - Localization.lang("Unable to save library") - ); + dialogService.notify(Localization.lang("Unable to save library")); } catch (Throwable ex) { - LOGGER.error( - "A problem occurred when trying to save the file", - ex - ); + LOGGER.error("A problem occurred when trying to save the file", ex); dialogService.showErrorDialogAndWait( Localization.lang("Save library"), Localization.lang("Could not save file."), @@ -1262,10 +1108,7 @@ public void closeTab(LibraryTab libraryTab) { final BibDatabaseContext context = libraryTab.getBibDatabaseContext(); - if ( - libraryTab.isModified() && - (context.getLocation() == DatabaseLocation.LOCAL) - ) { + if (libraryTab.isModified() && (context.getLocation() == DatabaseLocation.LOCAL)) { if (confirmClose(libraryTab)) { removeTab(libraryTab); } else { @@ -1328,17 +1171,11 @@ private void copyGroupTreeNode( GroupTreeNode parent, GroupTreeNode groupTreeNodeToCopy ) { - List allEntries = getCurrentLibraryTab() - .getBibDatabaseContext() - .getEntries(); + List allEntries = getCurrentLibraryTab().getBibDatabaseContext().getEntries(); // add groupTreeNodeToCopy to the parent-- in the first run that will the source/main GroupTreeNode - GroupTreeNode copiedNode = parent.addSubgroup( - groupTreeNodeToCopy.copyNode().getGroup() - ); + GroupTreeNode copiedNode = parent.addSubgroup(groupTreeNodeToCopy.copyNode().getGroup()); // add all entries of a groupTreeNode to the new library. - destinationLibraryTab.dropEntry( - groupTreeNodeToCopy.getEntriesInGroup(allEntries) - ); + destinationLibraryTab.dropEntry(groupTreeNodeToCopy.getEntriesInGroup(allEntries)); // List of all children of groupTreeNodeToCopy List children = groupTreeNodeToCopy.getChildren(); @@ -1351,13 +1188,7 @@ private void copyGroupTreeNode( } private void copyRootNode(LibraryTab destinationLibraryTab) { - if ( - !destinationLibraryTab - .getBibDatabaseContext() - .getMetaData() - .getGroups() - .isEmpty() - ) { + if (!destinationLibraryTab.getBibDatabaseContext().getMetaData().getGroups().isEmpty()) { return; } // a root (all entries) GroupTreeNode @@ -1401,10 +1232,7 @@ protected static class CloseDatabaseAction extends SimpleCommand { private final LibraryTabContainer tabContainer; private final LibraryTab libraryTab; - public CloseDatabaseAction( - LibraryTabContainer tabContainer, - LibraryTab libraryTab - ) { + public CloseDatabaseAction(LibraryTabContainer tabContainer, LibraryTab libraryTab) { this.tabContainer = tabContainer; this.libraryTab = libraryTab; } @@ -1457,9 +1285,7 @@ private class OpenDatabaseFolder extends SimpleCommand { private final Supplier databaseContext; - public OpenDatabaseFolder( - Supplier databaseContext - ) { + public OpenDatabaseFolder(Supplier databaseContext) { this.databaseContext = databaseContext; } @@ -1487,8 +1313,7 @@ private class UndoRedoEventManager { @Subscribe public void listen(UndoRedoEvent event) { updateTexts(event); - JabRefFrame.this.getCurrentLibraryTab() - .updateEntryEditorIfShowing(); + JabRefFrame.this.getCurrentLibraryTab().updateEntryEditorIfShowing(); } @Subscribe diff --git a/src/main/java/org/jabref/gui/JabRefGUI.java b/src/main/java/org/jabref/gui/JabRefGUI.java index edb12998b51..c6cfc0a40d5 100644 --- a/src/main/java/org/jabref/gui/JabRefGUI.java +++ b/src/main/java/org/jabref/gui/JabRefGUI.java @@ -35,9 +35,7 @@ public class JabRefGUI { - private static final Logger LOGGER = LoggerFactory.getLogger( - JabRefGUI.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(JabRefGUI.class); private static JabRefFrame mainFrame; private final PreferencesService preferencesService; @@ -69,9 +67,7 @@ public JabRefGUI( openWindow(mainStage); EasyBind.subscribe( - preferencesService - .getInternalPreferences() - .versionCheckEnabledProperty(), + preferencesService.getInternalPreferences().versionCheckEnabledProperty(), enabled -> { if (enabled) { new VersionWorker( @@ -98,17 +94,13 @@ private void setupProxy() { if ( preferencesService.getProxyPreferences().shouldPersistPassword() && - StringUtil.isNotBlank( - preferencesService.getProxyPreferences().getPassword() - ) + StringUtil.isNotBlank(preferencesService.getProxyPreferences().getPassword()) ) { ProxyRegisterer.register(preferencesService.getProxyPreferences()); return; } - DialogService dialogService = Injector.instantiateModelOrService( - DialogService.class - ); + DialogService dialogService = Injector.instantiateModelOrService(DialogService.class); Optional password = dialogService.showPasswordDialogAndWait( Localization.lang("Proxy configuration"), Localization.lang("Proxy requires password"), @@ -116,9 +108,7 @@ private void setupProxy() { ); if (password.isPresent()) { - preferencesService - .getProxyPreferences() - .setPassword(password.get()); + preferencesService.getProxyPreferences().setPassword(password.get()); ProxyRegisterer.register(preferencesService.getProxyPreferences()); } else { LOGGER.warn("No proxy password specified"); @@ -142,9 +132,7 @@ private void openWindow(Stage mainStage) { if (guiPreferences.isWindowMaximised()) { mainStage.setMaximized(true); } - if ( - (Screen.getScreens().size() == 1) && isWindowPositionOutOfBounds() - ) { + if ((Screen.getScreens().size() == 1) && isWindowPositionOutOfBounds()) { // corrects the Window, if it is outside the mainscreen LOGGER.debug("The Jabref window is outside the main screen"); mainStage.setX(0); @@ -210,10 +198,7 @@ private void openWindow(Stage mainStage) { */ private void openDatabases() { // If the option is enabled, open the last edited libraries, if any. - if ( - !isBlank && - preferencesService.getWorkspacePreferences().shouldOpenLastEdited() - ) { + if (!isBlank && preferencesService.getWorkspacePreferences().shouldOpenLastEdited()) { openLastEditedDatabases(); } @@ -297,30 +282,20 @@ private void openDatabases() { String message = Localization.lang( "Error opening file '%0'", - pr - .getPath() - .map(Path::toString) - .orElse("(File name unknown)") + pr.getPath().map(Path::toString).orElse("(File name unknown)") ) + "\n" + pr.getErrorMessage(); mainFrame .getDialogService() - .showErrorDialogAndWait( - Localization.lang("Error opening file"), - message - ); + .showErrorDialogAndWait(Localization.lang("Error opening file"), message); } // Display warnings, if any int tabNumber = 0; for (ParserResult pr : parserResults) { - ParserResultWarningDialog.showParserResultWarningDialog( - pr, - mainFrame, - tabNumber++ - ); + ParserResultWarningDialog.showParserResultWarningDialog(pr, mainFrame, tabNumber++); } // After adding the databases, go through each and see if @@ -332,11 +307,7 @@ private void openDatabases() { // This is because importToOpen might have been used, which adds to // loadedDatabases, but not to getBasePanelCount() - for ( - int i = 0; - (i < parserResults.size()) && (i < mainFrame.getBasePanelCount()); - i++ - ) { + for (int i = 0; (i < parserResults.size()) && (i < mainFrame.getBasePanelCount()); i++) { ParserResult pr = parserResults.get(i); LibraryTab libraryTab = mainFrame.getLibraryTabAt(i); @@ -401,17 +372,12 @@ private boolean isWindowPositionOutOfBounds() { } private void openLastEditedDatabases() { - List lastFiles = preferencesService - .getGuiPreferences() - .getLastFilesOpened(); + List lastFiles = preferencesService.getGuiPreferences().getLastFilesOpened(); if (lastFiles.isEmpty()) { return; } - List filesToOpen = lastFiles - .stream() - .map(Path::of) - .collect(Collectors.toList()); + List filesToOpen = lastFiles.stream().map(Path::of).collect(Collectors.toList()); getMainFrame().getOpenDatabaseAction().openFiles(filesToOpen); } diff --git a/src/main/java/org/jabref/gui/LibraryTab.java b/src/main/java/org/jabref/gui/LibraryTab.java index 7150264d135..fdf9223ed68 100644 --- a/src/main/java/org/jabref/gui/LibraryTab.java +++ b/src/main/java/org/jabref/gui/LibraryTab.java @@ -79,9 +79,7 @@ public class LibraryTab extends Tab { - private static final Logger LOGGER = LoggerFactory.getLogger( - LibraryTab.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(LibraryTab.class); private final JabRefFrame frame; private final CountingUndoManager undoManager; private final DialogService dialogService; @@ -89,11 +87,8 @@ public class LibraryTab extends Tab { private final FileUpdateMonitor fileUpdateMonitor; private final StateManager stateManager; private final BibEntryTypesManager entryTypesManager; - private final BooleanProperty changedProperty = new SimpleBooleanProperty( - false - ); - private final BooleanProperty nonUndoableChangeProperty = - new SimpleBooleanProperty(false); + private final BooleanProperty changedProperty = new SimpleBooleanProperty(false); + private final BooleanProperty nonUndoableChangeProperty = new SimpleBooleanProperty(false); private BibDatabaseContext bibDatabaseContext; private MainTableDataModel tableModel; @@ -151,18 +146,11 @@ public LibraryTab( bibDatabaseContext.getMetaData().registerListener(this); this.tableModel = - new MainTableDataModel( - getBibDatabaseContext(), - preferencesService, - stateManager - ); + new MainTableDataModel(getBibDatabaseContext(), preferencesService, stateManager); citationStyleCache = new CitationStyleCache(bibDatabaseContext); annotationCache = - new FileAnnotationCache( - bibDatabaseContext, - preferencesService.getFilePreferences() - ); + new FileAnnotationCache(bibDatabaseContext, preferencesService.getFilePreferences()); setupMainPanel(); setupAutoCompletion(); @@ -171,13 +159,11 @@ public LibraryTab( this.getDatabase().registerListener(new EntriesRemovedListener()); // ensure that at each addition of a new entry, the entry is added to the groups interface - this.bibDatabaseContext.getDatabase() - .registerListener(new GroupTreeListener()); + this.bibDatabaseContext.getDatabase().registerListener(new GroupTreeListener()); // ensure that all entry changes mark the panel as changed this.bibDatabaseContext.getDatabase().registerListener(this); - this.getDatabase() - .registerListener(new UpdateTimestampListener(preferencesService)); + this.getDatabase().registerListener(new UpdateTimestampListener(preferencesService)); this.entryEditor = new EntryEditor(this); @@ -196,23 +182,14 @@ public LibraryTab( }); } - private static void addChangedInformation( - StringBuilder text, - String fileName - ) { + private static void addChangedInformation(StringBuilder text, String fileName) { text.append("\n"); text.append(Localization.lang("Library '%0' has changed.", fileName)); } - private static void addModeInfo( - StringBuilder text, - BibDatabaseContext bibDatabaseContext - ) { + private static void addModeInfo(StringBuilder text, BibDatabaseContext bibDatabaseContext) { String mode = bibDatabaseContext.getMode().getFormattedName(); - String modeInfo = String.format( - "\n%s", - Localization.lang("%0 mode", mode) - ); + String modeInfo = String.format("\n%s", Localization.lang("%0 mode", mode)); text.append(modeInfo); } @@ -226,9 +203,7 @@ private static void addSharedDbInformation( text.append("]"); } - public void setDataLoadingTask( - BackgroundTask dataLoadingTask - ) { + public void setDataLoadingTask(BackgroundTask dataLoadingTask) { this.dataLoadingTask = dataLoadingTask; } @@ -263,17 +238,10 @@ public void onDatabaseLoadingSucceed(ParserResult result) { feedData(context); - if ( - preferencesService - .getFilePreferences() - .shouldFulltextIndexLinkedFiles() - ) { + if (preferencesService.getFilePreferences().shouldFulltextIndexLinkedFiles()) { try { indexingTaskManager.updateIndex( - PdfIndexer.of( - bibDatabaseContext, - preferencesService.getFilePreferences() - ), + PdfIndexer.of(bibDatabaseContext, preferencesService.getFilePreferences()), bibDatabaseContext ); } catch (IOException e) { @@ -293,18 +261,10 @@ public void onDatabaseLoadingFailed(Exception ex) { dialogService.showErrorDialogAndWait(title, content, ex); } - public void feedData( - BibDatabaseContext bibDatabaseContextFromParserResult - ) { + public void feedData(BibDatabaseContext bibDatabaseContextFromParserResult) { cleanUp(); - if ( - this.getTabPane() - .getSelectionModel() - .selectedItemProperty() - .get() - .equals(this) - ) { + if (this.getTabPane().getSelectionModel().selectedItemProperty().get().equals(this)) { // If you open an existing library, a library tab with a loading animation is added immediately. // At that point, the library tab is given a temporary bibDatabaseContext with no entries. // This line is necessary because, while there is already a binding that updates the active database when a new tab is added, @@ -317,16 +277,13 @@ public void feedData( Optional foundExistingBibDatabase = stateManager .getOpenDatabases() .stream() - .filter(databaseContext -> - databaseContext.equals(this.bibDatabaseContext) - ) + .filter(databaseContext -> databaseContext.equals(this.bibDatabaseContext)) .findFirst(); foundExistingBibDatabase.ifPresent(databaseContext -> stateManager.getOpenDatabases().remove(databaseContext) ); - this.bibDatabaseContext = - Objects.requireNonNull(bibDatabaseContextFromParserResult); + this.bibDatabaseContext = Objects.requireNonNull(bibDatabaseContextFromParserResult); stateManager.getOpenDatabases().add(bibDatabaseContextFromParserResult); @@ -334,13 +291,8 @@ public void feedData( bibDatabaseContextFromParserResult.getMetaData().registerListener(this); this.tableModel = - new MainTableDataModel( - getBibDatabaseContext(), - preferencesService, - stateManager - ); - citationStyleCache = - new CitationStyleCache(bibDatabaseContextFromParserResult); + new MainTableDataModel(getBibDatabaseContext(), preferencesService, stateManager); + citationStyleCache = new CitationStyleCache(bibDatabaseContextFromParserResult); annotationCache = new FileAnnotationCache( bibDatabaseContextFromParserResult, @@ -353,13 +305,11 @@ public void feedData( this.getDatabase().registerListener(new EntriesRemovedListener()); // ensure that at each addition of a new entry, the entry is added to the groups interface - this.bibDatabaseContext.getDatabase() - .registerListener(new GroupTreeListener()); + this.bibDatabaseContext.getDatabase().registerListener(new GroupTreeListener()); // ensure that all entry changes mark the panel as changed this.bibDatabaseContext.getDatabase().registerListener(this); - this.getDatabase() - .registerListener(new UpdateTimestampListener(preferencesService)); + this.getDatabase().registerListener(new UpdateTimestampListener(preferencesService)); this.entryEditor = new EntryEditor(this); @@ -378,16 +328,9 @@ public void feedData( public void installAutosaveManagerAndBackupManager() { if (isDatabaseReadyForAutoSave(bibDatabaseContext)) { - AutosaveManager autosaveManager = AutosaveManager.start( - bibDatabaseContext - ); + AutosaveManager autosaveManager = AutosaveManager.start(bibDatabaseContext); autosaveManager.registerListener( - new AutosaveUiManager( - this, - dialogService, - preferencesService, - entryTypesManager - ) + new AutosaveUiManager(this, dialogService, preferencesService, entryTypesManager) ); } if ( @@ -407,9 +350,7 @@ private boolean isDatabaseReadyForAutoSave(BibDatabaseContext context) { return ( ((context.getLocation() == DatabaseLocation.SHARED) || ((context.getLocation() == DatabaseLocation.LOCAL) && - preferencesService - .getLibraryPreferences() - .shouldAutoSave())) && + preferencesService.getLibraryPreferences().shouldAutoSave())) && context.getDatabasePath().isPresent() ); } @@ -429,9 +370,7 @@ private boolean isDatabaseReadyForBackup(BibDatabaseContext context) { * Example: *jabref-authors.bib – testbib */ public void updateTabTitle(boolean isChanged) { - boolean isAutosaveEnabled = preferencesService - .getLibraryPreferences() - .shouldAutoSave(); + boolean isAutosaveEnabled = preferencesService.getLibraryPreferences().shouldAutoSave(); DatabaseLocation databaseLocation = bibDatabaseContext.getLocation(); Optional file = bibDatabaseContext.getDatabasePath(); @@ -471,9 +410,7 @@ public void updateTabTitle(boolean isChanged) { stateManager.collectAllDatabasePaths(), databasePath ); - uniquePathPart.ifPresent(part -> - tabTitle.append(" \u2013 ").append(part) - ); + uniquePathPart.ifPresent(part -> tabTitle.append(" \u2013 ").append(part)); } else { if (databaseLocation == DatabaseLocation.LOCAL) { tabTitle.append(Localization.lang("untitled")); @@ -492,10 +429,7 @@ public void updateTabTitle(boolean isChanged) { (databaseLocation == DatabaseLocation.LOCAL) && bibDatabaseContext.getDatabase().hasEntries() ) { - addChangedInformation( - toolTipText, - Localization.lang("untitled") - ); + addChangedInformation(toolTipText, Localization.lang("untitled")); } } @@ -504,11 +438,7 @@ public void updateTabTitle(boolean isChanged) { setTooltip(new Tooltip(toolTipText.toString())); }); - if ( - preferencesService - .getFilePreferences() - .shouldFulltextIndexLinkedFiles() - ) { + if (preferencesService.getFilePreferences().shouldFulltextIndexLinkedFiles()) { indexingTaskManager.updateDatabaseName(tabTitle.toString()); } } @@ -560,13 +490,7 @@ private void delete(boolean cut, List entries) { } getUndoManager() - .addEdit( - new UndoableRemoveEntries( - bibDatabaseContext.getDatabase(), - entries, - cut - ) - ); + .addEdit(new UndoableRemoveEntries(bibDatabaseContext.getDatabase(), entries, cut)); bibDatabaseContext.getDatabase().removeEntries(entries); ensureNotShowingBottomPanel(entries); @@ -621,19 +545,10 @@ public void insertEntries(final List entries) { ); // Create an UndoableInsertEntries object. getUndoManager() - .addEdit( - new UndoableInsertEntries( - bibDatabaseContext.getDatabase(), - entries - ) - ); + .addEdit(new UndoableInsertEntries(bibDatabaseContext.getDatabase(), entries)); this.changedProperty.setValue(true); // The database just changed. - if ( - preferencesService - .getEntryEditorPreferences() - .shouldOpenOnNewEntry() - ) { + if (preferencesService.getEntryEditorPreferences().shouldOpenOnNewEntry()) { showAndEdit(entries.get(0)); } clearAndSelect(entries.get(0)); @@ -730,10 +645,7 @@ private void setupAutoCompletion() { suggestionProviders = new SuggestionProviders(); } searchAutoCompleter = - new PersonNameSuggestionProvider( - FieldFactory.getPersonNameFields(), - getDatabase() - ); + new PersonNameSuggestionProvider(FieldFactory.getPersonNameFields(), getDatabase()); } public void updateSearchManager() { @@ -762,9 +674,7 @@ public void showAndEdit(BibEntry entry) { private void showBottomPane(BasePanelMode newMode) { if (newMode != BasePanelMode.SHOWING_EDITOR) { - throw new UnsupportedOperationException( - "new mode not recognized: " + newMode.name() - ); + throw new UnsupportedOperationException("new mode not recognized: " + newMode.name()); } Node pane = entryEditor; @@ -798,17 +708,13 @@ public void clearAndSelect(final BibEntry bibEntry) { public void selectPreviousEntry() { mainTable .getSelectionModel() - .clearAndSelect( - mainTable.getSelectionModel().getSelectedIndex() - 1 - ); + .clearAndSelect(mainTable.getSelectionModel().getSelectedIndex() - 1); } public void selectNextEntry() { mainTable .getSelectionModel() - .clearAndSelect( - mainTable.getSelectionModel().getSelectedIndex() + 1 - ); + .clearAndSelect(mainTable.getSelectionModel().getSelectedIndex() + 1); } /** @@ -847,9 +753,7 @@ public void updateEntryEditorIfShowing() { public synchronized void markChangedOrUnChanged() { if (undoManager.hasChanged()) { this.changedProperty.setValue(true); - } else if ( - changedProperty.getValue() && !nonUndoableChangeProperty.getValue() - ) { + } else if (changedProperty.getValue() && !nonUndoableChangeProperty.getValue()) { this.changedProperty.setValue(false); } } @@ -859,13 +763,9 @@ public BibDatabase getDatabase() { } private boolean showDeleteConfirmationDialog(int numberOfEntries) { - if ( - preferencesService.getWorkspacePreferences().shouldConfirmDelete() - ) { + if (preferencesService.getWorkspacePreferences().shouldConfirmDelete()) { String title = Localization.lang("Delete entry"); - String message = Localization.lang( - "Really delete the selected entry?" - ); + String message = Localization.lang("Really delete the selected entry?"); String okButton = Localization.lang("Delete entry"); String cancelButton = Localization.lang("Keep entry"); if (numberOfEntries > 1) { @@ -885,10 +785,7 @@ private boolean showDeleteConfirmationDialog(int numberOfEntries) { okButton, cancelButton, Localization.lang("Do not ask again"), - optOut -> - preferencesService - .getWorkspacePreferences() - .setConfirmDelete(!optOut) + optOut -> preferencesService.getWorkspacePreferences().setConfirmDelete(!optOut) ); } else { return true; @@ -949,9 +846,7 @@ public String formatOutputMessage(String start, int count) { "%s %d %s.", start, count, - (count > 1 - ? Localization.lang("entries") - : Localization.lang("entry")) + (count > 1 ? Localization.lang("entries") : Localization.lang("entry")) ); } @@ -970,9 +865,7 @@ public Optional getCurrentSearchQuery() { /** * Set the query the user currently searches while this basepanel is active */ - public void setCurrentSearchQuery( - Optional currentSearchQuery - ) { + public void setCurrentSearchQuery(Optional currentSearchQuery) { this.currentSearchQuery = currentSearchQuery; } @@ -1117,25 +1010,16 @@ private class GroupTreeListener { @Subscribe public void listen(EntriesAddedEvent addedEntriesEvent) { // if the event is an undo, don't add it to the current group - if ( - addedEntriesEvent.getEntriesEventSource() == - EntriesEventSource.UNDO - ) { + if (addedEntriesEvent.getEntriesEventSource() == EntriesEventSource.UNDO) { return; } // Automatically add new entries to the selected group (or set of groups) - if ( - preferencesService - .getGroupsPreferences() - .shouldAutoAssignGroup() - ) { + if (preferencesService.getGroupsPreferences().shouldAutoAssignGroup()) { stateManager .getSelectedGroup(bibDatabaseContext) .forEach(selectedGroup -> - selectedGroup.addEntriesToGroup( - addedEntriesEvent.getBibEntries() - ) + selectedGroup.addEntriesToGroup(addedEntriesEvent.getBibEntries()) ); } } @@ -1153,22 +1037,14 @@ private class IndexUpdateListener { @Subscribe public void listen(EntriesAddedEvent addedEntryEvent) { - if ( - preferencesService - .getFilePreferences() - .shouldFulltextIndexLinkedFiles() - ) { + if (preferencesService.getFilePreferences().shouldFulltextIndexLinkedFiles()) { try { PdfIndexer pdfIndexer = PdfIndexer.of( bibDatabaseContext, preferencesService.getFilePreferences() ); for (BibEntry addedEntry : addedEntryEvent.getBibEntries()) { - indexingTaskManager.addToIndex( - pdfIndexer, - addedEntry, - bibDatabaseContext - ); + indexingTaskManager.addToIndex(pdfIndexer, addedEntry, bibDatabaseContext); } } catch (IOException e) { LOGGER.error("Cannot access lucene index", e); @@ -1178,21 +1054,14 @@ public void listen(EntriesAddedEvent addedEntryEvent) { @Subscribe public void listen(EntriesRemovedEvent removedEntriesEvent) { - if ( - preferencesService - .getFilePreferences() - .shouldFulltextIndexLinkedFiles() - ) { + if (preferencesService.getFilePreferences().shouldFulltextIndexLinkedFiles()) { try { PdfIndexer pdfIndexer = PdfIndexer.of( bibDatabaseContext, preferencesService.getFilePreferences() ); for (BibEntry removedEntry : removedEntriesEvent.getBibEntries()) { - indexingTaskManager.removeFromIndex( - pdfIndexer, - removedEntry - ); + indexingTaskManager.removeFromIndex(pdfIndexer, removedEntry); } } catch (IOException e) { LOGGER.error("Cannot access lucene index", e); @@ -1202,11 +1071,7 @@ public void listen(EntriesRemovedEvent removedEntriesEvent) { @Subscribe public void listen(FieldChangedEvent fieldChangedEvent) { - if ( - preferencesService - .getFilePreferences() - .shouldFulltextIndexLinkedFiles() - ) { + if (preferencesService.getFilePreferences().shouldFulltextIndexLinkedFiles()) { if (fieldChangedEvent.getField().equals(StandardField.FILE)) { List oldFileList = FileFieldParser.parse( fieldChangedEvent.getOldValue() @@ -1217,9 +1082,7 @@ public void listen(FieldChangedEvent fieldChangedEvent) { List addedFiles = new ArrayList<>(newFileList); addedFiles.remove(oldFileList); - List removedFiles = new ArrayList<>( - oldFileList - ); + List removedFiles = new ArrayList<>(oldFileList); removedFiles.remove(newFileList); try { @@ -1258,12 +1121,7 @@ public DatabaseNotification(Node content) { super(content); } - public void notify( - Node graphic, - String text, - List actions, - Duration duration - ) { + public void notify(Node graphic, String text, List actions, Duration duration) { this.setGraphic(graphic); this.setText(text); this.getActions().setAll(actions); diff --git a/src/main/java/org/jabref/gui/MainApplication.java b/src/main/java/org/jabref/gui/MainApplication.java index f83dcc3a9a7..307708c1a1a 100644 --- a/src/main/java/org/jabref/gui/MainApplication.java +++ b/src/main/java/org/jabref/gui/MainApplication.java @@ -36,13 +36,7 @@ public static void main( public void start(Stage mainStage) { FallbackExceptionHandler.installExceptionHandler(); Globals.startBackgroundTasks(); - new JabRefGUI( - mainStage, - parserResults, - isBlank, - preferences, - fileUpdateMonitor - ); + new JabRefGUI(mainStage, parserResults, isBlank, preferences, fileUpdateMonitor); } @Override diff --git a/src/main/java/org/jabref/gui/MainMenu.java b/src/main/java/org/jabref/gui/MainMenu.java index 15b89537965..89922a08313 100644 --- a/src/main/java/org/jabref/gui/MainMenu.java +++ b/src/main/java/org/jabref/gui/MainMenu.java @@ -133,10 +133,7 @@ private void createMenu() { StandardActions.NEW_LIBRARY, new NewDatabaseAction(frame, preferencesService) ), - factory.createMenuItem( - StandardActions.OPEN_LIBRARY, - frame.getOpenDatabaseAction() - ), + factory.createMenuItem(StandardActions.OPEN_LIBRARY, frame.getOpenDatabaseAction()), frame.getFileHistory(), factory.createMenuItem( StandardActions.SAVE_LIBRARY, @@ -251,10 +248,7 @@ private void createMenu() { new ShowPreferencesAction(frame, taskExecutor) ), new SeparatorMenuItem(), - factory.createMenuItem( - StandardActions.QUIT, - new JabRefFrame.CloseAction(frame) - ) + factory.createMenuItem(StandardActions.QUIT, new JabRefFrame.CloseAction(frame)) ); edit @@ -262,21 +256,11 @@ private void createMenu() { .addAll( factory.createMenuItem( StandardActions.UNDO, - new UndoRedoAction( - StandardActions.UNDO, - frame, - dialogService, - stateManager - ) + new UndoRedoAction(StandardActions.UNDO, frame, dialogService, stateManager) ), factory.createMenuItem( StandardActions.REDO, - new UndoRedoAction( - StandardActions.REDO, - frame, - dialogService, - stateManager - ) + new UndoRedoAction(StandardActions.REDO, frame, dialogService, stateManager) ), new SeparatorMenuItem(), factory.createMenuItem( @@ -399,11 +383,7 @@ private void createMenu() { SeparatorMenuItem specialFieldsSeparator = new SeparatorMenuItem(); specialFieldsSeparator .visibleProperty() - .bind( - preferencesService - .getSpecialFieldsPreferences() - .specialFieldsEnabledProperty() - ); + .bind(preferencesService.getSpecialFieldsPreferences().specialFieldsEnabledProperty()); edit .getItems() @@ -601,8 +581,7 @@ private void createMenu() { // @formatter:on getStyleClass().add("mainMenu"); - getMenus() - .addAll(file, edit, library, quality, lookup, tools, view, help); + getMenus().addAll(file, edit, library, quality, lookup, tools, view, help); setUseSystemMenuBar(true); } diff --git a/src/main/java/org/jabref/gui/MainToolBar.java b/src/main/java/org/jabref/gui/MainToolBar.java index 546227b2c11..c311e06e1b0 100644 --- a/src/main/java/org/jabref/gui/MainToolBar.java +++ b/src/main/java/org/jabref/gui/MainToolBar.java @@ -93,9 +93,7 @@ private void createToolBar() { pushToApplicationCommand.getAction(), pushToApplicationCommand ); - pushToApplicationCommand.registerReconfigurable( - pushToApplicationButton - ); + pushToApplicationCommand.registerReconfigurable(pushToApplicationButton); // Setup Toolbar @@ -146,50 +144,27 @@ private void createToolBar() { ), factory.createIconButton( StandardActions.NEW_ENTRY, - new NewEntryAction( - frame, - dialogService, - preferencesService, - stateManager - ) + new NewEntryAction(frame, dialogService, preferencesService, stateManager) ), createNewEntryFromIdButton(), factory.createIconButton( StandardActions.NEW_ENTRY_FROM_PLAIN_TEXT, - new ExtractBibtexAction( - dialogService, - preferencesService, - stateManager - ) + new ExtractBibtexAction(dialogService, preferencesService, stateManager) ), factory.createIconButton( StandardActions.DELETE_ENTRY, - new EditAction( - StandardActions.DELETE_ENTRY, - frame, - stateManager - ) + new EditAction(StandardActions.DELETE_ENTRY, frame, stateManager) ) ), new Separator(Orientation.VERTICAL), new HBox( factory.createIconButton( StandardActions.UNDO, - new UndoRedoAction( - StandardActions.UNDO, - frame, - dialogService, - stateManager - ) + new UndoRedoAction(StandardActions.UNDO, frame, dialogService, stateManager) ), factory.createIconButton( StandardActions.REDO, - new UndoRedoAction( - StandardActions.REDO, - frame, - dialogService, - stateManager - ) + new UndoRedoAction(StandardActions.REDO, frame, dialogService, stateManager) ), factory.createIconButton( StandardActions.CUT, @@ -197,19 +172,11 @@ private void createToolBar() { ), factory.createIconButton( StandardActions.COPY, - new EditAction( - StandardActions.COPY, - frame, - stateManager - ) + new EditAction(StandardActions.COPY, frame, stateManager) ), factory.createIconButton( StandardActions.PASTE, - new EditAction( - StandardActions.PASTE, - frame, - stateManager - ) + new EditAction(StandardActions.PASTE, frame, stateManager) ) ), new Separator(Orientation.VERTICAL), @@ -263,30 +230,23 @@ private void createToolBar() { Button createNewEntryFromIdButton() { Button newEntryFromIdButton = new Button(); - newEntryFromIdButton.setGraphic( - IconTheme.JabRefIcons.IMPORT.getGraphicNode() - ); + newEntryFromIdButton.setGraphic(IconTheme.JabRefIcons.IMPORT.getGraphicNode()); newEntryFromIdButton.getStyleClass().setAll("icon-button"); newEntryFromIdButton.setFocusTraversable(false); - newEntryFromIdButton - .disableProperty() - .bind(ActionHelper.needsDatabase(stateManager).not()); + newEntryFromIdButton.disableProperty().bind(ActionHelper.needsDatabase(stateManager).not()); newEntryFromIdButton.setOnMouseClicked(event -> { - GenerateEntryFromIdDialog entryFromId = - new GenerateEntryFromIdDialog( - frame.getCurrentLibraryTab(), - dialogService, - preferencesService, - taskExecutor, - stateManager - ); + GenerateEntryFromIdDialog entryFromId = new GenerateEntryFromIdDialog( + frame.getCurrentLibraryTab(), + dialogService, + preferencesService, + taskExecutor, + stateManager + ); if (entryFromIdPopOver == null) { entryFromIdPopOver = new PopOver(entryFromId.getDialogPane()); entryFromIdPopOver.setTitle(Localization.lang("Import by ID")); - entryFromIdPopOver.setArrowLocation( - PopOver.ArrowLocation.TOP_CENTER - ); + entryFromIdPopOver.setArrowLocation(PopOver.ArrowLocation.TOP_CENTER); entryFromIdPopOver.setContentNode(entryFromId.getDialogPane()); entryFromIdPopOver.show(newEntryFromIdButton); entryFromId.setEntryFromIdPopOver(entryFromIdPopOver); @@ -298,9 +258,7 @@ Button createNewEntryFromIdButton() { entryFromId.setEntryFromIdPopOver(entryFromIdPopOver); } }); - newEntryFromIdButton.setTooltip( - new Tooltip(Localization.lang("Import by ID")) - ); + newEntryFromIdButton.setTooltip(new Tooltip(Localization.lang("Import by ID"))); return newEntryFromIdButton; } @@ -310,12 +268,8 @@ Group createTaskIndicator() { indicator.getStyleClass().add("progress-indicatorToolbar"); indicator.progressProperty().bind(stateManager.getTasksProgress()); - Tooltip someTasksRunning = new Tooltip( - Localization.lang("Background Tasks are running") - ); - Tooltip noTasksRunning = new Tooltip( - Localization.lang("Background Tasks are done") - ); + Tooltip someTasksRunning = new Tooltip(Localization.lang("Background Tasks are running")); + Tooltip noTasksRunning = new Tooltip(Localization.lang("Background Tasks are done")); indicator.setTooltip(noTasksRunning); stateManager .getAnyTaskRunning() @@ -342,33 +296,21 @@ hide it and clip it to a square of (width x width) each time width is updated. indicator.setPrefWidth(newValue.doubleValue()); } if (newValue.doubleValue() > 0) { - Rectangle clip = new Rectangle( - newValue.doubleValue(), - newValue.doubleValue() - ); + Rectangle clip = new Rectangle(newValue.doubleValue(), newValue.doubleValue()); indicator.setClip(clip); } }); indicator.setOnMouseClicked(event -> { - TaskProgressView> taskProgressView = new TaskProgressView< - Task - >(); - EasyBind.bindContent( - taskProgressView.getTasks(), - stateManager.getBackgroundTasks() - ); + TaskProgressView> taskProgressView = new TaskProgressView>(); + EasyBind.bindContent(taskProgressView.getTasks(), stateManager.getBackgroundTasks()); taskProgressView.setRetainTasks(true); taskProgressView.setGraphicFactory(BackgroundTask::getIcon); if (progressViewPopOver == null) { progressViewPopOver = new PopOver(taskProgressView); - progressViewPopOver.setTitle( - Localization.lang("Background Tasks") - ); - progressViewPopOver.setArrowLocation( - PopOver.ArrowLocation.RIGHT_TOP - ); + progressViewPopOver.setTitle(Localization.lang("Background Tasks")); + progressViewPopOver.setArrowLocation(PopOver.ArrowLocation.RIGHT_TOP); progressViewPopOver.setContentNode(taskProgressView); progressViewPopOver.show(indicator); } else if (progressViewPopOver.isShowing()) { diff --git a/src/main/java/org/jabref/gui/OpenConsoleAction.java b/src/main/java/org/jabref/gui/OpenConsoleAction.java index 3808e28bc20..76810b10fc7 100644 --- a/src/main/java/org/jabref/gui/OpenConsoleAction.java +++ b/src/main/java/org/jabref/gui/OpenConsoleAction.java @@ -13,9 +13,7 @@ public class OpenConsoleAction extends SimpleCommand { - private static final Logger LOGGER = LoggerFactory.getLogger( - OpenConsoleAction.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(OpenConsoleAction.class); private final Supplier databaseContext; private final StateManager stateManager; private final PreferencesService preferencesService; @@ -60,11 +58,7 @@ public void execute() { .flatMap(BibDatabaseContext::getDatabasePath) .ifPresent(path -> { try { - JabRefDesktop.openConsole( - path, - preferencesService, - dialogService - ); + JabRefDesktop.openConsole(path, preferencesService, dialogService); } catch (IOException e) { LOGGER.info("Could not open console", e); } diff --git a/src/main/java/org/jabref/gui/SendAsEMailAction.java b/src/main/java/org/jabref/gui/SendAsEMailAction.java index 0ea00c2d41b..3a3f908b35e 100644 --- a/src/main/java/org/jabref/gui/SendAsEMailAction.java +++ b/src/main/java/org/jabref/gui/SendAsEMailAction.java @@ -33,9 +33,7 @@ @AllowedToUseAwt("Requires AWT to send an email") public abstract class SendAsEMailAction extends SimpleCommand { - private static final Logger LOGGER = LoggerFactory.getLogger( - SendAsEMailAction.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(SendAsEMailAction.class); private final DialogService dialogService; private final PreferencesService preferencesService; private final StateManager stateManager; @@ -67,17 +65,12 @@ public void execute() { } private String sendEmail() throws Exception { - if ( - !Desktop.isDesktopSupported() || - stateManager.getActiveDatabase().isEmpty() - ) { + if (!Desktop.isDesktopSupported() || stateManager.getActiveDatabase().isEmpty()) { return Localization.lang("Error creating email"); } if (stateManager.getSelectedEntries().isEmpty()) { - return Localization.lang( - "This operation requires one or more entries to be selected." - ); + return Localization.lang("This operation requires one or more entries to be selected."); } List entries = stateManager.getSelectedEntries(); @@ -116,14 +109,10 @@ private List getAttachments(List entries) { .getExternalApplicationsPreferences() .shouldAutoOpenEmailAttachmentsFolder(); - BibDatabaseContext databaseContext = stateManager - .getActiveDatabase() - .get(); + BibDatabaseContext databaseContext = stateManager.getActiveDatabase().get(); List fileList = FileUtil.getListOfLinkedFiles( entries, - databaseContext.getFileDirectories( - preferencesService.getFilePreferences() - ) + databaseContext.getFileDirectories(preferencesService.getFilePreferences()) ); List attachments = new ArrayList<>(); diff --git a/src/main/java/org/jabref/gui/SendAsKindleEmailAction.java b/src/main/java/org/jabref/gui/SendAsKindleEmailAction.java index 6baf340dca4..fa1e8fe9ee5 100644 --- a/src/main/java/org/jabref/gui/SendAsKindleEmailAction.java +++ b/src/main/java/org/jabref/gui/SendAsKindleEmailAction.java @@ -24,19 +24,13 @@ public SendAsKindleEmailAction( this.executable.bind( ActionHelper .needsEntriesSelected(stateManager) - .and( - ActionHelper.hasLinkedFileForSelectedEntries( - stateManager - ) - ) + .and(ActionHelper.hasLinkedFileForSelectedEntries(stateManager)) ); } @Override protected String getEmailAddress() { - return preferencesService - .getExternalApplicationsPreferences() - .getKindleEmail(); + return preferencesService.getExternalApplicationsPreferences().getKindleEmail(); } @Override diff --git a/src/main/java/org/jabref/gui/SendAsStandardEmailAction.java b/src/main/java/org/jabref/gui/SendAsStandardEmailAction.java index 1357db9229d..80f5de01114 100644 --- a/src/main/java/org/jabref/gui/SendAsStandardEmailAction.java +++ b/src/main/java/org/jabref/gui/SendAsStandardEmailAction.java @@ -22,9 +22,7 @@ */ public class SendAsStandardEmailAction extends SendAsEMailAction { - private static final Logger LOGGER = LoggerFactory.getLogger( - SendAsStandardEmailAction.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(SendAsStandardEmailAction.class); private final PreferencesService preferencesService; private final StateManager stateManager; private final BibEntryTypesManager entryTypesManager; @@ -50,17 +48,13 @@ protected String getEmailAddress() { @Override protected String getSubject() { - return preferencesService - .getExternalApplicationsPreferences() - .getEmailSubject(); + return preferencesService.getExternalApplicationsPreferences().getEmailSubject(); } @Override protected String getBody() { List entries = stateManager.getSelectedEntries(); - BibDatabaseContext databaseContext = stateManager - .getActiveDatabase() - .get(); + BibDatabaseContext databaseContext = stateManager.getActiveDatabase().get(); StringWriter rawEntries = new StringWriter(); BibWriter bibWriter = new BibWriter(rawEntries, OS.NEWLINE); @@ -71,11 +65,7 @@ protected String getBody() { for (BibEntry entry : entries) { try { - bibtexEntryWriter.write( - entry, - bibWriter, - databaseContext.getMode() - ); + bibtexEntryWriter.write(entry, bibWriter, databaseContext.getMode()); } catch (IOException e) { LOGGER.warn("Problem creating BibTeX file for mailing.", e); } diff --git a/src/main/java/org/jabref/gui/StateManager.java b/src/main/java/org/jabref/gui/StateManager.java index 3d479d5b531..01b807d090a 100644 --- a/src/main/java/org/jabref/gui/StateManager.java +++ b/src/main/java/org/jabref/gui/StateManager.java @@ -49,52 +49,41 @@ */ public class StateManager { - private static final Logger LOGGER = LoggerFactory.getLogger( - StateManager.class - ); - private final CustomLocalDragboard localDragboard = - new CustomLocalDragboard(); + private static final Logger LOGGER = LoggerFactory.getLogger(StateManager.class); + private final CustomLocalDragboard localDragboard = new CustomLocalDragboard(); private final ObservableList openDatabases = FXCollections.observableArrayList(); private final OptionalObjectProperty activeDatabase = OptionalObjectProperty.empty(); - private final ReadOnlyListWrapper activeGroups = - new ReadOnlyListWrapper<>(FXCollections.observableArrayList()); - private final ObservableList selectedEntries = - FXCollections.observableArrayList(); - private final ObservableMap< - BibDatabaseContext, - ObservableList - > selectedGroups = FXCollections.observableHashMap(); + private final ReadOnlyListWrapper activeGroups = new ReadOnlyListWrapper<>( + FXCollections.observableArrayList() + ); + private final ObservableList selectedEntries = FXCollections.observableArrayList(); + private final ObservableMap> selectedGroups = + FXCollections.observableHashMap(); private final OptionalObjectProperty activeSearchQuery = OptionalObjectProperty.empty(); - private final ObservableMap< - BibDatabaseContext, - IntegerProperty - > searchResultMap = FXCollections.observableHashMap(); - private final OptionalObjectProperty focusOwner = - OptionalObjectProperty.empty(); - private final ObservableList< - Pair, Task> - > backgroundTasks = FXCollections.observableArrayList(task -> - new Observable[] { - task.getValue().progressProperty(), - task.getValue().runningProperty(), - } - ); + private final ObservableMap searchResultMap = + FXCollections.observableHashMap(); + private final OptionalObjectProperty focusOwner = OptionalObjectProperty.empty(); + private final ObservableList, Task>> backgroundTasks = + FXCollections.observableArrayList(task -> + new Observable[] { + task.getValue().progressProperty(), + task.getValue().runningProperty(), + } + ); private final EasyBinding anyTaskRunning = EasyBind.reduce( backgroundTasks, tasks -> tasks.map(Pair::getValue).anyMatch(Task::isRunning) ); - private final EasyBinding anyTasksThatWillNotBeRecoveredRunning = - EasyBind.reduce( - backgroundTasks, - tasks -> - tasks.anyMatch(task -> - !task.getKey().willBeRecoveredAutomatically() && - task.getValue().isRunning() - ) - ); + private final EasyBinding anyTasksThatWillNotBeRecoveredRunning = EasyBind.reduce( + backgroundTasks, + tasks -> + tasks.anyMatch(task -> + !task.getKey().willBeRecoveredAutomatically() && task.getValue().isRunning() + ) + ); private final EasyBinding tasksProgress = EasyBind.reduce( backgroundTasks, tasks -> @@ -110,17 +99,13 @@ public class StateManager { private final ObservableList visibleSidePanes = FXCollections.observableArrayList(); - private final ObjectProperty< - LastAutomaticFieldEditorEdit - > lastAutomaticFieldEditorEdit = new SimpleObjectProperty<>(); + private final ObjectProperty lastAutomaticFieldEditorEdit = + new SimpleObjectProperty<>(); - private final ObservableList searchHistory = - FXCollections.observableArrayList(); + private final ObservableList searchHistory = FXCollections.observableArrayList(); public StateManager() { - activeGroups.bind( - Bindings.valueAt(selectedGroups, activeDatabase.orElseOpt(null)) - ); + activeGroups.bind(Bindings.valueAt(selectedGroups, activeDatabase.orElseOpt(null))); } public ObservableList getVisibleSidePaneComponents() { @@ -143,10 +128,7 @@ public OptionalObjectProperty activeSearchQueryProperty() { return activeSearchQuery; } - public void setActiveSearchResultSize( - BibDatabaseContext database, - IntegerProperty resultSize - ) { + public void setActiveSearchResultSize(BibDatabaseContext database, IntegerProperty resultSize) { searchResultMap.put(database, resultSize); } @@ -174,17 +156,11 @@ public void setSelectedGroups( List newSelectedGroups ) { Objects.requireNonNull(newSelectedGroups); - selectedGroups.put( - database, - FXCollections.observableArrayList(newSelectedGroups) - ); + selectedGroups.put(database, FXCollections.observableArrayList(newSelectedGroups)); } - public ObservableList getSelectedGroup( - BibDatabaseContext database - ) { - ObservableList selectedGroupsForDatabase = - selectedGroups.get(database); + public ObservableList getSelectedGroup(BibDatabaseContext database) { + ObservableList selectedGroupsForDatabase = selectedGroups.get(database); return selectedGroupsForDatabase != null ? selectedGroupsForDatabase : FXCollections.observableArrayList(); @@ -233,10 +209,7 @@ public ObservableList> getBackgroundTasks() { return EasyBind.map(backgroundTasks, Pair::getValue); } - public void addBackgroundTask( - BackgroundTask backgroundTask, - Task task - ) { + public void addBackgroundTask(BackgroundTask backgroundTask, Task task) { this.backgroundTasks.add(0, new Pair<>(backgroundTask, task)); } @@ -256,16 +229,11 @@ public DialogWindowState getDialogWindowState(String className) { return dialogWindowStates.get(className); } - public void setDialogWindowState( - String className, - DialogWindowState state - ) { + public void setDialogWindowState(String className, DialogWindowState state) { dialogWindowStates.put(className, state); } - public ObjectProperty< - LastAutomaticFieldEditorEdit - > lastAutomaticFieldEditorEditProperty() { + public ObjectProperty lastAutomaticFieldEditorEditProperty() { return lastAutomaticFieldEditorEdit; } diff --git a/src/main/java/org/jabref/gui/Telemetry.java b/src/main/java/org/jabref/gui/Telemetry.java index 8cb6d383364..4098b7d6dec 100644 --- a/src/main/java/org/jabref/gui/Telemetry.java +++ b/src/main/java/org/jabref/gui/Telemetry.java @@ -12,10 +12,7 @@ public static Optional getTelemetryClient() { return Optional.empty(); } - private static void start( - TelemetryPreferences telemetryPreferences, - BuildInfo buildInfo - ) {} + private static void start(TelemetryPreferences telemetryPreferences, BuildInfo buildInfo) {} public static void shutdown() { getTelemetryClient().ifPresent(client -> {}); diff --git a/src/main/java/org/jabref/gui/TelemetryClient.java b/src/main/java/org/jabref/gui/TelemetryClient.java index ba453a4d8d4..bb1bfe2c611 100644 --- a/src/main/java/org/jabref/gui/TelemetryClient.java +++ b/src/main/java/org/jabref/gui/TelemetryClient.java @@ -6,9 +6,5 @@ public class TelemetryClient { public void trackEvent(String actionName) {} - public void trackEvent( - String actionName, - Map source, - Map of - ) {} + public void trackEvent(String actionName, Map source, Map of) {} } diff --git a/src/main/java/org/jabref/gui/UpdateTimestampListener.java b/src/main/java/org/jabref/gui/UpdateTimestampListener.java index 03b237177de..964acc27ccc 100644 --- a/src/main/java/org/jabref/gui/UpdateTimestampListener.java +++ b/src/main/java/org/jabref/gui/UpdateTimestampListener.java @@ -22,11 +22,8 @@ public void listen(EntryChangedEvent event) { // The event source needs to be checked, since the timestamp is always updated on every change. The cleanup formatter is an exception to that behaviour, // since it just should move the contents from the timestamp field to modificationdate or creationdate. if ( - preferencesService - .getTimestampPreferences() - .shouldAddModificationDate() && - event.getEntriesEventSource() != - EntriesEventSource.CLEANUP_TIMESTAMP + preferencesService.getTimestampPreferences().shouldAddModificationDate() && + event.getEntriesEventSource() != EntriesEventSource.CLEANUP_TIMESTAMP ) { event .getBibEntry() diff --git a/src/main/java/org/jabref/gui/WaitForSaveFinishedDialog.java b/src/main/java/org/jabref/gui/WaitForSaveFinishedDialog.java index db0bb254e3b..369e0650cdb 100644 --- a/src/main/java/org/jabref/gui/WaitForSaveFinishedDialog.java +++ b/src/main/java/org/jabref/gui/WaitForSaveFinishedDialog.java @@ -20,9 +20,7 @@ public void showAndWait(List LibraryTabs) { Task waitForSaveFinished = new Task<>() { @Override protected Void call() throws Exception { - while ( - LibraryTabs.stream().anyMatch(LibraryTab::isSaving) - ) { + while (LibraryTabs.stream().anyMatch(LibraryTab::isSaving)) { if (isCancelled()) { return null; } else { @@ -35,8 +33,7 @@ protected Void call() throws Exception { dialogService.showProgressDialog( Localization.lang("Please wait..."), - Localization.lang("Waiting for save operation to finish") + - "...", + Localization.lang("Waiting for save operation to finish") + "...", waitForSaveFinished ); } diff --git a/src/main/java/org/jabref/gui/groups/GroupNodeViewModel.java b/src/main/java/org/jabref/gui/groups/GroupNodeViewModel.java index 0d91a71e858..3dbd80e9455 100644 --- a/src/main/java/org/jabref/gui/groups/GroupNodeViewModel.java +++ b/src/main/java/org/jabref/gui/groups/GroupNodeViewModel.java @@ -55,19 +55,16 @@ public class GroupNodeViewModel { private final BibDatabaseContext databaseContext; private final StateManager stateManager; private final GroupTreeNode groupNode; - private final ObservableList matchedEntries = - FXCollections.observableArrayList(); + private final ObservableList matchedEntries = FXCollections.observableArrayList(); private final SimpleBooleanProperty hasChildren; - private final SimpleBooleanProperty expandedProperty = - new SimpleBooleanProperty(); + private final SimpleBooleanProperty expandedProperty = new SimpleBooleanProperty(); private final BooleanBinding anySelectedEntriesMatched; private final BooleanBinding allSelectedEntriesMatched; private final TaskExecutor taskExecutor; private final CustomLocalDragboard localDragBoard; private final ObservableList entriesList; private final PreferencesService preferencesService; - private final InvalidationListener onInvalidatedGroup = listener -> - refreshGroup(); + private final InvalidationListener onInvalidatedGroup = listener -> refreshGroup(); public GroupNodeViewModel( BibDatabaseContext databaseContext, @@ -89,24 +86,15 @@ public GroupNodeViewModel( if (groupNode.getGroup() instanceof AutomaticGroup automaticGroup) { children = automaticGroup - .createSubgroups( - this.databaseContext.getDatabase().getEntries() - ) + .createSubgroups(this.databaseContext.getDatabase().getEntries()) .stream() .map(this::toViewModel) .sorted((group1, group2) -> - group1 - .getDisplayName() - .compareToIgnoreCase(group2.getDisplayName()) + group1.getDisplayName().compareToIgnoreCase(group2.getDisplayName()) ) - .collect( - Collectors.toCollection( - FXCollections::observableArrayList - ) - ); + .collect(Collectors.toCollection(FXCollections::observableArrayList)); } else { - children = - EasyBind.mapBacked(groupNode.getChildren(), this::toViewModel); + children = EasyBind.mapBacked(groupNode.getChildren(), this::toViewModel); } if (groupNode.getGroup() instanceof TexGroup) { databaseContext @@ -117,9 +105,7 @@ public GroupNodeViewModel( hasChildren = new SimpleBooleanProperty(); hasChildren.bind(Bindings.isNotEmpty(children)); EasyBind.subscribe( - preferencesService - .getGroupsPreferences() - .displayGroupCountProperty(), + preferencesService.getGroupsPreferences().displayGroupCountProperty(), shouldDisplay -> updateMatchedEntries() ); expandedProperty.set(groupNode.getGroup().isExpanded()); @@ -136,8 +122,7 @@ public GroupNodeViewModel( stateManager.getSelectedEntries(), groupNode::matches ); - anySelectedEntriesMatched = - selectedEntriesMatchStatus.anyMatch(matched -> matched); + anySelectedEntriesMatched = selectedEntriesMatchStatus.anyMatch(matched -> matched); // 'all' returns 'true' for empty streams, so this has to be checked explicitly allSelectedEntriesMatched = selectedEntriesMatchStatus @@ -288,19 +273,12 @@ public int hashCode() { public JabRefIcon getIcon() { Optional iconName = groupNode.getGroup().getIconName(); - return iconName - .flatMap(this::parseIcon) - .orElseGet(this::createDefaultIcon); + return iconName.flatMap(this::parseIcon).orElseGet(this::createDefaultIcon); } private JabRefIcon createDefaultIcon() { - Color color = groupNode - .getGroup() - .getColor() - .orElse(IconTheme.getDefaultGroupColor()); - return IconTheme.JabRefIcons.DEFAULT_GROUP_ICON_COLORED.withColor( - color - ); + Color color = groupNode.getGroup().getColor().orElse(IconTheme.getDefaultGroupColor()); + return IconTheme.JabRefIcons.DEFAULT_GROUP_ICON_COLORED.withColor(color); } private Optional parseIcon(String iconCode) { @@ -318,9 +296,7 @@ public GroupTreeNode getGroupNode() { /** * Gets invoked if an entry in the current database changes. */ - private void onDatabaseChanged( - ListChangeListener.Change change - ) { + private void onDatabaseChanged(ListChangeListener.Change change) { while (change.next()) { if (change.wasPermutated()) { // Nothing to do, as permutation doesn't change matched entries @@ -367,12 +343,9 @@ private void updateMatchedEntries() { // We calculate the new hit value // We could be more intelligent and try to figure out the new number of hits based on the entry change // for example, a previously matched entry gets removed -> hits = hits - 1 - if ( - preferencesService.getGroupsPreferences().shouldDisplayGroupCount() - ) { + if (preferencesService.getGroupsPreferences().shouldDisplayGroupCount()) { BackgroundTask - .wrap(() -> groupNode.findMatches(databaseContext.getDatabase()) - ) + .wrap(() -> groupNode.findMatches(databaseContext.getDatabase())) .onSuccess(entries -> { matchedEntries.clear(); matchedEntries.addAll(entries); @@ -397,10 +370,7 @@ boolean isMatchedBy(String searchString) { } public Color getColor() { - return groupNode - .getGroup() - .getColor() - .orElse(IconTheme.getDefaultGroupColor()); + return groupNode.getGroup().getColor().orElse(IconTheme.getDefaultGroupColor()); } public String getPath() { @@ -420,12 +390,9 @@ public Optional getChildByPath(String pathToSource) { */ public boolean acceptableDrop(Dragboard dragboard) { // TODO: we should also check isNodeDescendant - boolean canDropOtherGroup = dragboard.hasContent( - DragAndDropDataFormats.GROUP - ); + boolean canDropOtherGroup = dragboard.hasContent(DragAndDropDataFormats.GROUP); boolean canDropEntries = - localDragBoard.hasBibEntries() && - (groupNode.getGroup() instanceof GroupEntryChanger); + localDragBoard.hasBibEntries() && (groupNode.getGroup() instanceof GroupEntryChanger); return canDropOtherGroup || canDropEntries; } @@ -448,10 +415,7 @@ public Optional getParent() { return groupNode.getParent(); } - public void draggedOn( - GroupNodeViewModel target, - DroppingMouseLocation mouseLocation - ) { + public void draggedOn(GroupNodeViewModel target, DroppingMouseLocation mouseLocation) { // No action, if the target is the same as the source if (this.equals(target)) { return; @@ -497,9 +461,7 @@ public boolean canAddEntriesIn() { return false; } else if (group instanceof ExplicitGroup) { return true; - } else if ( - group instanceof LastNameGroup || group instanceof RegexKeywordGroup - ) { + } else if (group instanceof LastNameGroup || group instanceof RegexKeywordGroup) { return groupNode .getParent() .map(parent -> parent.getGroup()) @@ -521,8 +483,7 @@ public boolean canAddEntriesIn() { return false; } else { throw new UnsupportedOperationException( - "canAddEntriesIn method not yet implemented in group: " + - group.getClass().getName() + "canAddEntriesIn method not yet implemented in group: " + group.getClass().getName() ); } } @@ -553,8 +514,7 @@ public boolean canBeDragged() { return true; } else { throw new UnsupportedOperationException( - "canBeDragged method not yet implemented in group: " + - group.getClass().getName() + "canBeDragged method not yet implemented in group: " + group.getClass().getName() ); } } @@ -585,8 +545,7 @@ public boolean canAddGroupsIn() { return true; } else { throw new UnsupportedOperationException( - "canAddGroupsIn method not yet implemented in group: " + - group.getClass().getName() + "canAddGroupsIn method not yet implemented in group: " + group.getClass().getName() ); } } @@ -617,8 +576,7 @@ public boolean canRemove() { return true; } else { throw new UnsupportedOperationException( - "canRemove method not yet implemented in group: " + - group.getClass().getName() + "canRemove method not yet implemented in group: " + group.getClass().getName() ); } } @@ -649,8 +607,7 @@ public boolean isEditable() { return true; } else { throw new UnsupportedOperationException( - "isEditable method not yet implemented in group: " + - group.getClass().getName() + "isEditable method not yet implemented in group: " + group.getClass().getName() ); } } diff --git a/src/main/java/org/jabref/gui/groups/GroupTreeNodeViewModel.java b/src/main/java/org/jabref/gui/groups/GroupTreeNodeViewModel.java index b1babbe6b79..49cc2bb4df8 100644 --- a/src/main/java/org/jabref/gui/groups/GroupTreeNodeViewModel.java +++ b/src/main/java/org/jabref/gui/groups/GroupTreeNodeViewModel.java @@ -20,9 +20,7 @@ public class GroupTreeNodeViewModel { - private static final Logger LOGGER = LoggerFactory.getLogger( - GroupTreeNodeViewModel.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(GroupTreeNodeViewModel.class); private final GroupTreeNode node; @@ -59,22 +57,14 @@ public String getDescription() { String shortDescription = ""; boolean showDynamic = true; if (group instanceof ExplicitGroup explicitGroup) { - shortDescription = - GroupDescriptions.getShortDescriptionExplicitGroup( - explicitGroup - ); + shortDescription = GroupDescriptions.getShortDescriptionExplicitGroup(explicitGroup); } else if (group instanceof KeywordGroup keywordGroup) { shortDescription = - GroupDescriptions.getShortDescriptionKeywordGroup( - keywordGroup, - showDynamic - ); + GroupDescriptions.getShortDescriptionKeywordGroup(keywordGroup, showDynamic); } else if (group instanceof SearchGroup searchGroup) { - shortDescription = - GroupDescriptions.getShortDescription(searchGroup, showDynamic); + shortDescription = GroupDescriptions.getShortDescription(searchGroup, showDynamic); } else { - shortDescription = - GroupDescriptions.getShortDescriptionAllEntriesGroup(); + shortDescription = GroupDescriptions.getShortDescriptionAllEntriesGroup(); } return "" + shortDescription + ""; } @@ -97,10 +87,7 @@ public void sortChildrenByName(boolean recursive) { getNode() .sortChildren( (node1, node2) -> - node1 - .getGroup() - .getName() - .compareToIgnoreCase(node2.getGroup().getName()), + node1.getGroup().getName().compareToIgnoreCase(node2.getGroup().getName()), recursive ); } @@ -160,10 +147,7 @@ public boolean canMoveRight() { ); } - public void changeEntriesTo( - List entries, - UndoManager undoManager - ) { + public void changeEntriesTo(List entries, UndoManager undoManager) { AbstractGroup group = node.getGroup(); List changesRemove = new ArrayList<>(); List changesAdd = new ArrayList<>(); @@ -194,25 +178,17 @@ public void changeEntriesTo( // Remember undo information if (!changesRemove.isEmpty()) { - AbstractUndoableEdit undoRemove = - UndoableChangeEntriesOfGroup.getUndoableEdit( - this, - changesRemove - ); + AbstractUndoableEdit undoRemove = UndoableChangeEntriesOfGroup.getUndoableEdit( + this, + changesRemove + ); if (!changesAdd.isEmpty() && (undoRemove != null)) { // we removed and added entries - undoRemove.addEdit( - UndoableChangeEntriesOfGroup.getUndoableEdit( - this, - changesAdd - ) - ); + undoRemove.addEdit(UndoableChangeEntriesOfGroup.getUndoableEdit(this, changesAdd)); } undoManager.addEdit(undoRemove); } else if (!changesAdd.isEmpty()) { - undoManager.addEdit( - UndoableChangeEntriesOfGroup.getUndoableEdit(this, changesAdd) - ); + undoManager.addEdit(UndoableChangeEntriesOfGroup.getUndoableEdit(this, changesAdd)); } } @@ -224,10 +200,7 @@ public boolean isAllEntriesGroup() { return getNode().getGroup() instanceof AllEntriesGroup; } - public void addNewGroup( - AbstractGroup newGroup, - CountingUndoManager undoManager - ) { + public void addNewGroup(AbstractGroup newGroup, CountingUndoManager undoManager) { GroupTreeNode newNode = GroupTreeNode.fromGroup(newGroup); this.getNode().addChild(newNode); @@ -246,9 +219,7 @@ public List addEntriesToGroup(List entries) { return node.addEntriesToGroup(entries); } - public void subscribeToDescendantChanged( - Consumer subscriber - ) { + public void subscribeToDescendantChanged(Consumer subscriber) { getNode() .subscribeToDescendantChanged(node -> subscriber.accept(new GroupTreeNodeViewModel(node)) diff --git a/src/main/java/org/jabref/gui/groups/GroupTreeView.java b/src/main/java/org/jabref/gui/groups/GroupTreeView.java index 16225eccc6c..09d38046997 100644 --- a/src/main/java/org/jabref/gui/groups/GroupTreeView.java +++ b/src/main/java/org/jabref/gui/groups/GroupTreeView.java @@ -68,31 +68,23 @@ public class GroupTreeView extends BorderPane { - private static final Logger LOGGER = LoggerFactory.getLogger( - GroupTreeView.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(GroupTreeView.class); - private static final PseudoClass PSEUDOCLASS_ANYSELECTED = - PseudoClass.getPseudoClass("any-selected"); - private static final PseudoClass PSEUDOCLASS_ALLSELECTED = - PseudoClass.getPseudoClass("all-selected"); - private static final PseudoClass PSEUDOCLASS_ROOTELEMENT = - PseudoClass.getPseudoClass("root"); - private static final PseudoClass PSEUDOCLASS_SUBELEMENT = - PseudoClass.getPseudoClass("sub"); // > 1 deep + private static final PseudoClass PSEUDOCLASS_ANYSELECTED = PseudoClass.getPseudoClass( + "any-selected" + ); + private static final PseudoClass PSEUDOCLASS_ALLSELECTED = PseudoClass.getPseudoClass( + "all-selected" + ); + private static final PseudoClass PSEUDOCLASS_ROOTELEMENT = PseudoClass.getPseudoClass("root"); + private static final PseudoClass PSEUDOCLASS_SUBELEMENT = PseudoClass.getPseudoClass("sub"); // > 1 deep private static final double SCROLL_SPEED_UP = 3.0; private TreeTableView groupTree; private TreeTableColumn mainColumn; - private TreeTableColumn< - GroupNodeViewModel, - GroupNodeViewModel - > numberColumn; - private TreeTableColumn< - GroupNodeViewModel, - GroupNodeViewModel - > expansionNodeColumn; + private TreeTableColumn numberColumn; + private TreeTableColumn expansionNodeColumn; private CustomTextField searchField; private final StateManager stateManager; @@ -130,9 +122,7 @@ public GroupTreeView( this.getStylesheets() .add( Objects - .requireNonNull( - GroupTreeView.class.getResource("GroupTree.css") - ) + .requireNonNull(GroupTreeView.class.getResource("GroupTree.css")) .toExternalForm() ); initialize(); @@ -166,17 +156,11 @@ private void createNodes() { groupTree = new TreeTableView<>(); groupTree.setId("groupTree"); - groupTree.setColumnResizePolicy( - TreeTableView.CONSTRAINED_RESIZE_POLICY_FLEX_LAST_COLUMN - ); - groupTree - .getColumns() - .addAll(List.of(mainColumn, numberColumn, expansionNodeColumn)); + groupTree.setColumnResizePolicy(TreeTableView.CONSTRAINED_RESIZE_POLICY_FLEX_LAST_COLUMN); + groupTree.getColumns().addAll(List.of(mainColumn, numberColumn, expansionNodeColumn)); this.setCenter(groupTree); - mainColumn - .prefWidthProperty() - .bind(groupTree.widthProperty().subtract(80d).subtract(15d)); + mainColumn.prefWidthProperty().bind(groupTree.widthProperty().subtract(80d).subtract(15d)); Button addNewGroup = new Button(Localization.lang("Add group")); addNewGroup.setId("addNewGroup"); @@ -210,8 +194,7 @@ private void initialize() { BindingsHelper.bindContentBidirectional( groupTree.getSelectionModel().getSelectedItems(), viewModel.selectedGroupsProperty(), - newSelectedGroups -> - newSelectedGroups.forEach(this::selectNode), + newSelectedGroups -> newSelectedGroups.forEach(this::selectNode), this::updateSelection ) ); @@ -222,16 +205,12 @@ private void initialize() { Duration.ofMillis(400), () -> { LOGGER.debug("Run group search {}", searchField.getText()); - viewModel - .filterTextProperty() - .setValue(searchField.textProperty().getValue()); + viewModel.filterTextProperty().setValue(searchField.textProperty().getValue()); } ); searchField .textProperty() - .addListener((observable, oldValue, newValue) -> - searchTask.restart() - ); + .addListener((observable, oldValue, newValue) -> searchTask.restart()); groupTree .rootProperty() @@ -282,8 +261,7 @@ private void initialize() { MouseEvent.MOUSE_PRESSED, (row, event) -> { if ( - ((MouseEvent) event).getButton() == - MouseButton.SECONDARY && + ((MouseEvent) event).getButton() == MouseButton.SECONDARY && !stateManager.getSelectedEntries().isEmpty() ) { // Prevent right-click to select group whe we have selected entries @@ -291,9 +269,7 @@ private void initialize() { } else if (event.getTarget() instanceof StackPane pane) { if ( pane.getStyleClass().contains("arrow") || - pane - .getStyleClass() - .contains("tree-disclosure-node") + pane.getStyleClass().contains("tree-disclosure-node") ) { event.consume(); } @@ -306,9 +282,7 @@ private void initialize() { row.setDisclosureNode(null); row .disclosureNodeProperty() - .addListener((observable, oldValue, newValue) -> - row.setDisclosureNode(null) - ); + .addListener((observable, oldValue, newValue) -> row.setDisclosureNode(null)); }) .setOnDragDetected(this::handleOnDragDetected) .setOnDragDropped(this::handleOnDragDropped) @@ -329,9 +303,7 @@ private void initialize() { PSEUDOCLASS_SUBELEMENT, row -> Bindings.createBooleanBinding( - () -> - (row != null) && - (groupTree.getTreeItemLevel(row.getTreeItem()) > 1), + () -> (row != null) && (groupTree.getTreeItemLevel(row.getTreeItem()) > 1), row.treeItemProperty() ) ) @@ -371,9 +343,7 @@ private StackPane createNumberCell(GroupNodeViewModel group) { } Text text = new Text(); EasyBind.subscribe( - preferencesService - .getGroupsPreferences() - .displayGroupCountProperty(), + preferencesService.getGroupsPreferences().displayGroupCountProperty(), shouldDisplayGroupCount -> { if (text.textProperty().isBound()) { text.textProperty().unbind(); @@ -383,12 +353,7 @@ private StackPane createNumberCell(GroupNodeViewModel group) { if (shouldDisplayGroupCount) { text .textProperty() - .bind( - group - .getHits() - .map(Number::intValue) - .map(this::getFormattedNumber) - ); + .bind(group.getHits().map(Number::intValue).map(this::getFormattedNumber)); Tooltip tooltip = new Tooltip(); tooltip.textProperty().bind(group.getHits().asString()); Tooltip.install(text, tooltip); @@ -416,14 +381,9 @@ private StackPane createNumberCell(GroupNodeViewModel group) { } else { reducedFontSize = 0.75; } - return String.format( - "-fx-font-size: %fem;", - reducedFontSize - ); + return String.format("-fx-font-size: %fem;", reducedFontSize); }, - preferencesService - .getWorkspacePreferences() - .mainFontSizeProperty() + preferencesService.getWorkspacePreferences().mainFontSizeProperty() ) ); @@ -477,10 +437,7 @@ private void handleOnDragDropped( Dragboard dragboard = event.getDragboard(); boolean success = false; - if ( - dragboard.hasContent(DragAndDropDataFormats.GROUP) && - row.getItem().canAddGroupsIn() - ) { + if (dragboard.hasContent(DragAndDropDataFormats.GROUP) && row.getItem().canAddGroupsIn()) { List pathToSources = (List) dragboard.getContent( DragAndDropDataFormats.GROUP ); @@ -541,9 +498,7 @@ private void handleOnDragOver( } } - private void updateSelection( - List> newSelectedGroups - ) { + private void updateSelection(List> newSelectedGroups) { if ((newSelectedGroups == null) || newSelectedGroups.isEmpty()) { viewModel.selectedGroupsProperty().clear(); } else { @@ -551,8 +506,7 @@ private void updateSelection( .stream() .filter(model -> (model != null) && - !(model.getValue().getGroupNode().getGroup() instanceof - AllEntriesGroup) + !(model.getValue().getGroupNode().getGroup() instanceof AllEntriesGroup) ) .map(TreeItem::getValue) .collect(Collectors.toList()); @@ -578,9 +532,7 @@ private void selectNode(GroupNodeViewModel value, boolean expandParents) { }); } - private Optional> getTreeItemByValue( - GroupNodeViewModel value - ) { + private Optional> getTreeItemByValue(GroupNodeViewModel value) { return getTreeItemByValue(groupTree.getRoot(), value); } @@ -617,8 +569,7 @@ private void setupDragScrolling() { () -> getVerticalScrollbar() .ifPresent(scrollBar -> { - double newValue = - scrollBar.getValue() + scrollVelocity; + double newValue = scrollBar.getValue() + scrollVelocity; newValue = Math.min(newValue, 1d); newValue = Math.max(newValue, 0d); scrollBar.setValue(newValue); @@ -643,19 +594,15 @@ private void setupDragScrolling() { double distanceFromNonScrollableInsideArea; if (scrollingUp) { - distanceFromNonScrollableInsideArea = - scrollableAreaHeight - event.getY(); + distanceFromNonScrollableInsideArea = scrollableAreaHeight - event.getY(); } else { distanceFromNonScrollableInsideArea = - scrollableAreaHeight - - (groupTree.getHeight() - event.getY()); + scrollableAreaHeight - (groupTree.getHeight() - event.getY()); } // part "(1+x)" of formula "speed = 20px/s (1+x)" (proposed by https://github.com/JabRef/jabref/issues/9754#issuecomment-1766864908) // / 10.0 is because of the 100 milliseconds above. (it is 20px per second, 10.0 * 100.0 ms = 1 second) - scrollVelocity = - (baseFactor * (1.0 + distanceFromNonScrollableInsideArea)) / - 10.0; + scrollVelocity = (baseFactor * (1.0 + distanceFromNonScrollableInsideArea)) / 10.0; if (scrollingUp) { scrollVelocity = -scrollVelocity; } @@ -687,8 +634,7 @@ private void initScrolling() { heightOfOneNode = heightOfOneNode * 2.0; // At most scroll area is three entries large - scrollableAreaHeight = - Math.min(heightOfOneNode * 3.0, groupTree.getHeight() / 3.0); + scrollableAreaHeight = Math.min(heightOfOneNode * 3.0, groupTree.getHeight() / 3.0); upperBorder = scrollableAreaHeight; lowerBorder = groupTree.getHeight() - scrollableAreaHeight; @@ -716,9 +662,7 @@ private ContextMenu createContextMenuForGroup(GroupNodeViewModel group) { } ContextMenu contextMenu = new ContextMenu(); - ActionFactory factory = new ActionFactory( - preferencesService.getKeyBindingRepository() - ); + ActionFactory factory = new ActionFactory(preferencesService.getKeyBindingRepository()); MenuItem removeGroup; if (group.hasSubgroups() && group.canAddGroupsIn() && !group.isRoot()) { @@ -745,10 +689,7 @@ private ContextMenu createContextMenuForGroup(GroupNodeViewModel group) { removeGroup = factory.createMenuItem( StandardActions.GROUP_REMOVE, - new GroupTreeView.ContextAction( - StandardActions.GROUP_REMOVE, - group - ) + new GroupTreeView.ContextAction(StandardActions.GROUP_REMOVE, group) ); } @@ -767,38 +708,23 @@ private ContextMenu createContextMenuForGroup(GroupNodeViewModel group) { ), factory.createMenuItem( StandardActions.GROUP_SUBGROUP_REMOVE, - new ContextAction( - StandardActions.GROUP_SUBGROUP_REMOVE, - group - ) + new ContextAction(StandardActions.GROUP_SUBGROUP_REMOVE, group) ), factory.createMenuItem( StandardActions.GROUP_SUBGROUP_SORT, - new ContextAction( - StandardActions.GROUP_SUBGROUP_SORT, - group - ) + new ContextAction(StandardActions.GROUP_SUBGROUP_SORT, group) ), factory.createMenuItem( StandardActions.GROUP_SUBGROUP_SORT_REVERSE, - new ContextAction( - StandardActions.GROUP_SUBGROUP_SORT_REVERSE, - group - ) + new ContextAction(StandardActions.GROUP_SUBGROUP_SORT_REVERSE, group) ), factory.createMenuItem( StandardActions.GROUP_SUBGROUP_SORT_ENTRIES, - new ContextAction( - StandardActions.GROUP_SUBGROUP_SORT_ENTRIES, - group - ) + new ContextAction(StandardActions.GROUP_SUBGROUP_SORT_ENTRIES, group) ), factory.createMenuItem( StandardActions.GROUP_SUBGROUP_SORT_ENTRIES_REVERSE, - new ContextAction( - StandardActions.GROUP_SUBGROUP_SORT_ENTRIES_REVERSE, - group - ) + new ContextAction(StandardActions.GROUP_SUBGROUP_SORT_ENTRIES_REVERSE, group) ), new SeparatorMenuItem(), factory.createMenuItem( @@ -807,10 +733,7 @@ private ContextMenu createContextMenuForGroup(GroupNodeViewModel group) { ), factory.createMenuItem( StandardActions.GROUP_ENTRIES_REMOVE, - new ContextAction( - StandardActions.GROUP_ENTRIES_REMOVE, - group - ) + new ContextAction(StandardActions.GROUP_ENTRIES_REMOVE, group) ) ); @@ -846,11 +769,7 @@ private void setupClearButtonField(CustomTextField customTextField) { ); m.setAccessible(true); m.invoke(null, customTextField, customTextField.rightProperty()); - } catch ( - NoSuchMethodException - | IllegalAccessException - | InvocationTargetException ex - ) { + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) { LOGGER.error("Failed to decorate text field with clear button", ex); } } @@ -869,10 +788,7 @@ public void expandGroup(TreeItem treeItem) { return; } - if ( - (System.currentTimeMillis() - this.dragStarted) > - DRAG_TIME_BEFORE_EXPANDING_MS - ) { + if ((System.currentTimeMillis() - this.dragStarted) > DRAG_TIME_BEFORE_EXPANDING_MS) { // expand or collapse the tree item and reset the time this.dragStarted = System.currentTimeMillis(); this.draggedItem.setExpanded(!this.draggedItem.isExpanded()); @@ -888,10 +804,7 @@ private class ContextAction extends SimpleCommand { private final StandardActions command; private final GroupNodeViewModel group; - public ContextAction( - StandardActions command, - GroupNodeViewModel group - ) { + public ContextAction(StandardActions command, GroupNodeViewModel group) { this.command = command; this.group = group; @@ -914,8 +827,7 @@ public ContextAction( group.hasSubgroups() && group.canAddEntriesIn()) || group.isRoot(); - case GROUP_ENTRIES_ADD, - GROUP_ENTRIES_REMOVE -> group.canAddEntriesIn(); + case GROUP_ENTRIES_ADD, GROUP_ENTRIES_REMOVE -> group.canAddEntriesIn(); default -> true; } ) @@ -926,12 +838,8 @@ public ContextAction( public void execute() { switch (command) { case GROUP_REMOVE -> viewModel.removeGroupNoSubgroups(group); - case GROUP_REMOVE_KEEP_SUBGROUPS -> viewModel.removeGroupKeepSubgroups( - group - ); - case GROUP_REMOVE_WITH_SUBGROUPS -> viewModel.removeGroupAndSubgroups( - group - ); + case GROUP_REMOVE_KEEP_SUBGROUPS -> viewModel.removeGroupKeepSubgroups(group); + case GROUP_REMOVE_WITH_SUBGROUPS -> viewModel.removeGroupAndSubgroups(group); case GROUP_EDIT -> { viewModel.editGroup(group); groupTree.refresh(); @@ -954,9 +862,7 @@ public void execute() { group.getGroupNode() ); case GROUP_ENTRIES_ADD -> viewModel.addSelectedEntries(group); - case GROUP_ENTRIES_REMOVE -> viewModel.removeSelectedEntries( - group - ); + case GROUP_ENTRIES_REMOVE -> viewModel.removeSelectedEntries(group); } } } diff --git a/src/main/java/org/jabref/gui/groups/GroupTreeViewModel.java b/src/main/java/org/jabref/gui/groups/GroupTreeViewModel.java index 95783d332bd..5636f469970 100644 --- a/src/main/java/org/jabref/gui/groups/GroupTreeViewModel.java +++ b/src/main/java/org/jabref/gui/groups/GroupTreeViewModel.java @@ -42,18 +42,17 @@ public class GroupTreeViewModel extends AbstractViewModel { - private final ObjectProperty rootGroup = - new SimpleObjectProperty<>(); - private final ListProperty selectedGroups = - new SimpleListProperty<>(FXCollections.observableArrayList()); + private final ObjectProperty rootGroup = new SimpleObjectProperty<>(); + private final ListProperty selectedGroups = new SimpleListProperty<>( + FXCollections.observableArrayList() + ); private final StateManager stateManager; private final DialogService dialogService; private final PreferencesService preferences; private final TaskExecutor taskExecutor; private final CustomLocalDragboard localDragboard; - private final ObjectProperty< - Predicate - > filterPredicate = new SimpleObjectProperty<>(); + private final ObjectProperty> filterPredicate = + new SimpleObjectProperty<>(); private final StringProperty filterText = new SimpleStringProperty(); private final Comparator compAlphabetIgnoreCase = ( GroupTreeNode v1, @@ -65,28 +64,17 @@ public class GroupTreeViewModel extends AbstractViewModel { GroupTreeNode v2 ) -> v2.getName().compareToIgnoreCase(v1.getName()); - private final Comparator compEntries = ( - GroupTreeNode v1, - GroupTreeNode v2 - ) -> { - int numChildren1 = v1 - .getEntriesInGroup(this.currentDatabase.get().getEntries()) - .size(); - int numChildren2 = v2 - .getEntriesInGroup(this.currentDatabase.get().getEntries()) - .size(); + private final Comparator compEntries = (GroupTreeNode v1, GroupTreeNode v2) -> { + int numChildren1 = v1.getEntriesInGroup(this.currentDatabase.get().getEntries()).size(); + int numChildren2 = v2.getEntriesInGroup(this.currentDatabase.get().getEntries()).size(); return Integer.compare(numChildren2, numChildren1); }; private final Comparator compEntriesReverse = ( GroupTreeNode v1, GroupTreeNode v2 ) -> { - int numChildren1 = v1 - .getEntriesInGroup(this.currentDatabase.get().getEntries()) - .size(); - int numChildren2 = v2 - .getEntriesInGroup(this.currentDatabase.get().getEntries()) - .size(); + int numChildren1 = v1.getEntriesInGroup(this.currentDatabase.get().getEntries()).size(); + int numChildren2 = v2.getEntriesInGroup(this.currentDatabase.get().getEntries()).size(); return Integer.compare(numChildren1, numChildren2); }; private Optional currentDatabase = Optional.empty(); @@ -105,25 +93,18 @@ public GroupTreeViewModel( this.localDragboard = Objects.requireNonNull(localDragboard); // Register listener - EasyBind.subscribe( - stateManager.activeDatabaseProperty(), - this::onActiveDatabaseChanged - ); + EasyBind.subscribe(stateManager.activeDatabaseProperty(), this::onActiveDatabaseChanged); EasyBind.subscribe(selectedGroups, this::onSelectedGroupChanged); // Set-up bindings - filterPredicate.bind( - EasyBind.map(filterText, text -> group -> group.isMatchedBy(text)) - ); + filterPredicate.bind(EasyBind.map(filterText, text -> group -> group.isMatchedBy(text))); // Init refresh(); } private void refresh() { - onActiveDatabaseChanged( - stateManager.activeDatabaseProperty().getValue() - ); + onActiveDatabaseChanged(stateManager.activeDatabaseProperty().getValue()); } public ObjectProperty rootGroupProperty() { @@ -134,9 +115,7 @@ public ListProperty selectedGroupsProperty() { return selectedGroups; } - public ObjectProperty< - Predicate - > filterPredicateProperty() { + public ObjectProperty> filterPredicateProperty() { return filterPredicate; } @@ -148,14 +127,8 @@ public StringProperty filterTextProperty() { * Gets invoked if the user selects a different group. * We need to notify the {@link StateManager} about this change so that the main table gets updated. */ - private void onSelectedGroupChanged( - ObservableList newValue - ) { - if ( - !currentDatabase.equals( - stateManager.activeDatabaseProperty().getValue() - ) - ) { + private void onSelectedGroupChanged(ObservableList newValue) { + if (!currentDatabase.equals(stateManager.activeDatabaseProperty().getValue())) { // Switch of database occurred -> do nothing return; } @@ -184,9 +157,7 @@ public void addNewGroupToRoot() { } else { dialogService.showWarningDialogAndWait( Localization.lang("Cannot create group"), - Localization.lang( - "Cannot create group. Please create a library first." - ) + Localization.lang("Cannot create group. Please create a library first.") ); } } @@ -195,9 +166,7 @@ public void addNewGroupToRoot() { * Gets invoked if the user changes the active database. * We need to get the new group tree and update the view */ - private void onActiveDatabaseChanged( - Optional newDatabase - ) { + private void onActiveDatabaseChanged(Optional newDatabase) { if (newDatabase.isPresent()) { GroupNodeViewModel newRoot = newDatabase .map(BibDatabaseContext::getMetaData) @@ -254,15 +223,11 @@ private void onActiveDatabaseChanged( /** * Opens "New Group Dialog" and adds the resulting group as subgroup to the specified group */ - public void addNewSubgroup( - GroupNodeViewModel parent, - GroupDialogHeader groupDialogHeader - ) { + public void addNewSubgroup(GroupNodeViewModel parent, GroupDialogHeader groupDialogHeader) { currentDatabase.ifPresent(database -> { - Optional newGroup = - dialogService.showCustomDialogAndWait( - new GroupDialogView(database, null, groupDialogHeader) - ); + Optional newGroup = dialogService.showCustomDialogAndWait( + new GroupDialogView(database, null, groupDialogHeader) + ); newGroup.ifPresent(group -> { parent.addSubgroup(group); @@ -274,9 +239,7 @@ public void addNewSubgroup( // TODO: Expand parent to make new group visible // parent.expand(); - dialogService.notify( - Localization.lang("Added group \"%0\".", group.getName()) - ); + dialogService.notify(Localization.lang("Added group \"%0\".", group.getName())); writeGroupChangesToMetaData(); }); }); @@ -288,10 +251,7 @@ public void writeGroupChangesToMetaData() { ); } - private boolean isGroupTypeEqual( - AbstractGroup oldGroup, - AbstractGroup newGroup - ) { + private boolean isGroupTypeEqual(AbstractGroup oldGroup, AbstractGroup newGroup) { return oldGroup.getClass().equals(newGroup.getClass()); } @@ -324,10 +284,8 @@ boolean onlyMinorChanges(AbstractGroup oldGroup, AbstractGroup newGroup) { ) ); } else if (oldGroup.getClass() == RegexKeywordGroup.class) { - RegexKeywordGroup oldRegexKeywordGroup = - (RegexKeywordGroup) oldGroup; - RegexKeywordGroup newRegexKeywordGroup = - (RegexKeywordGroup) newGroup; + RegexKeywordGroup oldRegexKeywordGroup = (RegexKeywordGroup) oldGroup; + RegexKeywordGroup newRegexKeywordGroup = (RegexKeywordGroup) newGroup; return ( Objects.equals( @@ -352,16 +310,11 @@ boolean onlyMinorChanges(AbstractGroup oldGroup, AbstractGroup newGroup) { oldSearchGroup.getSearchExpression(), newSearchGroup.getSearchExpression() ) && - Objects.equals( - oldSearchGroup.getSearchFlags(), - newSearchGroup.getSearchFlags() - ) + Objects.equals(oldSearchGroup.getSearchFlags(), newSearchGroup.getSearchFlags()) ); } else if (oldGroup.getClass() == AutomaticKeywordGroup.class) { - AutomaticKeywordGroup oldAutomaticKeywordGroup = - (AutomaticKeywordGroup) oldGroup; - AutomaticKeywordGroup newAutomaticKeywordGroup = - (AutomaticKeywordGroup) oldGroup; + AutomaticKeywordGroup oldAutomaticKeywordGroup = (AutomaticKeywordGroup) oldGroup; + AutomaticKeywordGroup newAutomaticKeywordGroup = (AutomaticKeywordGroup) oldGroup; return ( Objects.equals( @@ -378,10 +331,8 @@ boolean onlyMinorChanges(AbstractGroup oldGroup, AbstractGroup newGroup) { ) ); } else if (oldGroup.getClass() == AutomaticPersonsGroup.class) { - AutomaticPersonsGroup oldAutomaticPersonsGroup = - (AutomaticPersonsGroup) oldGroup; - AutomaticPersonsGroup newAutomaticPersonsGroup = - (AutomaticPersonsGroup) newGroup; + AutomaticPersonsGroup oldAutomaticPersonsGroup = (AutomaticPersonsGroup) oldGroup; + AutomaticPersonsGroup newAutomaticPersonsGroup = (AutomaticPersonsGroup) newGroup; return Objects.equals( oldAutomaticPersonsGroup.getField().getName(), @@ -403,14 +354,13 @@ boolean onlyMinorChanges(AbstractGroup oldGroup, AbstractGroup newGroup) { */ public void editGroup(GroupNodeViewModel oldGroup) { currentDatabase.ifPresent(database -> { - Optional newGroup = - dialogService.showCustomDialogAndWait( - new GroupDialogView( - database, - oldGroup.getGroupNode().getGroup(), - GroupDialogHeader.SUBGROUP - ) - ); + Optional newGroup = dialogService.showCustomDialogAndWait( + new GroupDialogView( + database, + oldGroup.getGroupNode().getGroup(), + GroupDialogHeader.SUBGROUP + ) + ); newGroup.ifPresent(group -> { AbstractGroup oldGroupDef = oldGroup.getGroupNode().getGroup(); String oldGroupName = oldGroupDef.getName(); @@ -436,9 +386,7 @@ public void editGroup(GroupNodeViewModel oldGroup) { groupsWithSameName = databaseRootGroup .get() - .findChildrenSatisfying(g -> - g.getName().equals(oldGroupName) - ) + .findChildrenSatisfying(g -> g.getName().equals(oldGroupName)) .size(); } boolean removePreviousAssignments = true; @@ -449,18 +397,10 @@ public void editGroup(GroupNodeViewModel oldGroup) { oldGroup .getGroupNode() - .setGroup( - group, - true, - removePreviousAssignments, - database.getEntries() - ); + .setGroup(group, true, removePreviousAssignments, database.getEntries()); dialogService.notify( - Localization.lang( - "Modified group \"%0\".", - group.getName() - ) + Localization.lang("Modified group \"%0\".", group.getName()) ); writeGroupChangesToMetaData(); // This is ugly but we have no proper update mechanism in place to propagate the changes, so redraw everything @@ -468,13 +408,8 @@ public void editGroup(GroupNodeViewModel oldGroup) { return; } - if ( - groupTypeEqual && - onlyMinorChanges(oldGroup.getGroupNode().getGroup(), group) - ) { - oldGroup - .getGroupNode() - .setGroup(group, true, true, database.getEntries()); + if (groupTypeEqual && onlyMinorChanges(oldGroup.getGroupNode().getGroup(), group)) { + oldGroup.getGroupNode().setGroup(group, true, true, database.getEntries()); writeGroupChangesToMetaData(); refresh(); @@ -517,8 +452,7 @@ public void editGroup(GroupNodeViewModel oldGroup) { cancel ); boolean removePreviousAssignments = - (oldGroup.getGroupNode().getGroup() instanceof - ExplicitGroup) && + (oldGroup.getGroupNode().getGroup() instanceof ExplicitGroup) && (group instanceof ExplicitGroup); int groupsWithSameName = 0; @@ -531,9 +465,7 @@ public void editGroup(GroupNodeViewModel oldGroup) { groupsWithSameName = databaseRootGroup .get() - .findChildrenSatisfying(g -> - g.getName().equals(name) - ) + .findChildrenSatisfying(g -> g.getName().equals(name)) .size(); } // okay we found more than 2 groups with the same name @@ -544,34 +476,21 @@ public void editGroup(GroupNodeViewModel oldGroup) { if ( previousAssignments.isPresent() && - (previousAssignments.get().getButtonData() == - ButtonBar.ButtonData.YES) + (previousAssignments.get().getButtonData() == ButtonBar.ButtonData.YES) ) { oldGroup .getGroupNode() - .setGroup( - group, - true, - removePreviousAssignments, - database.getEntries() - ); + .setGroup(group, true, removePreviousAssignments, database.getEntries()); } else if ( previousAssignments.isPresent() && - (previousAssignments.get().getButtonData() == - ButtonBar.ButtonData.NO) + (previousAssignments.get().getButtonData() == ButtonBar.ButtonData.NO) ) { oldGroup .getGroupNode() - .setGroup( - group, - false, - removePreviousAssignments, - database.getEntries() - ); + .setGroup(group, false, removePreviousAssignments, database.getEntries()); } else if ( previousAssignments.isPresent() && - (previousAssignments.get().getButtonData() == - ButtonBar.ButtonData.CANCEL_CLOSE) + (previousAssignments.get().getButtonData() == ButtonBar.ButtonData.CANCEL_CLOSE) ) { return; } @@ -595,9 +514,7 @@ public void editGroup(GroupNodeViewModel oldGroup) { // undoAddPreviousEntries = UndoableChangeEntriesOfGroup.getUndoableEdit(null, addChange); // } - dialogService.notify( - Localization.lang("Modified group \"%0\".", group.getName()) - ); + dialogService.notify(Localization.lang("Modified group \"%0\".", group.getName())); writeGroupChangesToMetaData(); // This is ugly but we have no proper update mechanism in place to propagate the changes, so redraw everything refresh(); @@ -608,10 +525,7 @@ public void editGroup(GroupNodeViewModel oldGroup) { public void removeSubgroups(GroupNodeViewModel group) { boolean confirmation = dialogService.showConfirmationDialogAndWait( Localization.lang("Remove subgroups"), - Localization.lang( - "Remove all subgroups of \"%0\"?", - group.getDisplayName() - ) + Localization.lang("Remove all subgroups of \"%0\"?", group.getDisplayName()) ); if (confirmation) { /// TODO: Add undo @@ -622,10 +536,7 @@ public void removeSubgroups(GroupNodeViewModel group) { } group.getGroupNode().removeAllChildren(); dialogService.notify( - Localization.lang( - "Removed all subgroups of group \"%0\".", - group.getDisplayName() - ) + Localization.lang("Removed all subgroups of group \"%0\".", group.getDisplayName()) ); writeGroupChangesToMetaData(); } @@ -647,9 +558,7 @@ public void removeGroupKeepSubgroups(GroupNodeViewModel group) { confirmed = dialogService.showConfirmationDialogAndWait( Localization.lang("Remove groups"), - Localization.lang( - "Remove all selected groups and keep their subgroups?" - ), + Localization.lang("Remove all selected groups and keep their subgroups?"), Localization.lang("Remove all") ); } @@ -659,33 +568,23 @@ public void removeGroupKeepSubgroups(GroupNodeViewModel group) { // final UndoableAddOrRemoveGroup undo = new UndoableAddOrRemoveGroup(groupsRoot, node, UndoableAddOrRemoveGroup.REMOVE_NODE_KEEP_CHILDREN); // panel.getUndoManager().addEdit(undo); - List selectedGroupNodes = new ArrayList<>( - selectedGroups - ); + List selectedGroupNodes = new ArrayList<>(selectedGroups); selectedGroupNodes.forEach(eachNode -> { GroupTreeNode groupNode = eachNode.getGroupNode(); groupNode .getParent() .ifPresent(parent -> - groupNode.moveAllChildrenTo( - parent, - parent.getIndexOfChild(groupNode).get() - ) + groupNode.moveAllChildrenTo(parent, parent.getIndexOfChild(groupNode).get()) ); groupNode.removeFromParent(); }); if (selectedGroupNodes.size() > 1) { - dialogService.notify( - Localization.lang("Removed all selected groups.") - ); + dialogService.notify(Localization.lang("Removed all selected groups.")); } else { dialogService.notify( - Localization.lang( - "Removed group \"%0\".", - group.getDisplayName() - ) + Localization.lang("Removed group \"%0\".", group.getDisplayName()) ); } writeGroupChangesToMetaData(); @@ -711,9 +610,7 @@ public void removeGroupAndSubgroups(GroupNodeViewModel group) { confirmed = dialogService.showConfirmationDialogAndWait( Localization.lang("Remove groups and subgroups"), - Localization.lang( - "Remove all selected groups and their subgroups?" - ), + Localization.lang("Remove all selected groups and their subgroups?"), Localization.lang("Remove all") ); } @@ -723,9 +620,7 @@ public void removeGroupAndSubgroups(GroupNodeViewModel group) { // final UndoableAddOrRemoveGroup undo = new UndoableAddOrRemoveGroup(groupsRoot, node, UndoableAddOrRemoveGroup.REMOVE_NODE_AND_CHILDREN); // panel.getUndoManager().addEdit(undo); - ArrayList selectedGroupNodes = new ArrayList<>( - selectedGroups - ); + ArrayList selectedGroupNodes = new ArrayList<>(selectedGroups); selectedGroupNodes.forEach(eachNode -> { removeGroupsAndSubGroupsFromEntries(eachNode); eachNode.getGroupNode().removeFromParent(); @@ -733,9 +628,7 @@ public void removeGroupAndSubgroups(GroupNodeViewModel group) { if (selectedGroupNodes.size() > 1) { dialogService.notify( - Localization.lang( - "Removed all selected groups and their subgroups." - ) + Localization.lang("Removed all selected groups and their subgroups.") ); } else { dialogService.notify( @@ -758,19 +651,14 @@ public void removeGroupNoSubgroups(GroupNodeViewModel group) { confirmed = dialogService.showConfirmationDialogAndWait( Localization.lang("Remove group"), - Localization.lang( - "Remove group \"%0\"?", - group.getDisplayName() - ), + Localization.lang("Remove group \"%0\"?", group.getDisplayName()), Localization.lang("Remove") ); } else { confirmed = dialogService.showConfirmationDialogAndWait( Localization.lang("Remove groups and subgroups"), - Localization.lang( - "Remove all selected groups and their subgroups?" - ), + Localization.lang("Remove all selected groups and their subgroups?"), Localization.lang("Remove all") ); } @@ -780,24 +668,17 @@ public void removeGroupNoSubgroups(GroupNodeViewModel group) { // final UndoableAddOrRemoveGroup undo = new UndoableAddOrRemoveGroup(groupsRoot, node, UndoableAddOrRemoveGroup.REMOVE_NODE_WITHOUT_CHILDREN); // panel.getUndoManager().addEdit(undo); - ArrayList selectedGroupNodes = new ArrayList<>( - selectedGroups - ); + ArrayList selectedGroupNodes = new ArrayList<>(selectedGroups); selectedGroupNodes.forEach(eachNode -> { removeGroupsAndSubGroupsFromEntries(eachNode); eachNode.getGroupNode().removeFromParent(); }); if (selectedGroupNodes.size() > 1) { - dialogService.notify( - Localization.lang("Removed all selected groups.") - ); + dialogService.notify(Localization.lang("Removed all selected groups.")); } else { dialogService.notify( - Localization.lang( - "Removed group \"%0\".", - group.getDisplayName() - ) + Localization.lang("Removed group \"%0\".", group.getDisplayName()) ); } writeGroupChangesToMetaData(); @@ -813,16 +694,10 @@ void removeGroupsAndSubGroupsFromEntries(GroupNodeViewModel group) { if (group.getGroupNode().getGroup() instanceof ExplicitGroup) { int groupsWithSameName = 0; String name = group.getGroupNode().getGroup().getName(); - Optional rootGroup = currentDatabase - .get() - .getMetaData() - .getGroups(); + Optional rootGroup = currentDatabase.get().getMetaData().getGroups(); if (rootGroup.isPresent()) { groupsWithSameName = - rootGroup - .get() - .findChildrenSatisfying(g -> g.getName().equals(name)) - .size(); + rootGroup.get().findChildrenSatisfying(g -> g.getName().equals(name)).size(); } if (groupsWithSameName < 2) { List entriesInGroup = group @@ -838,9 +713,7 @@ public void addSelectedEntries(GroupNodeViewModel group) { // if (!WarnAssignmentSideEffects.warnAssignmentSideEffects(node.getNode().getGroup(), panel.frame())) { // return; // user aborted operation - group - .getGroupNode() - .addEntriesToGroup(stateManager.getSelectedEntries()); + group.getGroupNode().addEntriesToGroup(stateManager.getSelectedEntries()); // TODO: Add undo // NamedCompound undoAll = new NamedCompound(Localization.lang("change assignment of entries")); // if (!undoAdd.isEmpty()) { undo.addEdit(UndoableChangeEntriesOfGroup.getUndoableEdit(node, undoAdd)); } @@ -867,9 +740,7 @@ public void removeSelectedEntries(GroupNodeViewModel group) { // if (!WarnAssignmentSideEffects.warnAssignmentSideEffects(mNode.getNode().getGroup(), mPanel.frame())) { // return; // user aborted operation - group - .getGroupNode() - .removeEntriesFromGroup(stateManager.getSelectedEntries()); + group.getGroupNode().removeEntriesFromGroup(stateManager.getSelectedEntries()); // TODO: Add undo // if (!undo.isEmpty()) { // mPanel.getUndoManager().addEdit(UndoableChangeEntriesOfGroup.getUndoableEdit(mNode, undo)); diff --git a/src/main/java/org/jabref/gui/groups/GroupsPreferences.java b/src/main/java/org/jabref/gui/groups/GroupsPreferences.java index 0d44157b670..1692f790576 100644 --- a/src/main/java/org/jabref/gui/groups/GroupsPreferences.java +++ b/src/main/java/org/jabref/gui/groups/GroupsPreferences.java @@ -20,12 +20,9 @@ public GroupsPreferences( GroupHierarchyType defaultHierarchicalContext ) { this.groupViewMode = new SimpleObjectProperty<>(groupViewMode); - this.shouldAutoAssignGroup = - new SimpleBooleanProperty(shouldAutoAssignGroup); - this.shouldDisplayGroupCount = - new SimpleBooleanProperty(shouldDisplayGroupCount); - this.defaultHierarchicalContext = - new SimpleObjectProperty<>(defaultHierarchicalContext); + this.shouldAutoAssignGroup = new SimpleBooleanProperty(shouldAutoAssignGroup); + this.shouldDisplayGroupCount = new SimpleBooleanProperty(shouldDisplayGroupCount); + this.defaultHierarchicalContext = new SimpleObjectProperty<>(defaultHierarchicalContext); } public GroupViewMode getGroupViewMode() { @@ -68,15 +65,11 @@ public GroupHierarchyType getDefaultHierarchicalContext() { return defaultHierarchicalContext.get(); } - public ObjectProperty< - GroupHierarchyType - > defaultHierarchicalContextProperty() { + public ObjectProperty defaultHierarchicalContextProperty() { return defaultHierarchicalContext; } - public void setDefaultHierarchicalContext( - GroupHierarchyType defaultHierarchicalContext - ) { + public void setDefaultHierarchicalContext(GroupHierarchyType defaultHierarchicalContext) { this.defaultHierarchicalContext.set(defaultHierarchicalContext); } } diff --git a/src/main/java/org/jabref/gui/groups/UndoableAddOrRemoveGroup.java b/src/main/java/org/jabref/gui/groups/UndoableAddOrRemoveGroup.java index 53193339a5f..8beb917e9b2 100644 --- a/src/main/java/org/jabref/gui/groups/UndoableAddOrRemoveGroup.java +++ b/src/main/java/org/jabref/gui/groups/UndoableAddOrRemoveGroup.java @@ -75,9 +75,7 @@ public UndoableAddOrRemoveGroup( m_subtreeBackup = editType != UndoableAddOrRemoveGroup.REMOVE_NODE_KEEP_CHILDREN ? editedNode.getNode().copySubtree() - : GroupTreeNode.fromGroup( - editedNode.getNode().getGroup().deepCopy() - ); + : GroupTreeNode.fromGroup(editedNode.getNode().getGroup().deepCopy()); // remember path to edited node. this cannot be stored as a reference, // because the reference itself might change. the method below is more // robust. @@ -126,11 +124,7 @@ private void doOperation(boolean undo) { case REMOVE_NODE_KEEP_CHILDREN: // move all children to newNode, then add newNode GroupTreeNode newNode = m_subtreeBackup.copySubtree(); - for ( - int i = childIndex; - i < (childIndex + m_subtreeRootChildCount); - ++i - ) { + for (int i = childIndex; i < (childIndex + m_subtreeRootChildCount); ++i) { cursor.getChildAt(childIndex).get().moveTo(newNode); } newNode.moveTo(cursor, childIndex); @@ -148,15 +142,10 @@ private void doOperation(boolean undo) { break; case REMOVE_NODE_KEEP_CHILDREN: // remove node, then insert all children - GroupTreeNode removedNode = cursor - .getChildAt(childIndex) - .get(); + GroupTreeNode removedNode = cursor.getChildAt(childIndex).get(); cursor.removeChild(childIndex); while (removedNode.getNumberOfChildren() > 0) { - removedNode - .getFirstChild() - .get() - .moveTo(cursor, childIndex); + removedNode.getFirstChild().get().moveTo(cursor, childIndex); } break; case REMOVE_NODE_AND_CHILDREN: diff --git a/src/main/java/org/jabref/gui/groups/UndoableModifySubtree.java b/src/main/java/org/jabref/gui/groups/UndoableModifySubtree.java index 24ca7681a15..a668bbe4438 100644 --- a/src/main/java/org/jabref/gui/groups/UndoableModifySubtree.java +++ b/src/main/java/org/jabref/gui/groups/UndoableModifySubtree.java @@ -51,9 +51,7 @@ public void undo() { // remember modified children for redo m_modifiedSubtree.clear(); // get node to edit - final GroupTreeNode subtreeRoot = m_groupRoot - .getDescendant(m_subtreeRootPath) - .get(); // TODO: NULL + final GroupTreeNode subtreeRoot = m_groupRoot.getDescendant(m_subtreeRootPath).get(); // TODO: NULL m_modifiedSubtree.addAll(subtreeRoot.getChildren()); // keep subtree handle, but restore everything else from backup subtreeRoot.removeAllChildren(); @@ -65,9 +63,7 @@ public void undo() { @Override public void redo() { super.redo(); - final GroupTreeNode subtreeRoot = m_groupRoot - .getDescendant(m_subtreeRootPath) - .get(); // TODO: NULL + final GroupTreeNode subtreeRoot = m_groupRoot.getDescendant(m_subtreeRootPath).get(); // TODO: NULL subtreeRoot.removeAllChildren(); for (GroupTreeNode modifiedNode : m_modifiedSubtree) { modifiedNode.moveTo(subtreeRoot); diff --git a/src/main/java/org/jabref/gui/groups/UndoableMoveGroup.java b/src/main/java/org/jabref/gui/groups/UndoableMoveGroup.java index bc59f38bbe7..57c7de8b638 100644 --- a/src/main/java/org/jabref/gui/groups/UndoableMoveGroup.java +++ b/src/main/java/org/jabref/gui/groups/UndoableMoveGroup.java @@ -14,10 +14,7 @@ class UndoableMoveGroup extends AbstractUndoableJabRefEdit { private final List pathToOldParent; private final int oldChildIndex; - public UndoableMoveGroup( - GroupTreeNodeViewModel root, - MoveGroupChange moveChange - ) { + public UndoableMoveGroup(GroupTreeNodeViewModel root, MoveGroupChange moveChange) { this.root = Objects.requireNonNull(root); Objects.requireNonNull(moveChange); pathToOldParent = moveChange.getOldParent().getIndexedPathFromRoot(); @@ -35,31 +32,19 @@ public String getPresentationName() { public void undo() { super.undo(); - GroupTreeNode newParent = root - .getNode() - .getDescendant(pathToNewParent) - .get(); // TODO: NULL + GroupTreeNode newParent = root.getNode().getDescendant(pathToNewParent).get(); // TODO: NULL GroupTreeNode node = newParent.getChildAt(newChildIndex).get(); // TODO: Null // TODO: NULL - node.moveTo( - root.getNode().getDescendant(pathToOldParent).get(), - oldChildIndex - ); + node.moveTo(root.getNode().getDescendant(pathToOldParent).get(), oldChildIndex); } @Override public void redo() { super.redo(); - GroupTreeNode oldParent = root - .getNode() - .getDescendant(pathToOldParent) - .get(); // TODO: NULL + GroupTreeNode oldParent = root.getNode().getDescendant(pathToOldParent).get(); // TODO: NULL GroupTreeNode node = oldParent.getChildAt(oldChildIndex).get(); // TODO:Null // TODO: NULL - node.moveTo( - root.getNode().getDescendant(pathToNewParent).get(), - newChildIndex - ); + node.moveTo(root.getNode().getDescendant(pathToNewParent).get(), newChildIndex); } } diff --git a/src/main/java/org/jabref/gui/help/AboutAction.java b/src/main/java/org/jabref/gui/help/AboutAction.java index 7d22fddcd95..d4355aa51a8 100644 --- a/src/main/java/org/jabref/gui/help/AboutAction.java +++ b/src/main/java/org/jabref/gui/help/AboutAction.java @@ -14,9 +14,7 @@ public AboutAction() { @Override public void execute() { - DialogService dialogService = Injector.instantiateModelOrService( - DialogService.class - ); + DialogService dialogService = Injector.instantiateModelOrService(DialogService.class); dialogService.showCustomDialog(aboutDialogView); } diff --git a/src/main/java/org/jabref/gui/help/AboutDialogViewModel.java b/src/main/java/org/jabref/gui/help/AboutDialogViewModel.java index bd4635eec8e..68e114e6bc6 100644 --- a/src/main/java/org/jabref/gui/help/AboutDialogViewModel.java +++ b/src/main/java/org/jabref/gui/help/AboutDialogViewModel.java @@ -34,21 +34,15 @@ public class AboutDialogViewModel extends AbstractViewModel { "https://github.com/JabRef/jabref/blob/main/PRIVACY.md"; private final String changelogUrl; private final String versionInfo; - private final ReadOnlyStringWrapper environmentInfo = - new ReadOnlyStringWrapper(); - private final Logger logger = LoggerFactory.getLogger( - AboutDialogViewModel.class - ); + private final ReadOnlyStringWrapper environmentInfo = new ReadOnlyStringWrapper(); + private final Logger logger = LoggerFactory.getLogger(AboutDialogViewModel.class); private final ReadOnlyStringWrapper heading = new ReadOnlyStringWrapper(); - private final ReadOnlyStringWrapper maintainers = - new ReadOnlyStringWrapper(); + private final ReadOnlyStringWrapper maintainers = new ReadOnlyStringWrapper(); private final ReadOnlyStringWrapper license = new ReadOnlyStringWrapper(); - private final ReadOnlyBooleanWrapper isDevelopmentVersion = - new ReadOnlyBooleanWrapper(); + private final ReadOnlyBooleanWrapper isDevelopmentVersion = new ReadOnlyBooleanWrapper(); private final DialogService dialogService; private final PreferencesService preferencesService; - private final ReadOnlyStringWrapper developmentVersion = - new ReadOnlyStringWrapper(); + private final ReadOnlyStringWrapper developmentVersion = new ReadOnlyStringWrapper(); private final ClipBoardManager clipBoardManager; public AboutDialogViewModel( @@ -177,15 +171,9 @@ public void openDonation() { private void openWebsite(String url) { try { - JabRefDesktop.openBrowser( - url, - preferencesService.getFilePreferences() - ); + JabRefDesktop.openBrowser(url, preferencesService.getFilePreferences()); } catch (IOException e) { - dialogService.showErrorDialogAndWait( - Localization.lang("Could not open website."), - e - ); + dialogService.showErrorDialogAndWait(Localization.lang("Could not open website."), e); logger.error("Could not open default browser.", e); } } diff --git a/src/main/java/org/jabref/gui/help/ErrorConsoleAction.java b/src/main/java/org/jabref/gui/help/ErrorConsoleAction.java index 657a304ed32..cd0e1f4dc51 100644 --- a/src/main/java/org/jabref/gui/help/ErrorConsoleAction.java +++ b/src/main/java/org/jabref/gui/help/ErrorConsoleAction.java @@ -16,9 +16,7 @@ public class ErrorConsoleAction extends SimpleCommand { @Override public void execute() { - DialogService dialogService = Injector.instantiateModelOrService( - DialogService.class - ); + DialogService dialogService = Injector.instantiateModelOrService(DialogService.class); dialogService.showCustomDialog(new ErrorConsoleView()); } } diff --git a/src/main/java/org/jabref/gui/help/HelpAction.java b/src/main/java/org/jabref/gui/help/HelpAction.java index 0d7b19e44c7..cc6d2f373bf 100644 --- a/src/main/java/org/jabref/gui/help/HelpAction.java +++ b/src/main/java/org/jabref/gui/help/HelpAction.java @@ -29,11 +29,7 @@ public HelpAction( void openHelpPage(HelpFile helpPage) { StringBuilder sb = new StringBuilder("https://docs.jabref.org/"); sb.append(helpPage.getPageName()); - JabRefDesktop.openBrowserShowPopup( - sb.toString(), - dialogService, - filePreferences - ); + JabRefDesktop.openBrowserShowPopup(sb.toString(), dialogService, filePreferences); } @Override diff --git a/src/main/java/org/jabref/gui/help/NewVersionDialog.java b/src/main/java/org/jabref/gui/help/NewVersionDialog.java index a28ee0de2f3..74deea6fac4 100644 --- a/src/main/java/org/jabref/gui/help/NewVersionDialog.java +++ b/src/main/java/org/jabref/gui/help/NewVersionDialog.java @@ -50,8 +50,7 @@ public NewVersionDialog( } return true; }); - Button defaultButton = (Button) this.getDialogPane() - .lookupButton(btnDownloadUpdate); + Button defaultButton = (Button) this.getDialogPane().lookupButton(btnDownloadUpdate); defaultButton.setDefaultButton(true); Hyperlink lblMoreInformation = new Hyperlink( @@ -66,19 +65,11 @@ public NewVersionDialog( ); VBox container = new VBox( + new Label(Localization.lang("A new version of JabRef has been released.")), new Label( - Localization.lang("A new version of JabRef has been released.") - ), - new Label( - Localization.lang("Installed version") + - ": " + - currentVersion.getFullVersion() - ), - new Label( - Localization.lang("Latest version") + - ": " + - latestVersion.getFullVersion() + Localization.lang("Installed version") + ": " + currentVersion.getFullVersion() ), + new Label(Localization.lang("Latest version") + ": " + latestVersion.getFullVersion()), lblMoreInformation ); getDialogPane().setContent(container); diff --git a/src/main/java/org/jabref/gui/help/SearchForUpdateAction.java b/src/main/java/org/jabref/gui/help/SearchForUpdateAction.java index 84d47e8e063..70c229027ad 100644 --- a/src/main/java/org/jabref/gui/help/SearchForUpdateAction.java +++ b/src/main/java/org/jabref/gui/help/SearchForUpdateAction.java @@ -25,20 +25,13 @@ public SearchForUpdateAction( this.taskExecutor = taskExecutor; this.executable.bind( - preferencesService - .getInternalPreferences() - .versionCheckEnabledProperty() + preferencesService.getInternalPreferences().versionCheckEnabledProperty() ); } @Override public void execute() { - new VersionWorker( - buildInfo.version, - dialogService, - taskExecutor, - preferencesService - ) + new VersionWorker(buildInfo.version, dialogService, taskExecutor, preferencesService) .checkForNewVersionAsync(); } } diff --git a/src/main/java/org/jabref/gui/help/VersionWorker.java b/src/main/java/org/jabref/gui/help/VersionWorker.java index 813507fb1c5..74668c27877 100644 --- a/src/main/java/org/jabref/gui/help/VersionWorker.java +++ b/src/main/java/org/jabref/gui/help/VersionWorker.java @@ -26,9 +26,7 @@ */ public class VersionWorker { - private static final Logger LOGGER = LoggerFactory.getLogger( - VersionWorker.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(VersionWorker.class); /** * The current version of the installed JabRef @@ -89,14 +87,9 @@ public void checkForNewVersionDelayed() { /** * Prints the connection problem to the status bar and shows a dialog if it was executed manually */ - private void showConnectionError( - Exception exception, - boolean manualExecution - ) { + private void showConnectionError(Exception exception, boolean manualExecution) { if (manualExecution) { - String couldNotConnect = Localization.lang( - "Could not connect to the update server." - ); + String couldNotConnect = Localization.lang("Could not connect to the update server."); String tryLater = Localization.lang( "Please try again later and/or check your network connection." ); @@ -113,22 +106,14 @@ private void showConnectionError( * Prints up-to-date to the status bar (and shows a dialog it was executed manually) if there is now new version. * Shows a "New Version" Dialog to the user if there is. */ - private void showUpdateInfo( - Optional newerVersion, - boolean manualExecution - ) { + private void showUpdateInfo(Optional newerVersion, boolean manualExecution) { // no new version could be found, only respect the ignored version on automated version checks if ( newerVersion.isEmpty() || - (newerVersion - .get() - .equals(internalPreferences.getIgnoredVersion()) && - !manualExecution) + (newerVersion.get().equals(internalPreferences.getIgnoredVersion()) && !manualExecution) ) { if (manualExecution) { - dialogService.notify( - Localization.lang("JabRef is up-to-date.") - ); + dialogService.notify(Localization.lang("JabRef is up-to-date.")); } } else { // notify the user about a newer version diff --git a/src/main/java/org/jabref/gui/icon/IconTheme.java b/src/main/java/org/jabref/gui/icon/IconTheme.java index 9c8bd284fc5..8fd1b5e0951 100644 --- a/src/main/java/org/jabref/gui/icon/IconTheme.java +++ b/src/main/java/org/jabref/gui/icon/IconTheme.java @@ -53,9 +53,7 @@ public class IconTheme { public static final Color DEFAULT_DISABLED_COLOR = Color.web("#c8c8c8"); public static final Color SELECTED_COLOR = Color.web("#50618F"); private static final String DEFAULT_ICON_PATH = "/images/external/red.png"; - private static final Logger LOGGER = LoggerFactory.getLogger( - IconTheme.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(IconTheme.class); private static final Map KEY_TO_ICON = readIconThemeFile( IconTheme.class.getResource("/images/Icons.properties"), "/images/external/" @@ -72,12 +70,8 @@ public static Optional findIcon(String code, Color color) { } return ICON_NAMES .stream() - .filter(icon -> - icon.toString().equals(code.toUpperCase(Locale.ENGLISH)) - ) - .map(internalMat -> - new InternalMaterialDesignIcon(internalMat).withColor(color) - ) + .filter(icon -> icon.toString().equals(code.toUpperCase(Locale.ENGLISH))) + .map(internalMat -> new InternalMaterialDesignIcon(internalMat).withColor(color)) .findFirst(); } @@ -86,9 +80,7 @@ public static Image getJabRefImage() { } private static void loadAllIkons() { - ServiceLoader providers = ServiceLoader.load( - IkonProvider.class - ); + ServiceLoader providers = ServiceLoader.load(IkonProvider.class); for (IkonProvider provider : providers) { ICON_NAMES.addAll(allOf(provider.getIkon())); @@ -141,10 +133,7 @@ public static URL getIconUrl(String name) { * @return A Map containing all key-value pairs found. */ // FIXME: prefix can be removed?! - private static Map readIconThemeFile( - URL url, - String prefix - ) { + private static Map readIconThemeFile(URL url, String prefix) { Objects.requireNonNull(url, "url"); Objects.requireNonNull(prefix, "prefix"); @@ -152,10 +141,7 @@ private static Map readIconThemeFile( try ( BufferedReader in = new BufferedReader( - new InputStreamReader( - url.openStream(), - StandardCharsets.ISO_8859_1 - ) + new InputStreamReader(url.openStream(), StandardCharsets.ISO_8859_1) ) ) { String line; diff --git a/src/main/java/org/jabref/gui/icon/InternalMaterialDesignIcon.java b/src/main/java/org/jabref/gui/icon/InternalMaterialDesignIcon.java index 8ce08e50de6..e63db6f68f5 100644 --- a/src/main/java/org/jabref/gui/icon/InternalMaterialDesignIcon.java +++ b/src/main/java/org/jabref/gui/icon/InternalMaterialDesignIcon.java @@ -32,11 +32,7 @@ public InternalMaterialDesignIcon(Ikon... icons) { public InternalMaterialDesignIcon(List icons) { this.icons = icons; this.unicode = - icons - .stream() - .map(Ikon::getCode) - .map(String::valueOf) - .collect(Collectors.joining()); + icons.stream().map(Ikon::getCode).map(String::valueOf).collect(Collectors.joining()); this.color = Optional.empty(); } @@ -60,10 +56,7 @@ public Node getGraphicNode() { @Override public JabRefIcon disabled() { - return new InternalMaterialDesignIcon( - IconTheme.DEFAULT_DISABLED_COLOR, - icons - ); + return new InternalMaterialDesignIcon(IconTheme.DEFAULT_DISABLED_COLOR, icons); } @Override diff --git a/src/main/java/org/jabref/gui/icon/JabRefIconView.java b/src/main/java/org/jabref/gui/icon/JabRefIconView.java index dbbbd19cec3..48be39acde0 100644 --- a/src/main/java/org/jabref/gui/icon/JabRefIconView.java +++ b/src/main/java/org/jabref/gui/icon/JabRefIconView.java @@ -23,10 +23,7 @@ public JabRefIconView(JabRefIcons icon, int size) { this.glyphSize = new SimpleObjectProperty<>(size); EasyBind.subscribe(glyph, glyph -> setIconCode(glyph.getIkon())); - EasyBind.subscribe( - glyphSize, - glyphsize -> setIconSize(glyphsize.intValue()) - ); + EasyBind.subscribe(glyphSize, glyphsize -> setIconSize(glyphsize.intValue())); } public JabRefIconView(IconTheme.JabRefIcons icon) { @@ -38,10 +35,7 @@ public JabRefIconView(IconTheme.JabRefIcons icon) { int px = (int) size.pixels(getFont()); glyphSize.set(px); EasyBind.subscribe(glyph, glyph -> setIconCode(glyph.getIkon())); - EasyBind.subscribe( - glyphSize, - glyphsize -> setIconSize(glyphsize.intValue()) - ); + EasyBind.subscribe(glyphSize, glyphsize -> setIconSize(glyphsize.intValue())); } public JabRefIconView() { diff --git a/src/main/java/org/jabref/gui/icon/JabRefMaterialDesignIcon.java b/src/main/java/org/jabref/gui/icon/JabRefMaterialDesignIcon.java index 63c4514d451..6450f17fd02 100644 --- a/src/main/java/org/jabref/gui/icon/JabRefMaterialDesignIcon.java +++ b/src/main/java/org/jabref/gui/icon/JabRefMaterialDesignIcon.java @@ -40,17 +40,13 @@ public enum JabRefMaterialDesignIcon implements Ikon { this.code = code; } - public static JabRefMaterialDesignIcon findByDescription( - String description - ) { + public static JabRefMaterialDesignIcon findByDescription(String description) { for (JabRefMaterialDesignIcon font : values()) { if (font.getDescription().equals(description)) { return font; } } - throw new IllegalArgumentException( - "Icon description '" + description + "' is invalid!" - ); + throw new IllegalArgumentException("Icon description '" + description + "' is invalid!"); } @Override diff --git a/src/main/java/org/jabref/gui/icon/JabrefIconProvider.java b/src/main/java/org/jabref/gui/icon/JabrefIconProvider.java index 670b2ada618..f794bbccd47 100644 --- a/src/main/java/org/jabref/gui/icon/JabrefIconProvider.java +++ b/src/main/java/org/jabref/gui/icon/JabrefIconProvider.java @@ -2,8 +2,7 @@ import org.kordamp.ikonli.IkonProvider; -public class JabrefIconProvider - implements IkonProvider { +public class JabrefIconProvider implements IkonProvider { @Override public Class getIkon() { diff --git a/src/main/java/org/jabref/gui/importer/BibEntryTypePrefsAndFileViewModel.java b/src/main/java/org/jabref/gui/importer/BibEntryTypePrefsAndFileViewModel.java index 02dd0e55604..0ce96e4182a 100644 --- a/src/main/java/org/jabref/gui/importer/BibEntryTypePrefsAndFileViewModel.java +++ b/src/main/java/org/jabref/gui/importer/BibEntryTypePrefsAndFileViewModel.java @@ -16,9 +16,7 @@ public String toString() { return Localization.lang( "%0 (from file)\n%1 (current setting)", MetaDataSerializer.serializeCustomEntryTypes(customTypeFromFile), - MetaDataSerializer.serializeCustomEntryTypes( - customTypeFromPreferences - ) + MetaDataSerializer.serializeCustomEntryTypes(customTypeFromPreferences) ); } } diff --git a/src/main/java/org/jabref/gui/importer/GenerateEntryFromIdAction.java b/src/main/java/org/jabref/gui/importer/GenerateEntryFromIdAction.java index b25aa08a384..6f32392025b 100644 --- a/src/main/java/org/jabref/gui/importer/GenerateEntryFromIdAction.java +++ b/src/main/java/org/jabref/gui/importer/GenerateEntryFromIdAction.java @@ -23,9 +23,7 @@ public class GenerateEntryFromIdAction extends SimpleCommand { - private static final Logger LOGGER = LoggerFactory.getLogger( - GenerateEntryFromIdAction.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(GenerateEntryFromIdAction.class); private final LibraryTab libraryTab; private final DialogService dialogService; @@ -58,15 +56,12 @@ public GenerateEntryFromIdAction( @Override public void execute() { - BackgroundTask> backgroundTask = - searchAndImportEntryInBackground(); + BackgroundTask> backgroundTask = searchAndImportEntryInBackground(); backgroundTask.titleProperty().set(Localization.lang("Import by ID")); backgroundTask.showToUser(true); backgroundTask.onRunning(() -> { entryFromIdPopOver.hide(); - dialogService.notify( - "%s".formatted(backgroundTask.messageProperty().get()) - ); + dialogService.notify("%s".formatted(backgroundTask.messageProperty().get())); }); backgroundTask.onFailure(exception -> { String fetcherExceptionMessage = exception.getMessage(); @@ -87,11 +82,7 @@ public void execute() { "\n" + fetcherExceptionMessage; } else { - msg = - Localization.lang( - "Error message %0", - fetcherExceptionMessage - ); + msg = Localization.lang("Error message %0", fetcherExceptionMessage); } LOGGER.info(fetcherExceptionMessage, exception); @@ -127,10 +118,7 @@ public void execute() { dialogService, taskExecutor ); - handler.importEntryWithDuplicateCheck( - libraryTab.getBibDatabaseContext(), - entry - ); + handler.importEntryWithDuplicateCheck(libraryTab.getBibDatabaseContext(), entry); } else { dialogService.notify("No entry found or import canceled"); } @@ -138,9 +126,7 @@ public void execute() { backgroundTask.executeWith(taskExecutor); } - private BackgroundTask< - Optional - > searchAndImportEntryInBackground() { + private BackgroundTask> searchAndImportEntryInBackground() { return new BackgroundTask<>() { @Override protected Optional call() throws FetcherException { @@ -148,9 +134,7 @@ protected Optional call() throws FetcherException { return Optional.empty(); } updateMessage(Localization.lang("Searching...")); - return new CompositeIdFetcher( - preferencesService.getImportFormatPreferences() - ) + return new CompositeIdFetcher(preferencesService.getImportFormatPreferences()) .performSearchById(identifier); } }; diff --git a/src/main/java/org/jabref/gui/importer/GenerateEntryFromIdDialog.java b/src/main/java/org/jabref/gui/importer/GenerateEntryFromIdDialog.java index 900bc8ee477..646b6e283c2 100644 --- a/src/main/java/org/jabref/gui/importer/GenerateEntryFromIdDialog.java +++ b/src/main/java/org/jabref/gui/importer/GenerateEntryFromIdDialog.java @@ -51,9 +51,7 @@ public GenerateEntryFromIdDialog( this.libraryTab = libraryTab; this.taskExecutor = taskExecutor; this.stateManager = stateManager; - this.generateButton.setGraphic( - IconTheme.JabRefIcons.IMPORT.getGraphicNode() - ); + this.generateButton.setGraphic(IconTheme.JabRefIcons.IMPORT.getGraphicNode()); this.generateButton.setDefaultButton(true); } @@ -66,17 +64,16 @@ private void generateEntry() { this.idTextField.requestFocus(); - GenerateEntryFromIdAction generateEntryFromIdAction = - new GenerateEntryFromIdAction( - libraryTab, - dialogService, - preferencesService, - taskExecutor, - entryFromIdPopOver, - idTextField.getText(), - stateManager, - fileUpdateMonitor - ); + GenerateEntryFromIdAction generateEntryFromIdAction = new GenerateEntryFromIdAction( + libraryTab, + dialogService, + preferencesService, + taskExecutor, + entryFromIdPopOver, + idTextField.getText(), + stateManager, + fileUpdateMonitor + ); generateEntryFromIdAction.execute(); } diff --git a/src/main/java/org/jabref/gui/importer/GrobidOptInDialogHelper.java b/src/main/java/org/jabref/gui/importer/GrobidOptInDialogHelper.java index d10e1abc635..9a9489d8ae5 100644 --- a/src/main/java/org/jabref/gui/importer/GrobidOptInDialogHelper.java +++ b/src/main/java/org/jabref/gui/importer/GrobidOptInDialogHelper.java @@ -28,15 +28,14 @@ public static boolean showAndWaitIfUserIsUndecided( if (preferences.isGrobidOptOut()) { return false; } - boolean grobidEnabled = - dialogService.showConfirmationDialogWithOptOutAndWait( - Localization.lang("Remote services"), - Localization.lang( - "Allow sending PDF files and raw citation strings to a JabRef online service (Grobid) to determine Metadata. This produces better results." - ), - Localization.lang("Do not ask again"), - optOut -> preferences.grobidOptOutProperty().setValue(optOut) - ); + boolean grobidEnabled = dialogService.showConfirmationDialogWithOptOutAndWait( + Localization.lang("Remote services"), + Localization.lang( + "Allow sending PDF files and raw citation strings to a JabRef online service (Grobid) to determine Metadata. This produces better results." + ), + Localization.lang("Do not ask again"), + optOut -> preferences.grobidOptOutProperty().setValue(optOut) + ); preferences.grobidEnabledProperty().setValue(grobidEnabled); return grobidEnabled; } diff --git a/src/main/java/org/jabref/gui/importer/ImportCommand.java b/src/main/java/org/jabref/gui/importer/ImportCommand.java index 34a8aca7ac0..768db63068c 100644 --- a/src/main/java/org/jabref/gui/importer/ImportCommand.java +++ b/src/main/java/org/jabref/gui/importer/ImportCommand.java @@ -42,9 +42,7 @@ */ public class ImportCommand extends SimpleCommand { - private static final Logger LOGGER = LoggerFactory.getLogger( - ImportCommand.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(ImportCommand.class); public enum ImportMethod { AS_NEW, @@ -89,21 +87,14 @@ public void execute() { ); SortedSet importers = importFormatReader.getImportFormats(); - FileDialogConfiguration fileDialogConfiguration = - new FileDialogConfiguration.Builder() - .addExtensionFilter(FileFilterConverter.ANY_FILE) - .addExtensionFilter( - FileFilterConverter.forAllImporters(importers) - ) - .addExtensionFilter( - FileFilterConverter.importerToExtensionFilter(importers) - ) - .withInitialDirectory( - preferencesService - .getImporterPreferences() - .getImportWorkingDirectory() - ) - .build(); + FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() + .addExtensionFilter(FileFilterConverter.ANY_FILE) + .addExtensionFilter(FileFilterConverter.forAllImporters(importers)) + .addExtensionFilter(FileFilterConverter.importerToExtensionFilter(importers)) + .withInitialDirectory( + preferencesService.getImporterPreferences().getImportWorkingDirectory() + ) + .build(); dialogService .showFileOpenDialog(fileDialogConfiguration) .ifPresent(path -> @@ -123,10 +114,7 @@ private void importSingleFile( if (!Files.exists(file)) { dialogService.showErrorDialogAndWait( Localization.lang("Import"), - Localization.lang("File not found") + - ": '" + - file.getFileName() + - "'." + Localization.lang("File not found") + ": '" + file.getFileName() + "'." ); return; @@ -153,9 +141,7 @@ private void importSingleFile( .onFailure(ex -> { LOGGER.error("Error importing", ex); dialogService.notify( - Localization.lang( - "Error importing. See the error log for details." - ) + Localization.lang("Error importing. See the error log for details.") ); }) .executeWith(taskExecutor); @@ -171,20 +157,16 @@ private void importSingleFile( } // Set last working dir for import - preferencesService - .getImporterPreferences() - .setImportWorkingDirectory(file.getParent()); + preferencesService.getImporterPreferences().setImportWorkingDirectory(file.getParent()); } /** * @throws IOException of a specified importer */ - private ParserResult doImport(List files, Importer importFormat) - throws IOException { + private ParserResult doImport(List files, Importer importFormat) throws IOException { Optional importer = Optional.ofNullable(importFormat); // We import all files and collect their results - List imports = - new ArrayList<>(); + List imports = new ArrayList<>(); ImportFormatReader importFormatReader = new ImportFormatReader( preferencesService.getImporterPreferences(), preferencesService.getImportFormatPreferences(), @@ -213,17 +195,13 @@ private ParserResult doImport(List files, Importer importFormat) }); // This import method never throws an IOException imports.add( - importFormatReader.importUnknownFormat( - filename, - fileUpdateMonitor - ) + importFormatReader.importUnknownFormat(filename, fileUpdateMonitor) ); } else { DefaultTaskExecutor.runAndWaitInJavaFXThread(() -> { if ( ((importer.get() instanceof PdfGrobidImporter) || - (importer.get() instanceof - PdfMergeMetadataImporter)) && + (importer.get() instanceof PdfMergeMetadataImporter)) && GrobidOptInDialogHelper.showAndWaitIfUserIsUndecided( dialogService, preferencesService.getGrobidPreferences() @@ -232,29 +210,21 @@ private ParserResult doImport(List files, Importer importFormat) importFormatReader.reset(); } dialogService.notify( - Localization.lang( - "Importing in %0 format", - importer.get().getName() - ) + + Localization.lang("Importing in %0 format", importer.get().getName()) + "..." ); }); // Specific importer ParserResult pr = importer.get().importDatabase(filename); imports.add( - new ImportFormatReader.UnknownFormatImport( - importer.get().getName(), - pr - ) + new ImportFormatReader.UnknownFormatImport(importer.get().getName(), pr) ); } } catch (ImportException ex) { DefaultTaskExecutor.runAndWaitInJavaFXThread(() -> dialogService.showWarningDialogAndWait( Localization.lang("Import error"), - Localization.lang( - "Please check your library file for wrong syntax." - ) + + Localization.lang("Please check your library file for wrong syntax.") + "\n\n" + ex.getLocalizedMessage() ) @@ -281,9 +251,7 @@ private ParserResult doImport(List files, Importer importFormat) /** * TODO: Move this to logic package. Blocked by undo functionality. */ - public ParserResult mergeImportResults( - List imports - ) { + public ParserResult mergeImportResults(List imports) { BibDatabase resultDatabase = new BibDatabase(); ParserResult result = new ParserResult(resultDatabase); @@ -292,18 +260,12 @@ public ParserResult mergeImportResults( continue; } ParserResult parserResult = importResult.parserResult(); - resultDatabase.insertEntries( - parserResult.getDatabase().getEntries() - ); + resultDatabase.insertEntries(parserResult.getDatabase().getEntries()); - if ( - ImportFormatReader.BIBTEX_FORMAT.equals(importResult.format()) - ) { + if (ImportFormatReader.BIBTEX_FORMAT.equals(importResult.format())) { // additional treatment of BibTeX new DatabaseMerger( - preferencesService - .getBibEntryPreferences() - .getKeywordSeparator() + preferencesService.getBibEntryPreferences().getKeywordSeparator() ) .mergeMetaData( result.getMetaData(), diff --git a/src/main/java/org/jabref/gui/importer/ImportCustomEntryTypesDialog.java b/src/main/java/org/jabref/gui/importer/ImportCustomEntryTypesDialog.java index 2b13a8ff725..823f543a3f4 100644 --- a/src/main/java/org/jabref/gui/importer/ImportCustomEntryTypesDialog.java +++ b/src/main/java/org/jabref/gui/importer/ImportCustomEntryTypesDialog.java @@ -29,17 +29,12 @@ public class ImportCustomEntryTypesDialog extends BaseDialog { private CheckListView unknownEntryTypesCheckList; @FXML - private CheckListView< - BibEntryTypePrefsAndFileViewModel - > differentCustomizationCheckList; + private CheckListView differentCustomizationCheckList; private final BibDatabaseMode mode; private ImportCustomEntryTypesDialogViewModel viewModel; - public ImportCustomEntryTypesDialog( - BibDatabaseMode mode, - List customEntryTypes - ) { + public ImportCustomEntryTypesDialog(BibDatabaseMode mode, List customEntryTypes) { this.mode = mode; this.customEntryTypes = customEntryTypes; @@ -48,16 +43,12 @@ public ImportCustomEntryTypesDialog( setResultConverter(btn -> { if (btn == ButtonType.OK) { viewModel.importBibEntryTypes( - unknownEntryTypesCheckList - .getCheckModel() - .getCheckedItems(), + unknownEntryTypesCheckList.getCheckModel().getCheckedItems(), differentCustomizationCheckList .getCheckModel() .getCheckedItems() .stream() - .map( - BibEntryTypePrefsAndFileViewModel::customTypeFromPreferences - ) + .map(BibEntryTypePrefsAndFileViewModel::customTypeFromPreferences) .toList() ); } @@ -70,11 +61,7 @@ public ImportCustomEntryTypesDialog( @FXML public void initialize() { viewModel = - new ImportCustomEntryTypesDialogViewModel( - mode, - customEntryTypes, - preferencesService - ); + new ImportCustomEntryTypesDialogViewModel(mode, customEntryTypes, preferencesService); boxDifferentCustomization .visibleProperty() .bind(Bindings.isNotEmpty(viewModel.differentCustomizations())); @@ -83,25 +70,14 @@ public void initialize() { .bind(Bindings.isNotEmpty(viewModel.differentCustomizations())); unknownEntryTypesCheckList.setItems(viewModel.newTypes()); unknownEntryTypesCheckList.setCellFactory(listView -> - new CheckBoxListCell<>( - unknownEntryTypesCheckList::getItemBooleanProperty - ) { + new CheckBoxListCell<>(unknownEntryTypesCheckList::getItemBooleanProperty) { @Override - public void updateItem( - BibEntryType bibEntryType, - boolean empty - ) { + public void updateItem(BibEntryType bibEntryType, boolean empty) { super.updateItem(bibEntryType, empty); - setText( - bibEntryType == null - ? "" - : bibEntryType.getType().getDisplayName() - ); + setText(bibEntryType == null ? "" : bibEntryType.getType().getDisplayName()); } } ); - differentCustomizationCheckList.setItems( - viewModel.differentCustomizations() - ); + differentCustomizationCheckList.setItems(viewModel.differentCustomizations()); } } diff --git a/src/main/java/org/jabref/gui/importer/ImportCustomEntryTypesDialogViewModel.java b/src/main/java/org/jabref/gui/importer/ImportCustomEntryTypesDialogViewModel.java index dd1da7be7ad..d7c14b5d5df 100644 --- a/src/main/java/org/jabref/gui/importer/ImportCustomEntryTypesDialogViewModel.java +++ b/src/main/java/org/jabref/gui/importer/ImportCustomEntryTypesDialogViewModel.java @@ -21,11 +21,9 @@ public class ImportCustomEntryTypesDialogViewModel { private final BibDatabaseMode mode; private final PreferencesService preferencesService; - private final ObservableList newTypes = + private final ObservableList newTypes = FXCollections.observableArrayList(); + private final ObservableList differentCustomizationTypes = FXCollections.observableArrayList(); - private final ObservableList< - BibEntryTypePrefsAndFileViewModel - > differentCustomizationTypes = FXCollections.observableArrayList(); public ImportCustomEntryTypesDialogViewModel( BibDatabaseMode mode, @@ -36,27 +34,20 @@ public ImportCustomEntryTypesDialogViewModel( this.preferencesService = preferencesService; for (BibEntryType customType : entryTypes) { - Optional currentlyStoredType = - Globals.entryTypesManager.enrich(customType.getType(), mode); + Optional currentlyStoredType = Globals.entryTypesManager.enrich( + customType.getType(), + mode + ); if (currentlyStoredType.isEmpty()) { newTypes.add(customType); } else { if ( - !EntryTypeFactory.nameAndFieldsAreEqual( - customType, - currentlyStoredType.get() - ) + !EntryTypeFactory.nameAndFieldsAreEqual(customType, currentlyStoredType.get()) ) { - LOGGER.info( - "currently stored type: {}", - currentlyStoredType.get() - ); + LOGGER.info("currently stored type: {}", currentlyStoredType.get()); LOGGER.info("type provided by library: {}", customType); differentCustomizationTypes.add( - new BibEntryTypePrefsAndFileViewModel( - currentlyStoredType.get(), - customType - ) + new BibEntryTypePrefsAndFileViewModel(currentlyStoredType.get(), customType) ); } } @@ -67,9 +58,7 @@ public ObservableList newTypes() { return this.newTypes; } - public ObservableList< - BibEntryTypePrefsAndFileViewModel - > differentCustomizations() { + public ObservableList differentCustomizations() { return this.differentCustomizationTypes; } @@ -81,17 +70,13 @@ public void importBibEntryTypes( checkedUnknownEntryTypes.forEach(type -> Globals.entryTypesManager.addCustomOrModifiedType(type, mode) ); - preferencesService.storeCustomEntryTypesRepository( - Globals.entryTypesManager - ); + preferencesService.storeCustomEntryTypesRepository(Globals.entryTypesManager); } if (!checkedDifferentEntryTypes.isEmpty()) { checkedUnknownEntryTypes.forEach(type -> Globals.entryTypesManager.addCustomOrModifiedType(type, mode) ); - preferencesService.storeCustomEntryTypesRepository( - Globals.entryTypesManager - ); + preferencesService.storeCustomEntryTypesRepository(Globals.entryTypesManager); } } } diff --git a/src/main/java/org/jabref/gui/importer/ImportEntriesDialog.java b/src/main/java/org/jabref/gui/importer/ImportEntriesDialog.java index 38bba1df99d..9b5b86f002d 100644 --- a/src/main/java/org/jabref/gui/importer/ImportEntriesDialog.java +++ b/src/main/java/org/jabref/gui/importer/ImportEntriesDialog.java @@ -85,10 +85,7 @@ public class ImportEntriesDialog extends BaseDialog { * @param database the database to import into * @param task the task executed for parsing the selected files(s). */ - public ImportEntriesDialog( - BibDatabaseContext database, - BackgroundTask task - ) { + public ImportEntriesDialog(BibDatabaseContext database, BackgroundTask task) { this.database = database; this.task = task; ViewLoader.view(this).load().setAsDialogPane(this); @@ -169,17 +166,12 @@ private void initialize() { .bind(libraryListView.getSelectionModel().selectedItemProperty()); stateManager .getActiveDatabase() - .ifPresent(database1 -> - libraryListView.getSelectionModel().select(database1) - ); + .ifPresent(database1 -> libraryListView.getSelectionModel().select(database1)); - PseudoClass entrySelected = PseudoClass.getPseudoClass( - "entry-selected" - ); + PseudoClass entrySelected = PseudoClass.getPseudoClass("entry-selected"); new ViewModelListCellFactory() .withGraphic(entry -> { - ToggleButton addToggle = - IconTheme.JabRefIcons.ADD.asToggleButton(); + ToggleButton addToggle = IconTheme.JabRefIcons.ADD.asToggleButton(); EasyBind.subscribe( addToggle.selectedProperty(), selected -> { @@ -190,18 +182,14 @@ private void initialize() { .getGraphicNode() ); } else { - addToggle.setGraphic( - IconTheme.JabRefIcons.ADD.getGraphicNode() - ); + addToggle.setGraphic(IconTheme.JabRefIcons.ADD.getGraphicNode()); } } ); addToggle.getStyleClass().add("addEntryButton"); addToggle .selectedProperty() - .bindBidirectional( - entriesListView.getItemBooleanProperty(entry) - ); + .bindBidirectional(entriesListView.getItemBooleanProperty(entry)); HBox separator = new HBox(); HBox.setHgrow(separator, Priority.SOMETIMES); Node entryNode = getEntryNode(entry); @@ -213,8 +201,7 @@ private void initialize() { .wrap(() -> viewModel.hasDuplicate(entry)) .onSuccess(duplicateFound -> { if (duplicateFound) { - Button duplicateButton = - IconTheme.JabRefIcons.DUPLICATE.asButton(); + Button duplicateButton = IconTheme.JabRefIcons.DUPLICATE.asButton(); duplicateButton.setTooltip( new Tooltip( Localization.lang( @@ -222,9 +209,7 @@ private void initialize() { ) ) ); - duplicateButton.setOnAction(event -> - viewModel.resolveDuplicate(entry) - ); + duplicateButton.setOnAction(event -> viewModel.resolveDuplicate(entry)); container.getChildren().add(1, duplicateButton); } }) @@ -243,43 +228,26 @@ private void initialize() { .withOnMouseClickedEvent((entry, event) -> entriesListView.getCheckModel().toggleCheckState(entry) ) - .withPseudoClass( - entrySelected, - entriesListView::getItemBooleanProperty - ) + .withPseudoClass(entrySelected, entriesListView::getItemBooleanProperty) .install(entriesListView); selectedItems .textProperty() - .bind( - Bindings - .size(entriesListView.getCheckModel().getCheckedItems()) - .asString() - ); - totalItems - .textProperty() - .bind(Bindings.size(entriesListView.getItems()).asString()); + .bind(Bindings.size(entriesListView.getCheckModel().getCheckedItems()).asString()); + totalItems.textProperty().bind(Bindings.size(entriesListView.getItems()).asString()); entriesListView.setSelectionModel(new NoSelectionModel<>()); } private Node getEntryNode(BibEntry entry) { Node entryType = getIcon(entry.getType()).getGraphicNode(); entryType.getStyleClass().add("type"); - Label authors = new Label( - entry.getFieldOrAliasLatexFree(StandardField.AUTHOR).orElse("") - ); + Label authors = new Label(entry.getFieldOrAliasLatexFree(StandardField.AUTHOR).orElse("")); authors.getStyleClass().add("authors"); - Label title = new Label( - entry.getFieldOrAliasLatexFree(StandardField.TITLE).orElse("") - ); + Label title = new Label(entry.getFieldOrAliasLatexFree(StandardField.TITLE).orElse("")); title.getStyleClass().add("title"); - Label year = new Label( - entry.getFieldOrAliasLatexFree(StandardField.YEAR).orElse("") - ); + Label year = new Label(entry.getFieldOrAliasLatexFree(StandardField.YEAR).orElse("")); year.getStyleClass().add("year"); - Label journal = new Label( - entry.getFieldOrAliasLatexFree(StandardField.JOURNAL).orElse("") - ); + Label journal = new Label(entry.getFieldOrAliasLatexFree(StandardField.JOURNAL).orElse("")); journal.getStyleClass().add("journal"); VBox entryContainer = new VBox( @@ -290,9 +258,7 @@ private Node getEntryNode(BibEntry entry) { entry .getFieldOrAliasLatexFree(StandardField.ABSTRACT) .ifPresent(summaryText -> { - TextFlowLimited summary = new TextFlowLimited( - new Text(summaryText) - ); + TextFlowLimited summary = new TextFlowLimited(new Text(summaryText)); summary.getStyleClass().add("summary"); entryContainer.getChildren().add(summary); }); diff --git a/src/main/java/org/jabref/gui/importer/ImportEntriesViewModel.java b/src/main/java/org/jabref/gui/importer/ImportEntriesViewModel.java index 4f9d8d34322..62f1baca0d2 100644 --- a/src/main/java/org/jabref/gui/importer/ImportEntriesViewModel.java +++ b/src/main/java/org/jabref/gui/importer/ImportEntriesViewModel.java @@ -32,9 +32,7 @@ public class ImportEntriesViewModel extends AbstractViewModel { - private static final Logger LOGGER = LoggerFactory.getLogger( - ImportEntriesViewModel.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(ImportEntriesViewModel.class); private final StringProperty message; private final TaskExecutor taskExecutor; @@ -85,9 +83,7 @@ public ImportEntriesViewModel( entries.addAll(parserResult.getDatabase().getEntries()); if (entries.isEmpty()) { task.updateMessage( - Localization.lang( - "No entries corresponding to given query" - ) + Localization.lang("No entries corresponding to given query") ); } }) @@ -136,21 +132,12 @@ public boolean hasDuplicate(BibEntry entry) { * * @param entriesToImport subset of the entries contained in parserResult */ - public void importEntries( - List entriesToImport, - boolean shouldDownloadFiles - ) { + public void importEntries(List entriesToImport, boolean shouldDownloadFiles) { // Check if we are supposed to warn about duplicates. // If so, then see if there are duplicates, and warn if yes. - if ( - preferences - .getImporterPreferences() - .shouldWarnAboutDuplicatesOnImport() - ) { + if (preferences.getImporterPreferences().shouldWarnAboutDuplicatesOnImport()) { BackgroundTask - .wrap(() -> - entriesToImport.stream().anyMatch(this::hasDuplicate) - ) + .wrap(() -> entriesToImport.stream().anyMatch(this::hasDuplicate)) .onSuccess(duplicateFound -> { if (duplicateFound) { boolean continueImport = @@ -169,13 +156,9 @@ public void importEntries( ); if (!continueImport) { - dialogService.notify( - Localization.lang("Import canceled") - ); + dialogService.notify(Localization.lang("Import canceled")); } else { - buildImportHandlerThenImportEntries( - entriesToImport - ); + buildImportHandlerThenImportEntries(entriesToImport); } } else { buildImportHandlerThenImportEntries(entriesToImport); @@ -187,9 +170,7 @@ public void importEntries( } // Remember the selection in the dialog - preferences - .getFilePreferences() - .setDownloadLinkedFiles(shouldDownloadFiles); + preferences.getFilePreferences().setDownloadLinkedFiles(shouldDownloadFiles); if (shouldDownloadFiles) { for (BibEntry bibEntry : entriesToImport) { @@ -211,31 +192,19 @@ public void importEntries( } } - new DatabaseMerger( - preferences.getBibEntryPreferences().getKeywordSeparator() - ) - .mergeStrings( - databaseContext.getDatabase(), - parserResult.getDatabase() - ); - new DatabaseMerger( - preferences.getBibEntryPreferences().getKeywordSeparator() - ) + new DatabaseMerger(preferences.getBibEntryPreferences().getKeywordSeparator()) + .mergeStrings(databaseContext.getDatabase(), parserResult.getDatabase()); + new DatabaseMerger(preferences.getBibEntryPreferences().getKeywordSeparator()) .mergeMetaData( databaseContext.getMetaData(), parserResult.getMetaData(), - parserResult - .getPath() - .map(path -> path.getFileName().toString()) - .orElse("unknown"), + parserResult.getPath().map(path -> path.getFileName().toString()).orElse("unknown"), parserResult.getDatabase().getEntries() ); // JabRefGUI.getMainFrame().getCurrentLibraryTab().markBaseChanged(); } - private void buildImportHandlerThenImportEntries( - List entriesToImport - ) { + private void buildImportHandlerThenImportEntries(List entriesToImport) { ImportHandler importHandler = new ImportHandler( selectedDb.getValue(), preferences, @@ -277,11 +246,7 @@ private Optional findInternalDuplicate(BibEntry entry) { public void resolveDuplicate(BibEntry entry) { // First, try to find duplicate in the existing library Optional other = new DuplicateCheck(entryTypesManager) - .containsDuplicate( - databaseContext.getDatabase(), - entry, - databaseContext.getMode() - ); + .containsDuplicate(databaseContext.getDatabase(), entry, databaseContext.getMode()); if (other.isPresent()) { DuplicateResolverDialog dialog = new DuplicateResolverDialog( other.get(), @@ -293,36 +258,21 @@ public void resolveDuplicate(BibEntry entry) { preferences ); - DuplicateResolverDialog.DuplicateResolverResult result = - dialogService - .showCustomDialogAndWait(dialog) - .orElse( - DuplicateResolverDialog.DuplicateResolverResult.BREAK - ); + DuplicateResolverDialog.DuplicateResolverResult result = dialogService + .showCustomDialogAndWait(dialog) + .orElse(DuplicateResolverDialog.DuplicateResolverResult.BREAK); - if ( - result == - DuplicateResolverDialog.DuplicateResolverResult.KEEP_LEFT - ) { + if (result == DuplicateResolverDialog.DuplicateResolverResult.KEEP_LEFT) { // TODO: Remove old entry. Or... add it to a list of entries // to be deleted. We only delete // it after Ok is clicked. // entriesToDelete.add(other.get()); - } else if ( - result == - DuplicateResolverDialog.DuplicateResolverResult.KEEP_RIGHT - ) { + } else if (result == DuplicateResolverDialog.DuplicateResolverResult.KEEP_RIGHT) { // Remove the entry from the import inspection dialog. entries.remove(entry); - } else if ( - result == - DuplicateResolverDialog.DuplicateResolverResult.KEEP_BOTH - ) { + } else if (result == DuplicateResolverDialog.DuplicateResolverResult.KEEP_BOTH) { // Do nothing. - } else if ( - result == - DuplicateResolverDialog.DuplicateResolverResult.KEEP_MERGE - ) { + } else if (result == DuplicateResolverDialog.DuplicateResolverResult.KEEP_MERGE) { // TODO: Remove old entry. Or... add it to a list of entries // to be deleted. We only delete // it after Ok is clicked. @@ -347,33 +297,18 @@ public void resolveDuplicate(BibEntry entry) { preferences ); - DuplicateResolverDialog.DuplicateResolverResult answer = - dialogService - .showCustomDialogAndWait(diag) - .orElse( - DuplicateResolverDialog.DuplicateResolverResult.BREAK - ); - if ( - answer == - DuplicateResolverDialog.DuplicateResolverResult.KEEP_LEFT - ) { + DuplicateResolverDialog.DuplicateResolverResult answer = dialogService + .showCustomDialogAndWait(diag) + .orElse(DuplicateResolverDialog.DuplicateResolverResult.BREAK); + if (answer == DuplicateResolverDialog.DuplicateResolverResult.KEEP_LEFT) { // Remove other entry entries.remove(other.get()); - } else if ( - answer == - DuplicateResolverDialog.DuplicateResolverResult.KEEP_RIGHT - ) { + } else if (answer == DuplicateResolverDialog.DuplicateResolverResult.KEEP_RIGHT) { // Remove entry entries.remove(entry); - } else if ( - answer == - DuplicateResolverDialog.DuplicateResolverResult.KEEP_BOTH - ) { + } else if (answer == DuplicateResolverDialog.DuplicateResolverResult.KEEP_BOTH) { // Do nothing - } else if ( - answer == - DuplicateResolverDialog.DuplicateResolverResult.KEEP_MERGE - ) { + } else if (answer == DuplicateResolverDialog.DuplicateResolverResult.KEEP_MERGE) { // Replace both entries by merged entry entries.add(diag.getMergedEntry()); entries.remove(entry); diff --git a/src/main/java/org/jabref/gui/importer/NewDatabaseAction.java b/src/main/java/org/jabref/gui/importer/NewDatabaseAction.java index 383b2cee2cb..968fc523e2e 100644 --- a/src/main/java/org/jabref/gui/importer/NewDatabaseAction.java +++ b/src/main/java/org/jabref/gui/importer/NewDatabaseAction.java @@ -19,10 +19,7 @@ public class NewDatabaseAction extends SimpleCommand { * @param jabRefFrame the application frame of JabRef * @param preferencesService the preferencesService of JabRef */ - public NewDatabaseAction( - JabRefFrame jabRefFrame, - PreferencesService preferencesService - ) { + public NewDatabaseAction(JabRefFrame jabRefFrame, PreferencesService preferencesService) { this.jabRefFrame = jabRefFrame; this.preferencesService = preferencesService; } @@ -31,9 +28,7 @@ public NewDatabaseAction( public void execute() { BibDatabaseContext bibDatabaseContext = new BibDatabaseContext(); bibDatabaseContext.setMode( - preferencesService - .getLibraryPreferences() - .getDefaultBibDatabaseMode() + preferencesService.getLibraryPreferences().getDefaultBibDatabaseMode() ); jabRefFrame.addTab(bibDatabaseContext, true); } diff --git a/src/main/java/org/jabref/gui/importer/NewEntryAction.java b/src/main/java/org/jabref/gui/importer/NewEntryAction.java index 525c49e8dac..68dae0e81e7 100644 --- a/src/main/java/org/jabref/gui/importer/NewEntryAction.java +++ b/src/main/java/org/jabref/gui/importer/NewEntryAction.java @@ -19,9 +19,7 @@ public class NewEntryAction extends SimpleCommand { - private static final Logger LOGGER = LoggerFactory.getLogger( - NewEntryAction.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(NewEntryAction.class); private final JabRefFrame jabRefFrame; @@ -63,16 +61,12 @@ public NewEntryAction( @Override public void execute() { if (jabRefFrame.getBasePanelCount() <= 0) { - LOGGER.error( - "Action 'New entry' must be disabled when no database is open." - ); + LOGGER.error("Action 'New entry' must be disabled when no database is open."); return; } if (type.isPresent()) { - jabRefFrame - .getCurrentLibraryTab() - .insertEntry(new BibEntry(type.get())); + jabRefFrame.getCurrentLibraryTab().insertEntry(new BibEntry(type.get())); } else { EntryTypeView typeChoiceDialog = new EntryTypeView( jabRefFrame.getCurrentLibraryTab(), @@ -87,9 +81,7 @@ public void execute() { } trackNewEntry(selectedType); - jabRefFrame - .getCurrentLibraryTab() - .insertEntry(new BibEntry(selectedType)); + jabRefFrame.getCurrentLibraryTab().insertEntry(new BibEntry(selectedType)); } } @@ -99,8 +91,6 @@ private void trackNewEntry(EntryType type) { Telemetry .getTelemetryClient() - .ifPresent(client -> - client.trackEvent("NewEntry", properties, new HashMap<>()) - ); + .ifPresent(client -> client.trackEvent("NewEntry", properties, new HashMap<>())); } } diff --git a/src/main/java/org/jabref/gui/importer/ParserResultWarningDialog.java b/src/main/java/org/jabref/gui/importer/ParserResultWarningDialog.java index b3434f2a5d0..b6831652afe 100644 --- a/src/main/java/org/jabref/gui/importer/ParserResultWarningDialog.java +++ b/src/main/java/org/jabref/gui/importer/ParserResultWarningDialog.java @@ -57,9 +57,7 @@ public static void showParserResultWarningDialog( final StringBuilder dialogContent = new StringBuilder(); int warningCount = 1; for (final String warning : warnings) { - dialogContent.append( - String.format("%d. %s%n", warningCount++, warning) - ); + dialogContent.append(String.format("%d. %s%n", warningCount++, warning)); } dialogContent.deleteCharAt(dialogContent.length() - 1); diff --git a/src/main/java/org/jabref/gui/importer/actions/CheckForNewEntryTypesAction.java b/src/main/java/org/jabref/gui/importer/actions/CheckForNewEntryTypesAction.java index fba51e2f192..60c8d202950 100644 --- a/src/main/java/org/jabref/gui/importer/actions/CheckForNewEntryTypesAction.java +++ b/src/main/java/org/jabref/gui/importer/actions/CheckForNewEntryTypesAction.java @@ -19,19 +19,13 @@ public class CheckForNewEntryTypesAction implements GUIPostOpenAction { @Override public boolean isActionNecessary(ParserResult parserResult) { - return !getListOfUnknownAndUnequalCustomizations(parserResult) - .isEmpty(); + return !getListOfUnknownAndUnequalCustomizations(parserResult).isEmpty(); } @Override - public void performAction( - LibraryTab libraryTab, - ParserResult parserResult - ) { + public void performAction(LibraryTab libraryTab, ParserResult parserResult) { BibDatabaseMode mode = getBibDatabaseModeFromParserResult(parserResult); - DialogService dialogService = Injector.instantiateModelOrService( - DialogService.class - ); + DialogService dialogService = Injector.instantiateModelOrService(DialogService.class); dialogService.showCustomDialogAndWait( new ImportCustomEntryTypesDialog( mode, @@ -40,33 +34,20 @@ public void performAction( ); } - private List getListOfUnknownAndUnequalCustomizations( - ParserResult parserResult - ) { + private List getListOfUnknownAndUnequalCustomizations(ParserResult parserResult) { BibDatabaseMode mode = getBibDatabaseModeFromParserResult(parserResult); return parserResult .getEntryTypes() .stream() - .filter(type -> - Globals.entryTypesManager.isDifferentCustomOrModifiedType( - type, - mode - ) - ) + .filter(type -> Globals.entryTypesManager.isDifferentCustomOrModifiedType(type, mode)) .collect(Collectors.toList()); } - private BibDatabaseMode getBibDatabaseModeFromParserResult( - ParserResult parserResult - ) { + private BibDatabaseMode getBibDatabaseModeFromParserResult(ParserResult parserResult) { return parserResult .getMetaData() .getMode() - .orElse( - Globals.prefs - .getLibraryPreferences() - .getDefaultBibDatabaseMode() - ); + .orElse(Globals.prefs.getLibraryPreferences().getDefaultBibDatabaseMode()); } } diff --git a/src/main/java/org/jabref/gui/importer/actions/MergeReviewIntoCommentAction.java b/src/main/java/org/jabref/gui/importer/actions/MergeReviewIntoCommentAction.java index b4b5ac0c712..609842a8879 100644 --- a/src/main/java/org/jabref/gui/importer/actions/MergeReviewIntoCommentAction.java +++ b/src/main/java/org/jabref/gui/importer/actions/MergeReviewIntoCommentAction.java @@ -14,21 +14,14 @@ public boolean isActionNecessary(ParserResult parserResult) { } @Override - public void performAction( - LibraryTab libraryTab, - ParserResult parserResult - ) { - MergeReviewIntoCommentMigration migration = - new MergeReviewIntoCommentMigration(); + public void performAction(LibraryTab libraryTab, ParserResult parserResult) { + MergeReviewIntoCommentMigration migration = new MergeReviewIntoCommentMigration(); migration.performMigration(parserResult); - List conflicts = - MergeReviewIntoCommentMigration.collectConflicts(parserResult); + List conflicts = MergeReviewIntoCommentMigration.collectConflicts(parserResult); if ( !conflicts.isEmpty() && - new MergeReviewIntoCommentConfirmationDialog( - libraryTab.frame().getDialogService() - ) + new MergeReviewIntoCommentConfirmationDialog(libraryTab.frame().getDialogService()) .askUserForMerge(conflicts) ) { migration.performConflictingMigration(parserResult); diff --git a/src/main/java/org/jabref/gui/importer/actions/MergeReviewIntoCommentConfirmationDialog.java b/src/main/java/org/jabref/gui/importer/actions/MergeReviewIntoCommentConfirmationDialog.java index f227201dc67..f2075e586ff 100644 --- a/src/main/java/org/jabref/gui/importer/actions/MergeReviewIntoCommentConfirmationDialog.java +++ b/src/main/java/org/jabref/gui/importer/actions/MergeReviewIntoCommentConfirmationDialog.java @@ -11,9 +11,7 @@ public class MergeReviewIntoCommentConfirmationDialog { private final DialogService dialogService; - public MergeReviewIntoCommentConfirmationDialog( - DialogService dialogService - ) { + public MergeReviewIntoCommentConfirmationDialog(DialogService dialogService) { this.dialogService = dialogService; } @@ -28,9 +26,7 @@ public boolean askUserForMerge(List conflicts) { String content = bibKeys + " " + - Localization.lang( - "has/have both a 'Comment' and a 'Review' field." - ) + + Localization.lang("has/have both a 'Comment' and a 'Review' field.") + "\n" + Localization.lang( "Since the 'Review' field was deprecated in JabRef 4.2, these two fields are about to be merged into the 'Comment' field." diff --git a/src/main/java/org/jabref/gui/importer/actions/OpenDatabaseAction.java b/src/main/java/org/jabref/gui/importer/actions/OpenDatabaseAction.java index 2157e51d9b5..8a36996afb5 100644 --- a/src/main/java/org/jabref/gui/importer/actions/OpenDatabaseAction.java +++ b/src/main/java/org/jabref/gui/importer/actions/OpenDatabaseAction.java @@ -42,9 +42,7 @@ // The action concerned with opening an existing database. public class OpenDatabaseAction extends SimpleCommand { - private static final Logger LOGGER = LoggerFactory.getLogger( - OpenDatabaseAction.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(OpenDatabaseAction.class); // List of actions that may need to be called after opening the file. Such as // upgrade actions etc. that may depend on the JabRef version that wrote the file: @@ -91,10 +89,7 @@ public OpenDatabaseAction( * @param libraryTab The BasePanel where the database is shown. * @param result The result of the BIB file parse operation. */ - public static void performPostOpenActions( - LibraryTab libraryTab, - ParserResult result - ) { + public static void performPostOpenActions(LibraryTab libraryTab, ParserResult result) { for (GUIPostOpenAction action : OpenDatabaseAction.POST_OPEN_ACTIONS) { if (action.isActionNecessary(result)) { action.performAction(libraryTab, result); @@ -105,17 +100,15 @@ public static void performPostOpenActions( @Override public void execute() { - FileDialogConfiguration fileDialogConfiguration = - new FileDialogConfiguration.Builder() - .addExtensionFilter(StandardFileType.BIBTEX_DB) - .withDefaultExtension(StandardFileType.BIBTEX_DB) - .withInitialDirectory(getInitialDirectory()) - .build(); + FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() + .addExtensionFilter(StandardFileType.BIBTEX_DB) + .withDefaultExtension(StandardFileType.BIBTEX_DB) + .withInitialDirectory(getInitialDirectory()) + .build(); - List filesToOpen = - dialogService.showFileOpenDialogAndGetMultipleFiles( - fileDialogConfiguration - ); + List filesToOpen = dialogService.showFileOpenDialogAndGetMultipleFiles( + fileDialogConfiguration + ); openFiles(filesToOpen); } @@ -124,9 +117,7 @@ public void execute() { */ private Path getInitialDirectory() { if (frame.getLibraryTabs().isEmpty()) { - return preferencesService - .getFilePreferences() - .getWorkingDirectory(); + return preferencesService.getFilePreferences().getWorkingDirectory(); } else { Optional databasePath = frame .getCurrentLibraryTab() @@ -134,11 +125,7 @@ private Path getInitialDirectory() { .getDatabasePath(); return databasePath .map(Path::getParent) - .orElse( - preferencesService - .getFilePreferences() - .getWorkingDirectory() - ); + .orElse(preferencesService.getFilePreferences().getWorkingDirectory()); } } @@ -164,23 +151,13 @@ public void openFiles(List filesToOpen) { int removed = 0; // Check if any of the files are already open: - for ( - Iterator iterator = filesToOpen.iterator(); - iterator.hasNext(); - ) { + for (Iterator iterator = filesToOpen.iterator(); iterator.hasNext();) { Path file = iterator.next(); for (int i = 0; i < frame.getLibraryTabs().size(); i++) { LibraryTab libraryTab = frame.getLibraryTabAt(i); if ( - (libraryTab - .getBibDatabaseContext() - .getDatabasePath() - .isPresent()) && - libraryTab - .getBibDatabaseContext() - .getDatabasePath() - .get() - .equals(file) + (libraryTab.getBibDatabaseContext().getDatabasePath().isPresent()) && + libraryTab.getBibDatabaseContext().getDatabasePath().get().equals(file) ) { iterator.remove(); removed++; @@ -198,9 +175,7 @@ public void openFiles(List filesToOpen) { // Run the actual open in a thread to prevent the program // locking until the file is loaded. if (!filesToOpen.isEmpty()) { - FileHistory fileHistory = preferencesService - .getGuiPreferences() - .getFileHistory(); + FileHistory fileHistory = preferencesService.getGuiPreferences().getFileHistory(); filesToOpen.forEach(theFile -> { // This method will execute the concrete file opening and loading in a background thread openTheFile(theFile); @@ -224,9 +199,7 @@ private void openTheFile(Path file) { return; } - BackgroundTask backgroundTask = BackgroundTask.wrap(() -> - loadDatabase(file) - ); + BackgroundTask backgroundTask = BackgroundTask.wrap(() -> loadDatabase(file)); // The backgroundTask is executed within the method createLibraryTab LibraryTab newTab = LibraryTab.createLibraryTab( backgroundTask, @@ -248,12 +221,8 @@ private ParserResult loadDatabase(Path file) throws Exception { dialogService.notify(Localization.lang("Opening") + ": '" + file + "'"); - preferencesService - .getFilePreferences() - .setWorkingDirectory(fileToLoad.getParent()); - Path backupDir = preferencesService - .getFilePreferences() - .getBackupDirectory(); + preferencesService.getFilePreferences().setWorkingDirectory(fileToLoad.getParent()); + Path backupDir = preferencesService.getFilePreferences().getBackupDirectory(); ParserResult parserResult = null; if (BackupManager.backupFileDiffers(fileToLoad, backupDir)) { @@ -283,9 +252,7 @@ private ParserResult loadDatabase(Path file) throws Exception { if (parserResult.hasWarnings()) { String content = - Localization.lang( - "Please check your library file for wrong syntax." - ) + + Localization.lang("Please check your library file for wrong syntax.") + "\n\n" + parserResult.getErrorMessage(); DefaultTaskExecutor.runInJavaFXThread(() -> @@ -325,10 +292,7 @@ private void trackOpenNewDatabase(LibraryTab libraryTab) { Map.of(), Map.of( "NumberOfEntries", - (double) libraryTab - .getBibDatabaseContext() - .getDatabase() - .getEntryCount() + (double) libraryTab.getBibDatabaseContext().getDatabase().getEntryCount() ) ) ); diff --git a/src/main/java/org/jabref/gui/importer/fetcher/LookupIdentifierAction.java b/src/main/java/org/jabref/gui/importer/fetcher/LookupIdentifierAction.java index 1f194a7def4..94bf2028f7e 100644 --- a/src/main/java/org/jabref/gui/importer/fetcher/LookupIdentifierAction.java +++ b/src/main/java/org/jabref/gui/importer/fetcher/LookupIdentifierAction.java @@ -25,12 +25,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class LookupIdentifierAction - extends SimpleCommand { +public class LookupIdentifierAction extends SimpleCommand { - private static final Logger LOGGER = LoggerFactory.getLogger( - LookupIdentifierAction.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(LookupIdentifierAction.class); private final JabRefFrame frame; @@ -53,16 +50,13 @@ public LookupIdentifierAction( this.taskExecutor = taskExecutor; this.executable.bind( - needsDatabase(this.stateManager) - .and(needsEntriesSelected(this.stateManager)) + needsDatabase(this.stateManager).and(needsEntriesSelected(this.stateManager)) ); this.statusMessage.bind( BindingsHelper.ifThenElse( executable, "", - Localization.lang( - "This operation requires one or more entries to be selected." - ) + Localization.lang("This operation requires one or more entries to be selected.") ) ); } @@ -71,8 +65,7 @@ public LookupIdentifierAction( public void execute() { try { BackgroundTask - .wrap(() -> lookupIdentifiers(stateManager.getSelectedEntries()) - ) + .wrap(() -> lookupIdentifiers(stateManager.getSelectedEntries())) .onSuccess(frame.getDialogService()::notify) .executeWith(taskExecutor); } catch (Exception e) { @@ -107,23 +100,15 @@ private String lookupIdentifiers(List bibEntries) { try { identifier = fetcher.findIdentifier(bibEntry); } catch (FetcherException e) { - LOGGER.error( - "Could not fetch " + fetcher.getIdentifierName(), - e - ); + LOGGER.error("Could not fetch " + fetcher.getIdentifierName(), e); } - if ( - identifier.isPresent() && - !bibEntry.hasField(identifier.get().getDefaultField()) - ) { + if (identifier.isPresent() && !bibEntry.hasField(identifier.get().getDefaultField())) { Optional fieldChange = bibEntry.setField( identifier.get().getDefaultField(), identifier.get().getNormalized() ); if (fieldChange.isPresent()) { - namedCompound.addEdit( - new UndoableFieldChange(fieldChange.get()) - ); + namedCompound.addEdit(new UndoableFieldChange(fieldChange.get())); foundCount++; final String nextStatusMessage = Localization.lang( "Looking up %0... - entry %1 out of %2 - found %3", diff --git a/src/main/java/org/jabref/gui/importer/fetcher/WebSearchPaneView.java b/src/main/java/org/jabref/gui/importer/fetcher/WebSearchPaneView.java index 7660bceb1b0..640280980fc 100644 --- a/src/main/java/org/jabref/gui/importer/fetcher/WebSearchPaneView.java +++ b/src/main/java/org/jabref/gui/importer/fetcher/WebSearchPaneView.java @@ -26,9 +26,7 @@ public class WebSearchPaneView extends VBox { - private static final PseudoClass QUERY_INVALID = PseudoClass.getPseudoClass( - "invalid" - ); + private static final PseudoClass QUERY_INVALID = PseudoClass.getPseudoClass("invalid"); private final WebSearchPaneViewModel viewModel; private final PreferencesService preferences; @@ -41,12 +39,7 @@ public WebSearchPaneView( ) { this.preferences = preferences; this.dialogService = dialogService; - this.viewModel = - new WebSearchPaneViewModel( - preferences, - dialogService, - stateManager - ); + this.viewModel = new WebSearchPaneViewModel(preferences, dialogService, stateManager); initialize(); } @@ -56,16 +49,12 @@ private void initialize() { .withText(SearchBasedFetcher::getName) .install(fetchers); fetchers.itemsProperty().bind(viewModel.fetchersProperty()); - fetchers - .valueProperty() - .bindBidirectional(viewModel.selectedFetcherProperty()); + fetchers.valueProperty().bindBidirectional(viewModel.selectedFetcherProperty()); fetchers.setMaxWidth(Double.POSITIVE_INFINITY); // Create help button for currently selected fetcher StackPane helpButtonContainer = new StackPane(); - ActionFactory factory = new ActionFactory( - preferences.getKeyBindingRepository() - ); + ActionFactory factory = new ActionFactory(preferences.getKeyBindingRepository()); EasyBind.subscribe( viewModel.selectedFetcherProperty(), fetcher -> { @@ -95,20 +84,10 @@ private void initialize() { EasyBind.subscribe( viewModel.queryValidationStatus().validProperty(), valid -> { - if ( - !valid && - viewModel - .queryValidationStatus() - .getHighestMessage() - .isPresent() - ) { + if (!valid && viewModel.queryValidationStatus().getHighestMessage().isPresent()) { query.setTooltip( new Tooltip( - viewModel - .queryValidationStatus() - .getHighestMessage() - .get() - .getMessage() + viewModel.queryValidationStatus().getHighestMessage().get().getMessage() ) ); query.pseudoClassStateChanged(QUERY_INVALID, true); diff --git a/src/main/java/org/jabref/gui/importer/fetcher/WebSearchPaneViewModel.java b/src/main/java/org/jabref/gui/importer/fetcher/WebSearchPaneViewModel.java index 03d7d5001b3..96ab632178e 100644 --- a/src/main/java/org/jabref/gui/importer/fetcher/WebSearchPaneViewModel.java +++ b/src/main/java/org/jabref/gui/importer/fetcher/WebSearchPaneViewModel.java @@ -38,10 +38,10 @@ public class WebSearchPaneViewModel { - private final ObjectProperty selectedFetcher = - new SimpleObjectProperty<>(); - private final ListProperty fetchers = - new SimpleListProperty<>(FXCollections.observableArrayList()); + private final ObjectProperty selectedFetcher = new SimpleObjectProperty<>(); + private final ListProperty fetchers = new SimpleListProperty<>( + FXCollections.observableArrayList() + ); private final StringProperty query = new SimpleStringProperty(); private final DialogService dialogService; private final PreferencesService preferencesService; @@ -67,18 +67,12 @@ public WebSearchPaneViewModel( ); // Choose last-selected fetcher as default - SidePanePreferences sidePanePreferences = - preferencesService.getSidePanePreferences(); - int defaultFetcherIndex = - sidePanePreferences.getWebSearchFetcherSelected(); - if ( - (defaultFetcherIndex <= 0) || - (defaultFetcherIndex >= fetchers.size()) - ) { + SidePanePreferences sidePanePreferences = preferencesService.getSidePanePreferences(); + int defaultFetcherIndex = sidePanePreferences.getWebSearchFetcherSelected(); + if ((defaultFetcherIndex <= 0) || (defaultFetcherIndex >= fetchers.size())) { selectedFetcherProperty().setValue(fetchers.get(0)); } else { - selectedFetcherProperty() - .setValue(fetchers.get(defaultFetcherIndex)); + selectedFetcherProperty().setValue(fetchers.get(defaultFetcherIndex)); } EasyBind.subscribe( selectedFetcherProperty(), @@ -110,10 +104,7 @@ public WebSearchPaneViewModel( int position = e.currentToken.beginColumn; if (element == null) { return ValidationMessage.error( - Localization.lang( - "Invalid query. Check position %0.", - position - ) + Localization.lang("Invalid query. Check position %0.", position) ); } else { return ValidationMessage.error( @@ -157,11 +148,7 @@ public StringProperty queryProperty() { public void search() { if (!preferencesService.getImporterPreferences().areImporterEnabled()) { - if ( - !preferencesService - .getImporterPreferences() - .areImporterEnabled() - ) { + if (!preferencesService.getImporterPreferences().areImporterEnabled()) { dialogService.notify(Localization.lang("Web search disabled")); return; } @@ -169,16 +156,12 @@ public void search() { String query = getQuery().trim(); if (StringUtil.isBlank(query)) { - dialogService.notify( - Localization.lang("Please enter a search string") - ); + dialogService.notify(Localization.lang("Please enter a search string")); return; } if (stateManager.getActiveDatabase().isEmpty()) { dialogService.notify( - Localization.lang( - "Please open or start a new library before searching" - ) + Localization.lang("Please open or start a new library before searching") ); return; } @@ -195,9 +178,7 @@ public void search() { parserResultCallable = () -> new ParserResult( - OptionalUtil.toList( - compositeIdFetcher.performSearchById(query) - ) + OptionalUtil.toList(compositeIdFetcher.performSearchById(query)) ); fetcherName = Localization.lang("Identifier-based Web Search"); } @@ -206,11 +187,7 @@ public void search() { Telemetry .getTelemetryClient() .ifPresent(client -> - client.trackEvent( - "search", - Map.of("fetcher", finalFetcherName), - Map.of() - ) + client.trackEvent("search", Map.of("fetcher", finalFetcherName), Map.of()) ); BackgroundTask task = BackgroundTask diff --git a/src/main/java/org/jabref/gui/integrity/IntegrityCheckAction.java b/src/main/java/org/jabref/gui/integrity/IntegrityCheckAction.java index 14fe8f47a14..5f18ce49a0b 100644 --- a/src/main/java/org/jabref/gui/integrity/IntegrityCheckAction.java +++ b/src/main/java/org/jabref/gui/integrity/IntegrityCheckAction.java @@ -56,17 +56,13 @@ public void execute() { preferencesService.getFilePreferences(), preferencesService.getCitationKeyPatternPreferences(), abbreviationRepository, - preferencesService - .getEntryEditorPreferences() - .shouldAllowIntegerEditionBibtex() + preferencesService.getEntryEditorPreferences().shouldAllowIntegerEditionBibtex() ); Task> task = new Task<>() { @Override protected List call() { - ObservableList entries = database - .getDatabase() - .getEntries(); + ObservableList entries = database.getDatabase().getEntries(); List result = new ArrayList<>( check.checkDatabase(database.getDatabase()) ); @@ -89,18 +85,12 @@ protected List call() { dialogService.notify(Localization.lang("No problems found.")); } else { dialogService.showCustomDialogAndWait( - new IntegrityCheckDialog( - messages, - frame.getCurrentLibraryTab() - ) + new IntegrityCheckDialog(messages, frame.getCurrentLibraryTab()) ); } }); task.setOnFailed(event -> - dialogService.showErrorDialogAndWait( - "Integrity check failed.", - task.getException() - ) + dialogService.showErrorDialogAndWait("Integrity check failed.", task.getException()) ); dialogService.showProgressDialog( diff --git a/src/main/java/org/jabref/gui/integrity/IntegrityCheckDialog.java b/src/main/java/org/jabref/gui/integrity/IntegrityCheckDialog.java index 39103b9ea00..2e873dc065e 100644 --- a/src/main/java/org/jabref/gui/integrity/IntegrityCheckDialog.java +++ b/src/main/java/org/jabref/gui/integrity/IntegrityCheckDialog.java @@ -52,10 +52,7 @@ public class IntegrityCheckDialog extends BaseDialog { private IntegrityCheckDialogViewModel viewModel; private TableFilter tableFilter; - public IntegrityCheckDialog( - List messages, - LibraryTab libraryTab - ) { + public IntegrityCheckDialog(List messages, LibraryTab libraryTab) { this.messages = messages; this.libraryTab = libraryTab; this.setTitle(Localization.lang("Check integrity")); @@ -66,19 +63,14 @@ public IntegrityCheckDialog( themeManager.updateFontStyle(getDialogPane().getScene()); } - private void onSelectionChanged( - ListChangeListener.Change change - ) { + private void onSelectionChanged(ListChangeListener.Change change) { if (change.next()) { change .getAddedSubList() .stream() .findFirst() .ifPresent(message -> - libraryTab.editEntryAndFocusField( - message.getEntry(), - message.getField() - ) + libraryTab.editEntryAndFocusField(message.getEntry(), message.getField()) ); } } @@ -91,20 +83,13 @@ public IntegrityCheckDialogViewModel getViewModel() { private void initialize() { viewModel = new IntegrityCheckDialogViewModel(messages); - messagesTable - .getSelectionModel() - .getSelectedItems() - .addListener(this::onSelectionChanged); + messagesTable.getSelectionModel().getSelectedItems().addListener(this::onSelectionChanged); messagesTable.setItems(viewModel.getMessages()); keyColumn.setCellValueFactory(row -> - new ReadOnlyStringWrapper( - row.getValue().getEntry().getCitationKey().orElse("") - ) + new ReadOnlyStringWrapper(row.getValue().getEntry().getCitationKey().orElse("")) ); fieldColumn.setCellValueFactory(row -> - new ReadOnlyStringWrapper( - row.getValue().getField().getDisplayName() - ) + new ReadOnlyStringWrapper(row.getValue().getField().getDisplayName()) ); messageColumn.setCellValueFactory(row -> new ReadOnlyStringWrapper(row.getValue().getMessage()) diff --git a/src/main/java/org/jabref/gui/journals/AbbreviateAction.java b/src/main/java/org/jabref/gui/journals/AbbreviateAction.java index 218f7aac0fa..df44a31c763 100644 --- a/src/main/java/org/jabref/gui/journals/AbbreviateAction.java +++ b/src/main/java/org/jabref/gui/journals/AbbreviateAction.java @@ -31,9 +31,7 @@ */ public class AbbreviateAction extends SimpleCommand { - private static final Logger LOGGER = LoggerFactory.getLogger( - AbbreviateAction.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(AbbreviateAction.class); private final StandardActions action; private final JabRefFrame frame; @@ -63,12 +61,9 @@ public AbbreviateAction( this.taskExecutor = taskExecutor; switch (action) { - case ABBREVIATE_DEFAULT -> abbreviationType = - AbbreviationType.DEFAULT; - case ABBREVIATE_DOTLESS -> abbreviationType = - AbbreviationType.DOTLESS; - case ABBREVIATE_SHORTEST_UNIQUE -> abbreviationType = - AbbreviationType.SHORTEST_UNIQUE; + case ABBREVIATE_DEFAULT -> abbreviationType = AbbreviationType.DEFAULT; + case ABBREVIATE_DOTLESS -> abbreviationType = AbbreviationType.DOTLESS; + case ABBREVIATE_SHORTEST_UNIQUE -> abbreviationType = AbbreviationType.SHORTEST_UNIQUE; default -> LOGGER.debug("Unknown action: " + action.name()); } @@ -116,19 +111,14 @@ public void execute() { } } - private String abbreviate( - BibDatabaseContext databaseContext, - List entries - ) { + private String abbreviate(BibDatabaseContext databaseContext, List entries) { UndoableAbbreviator undoableAbbreviator = new UndoableAbbreviator( abbreviationRepository, abbreviationType, journalAbbreviationPreferences.shouldUseFJournalField() ); - NamedCompound ce = new NamedCompound( - Localization.lang("Abbreviate journal names") - ); + NamedCompound ce = new NamedCompound(Localization.lang("Abbreviate journal names")); // Collect all callables to execute in one collection. Set> tasks = entries @@ -150,8 +140,7 @@ private String abbreviate( .collect(Collectors.toSet()); // Execute the callables and wait for the results. - List> futures = - JabRefExecutorService.INSTANCE.executeAll(tasks); + List> futures = JabRefExecutorService.INSTANCE.executeAll(tasks); // Evaluate the results of the callables. long count = futures @@ -173,23 +162,15 @@ private String abbreviate( ce.end(); frame.getUndoManager().addEdit(ce); frame.getCurrentLibraryTab().markBaseChanged(); - return Localization.lang( - "Abbreviated %0 journal names.", - String.valueOf(count) - ); + return Localization.lang("Abbreviated %0 journal names.", String.valueOf(count)); } - private String unabbreviate( - BibDatabaseContext databaseContext, - List entries - ) { + private String unabbreviate(BibDatabaseContext databaseContext, List entries) { UndoableUnabbreviator undoableAbbreviator = new UndoableUnabbreviator( Globals.journalAbbreviationRepository ); - NamedCompound ce = new NamedCompound( - Localization.lang("Unabbreviate journal names") - ); + NamedCompound ce = new NamedCompound(Localization.lang("Unabbreviate journal names")); int count = entries .stream() .mapToInt(entry -> @@ -208,17 +189,12 @@ private String unabbreviate( ) .sum(); if (count == 0) { - return Localization.lang( - "No journal names could be unabbreviated." - ); + return Localization.lang("No journal names could be unabbreviated."); } ce.end(); frame.getUndoManager().addEdit(ce); frame.getCurrentLibraryTab().markBaseChanged(); - return Localization.lang( - "Unabbreviated %0 journal names.", - String.valueOf(count) - ); + return Localization.lang("Unabbreviated %0 journal names.", String.valueOf(count)); } } diff --git a/src/main/java/org/jabref/gui/journals/UndoableAbbreviator.java b/src/main/java/org/jabref/gui/journals/UndoableAbbreviator.java index 05b6e65fca5..f66ca36537f 100644 --- a/src/main/java/org/jabref/gui/journals/UndoableAbbreviator.java +++ b/src/main/java/org/jabref/gui/journals/UndoableAbbreviator.java @@ -55,9 +55,7 @@ public boolean abbreviate( return false; // Unknown, cannot abbreviate anything. } - Abbreviation abbreviation = journalAbbreviationRepository - .get(text) - .get(); + Abbreviation abbreviation = journalAbbreviationRepository.get(text).get(); String newText = getAbbreviatedName(abbreviation); if (newText.equals(origText)) { @@ -67,24 +65,16 @@ public boolean abbreviate( // Store full name into fjournal but only if it exists if ( useFJournalField && - (StandardField.JOURNAL == fieldName || - StandardField.JOURNALTITLE == fieldName) + (StandardField.JOURNAL == fieldName || StandardField.JOURNALTITLE == fieldName) ) { entry.setField(AMSField.FJOURNAL, abbreviation.getName()); ce.addEdit( - new UndoableFieldChange( - entry, - AMSField.FJOURNAL, - null, - abbreviation.getName() - ) + new UndoableFieldChange(entry, AMSField.FJOURNAL, null, abbreviation.getName()) ); } entry.setField(fieldName, newText); - ce.addEdit( - new UndoableFieldChange(entry, fieldName, origText, newText) - ); + ce.addEdit(new UndoableFieldChange(entry, fieldName, origText, newText)); return true; } diff --git a/src/main/java/org/jabref/gui/journals/UndoableUnabbreviator.java b/src/main/java/org/jabref/gui/journals/UndoableUnabbreviator.java index f468299ac83..0cb758d64cc 100644 --- a/src/main/java/org/jabref/gui/journals/UndoableUnabbreviator.java +++ b/src/main/java/org/jabref/gui/journals/UndoableUnabbreviator.java @@ -14,9 +14,7 @@ public class UndoableUnabbreviator { private final JournalAbbreviationRepository journalAbbreviationRepository; - public UndoableUnabbreviator( - JournalAbbreviationRepository journalAbbreviationRepository - ) { + public UndoableUnabbreviator(JournalAbbreviationRepository journalAbbreviationRepository) { this.journalAbbreviationRepository = journalAbbreviationRepository; } @@ -56,23 +54,16 @@ public boolean unabbreviate( return false; // Cannot unabbreviate unabbreviated name. } - Abbreviation abbreviation = journalAbbreviationRepository - .get(text) - .get(); + Abbreviation abbreviation = journalAbbreviationRepository.get(text).get(); String newText = abbreviation.getName(); entry.setField(field, newText); ce.addEdit(new UndoableFieldChange(entry, field, origText, newText)); return true; } - public boolean restoreFromFJournal( - BibEntry entry, - Field field, - CompoundEdit ce - ) { + public boolean restoreFromFJournal(BibEntry entry, Field field, CompoundEdit ce) { if ( - (StandardField.JOURNAL != field && - StandardField.JOURNALTITLE != field) || + (StandardField.JOURNAL != field && StandardField.JOURNALTITLE != field) || !entry.hasField(AMSField.FJOURNAL) ) { return false; @@ -82,9 +73,7 @@ public boolean restoreFromFJournal( String newText = entry.getField(AMSField.FJOURNAL).get().trim(); entry.setField(AMSField.FJOURNAL, ""); - ce.addEdit( - new UndoableFieldChange(entry, AMSField.FJOURNAL, newText, "") - ); + ce.addEdit(new UndoableFieldChange(entry, AMSField.FJOURNAL, newText, "")); entry.setField(field, newText); ce.addEdit(new UndoableFieldChange(entry, field, origText, newText)); diff --git a/src/main/java/org/jabref/gui/keyboard/CodeAreaKeyBindings.java b/src/main/java/org/jabref/gui/keyboard/CodeAreaKeyBindings.java index bac36229026..e2d694c7846 100644 --- a/src/main/java/org/jabref/gui/keyboard/CodeAreaKeyBindings.java +++ b/src/main/java/org/jabref/gui/keyboard/CodeAreaKeyBindings.java @@ -22,29 +22,19 @@ public static void call( event.consume(); } case EDITOR_BACKWARD -> { - codeArea.previousChar( - NavigationActions.SelectionPolicy.CLEAR - ); + codeArea.previousChar(NavigationActions.SelectionPolicy.CLEAR); event.consume(); } case EDITOR_FORWARD -> { - codeArea.nextChar( - NavigationActions.SelectionPolicy.CLEAR - ); + codeArea.nextChar(NavigationActions.SelectionPolicy.CLEAR); event.consume(); } case EDITOR_WORD_BACKWARD -> { - codeArea.wordBreaksBackwards( - 2, - NavigationActions.SelectionPolicy.CLEAR - ); + codeArea.wordBreaksBackwards(2, NavigationActions.SelectionPolicy.CLEAR); event.consume(); } case EDITOR_WORD_FORWARD -> { - codeArea.wordBreaksForwards( - 2, - NavigationActions.SelectionPolicy.CLEAR - ); + codeArea.wordBreaksForwards(2, NavigationActions.SelectionPolicy.CLEAR); event.consume(); } case EDITOR_BEGINNING_DOC -> { @@ -52,15 +42,11 @@ public static void call( event.consume(); } case EDITOR_UP -> { - codeArea.paragraphStart( - NavigationActions.SelectionPolicy.CLEAR - ); + codeArea.paragraphStart(NavigationActions.SelectionPolicy.CLEAR); event.consume(); } case EDITOR_BEGINNING -> { - codeArea.lineStart( - NavigationActions.SelectionPolicy.CLEAR - ); + codeArea.lineStart(NavigationActions.SelectionPolicy.CLEAR); event.consume(); } case EDITOR_END_DOC -> { @@ -68,55 +54,33 @@ public static void call( event.consume(); } case EDITOR_DOWN -> { - codeArea.paragraphEnd( - NavigationActions.SelectionPolicy.CLEAR - ); + codeArea.paragraphEnd(NavigationActions.SelectionPolicy.CLEAR); event.consume(); } case EDITOR_END -> { - codeArea.lineEnd( - NavigationActions.SelectionPolicy.CLEAR - ); + codeArea.lineEnd(NavigationActions.SelectionPolicy.CLEAR); event.consume(); } case EDITOR_CAPITALIZE -> { int pos = codeArea.getCaretPosition(); - String text = codeArea.getText( - 0, - codeArea.getText().length() - ); - ResultingStringState res = StringManipulator.capitalize( - pos, - text - ); + String text = codeArea.getText(0, codeArea.getText().length()); + ResultingStringState res = StringManipulator.capitalize(pos, text); codeArea.replaceText(res.text); codeArea.displaceCaret(res.caretPosition); event.consume(); } case EDITOR_LOWERCASE -> { int pos = codeArea.getCaretPosition(); - String text = codeArea.getText( - 0, - codeArea.getText().length() - ); - ResultingStringState res = StringManipulator.lowercase( - pos, - text - ); + String text = codeArea.getText(0, codeArea.getText().length()); + ResultingStringState res = StringManipulator.lowercase(pos, text); codeArea.replaceText(res.text); codeArea.displaceCaret(res.caretPosition); event.consume(); } case EDITOR_UPPERCASE -> { int pos = codeArea.getCaretPosition(); - String text = codeArea.getText( - 0, - codeArea.getText().length() - ); - ResultingStringState res = StringManipulator.uppercase( - pos, - text - ); + String text = codeArea.getText(0, codeArea.getText().length()); + ResultingStringState res = StringManipulator.uppercase(pos, text); codeArea.clear(); codeArea.replaceText(res.text); codeArea.displaceCaret(res.caretPosition); @@ -130,26 +94,16 @@ public static void call( } case EDITOR_KILL_WORD -> { int pos = codeArea.getCaretPosition(); - String text = codeArea.getText( - 0, - codeArea.getText().length() - ); - ResultingStringState res = StringManipulator.killWord( - pos, - text - ); + String text = codeArea.getText(0, codeArea.getText().length()); + ResultingStringState res = StringManipulator.killWord(pos, text); codeArea.replaceText(res.text); codeArea.displaceCaret(res.caretPosition); event.consume(); } case EDITOR_KILL_WORD_BACKWARD -> { int pos = codeArea.getCaretPosition(); - String text = codeArea.getText( - 0, - codeArea.getText().length() - ); - ResultingStringState res = - StringManipulator.backwardKillWord(pos, text); + String text = codeArea.getText(0, codeArea.getText().length()); + ResultingStringState res = StringManipulator.backwardKillWord(pos, text); codeArea.replaceText(res.text); codeArea.displaceCaret(res.caretPosition); event.consume(); diff --git a/src/main/java/org/jabref/gui/keyboard/KeyBinding.java b/src/main/java/org/jabref/gui/keyboard/KeyBinding.java index 71fbddb7c7a..908559a4637 100644 --- a/src/main/java/org/jabref/gui/keyboard/KeyBinding.java +++ b/src/main/java/org/jabref/gui/keyboard/KeyBinding.java @@ -3,12 +3,7 @@ import org.jabref.logic.l10n.Localization; public enum KeyBinding { - EDITOR_DELETE( - "Delete", - Localization.lang("Delete text"), - "", - KeyBindingCategory.EDITOR - ), + EDITOR_DELETE("Delete", Localization.lang("Delete text"), "", KeyBindingCategory.EDITOR), // DELETE BACKWARDS = Rubout EDITOR_BACKWARD( "Move caret left", @@ -119,12 +114,7 @@ public enum KeyBinding { "ctrl+G", KeyBindingCategory.QUALITY ), - ACCEPT( - "Accept", - Localization.lang("Accept"), - "ctrl+ENTER", - KeyBindingCategory.EDIT - ), + ACCEPT("Accept", Localization.lang("Accept"), "ctrl+ENTER", KeyBindingCategory.EDIT), AUTOMATICALLY_LINK_FILES( "Automatically link files", Localization.lang("Automatically set file links"), @@ -137,24 +127,14 @@ public enum KeyBinding { "ctrl+F8", KeyBindingCategory.QUALITY ), - CLEANUP( - "Cleanup", - Localization.lang("Cleanup entries"), - "alt+F8", - KeyBindingCategory.QUALITY - ), + CLEANUP("Cleanup", Localization.lang("Cleanup entries"), "alt+F8", KeyBindingCategory.QUALITY), CLOSE_DATABASE( "Close library", Localization.lang("Close library"), "ctrl+W", KeyBindingCategory.FILE ), - CLOSE( - "Close dialog", - Localization.lang("Close dialog"), - "Esc", - KeyBindingCategory.VIEW - ), + CLOSE("Close dialog", Localization.lang("Close dialog"), "Esc", KeyBindingCategory.VIEW), COPY("Copy", Localization.lang("Copy"), "ctrl+C", KeyBindingCategory.EDIT), COPY_TITLE( "Copy title", @@ -224,12 +204,7 @@ public enum KeyBinding { "ctrl+E", KeyBindingCategory.VIEW ), - EXPORT( - "Export", - Localization.lang("Export"), - "ctrl+alt+e", - KeyBindingCategory.FILE - ), + EXPORT("Export", Localization.lang("Export"), "ctrl+alt+e", KeyBindingCategory.FILE), EXPORT_SELECTED( "Export Selected", Localization.lang("Export selected entries"), @@ -328,18 +303,8 @@ public enum KeyBinding { "ctrl+shift+A", KeyBindingCategory.BIBTEX ), - NEW_BOOK( - "New book", - Localization.lang("New book"), - "ctrl+shift+B", - KeyBindingCategory.BIBTEX - ), - NEW_ENTRY( - "New entry", - Localization.lang("New entry"), - "ctrl+N", - KeyBindingCategory.BIBTEX - ), + NEW_BOOK("New book", Localization.lang("New book"), "ctrl+shift+B", KeyBindingCategory.BIBTEX), + NEW_ENTRY("New entry", Localization.lang("New entry"), "ctrl+N", KeyBindingCategory.BIBTEX), NEW_ENTRY_FROM_PLAIN_TEXT( "New entry from plain text", Localization.lang("New entry from plain text"), @@ -413,12 +378,7 @@ public enum KeyBinding { "ctrl+O", KeyBindingCategory.FILE ), - OPEN_FILE( - "Open file", - Localization.lang("Open file"), - "F4", - KeyBindingCategory.TOOLS - ), + OPEN_FILE("Open file", Localization.lang("Open file"), "F4", KeyBindingCategory.TOOLS), OPEN_FOLDER( "Open folder", Localization.lang("Open folder"), @@ -437,12 +397,7 @@ public enum KeyBinding { "F3", KeyBindingCategory.TOOLS ), - PASTE( - "Paste", - Localization.lang("Paste"), - "ctrl+V", - KeyBindingCategory.EDIT - ), + PASTE("Paste", Localization.lang("Paste"), "ctrl+V", KeyBindingCategory.EDIT), PULL_CHANGES_FROM_SHARED_DATABASE( "Pull changes from shared database", Localization.lang("Pull changes from shared database"), @@ -467,12 +422,7 @@ public enum KeyBinding { "ctrl+L", KeyBindingCategory.TOOLS ), - QUIT_JABREF( - "Quit JabRef", - Localization.lang("Quit JabRef"), - "ctrl+Q", - KeyBindingCategory.FILE - ), + QUIT_JABREF("Quit JabRef", Localization.lang("Quit JabRef"), "ctrl+Q", KeyBindingCategory.FILE), REDO("Redo", Localization.lang("Redo"), "ctrl+Y", KeyBindingCategory.EDIT), REFRESH_OO( "Refresh OO", @@ -492,12 +442,7 @@ public enum KeyBinding { "ctrl+shift+D", KeyBindingCategory.BIBTEX ), - SAVE_ALL( - "Save all", - Localization.lang("Save all"), - "ctrl+alt+S", - KeyBindingCategory.FILE - ), + SAVE_ALL("Save all", Localization.lang("Save all"), "ctrl+alt+S", KeyBindingCategory.FILE), SAVE_DATABASE( "Save library", Localization.lang("Save library"), @@ -510,18 +455,8 @@ public enum KeyBinding { "ctrl+shift+S", KeyBindingCategory.FILE ), - SEARCH( - "Search", - Localization.lang("Search"), - "ctrl+F", - KeyBindingCategory.SEARCH - ), - SELECT_ALL( - "Select all", - Localization.lang("Select all"), - "ctrl+A", - KeyBindingCategory.EDIT - ), + SEARCH("Search", Localization.lang("Search"), "ctrl+F", KeyBindingCategory.SEARCH), + SELECT_ALL("Select all", Localization.lang("Select all"), "ctrl+A", KeyBindingCategory.EDIT), SELECT_FIRST_ENTRY( "Select first entry", Localization.lang("Select first entry"), @@ -565,12 +500,7 @@ public enum KeyBinding { KeyBindingCategory.TOOLS ), UNDO("Undo", Localization.lang("Undo"), "ctrl+Z", KeyBindingCategory.EDIT), - WEB_SEARCH( - "Web search", - Localization.lang("Web search"), - "alt+4", - KeyBindingCategory.SEARCH - ), + WEB_SEARCH("Web search", Localization.lang("Web search"), "alt+4", KeyBindingCategory.SEARCH), WRITE_METADATA_TO_PDF( "Write metadata to PDF files", Localization.lang("Write metadata to PDF files"), diff --git a/src/main/java/org/jabref/gui/keyboard/KeyBindingRepository.java b/src/main/java/org/jabref/gui/keyboard/KeyBindingRepository.java index 236d8d5932d..86315eb1b2b 100644 --- a/src/main/java/org/jabref/gui/keyboard/KeyBindingRepository.java +++ b/src/main/java/org/jabref/gui/keyboard/KeyBindingRepository.java @@ -30,13 +30,10 @@ public KeyBindingRepository(SortedMap bindings) { } public KeyBindingRepository(List bindNames, List bindings) { - this.bindings = - new TreeMap<>(Comparator.comparing(KeyBinding::getLocalization)); + this.bindings = new TreeMap<>(Comparator.comparing(KeyBinding::getLocalization)); if ( - (bindNames.isEmpty()) || - (bindings.isEmpty()) || - (bindNames.size() != bindings.size()) + (bindNames.isEmpty()) || (bindings.isEmpty()) || (bindNames.size() != bindings.size()) ) { // Use default key bindings for (KeyBinding keyBinding : KeyBinding.values()) { @@ -74,9 +71,7 @@ public Optional get(KeyBinding key) { public String get(String key) { Optional keyBinding = getKeyBinding(key); - Optional result = keyBinding.flatMap(k -> - Optional.ofNullable(bindings.get(k)) - ); + Optional result = keyBinding.flatMap(k -> Optional.ofNullable(bindings.get(k))); if (result.isPresent()) { return result.get(); @@ -110,8 +105,7 @@ private Optional getKeyBinding(String key) { } public void resetToDefault(String key) { - getKeyBinding(key) - .ifPresent(b -> bindings.put(b, b.getDefaultKeyBinding())); + getKeyBinding(key).ifPresent(b -> bindings.put(b, b.getDefaultKeyBinding())); } public void resetToDefault() { @@ -149,23 +143,14 @@ public Optional getKeyCombination(KeyBinding bindName) { * @param keyEvent as KeEvent * @return true if matching, else false */ - public boolean checkKeyCombinationEquality( - KeyBinding binding, - KeyEvent keyEvent - ) { + public boolean checkKeyCombinationEquality(KeyBinding binding, KeyEvent keyEvent) { return getKeyCombination(binding) - .filter(combination -> - checkKeyCombinationEquality(combination, keyEvent) - ) + .filter(combination -> checkKeyCombinationEquality(combination, keyEvent)) .isPresent(); } public List getBindNames() { - return bindings - .keySet() - .stream() - .map(KeyBinding::getConstant) - .collect(Collectors.toList()); + return bindings.keySet().stream().map(KeyBinding::getConstant).collect(Collectors.toList()); } public List getBindings() { diff --git a/src/main/java/org/jabref/gui/keyboard/TextInputKeyBindings.java b/src/main/java/org/jabref/gui/keyboard/TextInputKeyBindings.java index 1a643485962..22193d793ab 100644 --- a/src/main/java/org/jabref/gui/keyboard/TextInputKeyBindings.java +++ b/src/main/java/org/jabref/gui/keyboard/TextInputKeyBindings.java @@ -12,9 +12,7 @@ public class TextInputKeyBindings { public static void call(Scene scene, KeyEvent event) { if (scene.focusOwnerProperty().get() instanceof TextInputControl) { KeyBindingRepository keyBindingRepository = Globals.getKeyPrefs(); - TextInputControl focusedTextField = (TextInputControl) scene - .focusOwnerProperty() - .get(); + TextInputControl focusedTextField = (TextInputControl) scene.focusOwnerProperty().get(); keyBindingRepository .mapToKeyBinding(event) .ifPresent(binding -> { @@ -39,9 +37,7 @@ public static void call(Scene scene, KeyEvent event) { focusedTextField.nextWord(); event.consume(); } - case EDITOR_BEGINNING, - EDITOR_UP, - EDITOR_BEGINNING_DOC -> { + case EDITOR_BEGINNING, EDITOR_UP, EDITOR_BEGINNING_DOC -> { focusedTextField.home(); event.consume(); } @@ -55,8 +51,7 @@ public static void call(Scene scene, KeyEvent event) { 0, focusedTextField.getText().length() ); - ResultingStringState res = - StringManipulator.capitalize(pos, text); + ResultingStringState res = StringManipulator.capitalize(pos, text); focusedTextField.setText(res.text); focusedTextField.positionCaret(res.caretPosition); event.consume(); @@ -67,8 +62,7 @@ public static void call(Scene scene, KeyEvent event) { 0, focusedTextField.getText().length() ); - ResultingStringState res = - StringManipulator.lowercase(pos, text); + ResultingStringState res = StringManipulator.lowercase(pos, text); focusedTextField.setText(res.text); focusedTextField.positionCaret(res.caretPosition); event.consume(); @@ -79,17 +73,14 @@ public static void call(Scene scene, KeyEvent event) { 0, focusedTextField.getText().length() ); - ResultingStringState res = - StringManipulator.uppercase(pos, text); + ResultingStringState res = StringManipulator.uppercase(pos, text); focusedTextField.setText(res.text); focusedTextField.positionCaret(res.caretPosition); event.consume(); } case EDITOR_KILL_LINE -> { int pos = focusedTextField.getCaretPosition(); - focusedTextField.setText( - focusedTextField.getText(0, pos) - ); + focusedTextField.setText(focusedTextField.getText(0, pos)); focusedTextField.positionCaret(pos); event.consume(); } @@ -99,8 +90,7 @@ public static void call(Scene scene, KeyEvent event) { 0, focusedTextField.getText().length() ); - ResultingStringState res = - StringManipulator.killWord(pos, text); + ResultingStringState res = StringManipulator.killWord(pos, text); focusedTextField.setText(res.text); focusedTextField.positionCaret(res.caretPosition); event.consume(); @@ -111,8 +101,10 @@ public static void call(Scene scene, KeyEvent event) { 0, focusedTextField.getText().length() ); - ResultingStringState res = - StringManipulator.backwardKillWord(pos, text); + ResultingStringState res = StringManipulator.backwardKillWord( + pos, + text + ); focusedTextField.setText(res.text); focusedTextField.positionCaret(res.caretPosition); event.consume(); diff --git a/src/main/java/org/jabref/gui/libraryproperties/AbstractPropertiesTabView.java b/src/main/java/org/jabref/gui/libraryproperties/AbstractPropertiesTabView.java index 1f4d2d8f9df..de6cb3d0911 100644 --- a/src/main/java/org/jabref/gui/libraryproperties/AbstractPropertiesTabView.java +++ b/src/main/java/org/jabref/gui/libraryproperties/AbstractPropertiesTabView.java @@ -6,9 +6,7 @@ import org.jabref.gui.DialogService; import org.jabref.model.database.BibDatabaseContext; -public abstract class AbstractPropertiesTabView< - T extends PropertiesTabViewModel -> +public abstract class AbstractPropertiesTabView extends VBox implements PropertiesTab { diff --git a/src/main/java/org/jabref/gui/libraryproperties/LibraryPropertiesAction.java b/src/main/java/org/jabref/gui/libraryproperties/LibraryPropertiesAction.java index db41ee39517..179b3e1c58b 100644 --- a/src/main/java/org/jabref/gui/libraryproperties/LibraryPropertiesAction.java +++ b/src/main/java/org/jabref/gui/libraryproperties/LibraryPropertiesAction.java @@ -13,9 +13,7 @@ public class LibraryPropertiesAction extends SimpleCommand { - private static final Logger LOGGER = LoggerFactory.getLogger( - LibraryPropertiesAction.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(LibraryPropertiesAction.class); private final StateManager stateManager; private final Supplier alternateDatabase; @@ -35,9 +33,7 @@ public LibraryPropertiesAction( @Override public void execute() { - DialogService dialogService = Injector.instantiateModelOrService( - DialogService.class - ); + DialogService dialogService = Injector.instantiateModelOrService(DialogService.class); if (alternateDatabase != null) { dialogService.showCustomDialogAndWait( @@ -46,9 +42,7 @@ public void execute() { } else { if (stateManager.getActiveDatabase().isPresent()) { dialogService.showCustomDialogAndWait( - new LibraryPropertiesView( - stateManager.getActiveDatabase().get() - ) + new LibraryPropertiesView(stateManager.getActiveDatabase().get()) ); } else { LOGGER.warn("No library selected."); diff --git a/src/main/java/org/jabref/gui/libraryproperties/LibraryPropertiesView.java b/src/main/java/org/jabref/gui/libraryproperties/LibraryPropertiesView.java index 1732bc67c22..a300aa499ea 100644 --- a/src/main/java/org/jabref/gui/libraryproperties/LibraryPropertiesView.java +++ b/src/main/java/org/jabref/gui/libraryproperties/LibraryPropertiesView.java @@ -13,8 +13,7 @@ import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; -public class LibraryPropertiesView - extends BaseDialog { +public class LibraryPropertiesView extends BaseDialog { @FXML private TabPane tabPane; @@ -63,9 +62,7 @@ private void initialize() { scrollPane.setFitToWidth(true); tabPane.getTabs().add(new Tab(pane.getTabName(), scrollPane)); if (pane instanceof AbstractPropertiesTabView propertiesTab) { - propertiesTab - .prefHeightProperty() - .bind(tabPane.tabMaxHeightProperty()); + propertiesTab.prefHeightProperty().bind(tabPane.tabMaxHeightProperty()); propertiesTab.prefWidthProperty().bind(tabPane.widthProperty()); propertiesTab.getStyleClass().add("propertiesTab"); } diff --git a/src/main/java/org/jabref/gui/libraryproperties/constants/ConstantsItemModel.java b/src/main/java/org/jabref/gui/libraryproperties/constants/ConstantsItemModel.java index 63ee6bacad6..b044550a081 100644 --- a/src/main/java/org/jabref/gui/libraryproperties/constants/ConstantsItemModel.java +++ b/src/main/java/org/jabref/gui/libraryproperties/constants/ConstantsItemModel.java @@ -13,9 +13,7 @@ public class ConstantsItemModel { - private static final Pattern IS_NUMBER = Pattern.compile( - "-?\\d+(\\.\\d+)?" - ); + private static final Pattern IS_NUMBER = Pattern.compile("-?\\d+(\\.\\d+)?"); private final StringProperty labelProperty = new SimpleStringProperty(); private final StringProperty contentProperty = new SimpleStringProperty(); @@ -29,17 +27,10 @@ public ConstantsItemModel(String label, String content) { this.contentProperty.setValue(content); labelValidator = - new FunctionBasedValidator<>( - this.labelProperty, - ConstantsItemModel::validateLabel - ); + new FunctionBasedValidator<>(this.labelProperty, ConstantsItemModel::validateLabel); contentValidator = - new FunctionBasedValidator<>( - this.contentProperty, - ConstantsItemModel::validateContent - ); - combinedValidator = - new CompositeValidator(labelValidator, contentValidator); + new FunctionBasedValidator<>(this.contentProperty, ConstantsItemModel::validateContent); + combinedValidator = new CompositeValidator(labelValidator, contentValidator); } public ValidationStatus labelValidation() { @@ -74,24 +65,18 @@ private static ValidationMessage validateLabel(String input) { if (input == null) { return ValidationMessage.error("May not be null"); } else if (input.trim().isEmpty()) { - return ValidationMessage.error( - Localization.lang("Please enter the string's label") - ); + return ValidationMessage.error(Localization.lang("Please enter the string's label")); } else if (IS_NUMBER.matcher(input).matches()) { return ValidationMessage.error( Localization.lang("The label of the string cannot be a number.") ); } else if (input.contains("#")) { return ValidationMessage.error( - Localization.lang( - "The label of the string cannot contain the '#' character." - ) + Localization.lang("The label of the string cannot contain the '#' character.") ); } else if (input.contains(" ")) { return ValidationMessage.error( - Localization.lang( - "The label of the string cannot contain spaces." - ) + Localization.lang("The label of the string cannot contain spaces.") ); } else { return null; // everything is ok @@ -100,13 +85,9 @@ private static ValidationMessage validateLabel(String input) { private static ValidationMessage validateContent(String input) { if (input == null) { - return ValidationMessage.error( - Localization.lang("Must not be empty!") - ); + return ValidationMessage.error(Localization.lang("Must not be empty!")); } else if (input.trim().isEmpty()) { - return ValidationMessage.error( - Localization.lang("Must not be empty!") - ); + return ValidationMessage.error(Localization.lang("Must not be empty!")); } else { return null; // everything is ok } diff --git a/src/main/java/org/jabref/gui/libraryproperties/constants/ConstantsPropertiesView.java b/src/main/java/org/jabref/gui/libraryproperties/constants/ConstantsPropertiesView.java index 939af70db1f..4d3e607aafd 100644 --- a/src/main/java/org/jabref/gui/libraryproperties/constants/ConstantsPropertiesView.java +++ b/src/main/java/org/jabref/gui/libraryproperties/constants/ConstantsPropertiesView.java @@ -67,38 +67,27 @@ public void initialize() { preferencesService.getFilePreferences() ); - addStringButton.setTooltip( - new Tooltip(Localization.lang("New string")) - ); + addStringButton.setTooltip(new Tooltip(Localization.lang("New string"))); labelColumn.setSortable(true); labelColumn.setReorderable(false); - labelColumn.setCellValueFactory(cellData -> - cellData.getValue().labelProperty() - ); - new ViewModelTextFieldTableCellVisualizationFactory< - ConstantsItemModel, - String - >() + labelColumn.setCellValueFactory(cellData -> cellData.getValue().labelProperty()); + new ViewModelTextFieldTableCellVisualizationFactory() .withValidation(ConstantsItemModel::labelValidation) .install(labelColumn, new DefaultStringConverter()); labelColumn.setOnEditCommit( - ( - TableColumn.CellEditEvent cellEvent - ) -> { + (TableColumn.CellEditEvent cellEvent) -> { var tableView = cellEvent.getTableView(); ConstantsItemModel cellItem = tableView .getItems() .get(cellEvent.getTablePosition().getRow()); - Optional existingItem = - viewModel.labelAlreadyExists(cellEvent.getNewValue()); + Optional existingItem = viewModel.labelAlreadyExists( + cellEvent.getNewValue() + ); - if ( - existingItem.isPresent() && - !existingItem.get().equals(cellItem) - ) { + if (existingItem.isPresent() && !existingItem.get().equals(cellItem)) { dialogService.showErrorDialogAndWait( Localization.lang( "A string with the label '%0' already exists.", @@ -122,13 +111,8 @@ public void initialize() { contentColumn.setSortable(true); contentColumn.setReorderable(false); - contentColumn.setCellValueFactory(cellData -> - cellData.getValue().contentProperty() - ); - new ViewModelTextFieldTableCellVisualizationFactory< - ConstantsItemModel, - String - >() + contentColumn.setCellValueFactory(cellData -> cellData.getValue().contentProperty()); + new ViewModelTextFieldTableCellVisualizationFactory() .withValidation(ConstantsItemModel::contentValidation) .install(contentColumn, new DefaultStringConverter()); contentColumn.setOnEditCommit( @@ -138,25 +122,16 @@ public void initialize() { actionsColumn.setSortable(false); actionsColumn.setReorderable(false); - actionsColumn.setCellValueFactory(cellData -> - cellData.getValue().labelProperty() - ); + actionsColumn.setCellValueFactory(cellData -> cellData.getValue().labelProperty()); new ValueTableCellFactory() - .withGraphic(label -> - IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode() - ) + .withGraphic(label -> IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode()) .withTooltip(label -> Localization.lang("Remove string %0", label)) .withOnMouseClickedEvent(item -> - evt -> - viewModel.removeString( - stringsList.getFocusModel().getFocusedItem() - ) + evt -> viewModel.removeString(stringsList.getFocusModel().getFocusedItem()) ) .install(actionsColumn); - stringsList - .itemsProperty() - .bindBidirectional(viewModel.stringsListProperty()); + stringsList.itemsProperty().bindBidirectional(viewModel.stringsListProperty()); stringsList.setEditable(true); } diff --git a/src/main/java/org/jabref/gui/libraryproperties/constants/ConstantsPropertiesViewModel.java b/src/main/java/org/jabref/gui/libraryproperties/constants/ConstantsPropertiesViewModel.java index cf81acfac1a..a9f56702f68 100644 --- a/src/main/java/org/jabref/gui/libraryproperties/constants/ConstantsPropertiesViewModel.java +++ b/src/main/java/org/jabref/gui/libraryproperties/constants/ConstantsPropertiesViewModel.java @@ -25,8 +25,9 @@ public class ConstantsPropertiesViewModel implements PropertiesTabViewModel { private static final String NEW_STRING_LABEL = "NewString"; // must not contain spaces - private final ListProperty stringsListProperty = - new SimpleListProperty<>(FXCollections.observableArrayList()); + private final ListProperty stringsListProperty = new SimpleListProperty<>( + FXCollections.observableArrayList() + ); private final BooleanProperty validProperty = new SimpleBooleanProperty(); @@ -44,16 +45,12 @@ public ConstantsPropertiesViewModel( this.dialogService = dialogService; this.filePreferences = filePreferences; - ObservableList> allValidProperty = - EasyBind.map( - stringsListProperty, - ConstantsItemModel::combinedValidationValidProperty - ); + ObservableList> allValidProperty = EasyBind.map( + stringsListProperty, + ConstantsItemModel::combinedValidationValidProperty + ); validProperty.bind( - EasyBind.combine( - allValidProperty, - stream -> stream.allMatch(valid -> valid) - ) + EasyBind.combine(allValidProperty, stream -> stream.allMatch(valid -> valid)) ); } @@ -92,19 +89,12 @@ public void removeString(ConstantsItemModel item) { public void resortStrings() { // Resort the strings list in the same order as setValues() does stringsListProperty.sort( - Comparator.comparing(c -> - c.labelProperty().get().toLowerCase(Locale.ROOT) - ) + Comparator.comparing(c -> c.labelProperty().get().toLowerCase(Locale.ROOT)) ); } - private ConstantsItemModel convertFromBibTexString( - BibtexString bibtexString - ) { - return new ConstantsItemModel( - bibtexString.getName(), - bibtexString.getContent() - ); + private ConstantsItemModel convertFromBibTexString(BibtexString bibtexString) { + return new ConstantsItemModel(bibtexString.getName(), bibtexString.getContent()); } @Override @@ -119,9 +109,7 @@ public void storeSettings() { ); } - private BibtexString fromBibtexStringViewModel( - ConstantsItemModel viewModel - ) { + private BibtexString fromBibtexStringViewModel(ConstantsItemModel viewModel) { String label = viewModel.labelProperty().getValue(); String content = viewModel.contentProperty().getValue(); return new BibtexString(label, content); @@ -135,8 +123,7 @@ public Optional labelAlreadyExists(String label) { } public void openHelpPage() { - new HelpAction(HelpFile.STRING_EDITOR, dialogService, filePreferences) - .execute(); + new HelpAction(HelpFile.STRING_EDITOR, dialogService, filePreferences).execute(); } public ListProperty stringsListProperty() { diff --git a/src/main/java/org/jabref/gui/libraryproperties/contentselectors/ContentSelectorView.java b/src/main/java/org/jabref/gui/libraryproperties/contentselectors/ContentSelectorView.java index d8ff5228822..ab63ac907b7 100644 --- a/src/main/java/org/jabref/gui/libraryproperties/contentselectors/ContentSelectorView.java +++ b/src/main/java/org/jabref/gui/libraryproperties/contentselectors/ContentSelectorView.java @@ -17,8 +17,7 @@ import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.field.Field; -public class ContentSelectorView - extends AbstractPropertiesTabView { +public class ContentSelectorView extends AbstractPropertiesTabView { @FXML private Button removeFieldNameButton; @@ -53,8 +52,7 @@ public String getTabName() { @FXML public void initialize() { - this.viewModel = - new ContentSelectorViewModel(databaseContext, dialogService); + this.viewModel = new ContentSelectorViewModel(databaseContext, dialogService); initFieldNameComponents(); initKeywordsComponents(); @@ -68,13 +66,8 @@ private void initFieldNameComponents() { new ViewModelListCellFactory() .withText(Field::getDisplayName) .install(fieldsListView); - removeFieldNameButton - .disableProperty() - .bind(viewModel.isNoFieldNameSelected()); - EasyBind.subscribe( - viewModel.selectedFieldProperty(), - viewModel::populateKeywords - ); + removeFieldNameButton.disableProperty().bind(viewModel.isNoFieldNameSelected()); + EasyBind.subscribe(viewModel.selectedFieldProperty(), viewModel::populateKeywords); } private void initKeywordsComponents() { @@ -82,12 +75,8 @@ private void initKeywordsComponents() { viewModel .selectedKeywordProperty() .bind(keywordsListView.getSelectionModel().selectedItemProperty()); - addKeywordButton - .disableProperty() - .bind(viewModel.isFieldNameListEmpty()); - removeKeywordButton - .disableProperty() - .bind(viewModel.isNoKeywordSelected()); + addKeywordButton.disableProperty().bind(viewModel.isFieldNameListEmpty()); + removeKeywordButton.disableProperty().bind(viewModel.isNoKeywordSelected()); } @FXML @@ -97,8 +86,7 @@ private void addNewFieldName() { @FXML private void removeFieldName() { - getSelectedField() - .ifPresent(viewModel::showRemoveFieldNameConfirmationDialog); + getSelectedField().ifPresent(viewModel::showRemoveFieldNameConfirmationDialog); } @FXML @@ -111,10 +99,7 @@ private void removeKeyword() { Optional fieldName = getSelectedField(); Optional keywordToRemove = getSelectedKeyword(); if (fieldName.isPresent() && keywordToRemove.isPresent()) { - viewModel.showRemoveKeywordConfirmationDialog( - fieldName.get(), - keywordToRemove.get() - ); + viewModel.showRemoveKeywordConfirmationDialog(fieldName.get(), keywordToRemove.get()); } } @@ -127,9 +112,7 @@ private void initListView( } private Optional getSelectedField() { - return Optional - .of(fieldsListView.getSelectionModel()) - .map(SelectionModel::getSelectedItem); + return Optional.of(fieldsListView.getSelectionModel()).map(SelectionModel::getSelectedItem); } private Optional getSelectedKeyword() { diff --git a/src/main/java/org/jabref/gui/libraryproperties/contentselectors/ContentSelectorViewModel.java b/src/main/java/org/jabref/gui/libraryproperties/contentselectors/ContentSelectorViewModel.java index c6e3cc3b581..5381861e7dc 100644 --- a/src/main/java/org/jabref/gui/libraryproperties/contentselectors/ContentSelectorViewModel.java +++ b/src/main/java/org/jabref/gui/libraryproperties/contentselectors/ContentSelectorViewModel.java @@ -48,14 +48,10 @@ public class ContentSelectorViewModel implements PropertiesTabViewModel { private final ListProperty keywords = new SimpleListProperty<>( FXCollections.observableArrayList() ); - private final ObjectProperty selectedField = - new SimpleObjectProperty<>(); + private final ObjectProperty selectedField = new SimpleObjectProperty<>(); private final StringProperty selectedKeyword = new SimpleStringProperty(); - ContentSelectorViewModel( - BibDatabaseContext databaseContext, - DialogService dialogService - ) { + ContentSelectorViewModel(BibDatabaseContext databaseContext, DialogService dialogService) { this.metaData = databaseContext.getMetaData(); this.dialogService = dialogService; } @@ -84,9 +80,7 @@ public void setValues() { @Override public void storeSettings() { - List metaDataFields = metaData - .getContentSelectors() - .getFieldsWithSelectors(); + List metaDataFields = metaData.getContentSelectors().getFieldsWithSelectors(); if (isDefaultMap(fieldKeywordsMap)) { Iterator iterator = metaData @@ -163,10 +157,7 @@ private void addFieldIfUnique(Field fieldToAdd) { boolean exists = fieldKeywordsMap.containsKey(fieldToAdd); if (exists) { dialogService.showErrorDialogAndWait( - Localization.lang( - "Field name \"%0\" already exists", - fieldToAdd.getDisplayName() - ) + Localization.lang("Field name \"%0\" already exists", fieldToAdd.getDisplayName()) ); return; } @@ -177,9 +168,7 @@ private void addFieldIfUnique(Field fieldToAdd) { void showRemoveFieldNameConfirmationDialog(Field fieldToRemove) { if (fieldToRemove == null) { - dialogService.showErrorDialogAndWait( - Localization.lang("No field name selected!") - ); + dialogService.showErrorDialogAndWait(Localization.lang("No field name selected!")); return; } @@ -214,9 +203,7 @@ void showInputKeywordDialog(Field selectedField) { Localization.lang("Add new keyword"), Localization.lang("Keyword:") ) - .ifPresent(newKeyword -> - addKeywordIfUnique(selectedField, newKeyword) - ); + .ifPresent(newKeyword -> addKeywordIfUnique(selectedField, newKeyword)); } private void addKeywordIfUnique(Field field, String keywordToAdd) { @@ -228,26 +215,17 @@ private void addKeywordIfUnique(Field field, String keywordToAdd) { return; } - List existingKeywords = fieldKeywordsMap.getOrDefault( - field, - new ArrayList<>() - ); + List existingKeywords = fieldKeywordsMap.getOrDefault(field, new ArrayList<>()); existingKeywords.add(keywordToAdd); existingKeywords.sort(Comparator.naturalOrder()); fieldKeywordsMap.put(field, existingKeywords); populateKeywords(field); } - void showRemoveKeywordConfirmationDialog( - Field field, - String keywordToRemove - ) { + void showRemoveKeywordConfirmationDialog(Field field, String keywordToRemove) { boolean deleteConfirmed = dialogService.showConfirmationDialogAndWait( Localization.lang("Remove keyword"), - Localization.lang( - "Are you sure you want to remove keyword: \"%0\"?", - keywordToRemove - ) + Localization.lang("Are you sure you want to remove keyword: \"%0\"?", keywordToRemove) ); if (deleteConfirmed) { removeKeyword(field, keywordToRemove); @@ -287,8 +265,7 @@ private void updateMetaDataContentSelector( private boolean keywordsHaveChanged(Field field, List keywords) { HashSet keywordsSet = asHashSet(keywords); - List existingKeywords = - metaData.getContentSelectorValuesForField(field); + List existingKeywords = metaData.getContentSelectorValuesForField(field); if (!keywordsSet.equals(asHashSet(existingKeywords))) { return true; } diff --git a/src/main/java/org/jabref/gui/libraryproperties/general/GeneralPropertiesView.java b/src/main/java/org/jabref/gui/libraryproperties/general/GeneralPropertiesView.java index b771b17882a..38032e4d172 100644 --- a/src/main/java/org/jabref/gui/libraryproperties/general/GeneralPropertiesView.java +++ b/src/main/java/org/jabref/gui/libraryproperties/general/GeneralPropertiesView.java @@ -13,8 +13,7 @@ import org.jabref.model.database.BibDatabaseMode; import org.jabref.preferences.PreferencesService; -public class GeneralPropertiesView - extends AbstractPropertiesTabView { +public class GeneralPropertiesView extends AbstractPropertiesTabView { @FXML private ComboBox encoding; @@ -47,40 +46,26 @@ public String getTabName() { public void initialize() { this.viewModel = - new GeneralPropertiesViewModel( - databaseContext, - dialogService, - preferencesService - ); - - new ViewModelListCellFactory() - .withText(Charset::displayName) - .install(encoding); + new GeneralPropertiesViewModel(databaseContext, dialogService, preferencesService); + + new ViewModelListCellFactory().withText(Charset::displayName).install(encoding); encoding.disableProperty().bind(viewModel.encodingDisableProperty()); encoding.itemsProperty().bind(viewModel.encodingsProperty()); - encoding - .valueProperty() - .bindBidirectional(viewModel.selectedEncodingProperty()); + encoding.valueProperty().bindBidirectional(viewModel.selectedEncodingProperty()); new ViewModelListCellFactory() .withText(BibDatabaseMode::getFormattedName) .install(databaseMode); databaseMode.itemsProperty().bind(viewModel.databaseModesProperty()); - databaseMode - .valueProperty() - .bindBidirectional(viewModel.selectedDatabaseModeProperty()); + databaseMode.valueProperty().bindBidirectional(viewModel.selectedDatabaseModeProperty()); generalFileDirectory .textProperty() - .bindBidirectional( - viewModel.generalFileDirectoryPropertyProperty() - ); + .bindBidirectional(viewModel.generalFileDirectoryPropertyProperty()); userSpecificFileDirectory .textProperty() .bindBidirectional(viewModel.userSpecificFileDirectoryProperty()); - laTexFileDirectory - .textProperty() - .bindBidirectional(viewModel.laTexFileDirectoryProperty()); + laTexFileDirectory.textProperty().bindBidirectional(viewModel.laTexFileDirectoryProperty()); } @FXML diff --git a/src/main/java/org/jabref/gui/libraryproperties/general/GeneralPropertiesViewModel.java b/src/main/java/org/jabref/gui/libraryproperties/general/GeneralPropertiesViewModel.java index 00fb964da18..870efd57b45 100644 --- a/src/main/java/org/jabref/gui/libraryproperties/general/GeneralPropertiesViewModel.java +++ b/src/main/java/org/jabref/gui/libraryproperties/general/GeneralPropertiesViewModel.java @@ -24,29 +24,21 @@ public class GeneralPropertiesViewModel implements PropertiesTabViewModel { - private final BooleanProperty encodingDisableProperty = - new SimpleBooleanProperty(); - private final ListProperty encodingsProperty = - new SimpleListProperty<>( - FXCollections.observableArrayList(Encodings.getCharsets()) - ); - private final ObjectProperty selectedEncodingProperty = - new SimpleObjectProperty<>(Encodings.getCharsets().get(0)); - private final ListProperty databaseModesProperty = - new SimpleListProperty<>( - FXCollections.observableArrayList(BibDatabaseMode.values()) - ); - private final SimpleObjectProperty< - BibDatabaseMode - > selectedDatabaseModeProperty = new SimpleObjectProperty<>( - BibDatabaseMode.BIBLATEX + private final BooleanProperty encodingDisableProperty = new SimpleBooleanProperty(); + private final ListProperty encodingsProperty = new SimpleListProperty<>( + FXCollections.observableArrayList(Encodings.getCharsets()) + ); + private final ObjectProperty selectedEncodingProperty = new SimpleObjectProperty<>( + Encodings.getCharsets().get(0) ); - private final StringProperty generalFileDirectoryProperty = - new SimpleStringProperty(""); - private final StringProperty userSpecificFileDirectoryProperty = - new SimpleStringProperty(""); - private final StringProperty laTexFileDirectoryProperty = - new SimpleStringProperty(""); + private final ListProperty databaseModesProperty = new SimpleListProperty<>( + FXCollections.observableArrayList(BibDatabaseMode.values()) + ); + private final SimpleObjectProperty selectedDatabaseModeProperty = + new SimpleObjectProperty<>(BibDatabaseMode.BIBLATEX); + private final StringProperty generalFileDirectoryProperty = new SimpleStringProperty(""); + private final StringProperty userSpecificFileDirectoryProperty = new SimpleStringProperty(""); + private final StringProperty laTexFileDirectoryProperty = new SimpleStringProperty(""); private final DialogService dialogService; private final PreferencesService preferencesService; @@ -67,42 +59,27 @@ public class GeneralPropertiesViewModel implements PropertiesTabViewModel { this.directoryDialogConfiguration = new DirectoryDialogConfiguration.Builder() - .withInitialDirectory( - preferencesService - .getFilePreferences() - .getWorkingDirectory() - ) + .withInitialDirectory(preferencesService.getFilePreferences().getWorkingDirectory()) .build(); } @Override public void setValues() { - boolean isShared = - databaseContext.getLocation() == DatabaseLocation.SHARED; + boolean isShared = databaseContext.getLocation() == DatabaseLocation.SHARED; encodingDisableProperty.setValue(isShared); // the encoding of shared database is always UTF-8 - selectedEncodingProperty.setValue( - metaData.getEncoding().orElse(StandardCharsets.UTF_8) - ); - selectedDatabaseModeProperty.setValue( - metaData.getMode().orElse(BibDatabaseMode.BIBLATEX) - ); - generalFileDirectoryProperty.setValue( - metaData.getDefaultFileDirectory().orElse("").trim() - ); + selectedEncodingProperty.setValue(metaData.getEncoding().orElse(StandardCharsets.UTF_8)); + selectedDatabaseModeProperty.setValue(metaData.getMode().orElse(BibDatabaseMode.BIBLATEX)); + generalFileDirectoryProperty.setValue(metaData.getDefaultFileDirectory().orElse("").trim()); userSpecificFileDirectoryProperty.setValue( metaData - .getUserFileDirectory( - preferencesService.getFilePreferences().getUserAndHost() - ) + .getUserFileDirectory(preferencesService.getFilePreferences().getUserAndHost()) .orElse("") .trim() ); laTexFileDirectoryProperty.setValue( metaData - .getLatexFileDirectory( - preferencesService.getFilePreferences().getUserAndHost() - ) + .getLatexFileDirectory(preferencesService.getFilePreferences().getUserAndHost()) .map(Path::toString) .orElse("") ); @@ -115,17 +92,14 @@ public void storeSettings() { newMetaData.setEncoding(selectedEncodingProperty.getValue()); newMetaData.setMode(selectedDatabaseModeProperty.getValue()); - String generalFileDirectory = generalFileDirectoryProperty - .getValue() - .trim(); + String generalFileDirectory = generalFileDirectoryProperty.getValue().trim(); if (generalFileDirectory.isEmpty()) { newMetaData.clearDefaultFileDirectory(); } else { newMetaData.setDefaultFileDirectory(generalFileDirectory); } - String userSpecificFileDirectory = - userSpecificFileDirectoryProperty.getValue(); + String userSpecificFileDirectory = userSpecificFileDirectoryProperty.getValue(); if (userSpecificFileDirectory.isEmpty()) { newMetaData.clearUserFileDirectory( preferencesService.getFilePreferences().getUserAndHost() @@ -155,10 +129,7 @@ public void storeSettings() { public void browseGeneralDir() { dialogService .showDirectorySelectionDialog(directoryDialogConfiguration) - .ifPresent(dir -> - generalFileDirectoryProperty.setValue( - dir.toAbsolutePath().toString() - ) + .ifPresent(dir -> generalFileDirectoryProperty.setValue(dir.toAbsolutePath().toString()) ); } @@ -166,20 +137,14 @@ public void browseUserDir() { dialogService .showDirectorySelectionDialog(directoryDialogConfiguration) .ifPresent(dir -> - userSpecificFileDirectoryProperty.setValue( - dir.toAbsolutePath().toString() - ) + userSpecificFileDirectoryProperty.setValue(dir.toAbsolutePath().toString()) ); } public void browseLatexDir() { dialogService .showDirectorySelectionDialog(directoryDialogConfiguration) - .ifPresent(dir -> - laTexFileDirectoryProperty.setValue( - dir.toAbsolutePath().toString() - ) - ); + .ifPresent(dir -> laTexFileDirectoryProperty.setValue(dir.toAbsolutePath().toString())); } public BooleanProperty encodingDisableProperty() { @@ -198,9 +163,7 @@ public ListProperty databaseModesProperty() { return databaseModesProperty; } - public SimpleObjectProperty< - BibDatabaseMode - > selectedDatabaseModeProperty() { + public SimpleObjectProperty selectedDatabaseModeProperty() { return selectedDatabaseModeProperty; } diff --git a/src/main/java/org/jabref/gui/libraryproperties/keypattern/KeyPatternPropertiesView.java b/src/main/java/org/jabref/gui/libraryproperties/keypattern/KeyPatternPropertiesView.java index fe35f92c916..003481d881e 100644 --- a/src/main/java/org/jabref/gui/libraryproperties/keypattern/KeyPatternPropertiesView.java +++ b/src/main/java/org/jabref/gui/libraryproperties/keypattern/KeyPatternPropertiesView.java @@ -45,11 +45,7 @@ public String getTabName() { } public void initialize() { - this.viewModel = - new KeyPatternPropertiesViewModel( - databaseContext, - preferencesService - ); + this.viewModel = new KeyPatternPropertiesViewModel(databaseContext, preferencesService); bibtexKeyPatternTable .patternListProperty() @@ -78,18 +74,12 @@ public void setValues() { databaseContext .getMetaData() .getMode() - .orElse( - preferencesService - .getLibraryPreferences() - .getDefaultBibDatabaseMode() - ) + .orElse(preferencesService.getLibraryPreferences().getDefaultBibDatabaseMode()) ), databaseContext .getMetaData() .getCiteKeyPattern( - preferencesService - .getCitationKeyPatternPreferences() - .getKeyPattern() + preferencesService.getCitationKeyPatternPreferences().getKeyPattern() ) ); } diff --git a/src/main/java/org/jabref/gui/libraryproperties/keypattern/KeyPatternPropertiesViewModel.java b/src/main/java/org/jabref/gui/libraryproperties/keypattern/KeyPatternPropertiesViewModel.java index 78ece995e50..be6aa9e5e8a 100644 --- a/src/main/java/org/jabref/gui/libraryproperties/keypattern/KeyPatternPropertiesViewModel.java +++ b/src/main/java/org/jabref/gui/libraryproperties/keypattern/KeyPatternPropertiesViewModel.java @@ -16,19 +16,15 @@ public class KeyPatternPropertiesViewModel implements PropertiesTabViewModel { // The list and the default properties are being overwritten by the bound properties of the tableView, but to // prevent an NPE on storing the preferences before lazy-loading of the setValues, they need to be initialized. - private final ListProperty< - CitationKeyPatternPanelItemModel - > patternListProperty = new SimpleListProperty<>( - FXCollections.observableArrayList() - ); - private final ObjectProperty< - CitationKeyPatternPanelItemModel - > defaultKeyPatternProperty = new SimpleObjectProperty<>( - new CitationKeyPatternPanelItemModel( - new CitationKeyPatternPanelViewModel.DefaultEntryType(), - "" - ) - ); + private final ListProperty patternListProperty = + new SimpleListProperty<>(FXCollections.observableArrayList()); + private final ObjectProperty defaultKeyPatternProperty = + new SimpleObjectProperty<>( + new CitationKeyPatternPanelItemModel( + new CitationKeyPatternPanelViewModel.DefaultEntryType(), + "" + ) + ); private final PreferencesService preferencesService; @@ -49,47 +45,33 @@ public void setValues() { @Override public void storeSettings() { - DatabaseCitationKeyPattern newKeyPattern = - new DatabaseCitationKeyPattern( - preferencesService - .getCitationKeyPatternPreferences() - .getKeyPattern() - ); + DatabaseCitationKeyPattern newKeyPattern = new DatabaseCitationKeyPattern( + preferencesService.getCitationKeyPatternPreferences().getKeyPattern() + ); patternListProperty.forEach(item -> { String patternString = item.getPattern(); if (!item.getEntryType().getName().equals("default")) { if (!patternString.trim().isEmpty()) { - newKeyPattern.addCitationKeyPattern( - item.getEntryType(), - patternString - ); + newKeyPattern.addCitationKeyPattern(item.getEntryType(), patternString); } } }); - if ( - !defaultKeyPatternProperty.getValue().getPattern().trim().isEmpty() - ) { + if (!defaultKeyPatternProperty.getValue().getPattern().trim().isEmpty()) { // we do not trim the value at the assignment to enable users to have spaces at the beginning and // at the end of the pattern - newKeyPattern.setDefaultValue( - defaultKeyPatternProperty.getValue().getPattern() - ); + newKeyPattern.setDefaultValue(defaultKeyPatternProperty.getValue().getPattern()); } databaseContext.getMetaData().setCiteKeyPattern(newKeyPattern); } - public ListProperty< - CitationKeyPatternPanelItemModel - > patternListProperty() { + public ListProperty patternListProperty() { return patternListProperty; } - public ObjectProperty< - CitationKeyPatternPanelItemModel - > defaultKeyPatternProperty() { + public ObjectProperty defaultKeyPatternProperty() { return defaultKeyPatternProperty; } } diff --git a/src/main/java/org/jabref/gui/libraryproperties/preamble/PreamblePropertiesView.java b/src/main/java/org/jabref/gui/libraryproperties/preamble/PreamblePropertiesView.java index 70378775674..c0fb4a17aac 100644 --- a/src/main/java/org/jabref/gui/libraryproperties/preamble/PreamblePropertiesView.java +++ b/src/main/java/org/jabref/gui/libraryproperties/preamble/PreamblePropertiesView.java @@ -9,8 +9,7 @@ import org.jabref.logic.l10n.Localization; import org.jabref.model.database.BibDatabaseContext; -public class PreamblePropertiesView - extends AbstractPropertiesTabView { +public class PreamblePropertiesView extends AbstractPropertiesTabView { @FXML private TextArea preamble; @@ -30,8 +29,7 @@ public String getTabName() { } public void initialize() { - this.viewModel = - new PreamblePropertiesViewModel(databaseContext, undoManager); + this.viewModel = new PreamblePropertiesViewModel(databaseContext, undoManager); preamble.textProperty().bindBidirectional(viewModel.preambleProperty()); } diff --git a/src/main/java/org/jabref/gui/libraryproperties/preamble/PreamblePropertiesViewModel.java b/src/main/java/org/jabref/gui/libraryproperties/preamble/PreamblePropertiesViewModel.java index e13c377d8da..d995193b6c6 100644 --- a/src/main/java/org/jabref/gui/libraryproperties/preamble/PreamblePropertiesViewModel.java +++ b/src/main/java/org/jabref/gui/libraryproperties/preamble/PreamblePropertiesViewModel.java @@ -9,38 +9,25 @@ public class PreamblePropertiesViewModel implements PropertiesTabViewModel { - private final StringProperty preambleProperty = new SimpleStringProperty( - "" - ); + private final StringProperty preambleProperty = new SimpleStringProperty(""); private final BibDatabaseContext databaseContext; private final UndoManager undoManager; - PreamblePropertiesViewModel( - BibDatabaseContext databaseContext, - UndoManager undoManager - ) { + PreamblePropertiesViewModel(BibDatabaseContext databaseContext, UndoManager undoManager) { this.undoManager = undoManager; this.databaseContext = databaseContext; } @Override public void setValues() { - preambleProperty.setValue( - databaseContext.getDatabase().getPreamble().orElse("") - ); + preambleProperty.setValue(databaseContext.getDatabase().getPreamble().orElse("")); } @Override public void storeSettings() { String newPreamble = preambleProperty.getValue(); - if ( - !databaseContext - .getDatabase() - .getPreamble() - .orElse("") - .equals(newPreamble) - ) { + if (!databaseContext.getDatabase().getPreamble().orElse("").equals(newPreamble)) { undoManager.addEdit( new UndoablePreambleChange( databaseContext.getDatabase(), diff --git a/src/main/java/org/jabref/gui/libraryproperties/saving/SavingPropertiesView.java b/src/main/java/org/jabref/gui/libraryproperties/saving/SavingPropertiesView.java index 5656e10c34a..e5a3e83033a 100644 --- a/src/main/java/org/jabref/gui/libraryproperties/saving/SavingPropertiesView.java +++ b/src/main/java/org/jabref/gui/libraryproperties/saving/SavingPropertiesView.java @@ -40,13 +40,10 @@ public String getTabName() { } public void initialize() { - this.viewModel = - new SavingPropertiesViewModel(databaseContext, preferencesService); + this.viewModel = new SavingPropertiesViewModel(databaseContext, preferencesService); protect.disableProperty().bind(viewModel.protectDisableProperty()); - protect - .selectedProperty() - .bindBidirectional(viewModel.libraryProtectedProperty()); + protect.selectedProperty().bindBidirectional(viewModel.libraryProtectedProperty()); saveOrderConfigPanel .saveInOriginalProperty() @@ -57,9 +54,7 @@ public void initialize() { saveOrderConfigPanel .saveInSpecifiedOrderProperty() .bindBidirectional(viewModel.saveInSpecifiedOrderProperty()); - saveOrderConfigPanel - .sortableFieldsProperty() - .bind(viewModel.sortableFieldsProperty()); + saveOrderConfigPanel.sortableFieldsProperty().bind(viewModel.sortableFieldsProperty()); saveOrderConfigPanel .sortCriteriaProperty() .bindBidirectional(viewModel.sortCriteriaProperty()); diff --git a/src/main/java/org/jabref/gui/libraryproperties/saving/SavingPropertiesViewModel.java b/src/main/java/org/jabref/gui/libraryproperties/saving/SavingPropertiesViewModel.java index 4eda5b23519..f370d630eb6 100644 --- a/src/main/java/org/jabref/gui/libraryproperties/saving/SavingPropertiesViewModel.java +++ b/src/main/java/org/jabref/gui/libraryproperties/saving/SavingPropertiesViewModel.java @@ -36,30 +36,24 @@ public class SavingPropertiesViewModel implements PropertiesTabViewModel { ) ); - private final BooleanProperty protectDisableProperty = - new SimpleBooleanProperty(); - private final BooleanProperty libraryProtectedProperty = - new SimpleBooleanProperty(); + private final BooleanProperty protectDisableProperty = new SimpleBooleanProperty(); + private final BooleanProperty libraryProtectedProperty = new SimpleBooleanProperty(); // SaveOrderConfigPanel - private final BooleanProperty saveInOriginalProperty = - new SimpleBooleanProperty(); - private final BooleanProperty saveInTableOrderProperty = - new SimpleBooleanProperty(); - private final BooleanProperty saveInSpecifiedOrderProperty = - new SimpleBooleanProperty(); - private final ListProperty sortableFieldsProperty = - new SimpleListProperty<>(FXCollections.observableArrayList()); + private final BooleanProperty saveInOriginalProperty = new SimpleBooleanProperty(); + private final BooleanProperty saveInTableOrderProperty = new SimpleBooleanProperty(); + private final BooleanProperty saveInSpecifiedOrderProperty = new SimpleBooleanProperty(); + private final ListProperty sortableFieldsProperty = new SimpleListProperty<>( + FXCollections.observableArrayList() + ); private final ListProperty sortCriteriaProperty = - new SimpleListProperty<>( - FXCollections.observableArrayList(new ArrayList<>()) - ); + new SimpleListProperty<>(FXCollections.observableArrayList(new ArrayList<>())); // FieldFormatterCleanupsPanel - private final BooleanProperty cleanupsDisableProperty = - new SimpleBooleanProperty(); - private final ListProperty cleanupsProperty = - new SimpleListProperty<>(FXCollections.emptyObservableList()); + private final BooleanProperty cleanupsDisableProperty = new SimpleBooleanProperty(); + private final ListProperty cleanupsProperty = new SimpleListProperty<>( + FXCollections.emptyObservableList() + ); private final BibDatabaseContext databaseContext; private final MetaData initialMetaData; @@ -73,8 +67,7 @@ public SavingPropertiesViewModel( this.databaseContext = databaseContext; this.preferencesService = preferencesService; this.initialMetaData = databaseContext.getMetaData(); - this.saveOrder = - initialMetaData.getSaveOrder().orElse(UI_DEFAULT_SAVE_ORDER); + this.saveOrder = initialMetaData.getSaveOrder().orElse(UI_DEFAULT_SAVE_ORDER); } @Override @@ -97,42 +90,30 @@ public void setValues() { fields.add(InternalField.KEY_FIELD); fields.add(InternalField.TYPE_HEADER); - sortableFieldsProperty.addAll( - FieldFactory.getStandardFieldsWithCitationKey() - ); + sortableFieldsProperty.addAll(FieldFactory.getStandardFieldsWithCitationKey()); sortCriteriaProperty.clear(); sortCriteriaProperty.addAll( - saveOrder - .getSortCriteria() - .stream() - .map(SortCriterionViewModel::new) - .toList() + saveOrder.getSortCriteria().stream().map(SortCriterionViewModel::new).toList() ); // FieldFormatterCleanupsPanel, included via in FXML - Optional saveActions = - initialMetaData.getSaveActions(); + Optional saveActions = initialMetaData.getSaveActions(); saveActions.ifPresentOrElse( value -> { cleanupsDisableProperty.setValue(!value.isEnabled()); cleanupsProperty.setValue( - FXCollections.observableArrayList( - value.getConfiguredActions() - ) + FXCollections.observableArrayList(value.getConfiguredActions()) ); }, () -> { - CleanupPreferences defaultPreset = - preferencesService.getDefaultCleanupPreset(); + CleanupPreferences defaultPreset = preferencesService.getDefaultCleanupPreset(); cleanupsDisableProperty.setValue( !defaultPreset.getFieldFormatterCleanups().isEnabled() ); cleanupsProperty.setValue( FXCollections.observableArrayList( - defaultPreset - .getFieldFormatterCleanups() - .getConfiguredActions() + defaultPreset.getFieldFormatterCleanups().getConfiguredActions() ) ); } @@ -149,11 +130,10 @@ public void storeSettings() { newMetaData.markAsNotProtected(); } - FieldFormatterCleanups fieldFormatterCleanups = - new FieldFormatterCleanups( - !cleanupsDisableProperty().getValue(), - cleanupsProperty() - ); + FieldFormatterCleanups fieldFormatterCleanups = new FieldFormatterCleanups( + !cleanupsDisableProperty().getValue(), + cleanupsProperty() + ); if ( FieldFormatterCleanups.DEFAULT_SAVE_ACTIONS.equals( @@ -175,10 +155,7 @@ public void storeSettings() { saveInSpecifiedOrderProperty.getValue(), saveInOriginalProperty.getValue() ), - sortCriteriaProperty - .stream() - .map(SortCriterionViewModel::getCriterion) - .toList() + sortCriteriaProperty.stream().map(SortCriterionViewModel::getCriterion).toList() ); if (!newSaveOrder.equals(saveOrder)) { diff --git a/src/main/java/org/jabref/gui/linkedfile/AttachFileAction.java b/src/main/java/org/jabref/gui/linkedfile/AttachFileAction.java index 58825eb57ac..0c2064e393e 100644 --- a/src/main/java/org/jabref/gui/linkedfile/AttachFileAction.java +++ b/src/main/java/org/jabref/gui/linkedfile/AttachFileAction.java @@ -35,32 +35,24 @@ public AttachFileAction( this.dialogService = dialogService; this.filePreferences = filePreferences; - this.executable.bind( - ActionHelper.needsEntriesSelected(1, stateManager) - ); + this.executable.bind(ActionHelper.needsEntriesSelected(1, stateManager)); } @Override public void execute() { if (stateManager.getActiveDatabase().isEmpty()) { - dialogService.notify( - Localization.lang("This operation requires an open library.") - ); + dialogService.notify(Localization.lang("This operation requires an open library.")); return; } if (stateManager.getSelectedEntries().size() != 1) { dialogService.notify( - Localization.lang( - "This operation requires exactly one item to be selected." - ) + Localization.lang("This operation requires exactly one item to be selected.") ); return; } - BibDatabaseContext databaseContext = stateManager - .getActiveDatabase() - .get(); + BibDatabaseContext databaseContext = stateManager.getActiveDatabase().get(); BibEntry entry = stateManager.getSelectedEntries().get(0); @@ -68,10 +60,9 @@ public void execute() { .getFirstExistingFileDir(filePreferences) .orElse(filePreferences.getWorkingDirectory()); - FileDialogConfiguration fileDialogConfiguration = - new FileDialogConfiguration.Builder() - .withInitialDirectory(workingDirectory) - .build(); + FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() + .withInitialDirectory(workingDirectory) + .build(); dialogService .showFileOpenDialog(fileDialogConfiguration) @@ -82,20 +73,14 @@ public void execute() { filePreferences ); - LinkedFileEditDialogView dialog = new LinkedFileEditDialogView( - linkedFile - ); + LinkedFileEditDialogView dialog = new LinkedFileEditDialogView(linkedFile); dialogService .showCustomDialogAndWait(dialog) .ifPresent(editedLinkedFile -> { - Optional fieldChange = entry.addFile( - editedLinkedFile - ); + Optional fieldChange = entry.addFile(editedLinkedFile); fieldChange.ifPresent(change -> { - UndoableFieldChange ce = new UndoableFieldChange( - change - ); + UndoableFieldChange ce = new UndoableFieldChange(change); libraryTab.getUndoManager().addEdit(ce); libraryTab.markBaseChanged(); }); diff --git a/src/main/java/org/jabref/gui/linkedfile/AttachFileFromURLAction.java b/src/main/java/org/jabref/gui/linkedfile/AttachFileFromURLAction.java index be98c61c1de..a0c39469167 100644 --- a/src/main/java/org/jabref/gui/linkedfile/AttachFileFromURLAction.java +++ b/src/main/java/org/jabref/gui/linkedfile/AttachFileFromURLAction.java @@ -35,32 +35,24 @@ public AttachFileFromURLAction( this.taskExecutor = taskExecutor; this.preferencesService = preferencesService; - this.executable.bind( - ActionHelper.needsEntriesSelected(1, stateManager) - ); + this.executable.bind(ActionHelper.needsEntriesSelected(1, stateManager)); } @Override public void execute() { if (stateManager.getActiveDatabase().isEmpty()) { - dialogService.notify( - Localization.lang("This operation requires an open library.") - ); + dialogService.notify(Localization.lang("This operation requires an open library.")); return; } if (stateManager.getSelectedEntries().size() != 1) { dialogService.notify( - Localization.lang( - "This operation requires exactly one item to be selected." - ) + Localization.lang("This operation requires exactly one item to be selected.") ); return; } - BibDatabaseContext databaseContext = stateManager - .getActiveDatabase() - .get(); + BibDatabaseContext databaseContext = stateManager.getActiveDatabase().get(); BibEntry entry = stateManager.getSelectedEntries().get(0); @@ -85,10 +77,7 @@ public void execute() { ); onlineFile.download(); } catch (MalformedURLException exception) { - dialogService.showErrorDialogAndWait( - Localization.lang("Invalid URL"), - exception - ); + dialogService.showErrorDialogAndWait(Localization.lang("Invalid URL"), exception); } } diff --git a/src/main/java/org/jabref/gui/linkedfile/DeleteFileAction.java b/src/main/java/org/jabref/gui/linkedfile/DeleteFileAction.java index 146f9250b02..36e38550662 100644 --- a/src/main/java/org/jabref/gui/linkedfile/DeleteFileAction.java +++ b/src/main/java/org/jabref/gui/linkedfile/DeleteFileAction.java @@ -22,9 +22,7 @@ public class DeleteFileAction extends SimpleCommand { - private static final Logger LOGGER = LoggerFactory.getLogger( - DeleteFileAction.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(DeleteFileAction.class); private final DialogService dialogService; private final PreferencesService preferences; @@ -54,9 +52,7 @@ public void execute() { if (toBeDeleted.isEmpty()) { dialogService.notify( - Localization.lang( - "This operation requires selected linked files." - ) + Localization.lang("This operation requires selected linked files.") ); return; } @@ -65,8 +61,7 @@ public void execute() { String dialogContent; if (toBeDeleted.size() != 1) { - dialogTitle = - Localization.lang("Delete %0 files", toBeDeleted.size()); + dialogTitle = Localization.lang("Delete %0 files", toBeDeleted.size()); dialogContent = Localization.lang( "Delete %0 files permanently from disk, or just remove the files from the entry? " + @@ -80,11 +75,7 @@ public void execute() { .findIn(databaseContext, preferences.getFilePreferences()); if (file.isPresent()) { - dialogTitle = - Localization.lang( - "Delete '%0'", - file.get().getFileName().toString() - ); + dialogTitle = Localization.lang("Delete '%0'", file.get().getFileName().toString()); dialogContent = Localization.lang( "Delete '%0' permanently from disk, or just remove the file from the entry? " + @@ -106,18 +97,15 @@ public void execute() { Localization.lang("Remove from entry"), ButtonBar.ButtonData.YES ); - ButtonType deleteFromEntry = new ButtonType( - Localization.lang("Delete from disk") + ButtonType deleteFromEntry = new ButtonType(Localization.lang("Delete from disk")); + Optional buttonType = dialogService.showCustomButtonDialogAndWait( + Alert.AlertType.INFORMATION, + dialogTitle, + dialogContent, + removeFromEntry, + deleteFromEntry, + ButtonType.CANCEL ); - Optional buttonType = - dialogService.showCustomButtonDialogAndWait( - Alert.AlertType.INFORMATION, - dialogTitle, - dialogContent, - removeFromEntry, - deleteFromEntry, - ButtonType.CANCEL - ); if (buttonType.isPresent()) { if (buttonType.get().equals(removeFromEntry)) { @@ -136,10 +124,7 @@ public void execute() { * @param toBeDeleted the files to be deleted * @param deleteFromDisk if true, the files are deleted from disk, otherwise they are only removed from the entry */ - private void deleteFiles( - List toBeDeleted, - boolean deleteFromDisk - ) { + private void deleteFiles(List toBeDeleted, boolean deleteFromDisk) { for (LinkedFileViewModel fileViewModel : toBeDeleted) { if (fileViewModel.getFile().isOnlineLink()) { viewModel.removeFileLink(fileViewModel); @@ -160,10 +145,7 @@ private void deleteFiles( public void deleteFileFromDisk(LinkedFileViewModel fileViewModel) { LinkedFile linkedFile = fileViewModel.getFile(); - Optional file = linkedFile.findIn( - databaseContext, - preferences.getFilePreferences() - ); + Optional file = linkedFile.findIn(databaseContext, preferences.getFilePreferences()); if (file.isEmpty()) { LOGGER.warn("Could not find file {}", linkedFile.getLink()); @@ -177,18 +159,11 @@ public void deleteFileFromDisk(LinkedFileViewModel fileViewModel) { Localization.lang("Cannot delete file"), Localization.lang("File permission error") ); - LOGGER.warn( - "File permission error while deleting: {}", - linkedFile, - ex - ); + LOGGER.warn("File permission error while deleting: {}", linkedFile, ex); } } else { dialogService.notify( - Localization.lang( - "Error accessing file '%0'.", - linkedFile.getLink() - ) + Localization.lang("Error accessing file '%0'.", linkedFile.getLink()) ); } } diff --git a/src/main/java/org/jabref/gui/linkedfile/LinkedFileEditDialogView.java b/src/main/java/org/jabref/gui/linkedfile/LinkedFileEditDialogView.java index 019e032fd25..e88cd5d6808 100644 --- a/src/main/java/org/jabref/gui/linkedfile/LinkedFileEditDialogView.java +++ b/src/main/java/org/jabref/gui/linkedfile/LinkedFileEditDialogView.java @@ -45,9 +45,7 @@ public LinkedFileEditDialogView(LinkedFile linkedFile) { ViewLoader.view(this).load().setAsContent(this.getDialogPane()); - this.getDialogPane() - .getButtonTypes() - .addAll(ButtonType.APPLY, ButtonType.CANCEL); + this.getDialogPane().getButtonTypes().addAll(ButtonType.APPLY, ButtonType.CANCEL); this.setResizable(false); this.setTitle(Localization.lang("Edit file link")); @@ -69,21 +67,15 @@ private void initialize() { dialogService, preferences.getFilePreferences() ); - fileType - .itemsProperty() - .bindBidirectional(viewModel.externalFileTypeProperty()); + fileType.itemsProperty().bindBidirectional(viewModel.externalFileTypeProperty()); new ViewModelListCellFactory() .withIcon(ExternalFileType::getIcon) .withText(ExternalFileType::getName) .install(fileType); - description - .textProperty() - .bindBidirectional(viewModel.descriptionProperty()); + description.textProperty().bindBidirectional(viewModel.descriptionProperty()); link.textProperty().bindBidirectional(viewModel.linkProperty()); - fileType - .valueProperty() - .bindBidirectional(viewModel.selectedExternalFileTypeProperty()); + fileType.valueProperty().bindBidirectional(viewModel.selectedExternalFileTypeProperty()); } @FXML diff --git a/src/main/java/org/jabref/gui/linkedfile/LinkedFilesEditDialogViewModel.java b/src/main/java/org/jabref/gui/linkedfile/LinkedFilesEditDialogViewModel.java index 3d3617efe19..e2f38e68e4d 100644 --- a/src/main/java/org/jabref/gui/linkedfile/LinkedFilesEditDialogViewModel.java +++ b/src/main/java/org/jabref/gui/linkedfile/LinkedFilesEditDialogViewModel.java @@ -28,18 +28,15 @@ public class LinkedFilesEditDialogViewModel extends AbstractViewModel { - private static final Pattern REMOTE_LINK_PATTERN = Pattern.compile( - "[a-z]+://.*" - ); + private static final Pattern REMOTE_LINK_PATTERN = Pattern.compile("[a-z]+://.*"); private final StringProperty link = new SimpleStringProperty(""); private final StringProperty description = new SimpleStringProperty(""); - private final ListProperty allExternalFileTypes = - new SimpleListProperty<>(FXCollections.emptyObservableList()); + private final ListProperty allExternalFileTypes = new SimpleListProperty<>( + FXCollections.emptyObservableList() + ); private final ObjectProperty selectedExternalFileType = new SimpleObjectProperty<>(); - private final ObservableOptionalValue< - ExternalFileType - > monadicSelectedExternalFileType; + private final ObservableOptionalValue monadicSelectedExternalFileType; private final BibDatabaseContext database; private final DialogService dialogService; private final FilePreferences filePreferences; @@ -54,13 +51,10 @@ public LinkedFilesEditDialogViewModel( this.dialogService = dialogService; this.filePreferences = filePreferences; allExternalFileTypes.set( - FXCollections.observableArrayList( - filePreferences.getExternalFileTypes() - ) + FXCollections.observableArrayList(filePreferences.getExternalFileTypes()) ); - monadicSelectedExternalFileType = - EasyBind.wrapNullable(selectedExternalFileType); + monadicSelectedExternalFileType = EasyBind.wrapNullable(selectedExternalFileType); setValues(linkedFile); } @@ -84,20 +78,15 @@ private void setExternalFileTypeByExtension(String link) { public void openBrowseDialog() { String fileText = link.get(); - Optional file = FileUtil.find( - database, - fileText, - filePreferences - ); + Optional file = FileUtil.find(database, fileText, filePreferences); Path workingDir = file.orElse(filePreferences.getWorkingDirectory()); String fileName = Path.of(fileText).getFileName().toString(); - FileDialogConfiguration fileDialogConfiguration = - new FileDialogConfiguration.Builder() - .withInitialDirectory(workingDir) - .withInitialFileName(fileName) - .build(); + FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() + .withInitialDirectory(workingDir) + .withInitialFileName(fileName) + .build(); dialogService .showFileOpenDialog(fileDialogConfiguration) @@ -122,20 +111,14 @@ public void setValues(LinkedFile linkedFile) { selectedExternalFileType.setValue(null); // See what is a reasonable selection for the type combobox: - Optional fileType = - ExternalFileTypes.getExternalFileTypeByLinkedFile( - linkedFile, - false, - filePreferences - ); - if ( - fileType.isPresent() && - !(fileType.get() instanceof UnknownExternalFileType) - ) { + Optional fileType = ExternalFileTypes.getExternalFileTypeByLinkedFile( + linkedFile, + false, + filePreferences + ); + if (fileType.isPresent() && !(fileType.get() instanceof UnknownExternalFileType)) { selectedExternalFileType.setValue(fileType.get()); - } else if ( - (linkedFile.getLink() != null) && (!linkedFile.getLink().isEmpty()) - ) { + } else if ((linkedFile.getLink() != null) && (!linkedFile.getLink().isEmpty())) { setExternalFileTypeByExtension(linkedFile.getLink()); } } @@ -164,30 +147,16 @@ public LinkedFile getNewLinkedFile() { if (LinkedFile.isOnlineLink(link.getValue())) { try { - return new LinkedFile( - description.getValue(), - new URL(link.getValue()), - fileType - ); + return new LinkedFile(description.getValue(), new URL(link.getValue()), fileType); } catch (MalformedURLException e) { - return new LinkedFile( - description.getValue(), - link.getValue(), - fileType - ); + return new LinkedFile(description.getValue(), link.getValue(), fileType); } } - return new LinkedFile( - description.getValue(), - Path.of(link.getValue()), - fileType - ); + return new LinkedFile(description.getValue(), Path.of(link.getValue()), fileType); } private String relativize(Path filePath) { - List fileDirectories = database.getFileDirectories( - filePreferences - ); + List fileDirectories = database.getFileDirectories(filePreferences); return FileUtil.relativize(filePath, fileDirectories).toString(); } } diff --git a/src/main/java/org/jabref/gui/maintable/BibEntryTableViewModel.java b/src/main/java/org/jabref/gui/maintable/BibEntryTableViewModel.java index e9de99a19b8..fdb80c40e28 100644 --- a/src/main/java/org/jabref/gui/maintable/BibEntryTableViewModel.java +++ b/src/main/java/org/jabref/gui/maintable/BibEntryTableViewModel.java @@ -34,11 +34,8 @@ public class BibEntryTableViewModel { private final BibEntry entry; - private final ObservableValue< - MainTableFieldValueFormatter - > fieldValueFormatter; - private final Map> fieldValues = - new HashMap<>(); + private final ObservableValue fieldValueFormatter; + private final Map> fieldValues = new HashMap<>(); private final Map< SpecialField, OptionalBinding @@ -61,14 +58,11 @@ public BibEntryTableViewModel( .mapOpt(FileFieldParser::parse) .orElseOpt(Collections.emptyList()); this.linkedIdentifiers = createLinkedIdentifiersBinding(entry); - this.matchedGroups = - createMatchedGroupsBinding(bibDatabaseContext, entry); + this.matchedGroups = createMatchedGroupsBinding(bibDatabaseContext, entry); this.bibDatabaseContext = bibDatabaseContext; } - private static EasyBinding< - Map - > createLinkedIdentifiersBinding(BibEntry entry) { + private static EasyBinding> createLinkedIdentifiersBinding(BibEntry entry) { return EasyBind.combine( entry.getFieldBinding(StandardField.URL), entry.getFieldBinding(StandardField.DOI), @@ -77,18 +71,11 @@ > createLinkedIdentifiersBinding(BibEntry entry) { entry.getFieldBinding(StandardField.ISBN), (url, doi, uri, eprint, isbn) -> { Map identifiers = new HashMap<>(); - url.ifPresent(value -> identifiers.put(StandardField.URL, value) - ); - doi.ifPresent(value -> identifiers.put(StandardField.DOI, value) - ); - uri.ifPresent(value -> identifiers.put(StandardField.URI, value) - ); - eprint.ifPresent(value -> - identifiers.put(StandardField.EPRINT, value) - ); - isbn.ifPresent(value -> - identifiers.put(StandardField.ISBN, value) - ); + url.ifPresent(value -> identifiers.put(StandardField.URL, value)); + doi.ifPresent(value -> identifiers.put(StandardField.DOI, value)); + uri.ifPresent(value -> identifiers.put(StandardField.URI, value)); + eprint.ifPresent(value -> identifiers.put(StandardField.EPRINT, value)); + isbn.ifPresent(value -> identifiers.put(StandardField.ISBN, value)); return identifiers; } ); @@ -115,13 +102,7 @@ private static Binding> createMatchedGroupsBinding( .getMatchingGroups(entry) .stream() .map(GroupTreeNode::getGroup) - .filter( - Predicate.not( - Predicate.isEqual( - groupTreeNode.getGroup() - ) - ) - ) + .filter(Predicate.not(Predicate.isEqual(groupTreeNode.getGroup()))) .collect(Collectors.toList()) ) .orElse(Collections.emptyList()) @@ -145,39 +126,29 @@ public ObservableValue> getMatchedGroups() { return matchedGroups; } - public ObservableValue< - Optional - > getSpecialField(SpecialField field) { - OptionalBinding value = - specialFieldValues.get(field); + public ObservableValue> getSpecialField( + SpecialField field + ) { + OptionalBinding value = specialFieldValues.get(field); // Fetch possibly updated value from BibEntry entry Optional currentValue = this.entry.getField(field); if (value != null) { if (currentValue.isEmpty() && value.getValue().isEmpty()) { var zeroValue = getField(field) .flatMapOpt(fieldValue -> - field - .parseValue("CLEAR_RANK") - .map(SpecialFieldValueViewModel::new) + field.parseValue("CLEAR_RANK").map(SpecialFieldValueViewModel::new) ); specialFieldValues.put(field, zeroValue); return zeroValue; } else if ( value.getValue().isEmpty() || - !value - .getValue() - .get() - .getValue() - .getFieldValue() - .equals(currentValue) + !value.getValue().get().getValue().getFieldValue().equals(currentValue) ) { // specialFieldValues value and BibEntry value differ => Set specialFieldValues value to BibEntry value value = getField(field) .flatMapOpt(fieldValue -> - field - .parseValue(fieldValue) - .map(SpecialFieldValueViewModel::new) + field.parseValue(fieldValue).map(SpecialFieldValueViewModel::new) ); specialFieldValues.put(field, value); return value; @@ -186,9 +157,7 @@ > getSpecialField(SpecialField field) { value = getField(field) .flatMapOpt(fieldValue -> - field - .parseValue(fieldValue) - .map(SpecialFieldValueViewModel::new) + field.parseValue(fieldValue).map(SpecialFieldValueViewModel::new) ); specialFieldValues.put(field, value); } @@ -201,17 +170,12 @@ public ObservableValue getFields(OrFields fields) { return value; } - ArrayList observables = new ArrayList<>( - List.of(entry.getObservables()) - ); + ArrayList observables = new ArrayList<>(List.of(entry.getObservables())); observables.add(fieldValueFormatter); value = Bindings.createStringBinding( - () -> - fieldValueFormatter - .getValue() - .formatFieldsValues(fields, entry), + () -> fieldValueFormatter.getValue().formatFieldsValues(fields, entry), observables.toArray(Observable[]::new) ); fieldValues.put(fields, value); diff --git a/src/main/java/org/jabref/gui/maintable/CellFactory.java b/src/main/java/org/jabref/gui/maintable/CellFactory.java index 9f200ed0fe7..07879f7d094 100644 --- a/src/main/java/org/jabref/gui/maintable/CellFactory.java +++ b/src/main/java/org/jabref/gui/maintable/CellFactory.java @@ -18,10 +18,7 @@ public class CellFactory { private final Map TABLE_ICONS = new HashMap<>(); - public CellFactory( - PreferencesService preferencesService, - UndoManager undoManager - ) { + public CellFactory(PreferencesService preferencesService, UndoManager undoManager) { JabRefIcon icon; icon = IconTheme.JabRefIcons.PDF_FILE; // icon.setToo(Localization.lang("Open") + " PDF"); diff --git a/src/main/java/org/jabref/gui/maintable/ColumnPreferences.java b/src/main/java/org/jabref/gui/maintable/ColumnPreferences.java index 83bf000327e..6516ef2bbc5 100644 --- a/src/main/java/org/jabref/gui/maintable/ColumnPreferences.java +++ b/src/main/java/org/jabref/gui/maintable/ColumnPreferences.java @@ -17,8 +17,7 @@ public ColumnPreferences( List columnSortOrder ) { this.columns = FXCollections.observableArrayList(columns); - this.columnSortOrder = - FXCollections.observableArrayList(columnSortOrder); + this.columnSortOrder = FXCollections.observableArrayList(columnSortOrder); } public ObservableList getColumns() { diff --git a/src/main/java/org/jabref/gui/maintable/MainTable.java b/src/main/java/org/jabref/gui/maintable/MainTable.java index a612623be0f..21566386467 100644 --- a/src/main/java/org/jabref/gui/maintable/MainTable.java +++ b/src/main/java/org/jabref/gui/maintable/MainTable.java @@ -55,9 +55,7 @@ public class MainTable extends TableView { - private static final Logger LOGGER = LoggerFactory.getLogger( - MainTable.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(MainTable.class); private final LibraryTab libraryTab; private final DialogService dialogService; @@ -96,8 +94,7 @@ public MainTable( this.entryTypesManager = entryTypesManager; this.taskExecutor = taskExecutor; UndoManager undoManager = libraryTab.getUndoManager(); - MainTablePreferences mainTablePreferences = - preferencesService.getMainTablePreferences(); + MainTablePreferences mainTablePreferences = preferencesService.getMainTablePreferences(); importHandler = new ImportHandler( @@ -185,19 +182,12 @@ public MainTable( this.setItems(model.getEntriesFilteredAndSorted()); // Enable sorting - model - .getEntriesFilteredAndSorted() - .comparatorProperty() - .bind(this.comparatorProperty()); + model.getEntriesFilteredAndSorted().comparatorProperty().bind(this.comparatorProperty()); - this.getStylesheets() - .add(MainTable.class.getResource("MainTable.css").toExternalForm()); + this.getStylesheets().add(MainTable.class.getResource("MainTable.css").toExternalForm()); // Store visual state - new PersistenceVisualStateTable( - this, - mainTablePreferences.getColumnPreferences() - ) + new PersistenceVisualStateTable(this, mainTablePreferences.getColumnPreferences()) .addListeners(); setupKeyBindings(keyBindingRepository); @@ -211,16 +201,15 @@ public MainTable( database.getDatabase().registerListener(this); - MainTableColumnFactory rightClickMenuFactory = - new MainTableColumnFactory( - database, - preferencesService, - preferencesService.getMainTableColumnPreferences(), - libraryTab.getUndoManager(), - dialogService, - stateManager, - taskExecutor - ); + MainTableColumnFactory rightClickMenuFactory = new MainTableColumnFactory( + database, + preferencesService, + preferencesService.getMainTableColumnPreferences(), + libraryTab.getUndoManager(), + dialogService, + stateManager, + taskExecutor + ); // Enable the header right-click menu. new MainTableHeaderContextMenu(this, rightClickMenuFactory).show(true); @@ -252,9 +241,7 @@ private void jumpToSearchKey( .stream() .filter(item -> Optional - .ofNullable( - sortedColumn.getCellObservableValue(item).getValue() - ) + .ofNullable(sortedColumn.getCellObservableValue(item).getValue()) .map(Object::toString) .orElse("") .toLowerCase() @@ -269,9 +256,7 @@ private void jumpToSearchKey( @Subscribe public void listen(EntriesAddedEvent event) { - DefaultTaskExecutor.runInJavaFXThread(() -> - clearAndSelect(event.getFirstEntry()) - ); + DefaultTaskExecutor.runInJavaFXThread(() -> clearAndSelect(event.getFirstEntry())); } public void clearAndSelect(BibEntry bibEntry) { @@ -296,10 +281,7 @@ public void copy() { ) ); } catch (IOException e) { - LOGGER.error( - "Error while copying selected entries to clipboard", - e - ); + LOGGER.error("Error while copying selected entries to clipboard", e); } } } @@ -343,8 +325,7 @@ private void setupKeyBindings(KeyBindingRepository keyBindings) { return; } - Optional keyBinding = - keyBindings.mapToKeyBinding(event); + Optional keyBinding = keyBindings.mapToKeyBinding(event); if (keyBinding.isPresent()) { switch (keyBinding.get()) { case SELECT_FIRST_ENTRY: @@ -429,10 +410,7 @@ private List handleNonBibTeXStringData(String data) { public void dropEntry(List entriesToAdd) { for (BibEntry entry : entriesToAdd) { - importHandler.importEntryWithDuplicateCheck( - database, - (BibEntry) entry.clone() - ); + importHandler.importEntryWithDuplicateCheck(database, (BibEntry) entry.clone()); } } @@ -535,9 +513,7 @@ private void handleOnDragDropped( switch (event.getTransferMode()) { case LINK -> { LOGGER.debug("Mode LINK"); // shift on win or no modifier - importHandler - .getLinker() - .addFilesToEntry(entry, files); + importHandler.getLinker().addFilesToEntry(entry, files); } case MOVE -> { LOGGER.debug("Mode MOVE"); // alt on win @@ -580,9 +556,7 @@ private void handleOnDragDroppedTableView(DragEvent event) { .stream() .map(File::toPath) .collect(Collectors.toList()); - importHandler - .importFilesInBackground(files) - .executeWith(taskExecutor); + importHandler.importFilesInBackground(files).executeWith(taskExecutor); success = true; } @@ -591,9 +565,7 @@ private void handleOnDragDroppedTableView(DragEvent event) { event.consume(); } - public void addSelectionListener( - ListChangeListener listener - ) { + public void addSelectionListener(ListChangeListener listener) { getSelectionModel().getSelectedItems().addListener(listener); } diff --git a/src/main/java/org/jabref/gui/maintable/MainTableColumnFactory.java b/src/main/java/org/jabref/gui/maintable/MainTableColumnFactory.java index 1f7eb42092c..060392fbdd1 100644 --- a/src/main/java/org/jabref/gui/maintable/MainTableColumnFactory.java +++ b/src/main/java/org/jabref/gui/maintable/MainTableColumnFactory.java @@ -45,9 +45,7 @@ public class MainTableColumnFactory { public static final String STYLE_ICON_COLUMN = "column-icon"; - private static final Logger LOGGER = LoggerFactory.getLogger( - MainTableColumnFactory.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(MainTableColumnFactory.class); private final PreferencesService preferencesService; private final ColumnPreferences columnPreferences; @@ -77,9 +75,7 @@ public MainTableColumnFactory( this.stateManager = stateManager; } - public TableColumn createColumn( - MainTableColumnModel column - ) { + public TableColumn createColumn(MainTableColumnModel column) { TableColumn returnColumn = null; switch (column.getType()) { case INDEX: @@ -104,9 +100,7 @@ public MainTableColumnFactory( break; case SPECIALFIELD: if (!column.getQualifier().isBlank()) { - Field field = FieldFactory.parseField( - column.getQualifier() - ); + Field field = FieldFactory.parseField(column.getQualifier()); if (field instanceof SpecialField) { returnColumn = createSpecialFieldColumn(column); } else { @@ -129,8 +123,7 @@ public MainTableColumnFactory( } public List> createColumns() { - List> columns = - new ArrayList<>(); + List> columns = new ArrayList<>(); columnPreferences .getColumns() @@ -153,25 +146,15 @@ public static void setExactWidth(TableColumn column, double width) { private TableColumn createIndexColumn( MainTableColumnModel columnModel ) { - TableColumn column = - new MainTableColumn<>(columnModel); + TableColumn column = new MainTableColumn<>(columnModel); Node header = new Text("#"); header.getStyleClass().add("mainTable-header"); - Tooltip.install( - header, - new Tooltip(MainTableColumnModel.Type.INDEX.getDisplayName()) - ); + Tooltip.install(header, new Tooltip(MainTableColumnModel.Type.INDEX.getDisplayName())); column.setGraphic(header); column.setStyle("-fx-alignment: CENTER-RIGHT;"); column.setCellValueFactory(cellData -> new ReadOnlyObjectWrapper<>( - String.valueOf( - cellData - .getTableView() - .getItems() - .indexOf(cellData.getValue()) + - 1 - ) + String.valueOf(cellData.getTableView().getItems().indexOf(cellData.getValue()) + 1) ) ); new ValueTableCellFactory() @@ -187,21 +170,16 @@ private TableColumn createIndexColumn( private TableColumn createGroupColumn( MainTableColumnModel columnModel ) { - TableColumn> column = - new MainTableColumn<>(columnModel); - Node headerGraphic = - IconTheme.JabRefIcons.DEFAULT_GROUP_ICON.getGraphicNode(); - Tooltip.install( - headerGraphic, - new Tooltip(Localization.lang("Group color")) + TableColumn> column = new MainTableColumn<>( + columnModel ); + Node headerGraphic = IconTheme.JabRefIcons.DEFAULT_GROUP_ICON.getGraphicNode(); + Tooltip.install(headerGraphic, new Tooltip(Localization.lang("Group color"))); column.setGraphic(headerGraphic); column.getStyleClass().add(STYLE_ICON_COLUMN); setExactWidth(column, ColumnPreferences.ICON_COLUMN_WIDTH); column.setResizable(false); - column.setCellValueFactory(cellData -> - cellData.getValue().getMatchedGroups() - ); + column.setCellValueFactory(cellData -> cellData.getValue().getMatchedGroups()); new ValueTableCellFactory>() .withGraphic(this::createGroupColorRegion) .install(column); @@ -245,9 +223,7 @@ private Node createGroupColorRegion( .map(AbstractGroup::getName) .collect(Collectors.joining(", ")); Tooltip tooltip = new Tooltip( - Localization.lang( - "Entry is contained in the following groups:" - ) + + Localization.lang("Entry is contained in the following groups:") + "\n" + matchedGroupsString ); @@ -269,10 +245,9 @@ private Node createGroupColorRegion( /** * Creates a clickable icons column for DOIs, URLs, URIs and EPrints. */ - private TableColumn< - BibEntryTableViewModel, - Map - > createIdentifierColumn(MainTableColumnModel columnModel) { + private TableColumn> createIdentifierColumn( + MainTableColumnModel columnModel + ) { return new LinkedIdentifierColumn( columnModel, cellFactory, @@ -290,21 +265,16 @@ > createIdentifierColumn(MainTableColumnModel columnModel) { BibEntryTableViewModel, Optional > createSpecialFieldColumn(MainTableColumnModel columnModel) { - return new SpecialFieldColumn( - columnModel, - preferencesService, - undoManager - ); + return new SpecialFieldColumn(columnModel, preferencesService, undoManager); } /** * Creates a column for all the linked files. Instead of creating a column for a single file type, like {@link * #createExtraFileColumn(MainTableColumnModel)} createExtraFileColumn} does, this creates one single column collecting all file links. */ - private TableColumn< - BibEntryTableViewModel, - List - > createFilesColumn(MainTableColumnModel columnModel) { + private TableColumn> createFilesColumn( + MainTableColumnModel columnModel + ) { return new FileColumn( columnModel, database, @@ -317,10 +287,9 @@ > createFilesColumn(MainTableColumnModel columnModel) { /** * Creates a column for all the linked files of a single file type. */ - private TableColumn< - BibEntryTableViewModel, - List - > createExtraFileColumn(MainTableColumnModel columnModel) { + private TableColumn> createExtraFileColumn( + MainTableColumnModel columnModel + ) { return new FileColumn( columnModel, database, diff --git a/src/main/java/org/jabref/gui/maintable/MainTableColumnModel.java b/src/main/java/org/jabref/gui/maintable/MainTableColumnModel.java index 89376a846cf..44c237a1589 100644 --- a/src/main/java/org/jabref/gui/maintable/MainTableColumnModel.java +++ b/src/main/java/org/jabref/gui/maintable/MainTableColumnModel.java @@ -26,9 +26,7 @@ public class MainTableColumnModel { public static final Character COLUMNS_QUALIFIER_DELIMITER = ':'; - private static final Logger LOGGER = LoggerFactory.getLogger( - MainTableColumnModel.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(MainTableColumnModel.class); public enum Type { INDEX("index", Localization.lang("Index")), @@ -79,8 +77,7 @@ public static Type fromString(String text) { } } - private final ObjectProperty typeProperty = - new SimpleObjectProperty<>(); + private final ObjectProperty typeProperty = new SimpleObjectProperty<>(); private final StringProperty qualifierProperty = new SimpleStringProperty(); private final DoubleProperty widthProperty = new SimpleDoubleProperty(); private final ObjectProperty sortTypeProperty = @@ -217,18 +214,12 @@ public boolean equals(Object o) { if (typeProperty.getValue() != that.typeProperty.getValue()) { return false; } - return Objects.equals( - qualifierProperty.getValue(), - that.qualifierProperty.getValue() - ); + return Objects.equals(qualifierProperty.getValue(), that.qualifierProperty.getValue()); } @Override public int hashCode() { - return Objects.hash( - typeProperty.getValue(), - qualifierProperty.getValue() - ); + return Objects.hash(typeProperty.getValue(), qualifierProperty.getValue()); } /** @@ -239,18 +230,12 @@ public int hashCode() { */ public static MainTableColumnModel parse(String rawColumnName) { Objects.requireNonNull(rawColumnName); - String[] splittedName = rawColumnName.split( - COLUMNS_QUALIFIER_DELIMITER.toString() - ); + String[] splittedName = rawColumnName.split(COLUMNS_QUALIFIER_DELIMITER.toString()); Type type = Type.fromString(splittedName[0]); String qualifier = ""; - if ( - (type == Type.NORMALFIELD) || - (type == Type.SPECIALFIELD) || - (type == Type.EXTRAFILE) - ) { + if ((type == Type.NORMALFIELD) || (type == Type.SPECIALFIELD) || (type == Type.EXTRAFILE)) { if (splittedName.length == 1) { qualifier = splittedName[0]; // By default the rawColumnName is parsed as NORMALFIELD } else { diff --git a/src/main/java/org/jabref/gui/maintable/MainTableDataModel.java b/src/main/java/org/jabref/gui/maintable/MainTableDataModel.java index 8cdce920a8a..f2cbf5e48ef 100644 --- a/src/main/java/org/jabref/gui/maintable/MainTableDataModel.java +++ b/src/main/java/org/jabref/gui/maintable/MainTableDataModel.java @@ -27,9 +27,7 @@ public class MainTableDataModel { private final FilteredList entriesFiltered; private final SortedList entriesFilteredAndSorted; - private final ObjectProperty< - MainTableFieldValueFormatter - > fieldValueFormatter; + private final ObjectProperty fieldValueFormatter; private final GroupsPreferences groupsPreferences; private final NameDisplayPreferences nameDisplayPreferences; private final BibDatabaseContext bibDatabaseContext; @@ -40,30 +38,20 @@ public MainTableDataModel( StateManager stateManager ) { this.groupsPreferences = preferencesService.getGroupsPreferences(); - this.nameDisplayPreferences = - preferencesService.getNameDisplayPreferences(); + this.nameDisplayPreferences = preferencesService.getNameDisplayPreferences(); this.bibDatabaseContext = context; this.fieldValueFormatter = new SimpleObjectProperty<>( - new MainTableFieldValueFormatter( - nameDisplayPreferences, - bibDatabaseContext - ) + new MainTableFieldValueFormatter(nameDisplayPreferences, bibDatabaseContext) ); ObservableList allEntries = BindingsHelper.forUI( context.getDatabase().getEntries() ); - ObservableList entriesViewModel = - EasyBind.mapBacked( - allEntries, - entry -> - new BibEntryTableViewModel( - entry, - bibDatabaseContext, - fieldValueFormatter - ) - ); + ObservableList entriesViewModel = EasyBind.mapBacked( + allEntries, + entry -> new BibEntryTableViewModel(entry, bibDatabaseContext, fieldValueFormatter) + ); entriesFiltered = new FilteredList<>(entriesViewModel); entriesFiltered @@ -73,8 +61,7 @@ public MainTableDataModel( stateManager.activeGroupProperty(), stateManager.activeSearchQueryProperty(), groupsPreferences.groupViewModeProperty(), - (groups, query, groupViewMode) -> - entry -> isMatched(groups, query, entry) + (groups, query, groupViewMode) -> entry -> isMatched(groups, query, entry) ) ); @@ -90,18 +77,11 @@ private boolean isMatched( Optional query, BibEntryTableViewModel entry ) { - return ( - isMatchedByGroup(groups, entry) && isMatchedBySearch(query, entry) - ); + return (isMatchedByGroup(groups, entry) && isMatchedBySearch(query, entry)); } - private boolean isMatchedBySearch( - Optional query, - BibEntryTableViewModel entry - ) { - return query - .map(matcher -> matcher.isMatch(entry.getEntry())) - .orElse(true); + private boolean isMatchedBySearch(Optional query, BibEntryTableViewModel entry) { + return query.map(matcher -> matcher.isMatch(entry.getEntry())).orElse(true); } private boolean isMatchedByGroup( @@ -113,9 +93,7 @@ private boolean isMatchedByGroup( .orElse(true); } - private Optional createGroupMatcher( - List selectedGroups - ) { + private Optional createGroupMatcher(List selectedGroups) { if ((selectedGroups == null) || selectedGroups.isEmpty()) { // No selected group, show all entries return Optional.empty(); @@ -139,10 +117,7 @@ public SortedList getEntriesFilteredAndSorted() { public void refresh() { this.fieldValueFormatter.setValue( - new MainTableFieldValueFormatter( - nameDisplayPreferences, - bibDatabaseContext - ) + new MainTableFieldValueFormatter(nameDisplayPreferences, bibDatabaseContext) ); } } diff --git a/src/main/java/org/jabref/gui/maintable/MainTableFieldValueFormatter.java b/src/main/java/org/jabref/gui/maintable/MainTableFieldValueFormatter.java index fc65aef7465..c64875123f9 100644 --- a/src/main/java/org/jabref/gui/maintable/MainTableFieldValueFormatter.java +++ b/src/main/java/org/jabref/gui/maintable/MainTableFieldValueFormatter.java @@ -35,26 +35,22 @@ public MainTableFieldValueFormatter( * @param entry the BibEntry of {@link BibEntryTableViewModel}. * @return The formatted name field. */ - public String formatFieldsValues( - final OrFields fields, - final BibEntry entry - ) { + public String formatFieldsValues(final OrFields fields, final BibEntry entry) { for (Field field : fields.getFields()) { if ( field.getProperties().contains(FieldProperty.PERSON_NAMES) && (displayStyle != DisplayStyle.AS_IS) ) { - Optional name = entry.getResolvedFieldOrAlias( - field, - bibDatabase - ); + Optional name = entry.getResolvedFieldOrAlias(field, bibDatabase); if (name.isPresent()) { return formatFieldWithAuthorValue(name.get()); } } else { - Optional content = - entry.getResolvedFieldOrAliasLatexFree(field, bibDatabase); + Optional content = entry.getResolvedFieldOrAliasLatexFree( + field, + bibDatabase + ); if (content.isPresent()) { return content.get(); @@ -90,16 +86,10 @@ private String formatFieldWithAuthorValue(final String nameToFormat) { default -> nameToFormat; case FIRSTNAME_LASTNAME -> authors .latexFree() - .getAsFirstLastNames( - abbreviationStyle == AbbreviationStyle.FULL, - false - ); + .getAsFirstLastNames(abbreviationStyle == AbbreviationStyle.FULL, false); case LASTNAME_FIRSTNAME -> authors .latexFree() - .getAsLastFirstNames( - abbreviationStyle == AbbreviationStyle.FULL, - false - ); + .getAsLastFirstNames(abbreviationStyle == AbbreviationStyle.FULL, false); case NATBIB -> authors.latexFree().getAsNatbib(); }; } diff --git a/src/main/java/org/jabref/gui/maintable/MainTableHeaderContextMenu.java b/src/main/java/org/jabref/gui/maintable/MainTableHeaderContextMenu.java index 1ba64926ccb..de6dc534be2 100644 --- a/src/main/java/org/jabref/gui/maintable/MainTableHeaderContextMenu.java +++ b/src/main/java/org/jabref/gui/maintable/MainTableHeaderContextMenu.java @@ -20,10 +20,7 @@ public class MainTableHeaderContextMenu extends ContextMenu { * Constructor for the right click menu * */ - public MainTableHeaderContextMenu( - MainTable mainTable, - MainTableColumnFactory factory - ) { + public MainTableHeaderContextMenu(MainTable mainTable, MainTableColumnFactory factory) { super(); this.mainTable = mainTable; this.factory = factory; @@ -52,14 +49,10 @@ public void show(boolean show) { private void constructItems(MainTable mainTable) { // Reset the right-click menu this.getItems().clear(); - List> commonColumns = - commonColumns(); + List> commonColumns = commonColumns(); // Populate the menu with currently used fields - for (TableColumn< - BibEntryTableViewModel, - ? - > column : mainTable.getColumns()) { + for (TableColumn column : mainTable.getColumns()) { // Append only if the column has not already been added (a common column) RightClickMenuItem itemToAdd = createMenuItem(column, true); this.getItems().add(itemToAdd); @@ -68,8 +61,7 @@ private void constructItems(MainTable mainTable) { MainTableColumn searchCol = (MainTableColumn) column; if (isACommonColumn(searchCol)) { commonColumns.removeIf(tableCol -> - ((MainTableColumn) tableCol).getModel() - .equals(searchCol.getModel()) + ((MainTableColumn) tableCol).getModel().equals(searchCol.getModel()) ); } } @@ -79,10 +71,7 @@ private void constructItems(MainTable mainTable) { // Append to the menu the current remaining columns in the common columns. - for (TableColumn< - BibEntryTableViewModel, - ? - > tableColumn : commonColumns) { + for (TableColumn tableColumn : commonColumns) { RightClickMenuItem itemToAdd = createMenuItem(tableColumn, false); this.getItems().add(itemToAdd); } @@ -108,8 +97,7 @@ private RightClickMenuItem createMenuItem( * */ private int obtainIndexOfColumn(MainTableColumn searchColumn) { - ObservableList> columns = - mainTable.getColumns(); + ObservableList> columns = mainTable.getColumns(); for (int i = 0; i < columns.size(); i++) { TableColumn column = columns.get(i); MainTableColumnModel model = ((MainTableColumn) column).getModel(); @@ -140,8 +128,7 @@ private void removeColumn(MainTableColumn tableColumn) { mainTable .getColumns() .removeIf(tableCol -> - ((MainTableColumn) tableCol).getModel() - .equals(tableColumn.getModel()) + ((MainTableColumn) tableCol).getModel().equals(tableColumn.getModel()) ); } @@ -184,72 +171,38 @@ private boolean isColumnInList( // Create the MainTableColumn Models from qualifiers + types. List commonColumns = new ArrayList<>(); + commonColumns.add(new MainTableColumnModel(MainTableColumnModel.Type.GROUPS)); + commonColumns.add(new MainTableColumnModel(MainTableColumnModel.Type.FILES)); + commonColumns.add(new MainTableColumnModel(MainTableColumnModel.Type.LINKED_IDENTIFIER)); commonColumns.add( - new MainTableColumnModel(MainTableColumnModel.Type.GROUPS) - ); - commonColumns.add( - new MainTableColumnModel(MainTableColumnModel.Type.FILES) - ); - commonColumns.add( - new MainTableColumnModel( - MainTableColumnModel.Type.LINKED_IDENTIFIER - ) - ); - commonColumns.add( - new MainTableColumnModel( - MainTableColumnModel.Type.NORMALFIELD, - entryTypeQualifier - ) + new MainTableColumnModel(MainTableColumnModel.Type.NORMALFIELD, entryTypeQualifier) ); commonColumns.add( - new MainTableColumnModel( - MainTableColumnModel.Type.NORMALFIELD, - authorEditQualifier - ) + new MainTableColumnModel(MainTableColumnModel.Type.NORMALFIELD, authorEditQualifier) ); commonColumns.add( - new MainTableColumnModel( - MainTableColumnModel.Type.NORMALFIELD, - titleQualifier - ) + new MainTableColumnModel(MainTableColumnModel.Type.NORMALFIELD, titleQualifier) ); commonColumns.add( - new MainTableColumnModel( - MainTableColumnModel.Type.NORMALFIELD, - yearQualifier - ) + new MainTableColumnModel(MainTableColumnModel.Type.NORMALFIELD, yearQualifier) ); commonColumns.add( - new MainTableColumnModel( - MainTableColumnModel.Type.NORMALFIELD, - journalBookQualifier - ) + new MainTableColumnModel(MainTableColumnModel.Type.NORMALFIELD, journalBookQualifier) ); commonColumns.add( - new MainTableColumnModel( - MainTableColumnModel.Type.SPECIALFIELD, - rankQualifier - ) + new MainTableColumnModel(MainTableColumnModel.Type.SPECIALFIELD, rankQualifier) ); commonColumns.add( - new MainTableColumnModel( - MainTableColumnModel.Type.SPECIALFIELD, - readStatusQualifier - ) + new MainTableColumnModel(MainTableColumnModel.Type.SPECIALFIELD, readStatusQualifier) ); commonColumns.add( - new MainTableColumnModel( - MainTableColumnModel.Type.SPECIALFIELD, - priorityQualifier - ) + new MainTableColumnModel(MainTableColumnModel.Type.SPECIALFIELD, priorityQualifier) ); // Create the Table Columns from the models using factory methods. - List> commonTableColumns = - new ArrayList<>(); + List> commonTableColumns = new ArrayList<>(); for (MainTableColumnModel columnModel : commonColumns) { - TableColumn tableColumn = - factory.createColumn(columnModel); + TableColumn tableColumn = factory.createColumn(columnModel); commonTableColumns.add(tableColumn); } return commonTableColumns; @@ -264,11 +217,7 @@ private class RightClickMenuItem extends RadioMenuItem { private int index; private boolean visibleInTable; - RightClickMenuItem( - String displayName, - MainTableColumn column, - boolean isVisible - ) { + RightClickMenuItem(String displayName, MainTableColumn column, boolean isVisible) { super(displayName); setVisibleInTable(isVisible); // Flag item as selected if the item is already in the main table. diff --git a/src/main/java/org/jabref/gui/maintable/MainTablePreferences.java b/src/main/java/org/jabref/gui/maintable/MainTablePreferences.java index 82af334c708..84c77f1495f 100644 --- a/src/main/java/org/jabref/gui/maintable/MainTablePreferences.java +++ b/src/main/java/org/jabref/gui/maintable/MainTablePreferences.java @@ -6,10 +6,8 @@ public class MainTablePreferences { private final ColumnPreferences columnPreferences; - private final BooleanProperty resizeColumnsToFit = - new SimpleBooleanProperty(); - private final BooleanProperty extraFileColumnsEnabled = - new SimpleBooleanProperty(); + private final BooleanProperty resizeColumnsToFit = new SimpleBooleanProperty(); + private final BooleanProperty extraFileColumnsEnabled = new SimpleBooleanProperty(); public MainTablePreferences( ColumnPreferences columnPreferences, diff --git a/src/main/java/org/jabref/gui/maintable/NameDisplayPreferences.java b/src/main/java/org/jabref/gui/maintable/NameDisplayPreferences.java index 29d505c4c25..a7079081374 100644 --- a/src/main/java/org/jabref/gui/maintable/NameDisplayPreferences.java +++ b/src/main/java/org/jabref/gui/maintable/NameDisplayPreferences.java @@ -18,15 +18,11 @@ public enum AbbreviationStyle { FULL, } - private final ObjectProperty displayStyle = - new SimpleObjectProperty<>(); + private final ObjectProperty displayStyle = new SimpleObjectProperty<>(); private final ObjectProperty abbreviationStyle = new SimpleObjectProperty<>(); - public NameDisplayPreferences( - DisplayStyle displayStyle, - AbbreviationStyle abbreviationStyle - ) { + public NameDisplayPreferences(DisplayStyle displayStyle, AbbreviationStyle abbreviationStyle) { this.displayStyle.set(displayStyle); this.abbreviationStyle.set(abbreviationStyle); } diff --git a/src/main/java/org/jabref/gui/maintable/OpenExternalFileAction.java b/src/main/java/org/jabref/gui/maintable/OpenExternalFileAction.java index 0713174f05a..a792c33aa3d 100644 --- a/src/main/java/org/jabref/gui/maintable/OpenExternalFileAction.java +++ b/src/main/java/org/jabref/gui/maintable/OpenExternalFileAction.java @@ -31,14 +31,7 @@ public OpenExternalFileAction( PreferencesService preferencesService, TaskExecutor taskExecutor ) { - this( - dialogService, - stateManager, - preferencesService, - null, - null, - taskExecutor - ); + this(dialogService, stateManager, preferencesService, null, null, taskExecutor); } public OpenExternalFileAction( @@ -78,11 +71,9 @@ public void execute() { .getActiveDatabase() .ifPresent(databaseContext -> { if (entry == null) { - final List selectedEntries = - stateManager.getSelectedEntries(); + final List selectedEntries = stateManager.getSelectedEntries(); - List linkedFileViewModelList = - new LinkedList<>(); + List linkedFileViewModelList = new LinkedList<>(); LinkedFileViewModel linkedFileViewModel; for (BibEntry entry : selectedEntries) { @@ -103,18 +94,15 @@ public void execute() { // ask the user when detecting # of files > FILES_LIMIT if (linkedFileViewModelList.size() > FILES_LIMIT) { - boolean continueOpening = - dialogService.showConfirmationDialogAndWait( - Localization.lang( - "Opening large number of files" - ), - Localization.lang( - "You are about to open %0 files. Continue?", - linkedFileViewModelList.size() - ), - Localization.lang("Continue"), - Localization.lang("Cancel") - ); + boolean continueOpening = dialogService.showConfirmationDialogAndWait( + Localization.lang("Opening large number of files"), + Localization.lang( + "You are about to open %0 files. Continue?", + linkedFileViewModelList.size() + ), + Localization.lang("Continue"), + Localization.lang("Cancel") + ); if (!continueOpening) { return; } @@ -122,15 +110,14 @@ public void execute() { linkedFileViewModelList.forEach(LinkedFileViewModel::open); } else { - LinkedFileViewModel linkedFileViewModel = - new LinkedFileViewModel( - linkedFile, - entry, - databaseContext, - taskExecutor, - dialogService, - preferencesService - ); + LinkedFileViewModel linkedFileViewModel = new LinkedFileViewModel( + linkedFile, + entry, + databaseContext, + taskExecutor, + dialogService, + preferencesService + ); linkedFileViewModel.open(); } }); diff --git a/src/main/java/org/jabref/gui/maintable/OpenFolderAction.java b/src/main/java/org/jabref/gui/maintable/OpenFolderAction.java index fce17337d25..15afebc5175 100644 --- a/src/main/java/org/jabref/gui/maintable/OpenFolderAction.java +++ b/src/main/java/org/jabref/gui/maintable/OpenFolderAction.java @@ -26,14 +26,7 @@ public OpenFolderAction( PreferencesService preferencesService, TaskExecutor taskExecutor ) { - this( - dialogService, - stateManager, - preferencesService, - null, - null, - taskExecutor - ); + this(dialogService, stateManager, preferencesService, null, null, taskExecutor); } public OpenFolderAction( @@ -53,10 +46,7 @@ public OpenFolderAction( if (this.linkedFile == null) { this.executable.bind( - ActionHelper.isFilePresentForSelectedEntry( - stateManager, - preferencesService - ) + ActionHelper.isFilePresentForSelectedEntry(stateManager, preferencesService) ); } else { this.setExecutable(true); @@ -74,27 +64,25 @@ public void execute() { .stream() .filter(entry -> !entry.getFiles().isEmpty()) .forEach(entry -> { - LinkedFileViewModel linkedFileViewModel = - new LinkedFileViewModel( - entry.getFiles().get(0), - entry, - databaseContext, - taskExecutor, - dialogService, - preferencesService - ); + LinkedFileViewModel linkedFileViewModel = new LinkedFileViewModel( + entry.getFiles().get(0), + entry, + databaseContext, + taskExecutor, + dialogService, + preferencesService + ); linkedFileViewModel.openFolder(); }); } else { - LinkedFileViewModel linkedFileViewModel = - new LinkedFileViewModel( - linkedFile, - entry, - databaseContext, - taskExecutor, - dialogService, - preferencesService - ); + LinkedFileViewModel linkedFileViewModel = new LinkedFileViewModel( + linkedFile, + entry, + databaseContext, + taskExecutor, + dialogService, + preferencesService + ); linkedFileViewModel.openFolder(); } }); diff --git a/src/main/java/org/jabref/gui/maintable/OpenUrlAction.java b/src/main/java/org/jabref/gui/maintable/OpenUrlAction.java index a4b9b6d5456..ea3b81a506d 100644 --- a/src/main/java/org/jabref/gui/maintable/OpenUrlAction.java +++ b/src/main/java/org/jabref/gui/maintable/OpenUrlAction.java @@ -30,21 +30,11 @@ public OpenUrlAction( this.stateManager = stateManager; this.preferences = preferences; - BooleanExpression fieldIsSet = - ActionHelper.isAnyFieldSetForSelectedEntry( - List.of( - StandardField.URL, - StandardField.DOI, - StandardField.URI, - StandardField.EPRINT - ), - stateManager - ); - this.executable.bind( - ActionHelper - .needsEntriesSelected(1, stateManager) - .and(fieldIsSet) - ); + BooleanExpression fieldIsSet = ActionHelper.isAnyFieldSetForSelectedEntry( + List.of(StandardField.URL, StandardField.DOI, StandardField.URI, StandardField.EPRINT), + stateManager + ); + this.executable.bind(ActionHelper.needsEntriesSelected(1, stateManager).and(fieldIsSet)); } @Override @@ -52,8 +42,7 @@ public void execute() { stateManager .getActiveDatabase() .ifPresent(databaseContext -> { - final List entries = - stateManager.getSelectedEntries(); + final List entries = stateManager.getSelectedEntries(); if (entries.size() != 1) { dialogService.notify( @@ -93,11 +82,7 @@ public void execute() { field.equals(StandardField.DOI) && preferences.getDOIPreferences().isUseCustom() ) { - JabRefDesktop.openCustomDoi( - link.get(), - preferences, - dialogService - ); + JabRefDesktop.openCustomDoi(link.get(), preferences, dialogService); } else { JabRefDesktop.openExternalViewer( databaseContext, diff --git a/src/main/java/org/jabref/gui/maintable/PersistenceVisualStateTable.java b/src/main/java/org/jabref/gui/maintable/PersistenceVisualStateTable.java index 3919c89b3fc..fd4bbeb6ab3 100644 --- a/src/main/java/org/jabref/gui/maintable/PersistenceVisualStateTable.java +++ b/src/main/java/org/jabref/gui/maintable/PersistenceVisualStateTable.java @@ -15,9 +15,7 @@ */ public class PersistenceVisualStateTable { - private static final Logger LOGGER = LoggerFactory.getLogger( - PersistenceVisualStateTable.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(PersistenceVisualStateTable.class); protected final TableView table; protected final ColumnPreferences preferences; @@ -31,15 +29,12 @@ public PersistenceVisualStateTable( } public void addListeners() { - table - .getColumns() - .addListener((InvalidationListener) obs -> updateColumns()); + table.getColumns().addListener((InvalidationListener) obs -> updateColumns()); table .getSortOrder() .addListener( - (ListChangeListener< - ? super TableColumn - >) obs -> updateSortOrder() + (ListChangeListener>) obs -> + updateSortOrder() ); // As we store the ColumnModels of the MainTable, we need to add the listener to the ColumnModel properties, diff --git a/src/main/java/org/jabref/gui/maintable/RightClickMenu.java b/src/main/java/org/jabref/gui/maintable/RightClickMenu.java index cb625c099f6..5a122d335cd 100644 --- a/src/main/java/org/jabref/gui/maintable/RightClickMenu.java +++ b/src/main/java/org/jabref/gui/maintable/RightClickMenu.java @@ -55,11 +55,7 @@ public static ContextMenu create( .addAll( factory.createMenuItem( StandardActions.COPY, - new EditAction( - StandardActions.COPY, - libraryTab.frame(), - stateManager - ) + new EditAction(StandardActions.COPY, libraryTab.frame(), stateManager) ), createCopySubMenu( factory, @@ -72,35 +68,19 @@ public static ContextMenu create( ), factory.createMenuItem( StandardActions.PASTE, - new EditAction( - StandardActions.PASTE, - libraryTab.frame(), - stateManager - ) + new EditAction(StandardActions.PASTE, libraryTab.frame(), stateManager) ), factory.createMenuItem( StandardActions.CUT, - new EditAction( - StandardActions.CUT, - libraryTab.frame(), - stateManager - ) + new EditAction(StandardActions.CUT, libraryTab.frame(), stateManager) ), factory.createMenuItem( StandardActions.MERGE_ENTRIES, - new MergeEntriesAction( - dialogService, - stateManager, - preferencesService - ) + new MergeEntriesAction(dialogService, stateManager, preferencesService) ), factory.createMenuItem( StandardActions.DELETE_ENTRY, - new EditAction( - StandardActions.DELETE_ENTRY, - libraryTab.frame(), - stateManager - ) + new EditAction(StandardActions.DELETE_ENTRY, libraryTab.frame(), stateManager) ), new SeparatorMenuItem(), createSendSubMenu( @@ -204,19 +184,11 @@ public static ContextMenu create( ), factory.createMenuItem( StandardActions.OPEN_URL, - new OpenUrlAction( - dialogService, - stateManager, - preferencesService - ) + new OpenUrlAction(dialogService, stateManager, preferencesService) ), factory.createMenuItem( StandardActions.SEARCH_SHORTSCIENCE, - new SearchShortScienceAction( - dialogService, - stateManager, - preferencesService - ) + new SearchShortScienceAction(dialogService, stateManager, preferencesService) ), new SeparatorMenuItem(), new ChangeEntryTypeMenu( @@ -337,12 +309,8 @@ private static Menu createCopySubMenu( ); // the submenu will behave dependent on what style is currently selected (citation/preview) - PreviewPreferences previewPreferences = - preferencesService.getPreviewPreferences(); - if ( - previewPreferences.getSelectedPreviewLayout() instanceof - CitationStylePreviewLayout - ) { + PreviewPreferences previewPreferences = preferencesService.getPreviewPreferences(); + if (previewPreferences.getSelectedPreviewLayout() instanceof CitationStylePreviewLayout) { copySpecialMenu .getItems() .addAll( diff --git a/src/main/java/org/jabref/gui/maintable/SearchShortScienceAction.java b/src/main/java/org/jabref/gui/maintable/SearchShortScienceAction.java index a515cb4e7bd..31fa56d39a3 100644 --- a/src/main/java/org/jabref/gui/maintable/SearchShortScienceAction.java +++ b/src/main/java/org/jabref/gui/maintable/SearchShortScienceAction.java @@ -35,9 +35,7 @@ public SearchShortScienceAction( StandardField.TITLE, stateManager ); - this.executable.bind( - needsEntriesSelected(1, stateManager).and(fieldIsSet) - ); + this.executable.bind(needsEntriesSelected(1, stateManager).and(fieldIsSet)); } @Override @@ -45,8 +43,7 @@ public void execute() { stateManager .getActiveDatabase() .ifPresent(databaseContext -> { - final List bibEntries = - stateManager.getSelectedEntries(); + final List bibEntries = stateManager.getSelectedEntries(); if (bibEntries.size() != 1) { dialogService.notify( @@ -70,9 +67,7 @@ public void execute() { ); } catch (IOException ex) { dialogService.showErrorDialogAndWait( - Localization.lang( - "Unable to open ShortScience." - ), + Localization.lang("Unable to open ShortScience."), ex ); } diff --git a/src/main/java/org/jabref/gui/maintable/SmartConstrainedResizePolicy.java b/src/main/java/org/jabref/gui/maintable/SmartConstrainedResizePolicy.java index 8d3ce694853..54dfea01146 100644 --- a/src/main/java/org/jabref/gui/maintable/SmartConstrainedResizePolicy.java +++ b/src/main/java/org/jabref/gui/maintable/SmartConstrainedResizePolicy.java @@ -16,8 +16,7 @@ * We make sure that the width of all columns sums up to the total width of the table. * However, in contrast to {@link TableView#CONSTRAINED_RESIZE_POLICY} we size the columns initially by their preferred width. */ -public class SmartConstrainedResizePolicy - implements Callback { +public class SmartConstrainedResizePolicy implements Callback { private static final Logger LOGGER = LoggerFactory.getLogger( SmartConstrainedResizePolicy.class @@ -34,8 +33,7 @@ public Boolean call(TableView.ResizeFeatures prop) { private Boolean initColumnSize(TableView table) { double tableWidth = getContentWidth(table); - List> visibleLeafColumns = - table.getVisibleLeafColumns(); + List> visibleLeafColumns = table.getVisibleLeafColumns(); double totalWidth = visibleLeafColumns .stream() .mapToDouble(TableColumnBase::getWidth) @@ -91,14 +89,8 @@ private void resize(TableColumnBase column, double delta) { private Boolean constrainedResize(TableView.ResizeFeatures prop) { TableView table = prop.getTable(); - List> visibleLeafColumns = - table.getVisibleLeafColumns(); - return constrainedResize( - prop, - false, - getContentWidth(table) - 2, - visibleLeafColumns - ); + List> visibleLeafColumns = table.getVisibleLeafColumns(); + return constrainedResize(prop, false, getContentWidth(table) - 2, visibleLeafColumns); } private Boolean constrainedResize( @@ -141,8 +133,7 @@ private Boolean constrainedResize( private Double getContentWidth(TableView table) { try { // TODO: reflective access, should be removed - Field privateStringField = - TableView.class.getDeclaredField("contentWidth"); + Field privateStringField = TableView.class.getDeclaredField("contentWidth"); privateStringField.setAccessible(true); return (Double) privateStringField.get(table); } catch (IllegalAccessException | NoSuchFieldException e) { diff --git a/src/main/java/org/jabref/gui/maintable/columns/FieldColumn.java b/src/main/java/org/jabref/gui/maintable/columns/FieldColumn.java index 88151eea4fa..22ae5f85483 100644 --- a/src/main/java/org/jabref/gui/maintable/columns/FieldColumn.java +++ b/src/main/java/org/jabref/gui/maintable/columns/FieldColumn.java @@ -31,10 +31,7 @@ public FieldColumn(MainTableColumnModel model) { if (fields.hasExactlyOne()) { // comparator can't parse more than one value - Field field = fields - .getFields() - .stream() - .collect(MoreCollectors.onlyElement()); + Field field = fields.getFields().stream().collect(MoreCollectors.onlyElement()); if ((field instanceof UnknownField) || field.isNumeric()) { this.setComparator(new NumericFieldComparator()); @@ -54,9 +51,7 @@ public String getDisplayName() { return fields.getDisplayName(); } - private ObservableValue getFieldValue( - BibEntryTableViewModel entry - ) { + private ObservableValue getFieldValue(BibEntryTableViewModel entry) { if (fields.isEmpty()) { return null; } else { diff --git a/src/main/java/org/jabref/gui/maintable/columns/FileColumn.java b/src/main/java/org/jabref/gui/maintable/columns/FileColumn.java index 6a44ed3f986..7b12126ef8f 100644 --- a/src/main/java/org/jabref/gui/maintable/columns/FileColumn.java +++ b/src/main/java/org/jabref/gui/maintable/columns/FileColumn.java @@ -54,10 +54,7 @@ public FileColumn( setCommonSettings(); Node headerGraphic = IconTheme.JabRefIcons.FILE.getGraphicNode(); - Tooltip.install( - headerGraphic, - new Tooltip(Localization.lang("Linked files")) - ); + Tooltip.install(headerGraphic, new Tooltip(Localization.lang("Linked files"))); this.setGraphic(headerGraphic); new ValueTableCellFactory>() @@ -66,20 +63,16 @@ public FileColumn( .withMenu(this::createFileMenu) .withOnMouseClickedEvent((entry, linkedFiles) -> event -> { - if ( - (event.getButton() == MouseButton.PRIMARY) && - (linkedFiles.size() == 1) - ) { + if ((event.getButton() == MouseButton.PRIMARY) && (linkedFiles.size() == 1)) { // Only one linked file -> open directly - LinkedFileViewModel linkedFileViewModel = - new LinkedFileViewModel( - linkedFiles.get(0), - entry.getEntry(), - database, - taskExecutor, - dialogService, - preferencesService - ); + LinkedFileViewModel linkedFileViewModel = new LinkedFileViewModel( + linkedFiles.get(0), + entry.getEntry(), + database, + taskExecutor, + dialogService, + preferencesService + ); linkedFileViewModel.open(); } } @@ -108,10 +101,7 @@ public FileColumn( this.setGraphic( ExternalFileTypes - .getExternalFileTypeByName( - fileType, - preferencesService.getFilePreferences() - ) + .getExternalFileTypeByName(fileType, preferencesService.getFilePreferences()) .map(ExternalFileType::getIcon) .orElse(IconTheme.JabRefIcons.FILE) .getGraphicNode() @@ -122,9 +112,7 @@ public FileColumn( createFileIcon( linkedFiles .stream() - .filter(linkedFile -> - linkedFile.getFileType().equalsIgnoreCase(fileType) - ) + .filter(linkedFile -> linkedFile.getFileType().equalsIgnoreCase(fileType)) .collect(Collectors.toList()) ) ) @@ -133,30 +121,19 @@ public FileColumn( private void setCommonSettings() { this.setResizable(false); - MainTableColumnFactory.setExactWidth( - this, - ColumnPreferences.ICON_COLUMN_WIDTH - ); + MainTableColumnFactory.setExactWidth(this, ColumnPreferences.ICON_COLUMN_WIDTH); this.getStyleClass().add(MainTableColumnFactory.STYLE_ICON_COLUMN); - this.setCellValueFactory(cellData -> - cellData.getValue().getLinkedFiles() - ); + this.setCellValueFactory(cellData -> cellData.getValue().getLinkedFiles()); } private String createFileTooltip(List linkedFiles) { if (!linkedFiles.isEmpty()) { - return Localization.lang( - "Open file %0", - linkedFiles.get(0).getLink() - ); + return Localization.lang("Open file %0", linkedFiles.get(0).getLink()); } return null; } - private ContextMenu createFileMenu( - BibEntryTableViewModel entry, - List linkedFiles - ) { + private ContextMenu createFileMenu(BibEntryTableViewModel entry, List linkedFiles) { if (linkedFiles.size() <= 1) { return null; } diff --git a/src/main/java/org/jabref/gui/maintable/columns/LibraryColumn.java b/src/main/java/org/jabref/gui/maintable/columns/LibraryColumn.java index 652342c381b..08b4e9ef3b6 100644 --- a/src/main/java/org/jabref/gui/maintable/columns/LibraryColumn.java +++ b/src/main/java/org/jabref/gui/maintable/columns/LibraryColumn.java @@ -15,9 +15,7 @@ public LibraryColumn(MainTableColumnModel model) { new ValueTableCellFactory() .withText(FileUtil::getBaseName) .install(this); - setCellValueFactory(param -> - param.getValue().bibDatabaseContextProperty() - ); + setCellValueFactory(param -> param.getValue().bibDatabaseContextProperty()); } public LibraryColumn() { diff --git a/src/main/java/org/jabref/gui/maintable/columns/LinkedIdentifierColumn.java b/src/main/java/org/jabref/gui/maintable/columns/LinkedIdentifierColumn.java index d8598b31ead..2450bce0b0c 100644 --- a/src/main/java/org/jabref/gui/maintable/columns/LinkedIdentifierColumn.java +++ b/src/main/java/org/jabref/gui/maintable/columns/LinkedIdentifierColumn.java @@ -27,8 +27,7 @@ /** * A clickable icons column for DOIs, URLs, URIs and EPrints. */ -public class LinkedIdentifierColumn - extends MainTableColumn> { +public class LinkedIdentifierColumn extends MainTableColumn> { private final BibDatabaseContext database; private final CellFactory cellFactory; @@ -50,20 +49,12 @@ public LinkedIdentifierColumn( this.preferences = preferences; Node headerGraphic = IconTheme.JabRefIcons.WWW.getGraphicNode(); - Tooltip.install( - headerGraphic, - new Tooltip(Localization.lang("Linked identifiers")) - ); + Tooltip.install(headerGraphic, new Tooltip(Localization.lang("Linked identifiers"))); this.setGraphic(headerGraphic); this.getStyleClass().add(MainTableColumnFactory.STYLE_ICON_COLUMN); - MainTableColumnFactory.setExactWidth( - this, - ColumnPreferences.ICON_COLUMN_WIDTH - ); + MainTableColumnFactory.setExactWidth(this, ColumnPreferences.ICON_COLUMN_WIDTH); this.setResizable(false); - this.setCellValueFactory(cellData -> - cellData.getValue().getLinkedIdentifiers() - ); + this.setCellValueFactory(cellData -> cellData.getValue().getLinkedIdentifiers()); new ValueTableCellFactory>() .withGraphic(this::createIdentifierGraphic) .withTooltip(this::createIdentifierTooltip) @@ -71,16 +62,8 @@ public LinkedIdentifierColumn( .withOnMouseClickedEvent((entry, linkedFiles) -> event -> { // If we only have one identifer, open directly - if ( - (linkedFiles.size() == 1) && - (event.getButton() == MouseButton.PRIMARY) - ) { - new OpenUrlAction( - dialogService, - stateManager, - preferences - ) - .execute(); + if ((linkedFiles.size() == 1) && (event.getButton() == MouseButton.PRIMARY)) { + new OpenUrlAction(dialogService, stateManager, preferences).execute(); } } ) diff --git a/src/main/java/org/jabref/gui/maintable/columns/SpecialFieldColumn.java b/src/main/java/org/jabref/gui/maintable/columns/SpecialFieldColumn.java index 4dc23d978c7..0608dcd943d 100644 --- a/src/main/java/org/jabref/gui/maintable/columns/SpecialFieldColumn.java +++ b/src/main/java/org/jabref/gui/maintable/columns/SpecialFieldColumn.java @@ -30,8 +30,7 @@ /** * A column that displays a SpecialField */ -public class SpecialFieldColumn - extends MainTableColumn> { +public class SpecialFieldColumn extends MainTableColumn> { private final PreferencesService preferencesService; private final UndoManager undoManager; @@ -45,9 +44,7 @@ public SpecialFieldColumn( this.preferencesService = preferencesService; this.undoManager = undoManager; - SpecialField specialField = (SpecialField) FieldFactory.parseField( - model.getQualifier() - ); + SpecialField specialField = (SpecialField) FieldFactory.parseField(model.getQualifier()); SpecialFieldViewModel specialFieldViewModel = new SpecialFieldViewModel( specialField, preferencesService, @@ -55,10 +52,7 @@ public SpecialFieldColumn( ); Node headerGraphic = specialFieldViewModel.getIcon().getGraphicNode(); - Tooltip.install( - headerGraphic, - new Tooltip(specialFieldViewModel.getLocalization()) - ); + Tooltip.install(headerGraphic, new Tooltip(specialFieldViewModel.getLocalization())); this.setGraphic(headerGraphic); this.getStyleClass().add(MainTableColumnFactory.STYLE_ICON_COLUMN); @@ -68,17 +62,11 @@ public SpecialFieldColumn( SpecialFieldsPreferences.COLUMN_RANKING_WIDTH ); this.setResizable(false); - new OptionalValueTableCellFactory< - BibEntryTableViewModel, - SpecialFieldValueViewModel - >() + new OptionalValueTableCellFactory() .withGraphic(this::createSpecialRating) .install(this); } else { - MainTableColumnFactory.setExactWidth( - this, - ColumnPreferences.ICON_COLUMN_WIDTH - ); + MainTableColumnFactory.setExactWidth(this, ColumnPreferences.ICON_COLUMN_WIDTH); this.setResizable(false); if (specialField.isSingleValueField()) { @@ -106,18 +94,13 @@ public SpecialFieldColumn( createSpecialFieldIcon(value, specialFieldViewModel) ) .withMenu((entry, value) -> - createSpecialFieldMenu( - entry.getEntry(), - specialFieldViewModel - ) + createSpecialFieldMenu(entry.getEntry(), specialFieldViewModel) ) .install(this); } } - this.setCellValueFactory(cellData -> - cellData.getValue().getSpecialField(specialField) - ); + this.setCellValueFactory(cellData -> cellData.getValue().getSpecialField(specialField)); if (specialField == SpecialField.RANKING) { this.setComparator(new RankingFieldComparator()); @@ -143,10 +126,7 @@ private Rating createSpecialRating( ranking.addEventFilter( MouseEvent.MOUSE_CLICKED, event -> { - if ( - event.getButton().equals(MouseButton.PRIMARY) && - event.getClickCount() == 2 - ) { + if (event.getButton().equals(MouseButton.PRIMARY) && event.getClickCount() == 2) { ranking.setRating(0); event.consume(); } else if (event.getButton().equals(MouseButton.SECONDARY)) { @@ -158,11 +138,7 @@ private Rating createSpecialRating( EasyBind.subscribe( ranking.ratingProperty(), rating -> - new SpecialFieldViewModel( - SpecialField.RANKING, - preferencesService, - undoManager - ) + new SpecialFieldViewModel(SpecialField.RANKING, preferencesService, undoManager) .setSpecialFieldValue( entry.getEntry(), SpecialFieldValue.getRating(rating.intValue()) @@ -172,10 +148,7 @@ private Rating createSpecialRating( return ranking; } - private ContextMenu createSpecialFieldMenu( - BibEntry entry, - SpecialFieldViewModel specialField - ) { + private ContextMenu createSpecialFieldMenu(BibEntry entry, SpecialFieldViewModel specialField) { ContextMenu contextMenu = new ContextMenu(); for (SpecialFieldValueViewModel value : specialField.getValues()) { @@ -183,8 +156,7 @@ private ContextMenu createSpecialFieldMenu( value.getMenuString(), value.getIcon().map(JabRefIcon::getGraphicNode).orElse(null) ); - menuItem.setOnAction(event -> - specialField.setSpecialFieldValue(entry, value.getValue()) + menuItem.setOnAction(event -> specialField.setSpecialFieldValue(entry, value.getValue()) ); contextMenu.getItems().add(menuItem); } diff --git a/src/main/java/org/jabref/gui/menus/ChangeEntryTypeAction.java b/src/main/java/org/jabref/gui/menus/ChangeEntryTypeAction.java index 8c2c15905b6..3b85ca0949b 100644 --- a/src/main/java/org/jabref/gui/menus/ChangeEntryTypeAction.java +++ b/src/main/java/org/jabref/gui/menus/ChangeEntryTypeAction.java @@ -19,29 +19,18 @@ public class ChangeEntryTypeAction extends SimpleCommand { private final UndoManager undoManager; private final ReadOnlyStringWrapper statusMessageProperty; - public ChangeEntryTypeAction( - EntryType type, - List entries, - UndoManager undoManager - ) { + public ChangeEntryTypeAction(EntryType type, List entries, UndoManager undoManager) { this.type = type; this.entries = entries; this.undoManager = undoManager; - this.statusMessageProperty = - new ReadOnlyStringWrapper(EntryTypeView.getDescription(type)); + this.statusMessageProperty = new ReadOnlyStringWrapper(EntryTypeView.getDescription(type)); } @Override public void execute() { - NamedCompound compound = new NamedCompound( - Localization.lang("Change entry type") - ); + NamedCompound compound = new NamedCompound(Localization.lang("Change entry type")); entries.forEach(e -> - e - .setType(type) - .ifPresent(change -> - compound.addEdit(new UndoableChangeType(change)) - ) + e.setType(type).ifPresent(change -> compound.addEdit(new UndoableChangeType(change))) ); undoManager.addEdit(compound); } diff --git a/src/main/java/org/jabref/gui/menus/ChangeEntryTypeMenu.java b/src/main/java/org/jabref/gui/menus/ChangeEntryTypeMenu.java index c6012d6c080..415230de4cb 100644 --- a/src/main/java/org/jabref/gui/menus/ChangeEntryTypeMenu.java +++ b/src/main/java/org/jabref/gui/menus/ChangeEntryTypeMenu.java @@ -45,17 +45,13 @@ public ChangeEntryTypeMenu( public ContextMenu asContextMenu() { ContextMenu menu = new ContextMenu(); - menu - .getItems() - .setAll(getMenuItems(entries, bibDatabaseContext, undoManager)); + menu.getItems().setAll(getMenuItems(entries, bibDatabaseContext, undoManager)); return menu; } public Menu asSubMenu() { Menu menu = new Menu(Localization.lang("Change entry type")); - menu - .getItems() - .setAll(getMenuItems(entries, bibDatabaseContext, undoManager)); + menu.getItems().setAll(getMenuItems(entries, bibDatabaseContext, undoManager)); return menu; } @@ -83,9 +79,7 @@ private ObservableList getMenuItems( entries, undoManager ) - .ifPresent(subMenu -> - items.addAll(new SeparatorMenuItem(), subMenu) - ); + .ifPresent(subMenu -> items.addAll(new SeparatorMenuItem(), subMenu)); } else { // Default BibTeX createSubMenu( @@ -97,15 +91,8 @@ private ObservableList getMenuItems( .ifPresent(items::add); // IEEETran - createSubMenu( - "IEEETran", - IEEETranEntryTypeDefinitions.ALL, - entries, - undoManager - ) - .ifPresent(subMenu -> - items.addAll(new SeparatorMenuItem(), subMenu) - ); + createSubMenu("IEEETran", IEEETranEntryTypeDefinitions.ALL, entries, undoManager) + .ifPresent(subMenu -> items.addAll(new SeparatorMenuItem(), subMenu)); // Custom types createSubMenu( @@ -114,9 +101,7 @@ private ObservableList getMenuItems( entries, undoManager ) - .ifPresent(subMenu -> - items.addAll(new SeparatorMenuItem(), subMenu) - ); + .ifPresent(subMenu -> items.addAll(new SeparatorMenuItem(), subMenu)); } return items; @@ -132,9 +117,7 @@ private Optional createSubMenu( if (!entryTypes.isEmpty()) { subMenu = factory.createMenu(() -> text); - subMenu - .getItems() - .addAll(fromEntryTypes(entryTypes, entries, undoManager)); + subMenu.getItems().addAll(fromEntryTypes(entryTypes, entries, undoManager)); } return Optional.ofNullable(subMenu); diff --git a/src/main/java/org/jabref/gui/menus/FileHistoryMenu.java b/src/main/java/org/jabref/gui/menus/FileHistoryMenu.java index efe525ef740..ff1701ef4d3 100644 --- a/src/main/java/org/jabref/gui/menus/FileHistoryMenu.java +++ b/src/main/java/org/jabref/gui/menus/FileHistoryMenu.java @@ -26,9 +26,7 @@ public FileHistoryMenu( setText(Localization.lang("Recent libraries")); this.clearRecentLibraries = new MenuItem(); - clearRecentLibraries.setText( - Localization.lang("Clear recent libraries") - ); + clearRecentLibraries.setText(Localization.lang("Clear recent libraries")); clearRecentLibraries.setOnAction(event -> clearLibrariesHistory()); this.history = fileHistory; @@ -56,9 +54,7 @@ public boolean openFileByKey(KeyEvent keyEvent) { if (num <= 0 || num > history.size()) { return false; } - this.openFile( - history.get(Integer.parseInt(keyEvent.getCharacter()) - 1) - ); + this.openFile(history.get(Integer.parseInt(keyEvent.getCharacter()) - 1)); return true; } diff --git a/src/main/java/org/jabref/gui/mergeentries/DiffHighlighting.java b/src/main/java/org/jabref/gui/mergeentries/DiffHighlighting.java index 07612ba76a9..67f1df56fc0 100644 --- a/src/main/java/org/jabref/gui/mergeentries/DiffHighlighting.java +++ b/src/main/java/org/jabref/gui/mergeentries/DiffHighlighting.java @@ -12,9 +12,7 @@ public class DiffHighlighting { - private static final Logger LOGGER = LoggerFactory.getLogger( - DiffHighlighting.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(DiffHighlighting.class); private DiffHighlighting() {} @@ -39,40 +37,28 @@ public static List generateDiffHighlighting( switch (delta.getType()) { case CHANGE: for (String line : lines) { - result.set( - startPos + offset, - forRemoved(line + separator) - ); + result.set(startPos + offset, forRemoved(line + separator)); offset++; } result.set( startPos + offset - 1, - forRemoved( - stringList.get((startPos + offset) - 1) + separator - ) + forRemoved(stringList.get((startPos + offset) - 1) + separator) ); result.add( startPos + offset, - forAdded( - String.join(separator, delta.getTarget().getLines()) - ) + forAdded(String.join(separator, delta.getTarget().getLines())) ); break; case DELETE: for (String line : lines) { - result.set( - startPos + offset, - forRemoved(line + separator) - ); + result.set(startPos + offset, forRemoved(line + separator)); offset++; } break; case INSERT: result.add( delta.getSource().getPosition(), - forAdded( - String.join(separator, delta.getTarget().getLines()) - ) + forAdded(String.join(separator, delta.getTarget().getLines())) ); break; default: @@ -127,19 +113,13 @@ public static List generateSymmetricHighlighting( switch (delta.getType()) { case CHANGE: for (String line : lines) { - result.set( - startPos + offset, - forChanged(line + separator) - ); + result.set(startPos + offset, forChanged(line + separator)); offset++; } break; case DELETE: for (String line : lines) { - result.set( - startPos + offset, - forAdded(line + separator) - ); + result.set(startPos + offset, forAdded(line + separator)); offset++; } break; diff --git a/src/main/java/org/jabref/gui/mergeentries/DiffHighlightingEllipsingTextFlow.java b/src/main/java/org/jabref/gui/mergeentries/DiffHighlightingEllipsingTextFlow.java index 3e8c5b9b9d1..2b7ef0c5062 100644 --- a/src/main/java/org/jabref/gui/mergeentries/DiffHighlightingEllipsingTextFlow.java +++ b/src/main/java/org/jabref/gui/mergeentries/DiffHighlightingEllipsingTextFlow.java @@ -19,16 +19,10 @@ public class DiffHighlightingEllipsingTextFlow extends TextFlow { private static final String DEFAULT_ELLIPSIS_STRING = "..."; private StringProperty ellipsisString; - private final ObservableList allChildren = - FXCollections.observableArrayList(); - private final ChangeListener sizeChangeListener = ( - observableValue, - number, - t1 - ) -> + private final ObservableList allChildren = FXCollections.observableArrayList(); + private final ChangeListener sizeChangeListener = (observableValue, number, t1) -> adjustText(); - private final ListChangeListener listChangeListener = - this::adjustChildren; + private final ListChangeListener listChangeListener = this::adjustChildren; private final String fullText; private final EasyObservableValue comparisonString; @@ -46,9 +40,7 @@ public DiffHighlightingEllipsingTextFlow( this.comparisonString = comparisonString; this.diffMode = diffMode; - comparisonString.addListener((obs, oldValue, newValue) -> - highlightDiff() - ); + comparisonString.addListener((obs, oldValue, newValue) -> highlightDiff()); diffMode.addListener((obs, oldValue, newValue) -> highlightDiff()); highlightDiff(); } @@ -58,9 +50,7 @@ public ObservableList getChildren() { return allChildren; } - private void adjustChildren( - ListChangeListener.Change change - ) { + private void adjustChildren(ListChangeListener.Change change) { super.getChildren().clear(); super.getChildren().addAll(allChildren); super.autosize(); @@ -100,27 +90,21 @@ private boolean fillUntilOverflowing() { if (super.getChildren().size() == allChildren.size()) { if (allChildren.size() > 0) { // all Texts are displayed, let's make sure all chars are as well - Node lastChildAsShown = super - .getChildren() - .get(super.getChildren().size() - 1); + Node lastChildAsShown = super.getChildren().get(super.getChildren().size() - 1); Node lastChild = allChildren.get(allChildren.size() - 1); if ( lastChildAsShown instanceof Text && ((Text) lastChildAsShown).getText().length() < ((Text) lastChild).getText().length() ) { - ((Text) lastChildAsShown).setText( - ((Text) lastChild).getText() - ); + ((Text) lastChildAsShown).setText(((Text) lastChild).getText()); } else { // nothing to fill the space with return false; } } } else { - super - .getChildren() - .add(allChildren.get(super.getChildren().size())); + super.getChildren().add(allChildren.get(super.getChildren().size())); } super.autosize(); } @@ -140,16 +124,10 @@ private boolean ellipseUntilTextFits() { return false; } lastChildAsShown = - (Text) super - .getChildren() - .remove(super.getChildren().size() - 1); + (Text) super.getChildren().remove(super.getChildren().size() - 1); } - Text shortenedChild = new Text( - ellipseString(lastChildAsShown.getText()) - ); - shortenedChild - .getStyleClass() - .addAll(lastChildAsShown.getStyleClass()); + Text shortenedChild = new Text(ellipseString(lastChildAsShown.getText())); + shortenedChild.getStyleClass().addAll(lastChildAsShown.getStyleClass()); super.getChildren().add(shortenedChild); super.autosize(); } @@ -158,10 +136,7 @@ private boolean ellipseUntilTextFits() { public void highlightDiff() { allChildren.clear(); - if ( - comparisonString.get() != null && - !comparisonString.get().equals(fullText) - ) { + if (comparisonString.get() != null && !comparisonString.get().equals(fullText)) { final List highlightedText = switch (diffMode.getValue()) { case PLAIN -> { @@ -206,9 +181,7 @@ public final void setEllipsisString(String value) { } public String getEllipsisString() { - return ellipsisString == null - ? DEFAULT_ELLIPSIS_STRING - : ellipsisString.get(); + return ellipsisString == null ? DEFAULT_ELLIPSIS_STRING : ellipsisString.get(); } public final StringProperty ellipsisStringProperty() { diff --git a/src/main/java/org/jabref/gui/mergeentries/FetchAndMergeEntry.java b/src/main/java/org/jabref/gui/mergeentries/FetchAndMergeEntry.java index 154ac10bc16..efc52e2ca6d 100644 --- a/src/main/java/org/jabref/gui/mergeentries/FetchAndMergeEntry.java +++ b/src/main/java/org/jabref/gui/mergeentries/FetchAndMergeEntry.java @@ -43,9 +43,7 @@ public class FetchAndMergeEntry { StandardField.EPRINT, StandardField.ISBN ); - private static final Logger LOGGER = LoggerFactory.getLogger( - FetchAndMergeEntry.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(FetchAndMergeEntry.class); private final DialogService dialogService; private final UndoManager undoManager; private final BibDatabaseContext bibDatabaseContext; @@ -78,16 +76,13 @@ public void fetchAndMerge(BibEntry entry, List fields) { for (Field field : fields) { Optional fieldContent = entry.getField(field); if (fieldContent.isPresent()) { - Optional fetcher = - WebFetchers.getIdBasedFetcherForField( - field, - preferencesService.getImportFormatPreferences() - ); + Optional fetcher = WebFetchers.getIdBasedFetcherForField( + field, + preferencesService.getImportFormatPreferences() + ); if (fetcher.isPresent()) { BackgroundTask - .wrap(() -> - fetcher.get().performSearchById(fieldContent.get()) - ) + .wrap(() -> fetcher.get().performSearchById(fieldContent.get())) .onSuccess(fetchedEntry -> { ImportCleanup cleanup = ImportCleanup.targeting( bibDatabaseContext.getMode() @@ -95,11 +90,7 @@ public void fetchAndMerge(BibEntry entry, List fields) { String type = field.getDisplayName(); if (fetchedEntry.isPresent()) { cleanup.doPostCleanup(fetchedEntry.get()); - showMergeDialog( - entry, - fetchedEntry.get(), - fetcher.get() - ); + showMergeDialog(entry, fetchedEntry.get(), fetcher.get()); } else { dialogService.notify( Localization.lang( @@ -121,13 +112,9 @@ public void fetchAndMerge(BibEntry entry, List fields) { "Fetching information using %0", fetcher.get().getName() ), - Localization.lang( - "No data was found for the identifier" - ) + Localization.lang("No data was found for the identifier") ); - } else if ( - exception instanceof FetcherServerException - ) { + } else if (exception instanceof FetcherServerException) { dialogService.showInformationDialogAndWait( Localization.lang( "Fetching information using %0", @@ -141,19 +128,14 @@ public void fetchAndMerge(BibEntry entry, List fields) { "Fetching information using %0", fetcher.get().getName() ), - Localization.lang( - "Error occurred %0", - exception.getMessage() - ) + Localization.lang("Error occurred %0", exception.getMessage()) ); } }) .executeWith(taskExecutor); } } else { - dialogService.notify( - Localization.lang("No %0 found", field.getDisplayName()) - ); + dialogService.notify(Localization.lang("No %0 found", field.getDisplayName())); } } } @@ -168,36 +150,22 @@ private void showMergeDialog( fetchedEntry, preferencesService ); - dialog.setTitle( - Localization.lang( - "Merge entry with %0 information", - fetcher.getName() - ) - ); + dialog.setTitle(Localization.lang("Merge entry with %0 information", fetcher.getName())); dialog.setLeftHeaderText(Localization.lang("Original entry")); - dialog.setRightHeaderText( - Localization.lang("Entry from %0", fetcher.getName()) - ); + dialog.setRightHeaderText(Localization.lang("Entry from %0", fetcher.getName())); Optional mergedEntry = dialogService .showCustomDialogAndWait(dialog) .map(EntriesMergeResult::mergedEntry); if (mergedEntry.isPresent()) { NamedCompound ce = new NamedCompound( - Localization.lang( - "Merge entry with %0 information", - fetcher.getName() - ) + Localization.lang("Merge entry with %0 information", fetcher.getName()) ); // Updated the original entry with the new fields - Set jointFields = new TreeSet<>( - Comparator.comparing(Field::getName) - ); + Set jointFields = new TreeSet<>(Comparator.comparing(Field::getName)); jointFields.addAll(mergedEntry.get().getFields()); - Set originalFields = new TreeSet<>( - Comparator.comparing(Field::getName) - ); + Set originalFields = new TreeSet<>(Comparator.comparing(Field::getName)); originalFields.addAll(originalEntry.getFields()); boolean edited = false; @@ -207,22 +175,15 @@ private void showMergeDialog( if (!oldType.equals(newType)) { originalEntry.setType(newType); - ce.addEdit( - new UndoableChangeType(originalEntry, oldType, newType) - ); + ce.addEdit(new UndoableChangeType(originalEntry, oldType, newType)); edited = true; } // fields for (Field field : jointFields) { Optional originalString = originalEntry.getField(field); - Optional mergedString = mergedEntry - .get() - .getField(field); - if ( - originalString.isEmpty() || - !originalString.equals(mergedString) - ) { + Optional mergedString = mergedEntry.get().getField(field); + if (originalString.isEmpty() || !originalString.equals(mergedString)) { originalEntry.setField(field, mergedString.get()); // mergedString always present ce.addEdit( new UndoableFieldChange( @@ -238,21 +199,11 @@ private void showMergeDialog( // Remove fields which are not in the merged entry, unless they are internal fields for (Field field : originalFields) { - if ( - !jointFields.contains(field) && - !FieldFactory.isInternalField(field) - ) { - Optional originalString = originalEntry.getField( - field - ); + if (!jointFields.contains(field) && !FieldFactory.isInternalField(field)) { + Optional originalString = originalEntry.getField(field); originalEntry.clearField(field); ce.addEdit( - new UndoableFieldChange( - originalEntry, - field, - originalString.get(), - null - ) + new UndoableFieldChange(originalEntry, field, originalString.get(), null) ); // originalString always present edited = true; } @@ -262,10 +213,7 @@ private void showMergeDialog( ce.end(); undoManager.addEdit(ce); dialogService.notify( - Localization.lang( - "Updated entry with info from %0", - fetcher.getName() - ) + Localization.lang("Updated entry with info from %0", fetcher.getName()) ); } else { dialogService.notify(Localization.lang("No information added")); @@ -280,30 +228,19 @@ public void fetchAndMerge(BibEntry entry, EntryBasedFetcher fetcher) { .wrap(() -> fetcher.performSearch(entry).stream().findFirst()) .onSuccess(fetchedEntry -> { if (fetchedEntry.isPresent()) { - ImportCleanup cleanup = ImportCleanup.targeting( - bibDatabaseContext.getMode() - ); + ImportCleanup cleanup = ImportCleanup.targeting(bibDatabaseContext.getMode()); cleanup.doPostCleanup(fetchedEntry.get()); showMergeDialog(entry, fetchedEntry.get(), fetcher); } else { dialogService.notify( - Localization.lang( - "Could not find any bibliographic information." - ) + Localization.lang("Could not find any bibliographic information.") ); } }) .onFailure(exception -> { - LOGGER.error( - "Error while fetching entry with {} ", - fetcher.getName(), - exception - ); + LOGGER.error("Error while fetching entry with {} ", fetcher.getName(), exception); dialogService.showErrorDialogAndWait( - Localization.lang( - "Error while fetching from %0", - fetcher.getName() - ), + Localization.lang("Error while fetching from %0", fetcher.getName()), exception ); }) diff --git a/src/main/java/org/jabref/gui/mergeentries/MergeEntriesAction.java b/src/main/java/org/jabref/gui/mergeentries/MergeEntriesAction.java index c2983cfe004..7411d249a03 100644 --- a/src/main/java/org/jabref/gui/mergeentries/MergeEntriesAction.java +++ b/src/main/java/org/jabref/gui/mergeentries/MergeEntriesAction.java @@ -29,10 +29,7 @@ public MergeEntriesAction( this.preferencesService = preferencesService; this.executable.bind( - ActionHelper.needsEntriesSelected( - NUMBER_OF_ENTRIES_NEEDED, - stateManager - ) + ActionHelper.needsEntriesSelected(NUMBER_OF_ENTRIES_NEEDED, stateManager) ); } @@ -48,9 +45,7 @@ public void execute() { // Inform the user to select entries first. dialogService.showInformationDialogAndWait( Localization.lang("Merge entries"), - Localization.lang( - "You have to choose exactly two entries to merge." - ) + Localization.lang("You have to choose exactly two entries to merge.") ); return; } @@ -75,26 +70,17 @@ public void execute() { second = one; } - MergeEntriesDialog dialog = new MergeEntriesDialog( - first, - second, - preferencesService - ); + MergeEntriesDialog dialog = new MergeEntriesDialog(first, second, preferencesService); dialog.setTitle(Localization.lang("Merge entries")); - Optional mergeResultOpt = - dialogService.showCustomDialogAndWait(dialog); + Optional mergeResultOpt = dialogService.showCustomDialogAndWait(dialog); mergeResultOpt.ifPresentOrElse( entriesMergeResult -> { - new MergeTwoEntriesAction(entriesMergeResult, stateManager) - .execute(); + new MergeTwoEntriesAction(entriesMergeResult, stateManager).execute(); dialogService.notify(Localization.lang("Merged entries")); }, - () -> - dialogService.notify( - Localization.lang("Canceled merging entries") - ) + () -> dialogService.notify(Localization.lang("Canceled merging entries")) ); } } diff --git a/src/main/java/org/jabref/gui/mergeentries/MergeEntriesDialog.java b/src/main/java/org/jabref/gui/mergeentries/MergeEntriesDialog.java index dc4a1791641..d7c28e5f103 100644 --- a/src/main/java/org/jabref/gui/mergeentries/MergeEntriesDialog.java +++ b/src/main/java/org/jabref/gui/mergeentries/MergeEntriesDialog.java @@ -15,11 +15,7 @@ public class MergeEntriesDialog extends BaseDialog { private final BibEntry one; private final BibEntry two; - public MergeEntriesDialog( - BibEntry one, - BibEntry two, - PreferencesService preferencesService - ) { + public MergeEntriesDialog(BibEntry one, BibEntry two, PreferencesService preferencesService) { threeWayMergeView = new ThreeWayMergeView(one, two, preferencesService); this.one = one; this.two = two; @@ -41,9 +37,7 @@ private void init() { Localization.lang("Merge entries"), ButtonBar.ButtonData.OK_DONE ); - this.getDialogPane() - .getButtonTypes() - .setAll(ButtonType.CANCEL, replaceEntries); + this.getDialogPane().getButtonTypes().setAll(ButtonType.CANCEL, replaceEntries); this.setResultConverter(buttonType -> { threeWayMergeView.saveConfiguration(); if (buttonType.equals(replaceEntries)) { diff --git a/src/main/java/org/jabref/gui/mergeentries/MergeResult.java b/src/main/java/org/jabref/gui/mergeentries/MergeResult.java index cffe2ac2f2f..a91af4d0083 100644 --- a/src/main/java/org/jabref/gui/mergeentries/MergeResult.java +++ b/src/main/java/org/jabref/gui/mergeentries/MergeResult.java @@ -2,8 +2,4 @@ import org.jabref.model.entry.BibEntry; -public record MergeResult( - BibEntry leftEntry, - BibEntry rightEntry, - BibEntry mergedEntry -) {} +public record MergeResult(BibEntry leftEntry, BibEntry rightEntry, BibEntry mergedEntry) {} diff --git a/src/main/java/org/jabref/gui/mergeentries/MergeTwoEntriesAction.java b/src/main/java/org/jabref/gui/mergeentries/MergeTwoEntriesAction.java index 4f5e3ef3e98..02980acab95 100644 --- a/src/main/java/org/jabref/gui/mergeentries/MergeTwoEntriesAction.java +++ b/src/main/java/org/jabref/gui/mergeentries/MergeTwoEntriesAction.java @@ -17,10 +17,7 @@ public class MergeTwoEntriesAction extends SimpleCommand { private final EntriesMergeResult entriesMergeResult; private final StateManager stateManager; - public MergeTwoEntriesAction( - EntriesMergeResult entriesMergeResult, - StateManager stateManager - ) { + public MergeTwoEntriesAction(EntriesMergeResult entriesMergeResult, StateManager stateManager) { this.entriesMergeResult = entriesMergeResult; this.stateManager = stateManager; } @@ -31,10 +28,7 @@ public void execute() { return; } - BibDatabase database = stateManager - .getActiveDatabase() - .get() - .getDatabase(); + BibDatabase database = stateManager.getActiveDatabase().get().getDatabase(); List entriesToRemove = Arrays.asList( entriesMergeResult.originalLeftEntry(), entriesMergeResult.originalRightEntry() @@ -43,9 +37,7 @@ public void execute() { database.insertEntry(entriesMergeResult.mergedEntry()); database.removeEntries(entriesToRemove); - NamedCompound ce = new NamedCompound( - Localization.lang("Merge entries") - ); + NamedCompound ce = new NamedCompound(Localization.lang("Merge entries")); ce.addEdit( new UndoableInsertEntries( stateManager.getActiveDatabase().get().getDatabase(), diff --git a/src/main/java/org/jabref/gui/mergeentries/MergeWithFetchedEntryAction.java b/src/main/java/org/jabref/gui/mergeentries/MergeWithFetchedEntryAction.java index 16e5ac7a47d..da2260f6fe5 100644 --- a/src/main/java/org/jabref/gui/mergeentries/MergeWithFetchedEntryAction.java +++ b/src/main/java/org/jabref/gui/mergeentries/MergeWithFetchedEntryAction.java @@ -55,16 +55,10 @@ public void execute() { dialogService.showInformationDialogAndWait( Localization.lang( "Merge entry with %0 information", - new OrFields( - StandardField.DOI, - StandardField.ISBN, - StandardField.EPRINT - ) + new OrFields(StandardField.DOI, StandardField.ISBN, StandardField.EPRINT) .getDisplayName() ), - Localization.lang( - "This operation requires exactly one item to be selected." - ) + Localization.lang("This operation requires exactly one item to be selected.") ); } diff --git a/src/main/java/org/jabref/gui/mergeentries/MultiMergeEntriesView.java b/src/main/java/org/jabref/gui/mergeentries/MultiMergeEntriesView.java index 383975af6ca..e1905f3e7e8 100644 --- a/src/main/java/org/jabref/gui/mergeentries/MultiMergeEntriesView.java +++ b/src/main/java/org/jabref/gui/mergeentries/MultiMergeEntriesView.java @@ -55,9 +55,7 @@ public class MultiMergeEntriesView extends BaseDialog { - private static final Logger LOGGER = LoggerFactory.getLogger( - MultiMergeEntriesView.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(MultiMergeEntriesView.class); // LEFT @FXML @@ -100,10 +98,7 @@ public class MultiMergeEntriesView extends BaseDialog { private final PreferencesService preferences; - public MultiMergeEntriesView( - PreferencesService preferences, - TaskExecutor taskExecutor - ) { + public MultiMergeEntriesView(PreferencesService preferences, TaskExecutor taskExecutor) { this.preferences = preferences; this.taskExecutor = taskExecutor; @@ -115,17 +110,13 @@ public MultiMergeEntriesView( Localization.lang("Merge entries"), ButtonBar.ButtonData.OK_DONE ); - this.getDialogPane() - .getButtonTypes() - .setAll(ButtonType.CANCEL, mergeEntries); + this.getDialogPane().getButtonTypes().setAll(ButtonType.CANCEL, mergeEntries); this.setResultConverter(viewModel::resultConverter); viewModel .entriesProperty() .addListener( - (ListChangeListener< - MultiMergeEntriesViewModel.EntrySource - >) c -> { + (ListChangeListener) c -> { while (c.next()) { if (c.wasAdded()) { for (MultiMergeEntriesViewModel.EntrySource entrySourceColumn : c.getAddedSubList()) { @@ -142,18 +133,10 @@ public MultiMergeEntriesView( .getFieldsObservable() .addListener( (MapChangeListener) change -> { - if ( - change.wasAdded() && - !fieldRows.containsKey(change.getKey()) - ) { + if (change.wasAdded() && !fieldRows.containsKey(change.getKey())) { FieldRow fieldRow = new FieldRow( change.getKey(), - viewModel - .mergedEntryProperty() - .get() - .getFields() - .size() - - 1 + viewModel.mergedEntryProperty().get().getFields().size() - 1 ); fieldRows.put(change.getKey(), fieldRow); } @@ -163,15 +146,9 @@ public MultiMergeEntriesView( @FXML public void initialize() { - topScrollPane - .hvalueProperty() - .bindBidirectional(centerScrollPane.hvalueProperty()); - leftScrollPane - .vvalueProperty() - .bindBidirectional(centerScrollPane.vvalueProperty()); - rightScrollPane - .vvalueProperty() - .bindBidirectional(centerScrollPane.vvalueProperty()); + topScrollPane.hvalueProperty().bindBidirectional(centerScrollPane.hvalueProperty()); + leftScrollPane.vvalueProperty().bindBidirectional(centerScrollPane.vvalueProperty()); + rightScrollPane.vvalueProperty().bindBidirectional(centerScrollPane.vvalueProperty()); viewModel .failedSuppliersProperty() @@ -181,10 +158,7 @@ public void initialize() { ? "" : Localization.lang( "Could not extract Metadata from: %0", - String.join( - ", ", - viewModel.failedSuppliersProperty() - ) + String.join(", ", viewModel.failedSuppliersProperty()) ) ) ); @@ -194,9 +168,7 @@ public void initialize() { private void fillDiffModes() { diffMode.setItems( - FXCollections.observableList( - List.of(DiffMode.PLAIN, DiffMode.WORD, DiffMode.CHARACTER) - ) + FXCollections.observableList(List.of(DiffMode.PLAIN, DiffMode.WORD, DiffMode.CHARACTER)) ); new ViewModelListCellFactory() .withText(DiffMode::getDisplayText) @@ -208,15 +180,10 @@ private void fillDiffModes() { ); } - private void addColumn( - MultiMergeEntriesViewModel.EntrySource entrySourceColumn - ) { + private void addColumn(MultiMergeEntriesViewModel.EntrySource entrySourceColumn) { // add header int columnIndex = supplierHeader.getChildren().size(); - ToggleButton header = generateEntryHeader( - entrySourceColumn, - columnIndex - ); + ToggleButton header = generateEntryHeader(entrySourceColumn, columnIndex); header.getStyleClass().add("toggle-button"); HBox.setHgrow(header, Priority.ALWAYS); supplierHeader.getChildren().add(header); @@ -236,10 +203,7 @@ private void addColumn( entrySourceColumn .isLoadingProperty() .addListener((observable, oldValue, newValue) -> { - if ( - !newValue && - entrySourceColumn.entryProperty().get() != null - ) { + if (!newValue && entrySourceColumn.entryProperty().get() != null) { writeBibEntryToColumn(entrySourceColumn, columnIndex); header.setDisable(false); } @@ -262,9 +226,7 @@ private ToggleButton generateEntryHeader( progressIndicator.setMinHeight(Control.USE_PREF_SIZE); progressIndicator.setMaxHeight(Control.USE_PREF_SIZE); header.setGraphic(progressIndicator); - progressIndicator - .visibleProperty() - .bind(column.isLoadingProperty()); + progressIndicator.visibleProperty().bind(column.isLoadingProperty()); } column @@ -312,10 +274,7 @@ private void writeBibEntryToColumn( * @param sourceButton the header button to setup * @param column the column this button is heading */ - private void setupSourceButtonAction( - ToggleButton sourceButton, - int column - ) { + private void setupSourceButtonAction(ToggleButton sourceButton, int column) { sourceButton .selectedProperty() .addListener((observable, oldValue, newValue) -> { @@ -330,9 +289,7 @@ private void setupSourceButtonAction( .stream() .filter(ToggleButton.class::isInstance) .forEach(toggleButton -> - ((ToggleButton) toggleButton).setSelected( - true - ) + ((ToggleButton) toggleButton).setSelected(true) ) ); sourceButton.setSelected(true); @@ -371,19 +328,11 @@ public Cell(String content, Field field, int columnIndex) { FieldRow row = fieldRows.get(field); prefWidthProperty() - .bind( - ((Region) supplierHeader - .getChildren() - .get(columnIndex)).widthProperty() - ); + .bind(((Region) supplierHeader.getChildren().get(columnIndex)).widthProperty()); setMinWidth(Control.USE_PREF_SIZE); setMaxWidth(Control.USE_PREF_SIZE); prefHeightProperty() - .bind( - ((Region) fieldEditor - .getChildren() - .get(row.rowIndex)).heightProperty() - ); + .bind(((Region) fieldEditor.getChildren().get(row.rowIndex)).heightProperty()); setMinHeight(Control.USE_PREF_SIZE); setMaxHeight(Control.USE_PREF_SIZE); @@ -401,11 +350,7 @@ public Cell(String content, Field field, int columnIndex) { DiffHighlightingEllipsingTextFlow buttonText = new DiffHighlightingEllipsingTextFlow( content, - viewModel - .mergedEntryProperty() - .get() - .getFieldBinding(field) - .asOrdinary(), + viewModel.mergedEntryProperty().get().getFieldBinding(field).asOrdinary(), diffMode.valueProperty() ); @@ -428,12 +373,9 @@ public Cell(String content, Field field, int columnIndex) { } if (field.equals(StandardField.DOI)) { - Button doiButton = - IconTheme.JabRefIcons.LOOKUP_IDENTIFIER.asButton(); + Button doiButton = IconTheme.JabRefIcons.LOOKUP_IDENTIFIER.asButton(); HBox.setHgrow(doiButton, Priority.NEVER); - doiButton - .prefHeightProperty() - .bind(cellButton.heightProperty()); + doiButton.prefHeightProperty().bind(cellButton.heightProperty()); doiButton.setMinHeight(Control.USE_PREF_SIZE); doiButton.setMaxHeight(Control.USE_PREF_SIZE); @@ -448,17 +390,9 @@ public Cell(String content, Field field, int columnIndex) { Localization.lang("From DOI"), () -> { try { - return doiFetcher - .performSearchById(content) - .get(); - } catch ( - FetcherException | NoSuchElementException e - ) { - LOGGER.warn( - "Failed to fetch BibEntry for DOI {}", - content, - e - ); + return doiFetcher.performSearchById(content).get(); + } catch (FetcherException | NoSuchElementException e) { + LOGGER.warn("Failed to fetch BibEntry for DOI {}", content, e); return null; } } @@ -474,18 +408,12 @@ public String getContent() { } public void addSource(String title, BibEntry entry) { - viewModel.addSource( - new MultiMergeEntriesViewModel.EntrySource(title, entry) - ); + viewModel.addSource(new MultiMergeEntriesViewModel.EntrySource(title, entry)); } public void addSource(String title, Supplier supplier) { viewModel.addSource( - new MultiMergeEntriesViewModel.EntrySource( - title, - supplier, - taskExecutor - ) + new MultiMergeEntriesViewModel.EntrySource(title, supplier, taskExecutor) ); } @@ -523,10 +451,7 @@ public FieldRow(Field field, int rowIndex) { .selectedToggleProperty() .addListener((obs, oldValue, newValue) -> { if (newValue == null) { - viewModel - .mergedEntryProperty() - .get() - .setField(field, ""); + viewModel.mergedEntryProperty().get().setField(field, ""); } else { viewModel .mergedEntryProperty() @@ -549,11 +474,7 @@ private void addRow(Field field) { VBox.setVgrow(fieldEditorCell, Priority.ALWAYS); fieldBinding = - viewModel - .mergedEntryProperty() - .get() - .getFieldBinding(field) - .asOrdinary(); + viewModel.mergedEntryProperty().get().getFieldBinding(field).asOrdinary(); BindingsHelper.bindBidirectional( fieldEditorCell.textProperty(), fieldBinding, @@ -564,10 +485,7 @@ private void addRow(Field field) { }, binding -> { if (binding != null) { - viewModel - .mergedEntryProperty() - .get() - .setField(field, binding); + viewModel.mergedEntryProperty().get().setField(field, binding); } } ); @@ -578,9 +496,7 @@ private void addRow(Field field) { // setup header label Label fieldHeaderLabel = new Label(field.getDisplayName()); - fieldHeaderLabel - .prefHeightProperty() - .bind(fieldEditorCell.heightProperty()); + fieldHeaderLabel.prefHeightProperty().bind(fieldEditorCell.heightProperty()); fieldHeaderLabel.setMaxWidth(Control.USE_PREF_SIZE); fieldHeaderLabel.setMinWidth(Control.USE_PREF_SIZE); fieldHeader.getChildren().add(fieldHeaderLabel); @@ -589,9 +505,7 @@ private void addRow(Field field) { RowConstraints constraint = new RowConstraints(); constraint.setMinHeight(Control.USE_PREF_SIZE); constraint.setMaxHeight(Control.USE_PREF_SIZE); - constraint - .prefHeightProperty() - .bind(fieldEditorCell.heightProperty()); + constraint.prefHeightProperty().bind(fieldEditorCell.heightProperty()); optionsGrid.getRowConstraints().add(constraint); } } diff --git a/src/main/java/org/jabref/gui/mergeentries/MultiMergeEntriesViewModel.java b/src/main/java/org/jabref/gui/mergeentries/MultiMergeEntriesViewModel.java index 27194ea7e66..f09523df67d 100644 --- a/src/main/java/org/jabref/gui/mergeentries/MultiMergeEntriesViewModel.java +++ b/src/main/java/org/jabref/gui/mergeentries/MultiMergeEntriesViewModel.java @@ -24,28 +24,24 @@ public class MultiMergeEntriesViewModel extends AbstractViewModel { FXCollections.observableArrayList() ); - private final ObjectProperty mergedEntry = - new SimpleObjectProperty<>(new BibEntry()); + private final ObjectProperty mergedEntry = new SimpleObjectProperty<>(new BibEntry()); - private final ListProperty failedSuppliers = - new SimpleListProperty<>(FXCollections.observableArrayList()); + private final ListProperty failedSuppliers = new SimpleListProperty<>( + FXCollections.observableArrayList() + ); public void addSource(EntrySource entrySource) { if (!entrySource.isLoading.getValue()) { updateFields(entrySource.entry.get()); } else { - entrySource.isLoading.addListener( - (observable, oldValue, newValue) -> { - if (!newValue) { - updateFields(entrySource.entry.get()); - if (entrySource.entryProperty().get() == null) { - failedSuppliers.add( - entrySource.titleProperty().get() - ); - } + entrySource.isLoading.addListener((observable, oldValue, newValue) -> { + if (!newValue) { + updateFields(entrySource.entry.get()); + if (entrySource.entryProperty().get() == null) { + failedSuppliers.add(entrySource.titleProperty().get()); } } - ); + }); } entries.add(entrySource); } @@ -54,19 +50,10 @@ public void updateFields(BibEntry entry) { if (entry == null) { return; } - for (Map.Entry fieldEntry : entry - .getFieldMap() - .entrySet()) { + for (Map.Entry fieldEntry : entry.getFieldMap().entrySet()) { // make sure there is a row for the field - if ( - !mergedEntry - .get() - .getFieldsObservable() - .containsKey(fieldEntry.getKey()) - ) { - mergedEntry - .get() - .setField(fieldEntry.getKey(), fieldEntry.getValue()); + if (!mergedEntry.get().getFieldsObservable().containsKey(fieldEntry.getKey())) { + mergedEntry.get().setField(fieldEntry.getKey(), fieldEntry.getValue()); } } } @@ -93,11 +80,8 @@ public ListProperty failedSuppliersProperty() { public static class EntrySource { private final StringProperty title = new SimpleStringProperty(""); - private final ObjectProperty entry = - new SimpleObjectProperty<>(); - private final BooleanProperty isLoading = new SimpleBooleanProperty( - false - ); + private final ObjectProperty entry = new SimpleObjectProperty<>(); + private final BooleanProperty isLoading = new SimpleBooleanProperty(false); public EntrySource( String title, diff --git a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/FieldRowView.java b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/FieldRowView.java index c9cd0a1cf6d..8077d93d871 100644 --- a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/FieldRowView.java +++ b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/FieldRowView.java @@ -28,15 +28,11 @@ */ public class FieldRowView { - private static final Logger LOGGER = LoggerFactory.getLogger( - FieldRowView.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(FieldRowView.class); protected final FieldRowViewModel viewModel; - protected final BooleanProperty shouldShowDiffs = new SimpleBooleanProperty( - true - ); + protected final BooleanProperty shouldShowDiffs = new SimpleBooleanProperty(true); private final FieldNameCell fieldNameCell; private final FieldValueCell leftValueCell; private final FieldValueCell rightValueCell; @@ -56,29 +52,14 @@ public FieldRowView( int rowIndex ) { viewModel = - new FieldRowViewModel( - field, - leftEntry, - rightEntry, - mergedEntry, - fieldMergerFactory - ); + new FieldRowViewModel(field, leftEntry, rightEntry, mergedEntry, fieldMergerFactory); fieldNameCell = new FieldNameCell(field.getDisplayName(), rowIndex); leftValueCell = - new FieldValueCell( - viewModel.getLeftFieldValue(), - rowIndex, - preferencesService - ); + new FieldValueCell(viewModel.getLeftFieldValue(), rowIndex, preferencesService); rightValueCell = - new FieldValueCell( - viewModel.getRightFieldValue(), - rowIndex, - preferencesService - ); - mergedValueCell = - new MergedFieldCell(viewModel.getMergedFieldValue(), rowIndex); + new FieldValueCell(viewModel.getRightFieldValue(), rowIndex, preferencesService); + mergedValueCell = new MergedFieldCell(viewModel.getMergedFieldValue(), rowIndex); // As a workaround we need to have a reference to the parent grid pane to be able to show/hide the row. // This won't be necessary when https://bugs.openjdk.org/browse/JDK-8136901 is fixed. @@ -91,25 +72,15 @@ public FieldRowView( }); if (FieldMergerFactory.canMerge(field)) { - ToggleMergeUnmergeButton toggleMergeUnmergeButton = - new ToggleMergeUnmergeButton(field); - toggleMergeUnmergeButton.setCanMerge( - !viewModel.hasEqualLeftAndRightValues() - ); + ToggleMergeUnmergeButton toggleMergeUnmergeButton = new ToggleMergeUnmergeButton(field); + toggleMergeUnmergeButton.setCanMerge(!viewModel.hasEqualLeftAndRightValues()); fieldNameCell.addSideButton(toggleMergeUnmergeButton); EasyBind.listen( toggleMergeUnmergeButton.fieldStateProperty(), ((observableValue, old, fieldState) -> { - LOGGER.debug( - "Field merge state is {} for field {}", - fieldState, - field - ); - if ( - fieldState == - ToggleMergeUnmergeButton.FieldState.MERGED - ) { + LOGGER.debug("Field merge state is {} for field {}", fieldState, field); + if (fieldState == ToggleMergeUnmergeButton.FieldState.MERGED) { viewModel.mergeFields(); } else { viewModel.unmergeFields(); @@ -120,15 +91,9 @@ public FieldRowView( toggleGroup.getToggles().addAll(leftValueCell, rightValueCell); - mergedValueCell - .textProperty() - .bindBidirectional(viewModel.mergedFieldValueProperty()); - leftValueCell - .textProperty() - .bindBidirectional(viewModel.leftFieldValueProperty()); - rightValueCell - .textProperty() - .bindBidirectional(viewModel.rightFieldValueProperty()); + mergedValueCell.textProperty().bindBidirectional(viewModel.mergedFieldValueProperty()); + leftValueCell.textProperty().bindBidirectional(viewModel.leftFieldValueProperty()); + rightValueCell.textProperty().bindBidirectional(viewModel.rightFieldValueProperty()); EasyBind.subscribe( viewModel.selectionProperty(), @@ -235,9 +200,7 @@ public void showDiff(ShowDiffConfig diffConfig) { // Clearing old diff styles based on previous diffConfig hideDiff(); if (shouldShowDiffs.get()) { - if ( - diffConfig.diffView() == ThreeWayMergeToolbar.DiffView.UNIFIED - ) { + if (diffConfig.diffView() == ThreeWayMergeToolbar.DiffView.UNIFIED) { new UnifiedDiffHighlighter( leftLabel, rightLabel, @@ -245,11 +208,7 @@ public void showDiff(ShowDiffConfig diffConfig) { ) .highlight(); } else { - new SplitDiffHighlighter( - leftLabel, - rightLabel, - diffConfig.diffHighlightingMethod() - ) + new SplitDiffHighlighter(leftLabel, rightLabel, diffConfig.diffHighlightingMethod()) .highlight(); } } @@ -259,12 +218,7 @@ public void hide() { if (parent != null) { parent .getChildren() - .removeAll( - leftValueCell, - rightValueCell, - mergedValueCell, - fieldNameCell - ); + .removeAll(leftValueCell, rightValueCell, mergedValueCell, fieldNameCell); } } @@ -273,12 +227,7 @@ public void show() { if (!parent.getChildren().contains(leftValueCell)) { parent .getChildren() - .addAll( - leftValueCell, - rightValueCell, - mergedValueCell, - fieldNameCell - ); + .addAll(leftValueCell, rightValueCell, mergedValueCell, fieldNameCell); } } } @@ -290,25 +239,13 @@ public void hideDiff() { LOGGER.debug("Hiding diffs..."); - int leftValueLength = getLeftValueCell() - .getStyleClassedLabel() - .getLength(); - getLeftValueCell() - .getStyleClassedLabel() - .clearStyle(0, leftValueLength); - getLeftValueCell() - .getStyleClassedLabel() - .replaceText(viewModel.getLeftFieldValue()); - - int rightValueLength = getRightValueCell() - .getStyleClassedLabel() - .getLength(); - getRightValueCell() - .getStyleClassedLabel() - .clearStyle(0, rightValueLength); - getRightValueCell() - .getStyleClassedLabel() - .replaceText(viewModel.getRightFieldValue()); + int leftValueLength = getLeftValueCell().getStyleClassedLabel().getLength(); + getLeftValueCell().getStyleClassedLabel().clearStyle(0, leftValueLength); + getLeftValueCell().getStyleClassedLabel().replaceText(viewModel.getLeftFieldValue()); + + int rightValueLength = getRightValueCell().getStyleClassedLabel().getLength(); + getRightValueCell().getStyleClassedLabel().clearStyle(0, rightValueLength); + getRightValueCell().getStyleClassedLabel().replaceText(viewModel.getRightFieldValue()); } public boolean hasEqualLeftAndRightValues() { diff --git a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/FieldRowViewModel.java b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/FieldRowViewModel.java index f110ad89f40..296bc2b05fd 100644 --- a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/FieldRowViewModel.java +++ b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/FieldRowViewModel.java @@ -35,21 +35,14 @@ public enum Selection { NONE, } - private final Logger LOGGER = LoggerFactory.getLogger( - FieldRowViewModel.class - ); - private final BooleanProperty isFieldsMerged = new SimpleBooleanProperty( - Boolean.FALSE - ); + private final Logger LOGGER = LoggerFactory.getLogger(FieldRowViewModel.class); + private final BooleanProperty isFieldsMerged = new SimpleBooleanProperty(Boolean.FALSE); - private final ObjectProperty selection = - new SimpleObjectProperty<>(); + private final ObjectProperty selection = new SimpleObjectProperty<>(); private final StringProperty leftFieldValue = new SimpleStringProperty(""); private final StringProperty rightFieldValue = new SimpleStringProperty(""); - private final StringProperty mergedFieldValue = new SimpleStringProperty( - "" - ); + private final StringProperty mergedFieldValue = new SimpleStringProperty(""); private final Field field; @@ -98,8 +91,7 @@ public FieldRowViewModel( mergedFieldValueProperty(), (obs, old, mergedFieldValue) -> { if (field.equals(InternalField.TYPE_HEADER)) { - getMergedEntry() - .setType(EntryTypeFactory.parse(mergedFieldValue)); + getMergedEntry().setType(EntryTypeFactory.parse(mergedFieldValue)); } else { getMergedEntry().setField(field, mergedFieldValue); } @@ -130,11 +122,7 @@ public FieldRowViewModel( EasyBind.subscribe( selectionProperty(), selection -> { - LOGGER.debug( - "Selecting {}' value for field {}", - selection, - field.getDisplayName() - ); + LOGGER.debug("Selecting {}' value for field {}", selection, field.getDisplayName()); switch (selection) { case LEFT -> EasyBind.subscribe( leftFieldValueProperty(), @@ -166,10 +154,7 @@ public FieldRowViewModel( } ); - EasyBind.subscribe( - hasEqualLeftAndRightBinding(), - this::setIsFieldsMerged - ); + EasyBind.subscribe(hasEqualLeftAndRightBinding(), this::setIsFieldsMerged); } public void selectNonEmptyValue() { @@ -223,10 +208,7 @@ public void mergeFields() { String oldRightFieldValue = getRightFieldValue(); FieldMerger fieldMerger = fieldMergerFactory.create(field); - String mergedFields = fieldMerger.merge( - getLeftFieldValue(), - getRightFieldValue() - ); + String mergedFields = fieldMerger.merge(getLeftFieldValue(), getRightFieldValue()); setLeftFieldValue(mergedFields); setRightFieldValue(mergedFields); @@ -234,11 +216,7 @@ public void mergeFields() { fieldsMergedEdit.redo(); } else { fieldsMergedEdit.addEdit( - new MergeFieldsUndo( - oldLeftFieldValue, - oldRightFieldValue, - mergedFields - ) + new MergeFieldsUndo(oldLeftFieldValue, oldRightFieldValue, mergedFields) ); fieldsMergedEdit.end(); } diff --git a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/PersonsNameFieldRowView.java b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/PersonsNameFieldRowView.java index b743eb728cc..47329a801ee 100644 --- a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/PersonsNameFieldRowView.java +++ b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/PersonsNameFieldRowView.java @@ -39,10 +39,7 @@ public PersonsNameFieldRowView( leftEntryNames = authorsParser.parse(viewModel.getLeftFieldValue()); rightEntryNames = authorsParser.parse(viewModel.getRightFieldValue()); - if ( - !viewModel.hasEqualLeftAndRightValues() && - leftEntryNames.equals(rightEntryNames) - ) { + if (!viewModel.hasEqualLeftAndRightValues() && leftEntryNames.equals(rightEntryNames)) { showPersonsNamesAreTheSameInfo(); shouldShowDiffs.set(false); } diff --git a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/ShowDiffConfig.java b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/ShowDiffConfig.java index 16ba4e818d4..5f70ac0db73 100644 --- a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/ShowDiffConfig.java +++ b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/ShowDiffConfig.java @@ -2,7 +2,4 @@ import org.jabref.gui.mergeentries.newmergedialog.toolbar.ThreeWayMergeToolbar.DiffView; -public record ShowDiffConfig( - DiffView diffView, - DiffMethod diffHighlightingMethod -) {} +public record ShowDiffConfig(DiffView diffView, DiffMethod diffHighlightingMethod) {} diff --git a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/ThreeWayMergeHeaderView.java b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/ThreeWayMergeHeaderView.java index 2f8a6d661c5..a911d8bf052 100644 --- a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/ThreeWayMergeHeaderView.java +++ b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/ThreeWayMergeHeaderView.java @@ -23,16 +23,9 @@ public ThreeWayMergeHeaderView(String leftHeader, String rightHeader) { this.leftHeaderCell = new HeaderCell(leftHeader); this.rightHeaderCell = new HeaderCell(rightHeader); - this.mergedHeaderCell = - new HeaderCell(Localization.lang("Merged Entry")); - - addRow( - 0, - new HeaderCell(""), - leftHeaderCell, - rightHeaderCell, - mergedHeaderCell - ); + this.mergedHeaderCell = new HeaderCell(Localization.lang("Merged Entry")); + + addRow(0, new HeaderCell(""), leftHeaderCell, rightHeaderCell, mergedHeaderCell); setPrefHeight(Control.USE_COMPUTED_SIZE); setMaxHeight(Control.USE_PREF_SIZE); diff --git a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/ThreeWayMergeView.java b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/ThreeWayMergeView.java index a3d0289e55b..bf3105d1bb2 100644 --- a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/ThreeWayMergeView.java +++ b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/ThreeWayMergeView.java @@ -21,21 +21,25 @@ public class ThreeWayMergeView extends VBox { public static final int GRID_COLUMN_MIN_WIDTH = 250; - public static final String LEFT_DEFAULT_HEADER = Localization.lang( - "Left Entry" + public static final String LEFT_DEFAULT_HEADER = Localization.lang("Left Entry"); + public static final String RIGHT_DEFAULT_HEADER = Localization.lang("Right Entry"); + + private final ColumnConstraints fieldNameColumnConstraints = new ColumnConstraints(150); + private final ColumnConstraints leftEntryColumnConstraints = new ColumnConstraints( + GRID_COLUMN_MIN_WIDTH, + 256, + Double.MAX_VALUE ); - public static final String RIGHT_DEFAULT_HEADER = Localization.lang( - "Right Entry" + private final ColumnConstraints rightEntryColumnConstraints = new ColumnConstraints( + GRID_COLUMN_MIN_WIDTH, + 256, + Double.MAX_VALUE + ); + private final ColumnConstraints mergedEntryColumnConstraints = new ColumnConstraints( + GRID_COLUMN_MIN_WIDTH, + 256, + Double.MAX_VALUE ); - - private final ColumnConstraints fieldNameColumnConstraints = - new ColumnConstraints(150); - private final ColumnConstraints leftEntryColumnConstraints = - new ColumnConstraints(GRID_COLUMN_MIN_WIDTH, 256, Double.MAX_VALUE); - private final ColumnConstraints rightEntryColumnConstraints = - new ColumnConstraints(GRID_COLUMN_MIN_WIDTH, 256, Double.MAX_VALUE); - private final ColumnConstraints mergedEntryColumnConstraints = - new ColumnConstraints(GRID_COLUMN_MIN_WIDTH, 256, Double.MAX_VALUE); private final ThreeWayMergeToolbar toolbar; private final ThreeWayMergeHeaderView headerView; private final ScrollPane scrollPane; @@ -59,10 +63,7 @@ public ThreeWayMergeView( this.preferencesService = preferencesService; getStylesheets() - .add( - ThreeWayMergeView.class.getResource("ThreeWayMergeView.css") - .toExternalForm() - ); + .add(ThreeWayMergeView.class.getResource("ThreeWayMergeView.css").toExternalForm()); viewModel = new ThreeWayMergeViewModel( (BibEntry) leftEntry.clone(), @@ -73,10 +74,7 @@ public ThreeWayMergeView( this.fieldMergerFactory = new FieldMergerFactory(preferencesService.getBibEntryPreferences()); this.keywordSeparator = - preferencesService - .getBibEntryPreferences() - .getKeywordSeparator() - .toString(); + preferencesService.getBibEntryPreferences().getKeywordSeparator().toString(); mergeGridPane = new GridPane(); scrollPane = new ScrollPane(); @@ -100,29 +98,17 @@ public ThreeWayMergeView( BibEntry rightEntry, PreferencesService preferencesService ) { - this( - leftEntry, - rightEntry, - LEFT_DEFAULT_HEADER, - RIGHT_DEFAULT_HEADER, - preferencesService - ); + this(leftEntry, rightEntry, LEFT_DEFAULT_HEADER, RIGHT_DEFAULT_HEADER, preferencesService); } private void initializeToolbar() { - toolbar.setOnSelectLeftEntryValuesButtonClicked( - this::selectLeftEntryValues - ); - toolbar.setOnSelectRightEntryValuesButtonClicked( - this::selectRightEntryValues - ); + toolbar.setOnSelectLeftEntryValuesButtonClicked(this::selectLeftEntryValues); + toolbar.setOnSelectRightEntryValuesButtonClicked(this::selectRightEntryValues); toolbar.showDiffProperty().addListener(e -> updateDiff()); toolbar.diffViewProperty().addListener(e -> updateDiff()); toolbar.diffHighlightingMethodProperty().addListener(e -> updateDiff()); - toolbar - .hideEqualFieldsProperty() - .addListener(e -> showOrHideEqualFields()); + toolbar.hideEqualFieldsProperty().addListener(e -> showOrHideEqualFields()); updateDiff(); showOrHideEqualFields(); @@ -145,14 +131,8 @@ private void updateDiff() { for (FieldRowView row : fieldRows) { if ( "Groups".equals(row.getFieldNameCell().getText()) && - (row - .getLeftValueCell() - .getText() - .contains(keywordSeparator) || - row - .getRightValueCell() - .getText() - .contains(keywordSeparator)) + (row.getLeftValueCell().getText().contains(keywordSeparator) || + row.getRightValueCell().getText().contains(keywordSeparator)) ) { row.showDiff( new ShowDiffConfig( @@ -208,11 +188,7 @@ private void initializeMergeGridPane() { mergedEntryColumnConstraints ); - for ( - int fieldIndex = 0; - fieldIndex < viewModel.numberOfVisibleFields(); - fieldIndex++ - ) { + for (int fieldIndex = 0; fieldIndex < viewModel.numberOfVisibleFields(); fieldIndex++) { addRow(fieldIndex); mergeGridPane.getRowConstraints().add(new RowConstraints()); diff --git a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/ThreeWayMergeViewModel.java b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/ThreeWayMergeViewModel.java index 76d2f5119e6..e7d102fd551 100644 --- a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/ThreeWayMergeViewModel.java +++ b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/ThreeWayMergeViewModel.java @@ -19,17 +19,13 @@ public class ThreeWayMergeViewModel extends AbstractViewModel { - private final ObjectProperty leftEntry = - new SimpleObjectProperty<>(); - private final ObjectProperty rightEntry = - new SimpleObjectProperty<>(); - private final ObjectProperty mergedEntry = - new SimpleObjectProperty<>(); + private final ObjectProperty leftEntry = new SimpleObjectProperty<>(); + private final ObjectProperty rightEntry = new SimpleObjectProperty<>(); + private final ObjectProperty mergedEntry = new SimpleObjectProperty<>(); private final StringProperty leftHeader = new SimpleStringProperty(); private final StringProperty rightHeader = new SimpleStringProperty(); - private final ObservableList visibleFields = - FXCollections.observableArrayList(); + private final ObservableList visibleFields = FXCollections.observableArrayList(); public ThreeWayMergeViewModel( BibEntry leftEntry, @@ -51,10 +47,7 @@ public ThreeWayMergeViewModel( setVisibleFields( Stream - .concat( - leftEntry.getFields().stream(), - rightEntry.getFields().stream() - ) + .concat(leftEntry.getFields().stream(), rightEntry.getFields().stream()) .collect(Collectors.toSet()) ); } diff --git a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/CopyFieldValueCommand.java b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/CopyFieldValueCommand.java index a9e4b43b5cf..936d1bc5999 100644 --- a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/CopyFieldValueCommand.java +++ b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/CopyFieldValueCommand.java @@ -10,10 +10,7 @@ public class CopyFieldValueCommand extends SimpleCommand { private final String fieldValue; private final ClipBoardManager clipBoardManager; - public CopyFieldValueCommand( - PreferencesService preferencesService, - final String fieldValue - ) { + public CopyFieldValueCommand(PreferencesService preferencesService, final String fieldValue) { Objects.requireNonNull(fieldValue, "Field value cannot be null"); this.fieldValue = fieldValue; this.clipBoardManager = new ClipBoardManager(preferencesService); diff --git a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/FieldValueCell.java b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/FieldValueCell.java index 55e574f4ce3..1b7cd1f23a1 100644 --- a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/FieldValueCell.java +++ b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/FieldValueCell.java @@ -39,15 +39,12 @@ */ public class FieldValueCell extends ThreeWayMergeCell implements Toggle { - public static final Logger LOGGER = LoggerFactory.getLogger( - FieldValueCell.class - ); + public static final Logger LOGGER = LoggerFactory.getLogger(FieldValueCell.class); public static final String DEFAULT_STYLE_CLASS = "merge-field-value"; public static final String SELECTION_BOX_STYLE_CLASS = "selection-box"; - private static final PseudoClass SELECTED_PSEUDO_CLASS = - PseudoClass.getPseudoClass("selected"); + private static final PseudoClass SELECTED_PSEUDO_CLASS = PseudoClass.getPseudoClass("selected"); private final PreferencesService preferencesService; @@ -62,11 +59,7 @@ public class FieldValueCell extends ThreeWayMergeCell implements Toggle { private final HBox actionsContainer = new HBox(); private final FieldValueCellViewModel viewModel; - public FieldValueCell( - String text, - int rowIndex, - PreferencesService preferencesService - ) { + public FieldValueCell(String text, int rowIndex, PreferencesService preferencesService) { super(text, rowIndex); this.preferencesService = preferencesService; this.factory = new ActionFactory(Globals.getKeyPrefs()); @@ -112,26 +105,20 @@ private void initializeLabel() { // Workarounds preventTextSelectionViaMouseEvents(); - label - .prefHeightProperty() - .bind(label.totalHeightEstimateProperty().orElseConst(-1d)); + label.prefHeightProperty().bind(label.totalHeightEstimateProperty().orElseConst(-1d)); // Fix text area consuming scroll events before they reach the outer scrollable label.addEventFilter( ScrollEvent.SCROLL, e -> { e.consume(); - FieldValueCell.this.fireEvent( - e.copyFor(e.getSource(), FieldValueCell.this) - ); + FieldValueCell.this.fireEvent(e.copyFor(e.getSource(), FieldValueCell.this)); } ); } private void initializeActions() { - actionsContainer - .getChildren() - .setAll(createOpenLinkButton(), createCopyButton()); + actionsContainer.getChildren().setAll(createOpenLinkButton(), createCopyButton()); actionsContainer.setAlignment(Pos.TOP_CENTER); actionsContainer.setPrefWidth(28); } @@ -167,10 +154,7 @@ public Button createOpenLinkButton() { Button openLinkButton = factory.createIconButton( () -> Localization.lang("Open Link"), - new OpenExternalLinkAction( - getText(), - preferencesService.getFilePreferences() - ) + new OpenExternalLinkAction(getText(), preferencesService.getFilePreferences()) ); openLinkButton.setGraphic(openLinkIcon); openLinkButton.setContentDisplay(ContentDisplay.GRAPHIC_ONLY); @@ -182,8 +166,7 @@ public Button createOpenLinkButton() { EasyBind.map( textProperty(), input -> - StringUtil.isNotBlank(input) && - (URLUtil.isURL(input) || DOI.isValid(input)) + StringUtil.isNotBlank(input) && (URLUtil.isURL(input) || DOI.isValid(input)) ) ); diff --git a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/FieldValueCellViewModel.java b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/FieldValueCellViewModel.java index e95e6858bec..ba6e5c3641d 100644 --- a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/FieldValueCellViewModel.java +++ b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/FieldValueCellViewModel.java @@ -15,8 +15,7 @@ public class FieldValueCellViewModel { FieldValueCell.class, "selected" ); - private final ObjectProperty toggleGroup = - new SimpleObjectProperty<>(); + private final ObjectProperty toggleGroup = new SimpleObjectProperty<>(); public FieldValueCellViewModel(String text) { setFieldValue(text); diff --git a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/HeaderCell.java b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/HeaderCell.java index 84ff082fdba..79d467290a5 100644 --- a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/HeaderCell.java +++ b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/HeaderCell.java @@ -25,12 +25,7 @@ private void initialize() { private void initializeLabel() { label.textProperty().bind(textProperty()); label.setPadding( - new Insets( - getPadding().getTop(), - getPadding().getRight(), - getPadding().getBottom(), - 16 - ) + new Insets(getPadding().getTop(), getPadding().getRight(), getPadding().getBottom(), 16) ); } } diff --git a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/MergedFieldCell.java b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/MergedFieldCell.java index d2b52d0aff0..bd8afd083fb 100644 --- a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/MergedFieldCell.java +++ b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/MergedFieldCell.java @@ -43,9 +43,7 @@ private void initializeTextArea() { ScrollEvent.SCROLL, e -> { e.consume(); - MergedFieldCell.this.fireEvent( - e.copyFor(e.getSource(), MergedFieldCell.this) - ); + MergedFieldCell.this.fireEvent(e.copyFor(e.getSource(), MergedFieldCell.this)); } ); } diff --git a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/OpenExternalLinkAction.java b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/OpenExternalLinkAction.java index 96a95423588..d51d50f4b18 100644 --- a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/OpenExternalLinkAction.java +++ b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/OpenExternalLinkAction.java @@ -14,18 +14,13 @@ */ public class OpenExternalLinkAction extends SimpleCommand { - private final Logger LOGGER = LoggerFactory.getLogger( - OpenExternalLinkAction.class - ); + private final Logger LOGGER = LoggerFactory.getLogger(OpenExternalLinkAction.class); private final FilePreferences filePreferences; private final String urlOrDoi; - public OpenExternalLinkAction( - String urlOrDoi, - FilePreferences filePreferences - ) { + public OpenExternalLinkAction(String urlOrDoi, FilePreferences filePreferences) { this.filePreferences = filePreferences; this.urlOrDoi = urlOrDoi; } @@ -35,22 +30,14 @@ public void execute() { try { if (DOI.isValid(urlOrDoi)) { JabRefDesktop.openBrowser( - DOI - .parse(urlOrDoi) - .flatMap(DOI::getExternalURI) - .map(URI::toString) - .orElse(""), + DOI.parse(urlOrDoi).flatMap(DOI::getExternalURI).map(URI::toString).orElse(""), filePreferences ); } else { JabRefDesktop.openBrowser(urlOrDoi, filePreferences); } } catch (IOException e) { - LOGGER.warn( - "Cannot open the given external link '{}'", - urlOrDoi, - e - ); + LOGGER.warn("Cannot open the given external link '{}'", urlOrDoi, e); } } } diff --git a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/ThreeWayMergeCell.java b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/ThreeWayMergeCell.java index e4c63df6786..536b1c2a899 100644 --- a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/ThreeWayMergeCell.java +++ b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/ThreeWayMergeCell.java @@ -21,19 +21,13 @@ public ThreeWayMergeCell(String text, int rowIndex) { EasyBind.subscribe( viewModel.oddProperty(), isOdd -> { - pseudoClassStateChanged( - PseudoClass.getPseudoClass(ODD_PSEUDO_CLASS), - isOdd - ); + pseudoClassStateChanged(PseudoClass.getPseudoClass(ODD_PSEUDO_CLASS), isOdd); } ); EasyBind.subscribe( viewModel.evenProperty(), isEven -> { - pseudoClassStateChanged( - PseudoClass.getPseudoClass(EVEN_PSEUDO_CLASS), - isEven - ); + pseudoClassStateChanged(PseudoClass.getPseudoClass(EVEN_PSEUDO_CLASS), isEven); } ); } diff --git a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/ThreeWayMergeCellViewModel.java b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/ThreeWayMergeCellViewModel.java index fe59de87c13..ec5f80de399 100644 --- a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/ThreeWayMergeCellViewModel.java +++ b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/ThreeWayMergeCellViewModel.java @@ -11,14 +11,8 @@ public class ThreeWayMergeCellViewModel { private final StringProperty text = new SimpleStringProperty(); - private final BooleanProperty odd = new SimpleBooleanProperty( - ThreeWayMergeCell.class, - "odd" - ); - private final BooleanProperty even = new SimpleBooleanProperty( - ThreeWayMergeCell.class, - "even" - ); + private final BooleanProperty odd = new SimpleBooleanProperty(ThreeWayMergeCell.class, "odd"); + private final BooleanProperty even = new SimpleBooleanProperty(ThreeWayMergeCell.class, "even"); public ThreeWayMergeCellViewModel(String text, int rowIndex) { setText(text); diff --git a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/sidebuttons/InfoButton.java b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/sidebuttons/InfoButton.java index 9a6de68df6a..878a2966b74 100644 --- a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/sidebuttons/InfoButton.java +++ b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/sidebuttons/InfoButton.java @@ -15,9 +15,7 @@ public class InfoButton extends Button { private final StringProperty infoMessage = new SimpleStringProperty(); - private final ActionFactory actionFactory = new ActionFactory( - Globals.getKeyPrefs() - ); + private final ActionFactory actionFactory = new ActionFactory(Globals.getKeyPrefs()); private final Action mergeAction = new Action() { @Override @@ -34,10 +32,7 @@ public String getText() { public InfoButton(String infoMessage) { this.infoMessage.setValue(infoMessage); configureButton(); - EasyBind.subscribe( - this.infoMessage, - newWarningMessage -> configureButton() - ); + EasyBind.subscribe(this.infoMessage, newWarningMessage -> configureButton()); } private void configureButton() { diff --git a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/sidebuttons/ToggleMergeUnmergeButton.java b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/sidebuttons/ToggleMergeUnmergeButton.java index 0b985304d3e..4f2c719a38b 100644 --- a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/sidebuttons/ToggleMergeUnmergeButton.java +++ b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/cell/sidebuttons/ToggleMergeUnmergeButton.java @@ -17,15 +17,12 @@ public class ToggleMergeUnmergeButton extends Button { - private final ObjectProperty fieldState = - new SimpleObjectProperty<>(FieldState.UNMERGED); - private final BooleanProperty canMerge = new SimpleBooleanProperty( - Boolean.TRUE + private final ObjectProperty fieldState = new SimpleObjectProperty<>( + FieldState.UNMERGED ); + private final BooleanProperty canMerge = new SimpleBooleanProperty(Boolean.TRUE); - private final ActionFactory actionFactory = new ActionFactory( - Globals.getKeyPrefs() - ); + private final ActionFactory actionFactory = new ActionFactory(Globals.getKeyPrefs()); private final Field field; @@ -40,20 +37,12 @@ public ToggleMergeUnmergeButton(Field field) { private void configureMergeButton() { ToggleMergeCommand mergeCommand = new ToggleMergeCommand(); - actionFactory.configureIconButton( - mergeCommand.mergeAction, - mergeCommand, - this - ); + actionFactory.configureIconButton(mergeCommand.mergeAction, mergeCommand, this); } private void configureUnmergeButton() { ToggleMergeCommand unmergeCommand = new ToggleMergeCommand(); - actionFactory.configureIconButton( - unmergeCommand.unmergeAction, - unmergeCommand, - this - ); + actionFactory.configureIconButton(unmergeCommand.unmergeAction, unmergeCommand, this); } public ObjectProperty fieldStateProperty() { diff --git a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/diffhighlighter/DiffHighlighter.java b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/diffhighlighter/DiffHighlighter.java index 53775f7ecb0..c578f53ba1d 100644 --- a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/diffhighlighter/DiffHighlighter.java +++ b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/diffhighlighter/DiffHighlighter.java @@ -6,8 +6,7 @@ import org.fxmisc.richtext.StyleClassedTextArea; import org.jabref.gui.mergeentries.newmergedialog.DiffMethod; -public abstract sealed class DiffHighlighter - permits SplitDiffHighlighter, UnifiedDiffHighlighter { +public abstract sealed class DiffHighlighter permits SplitDiffHighlighter, UnifiedDiffHighlighter { protected final StyleClassedTextArea sourceTextview; protected final StyleClassedTextArea targetTextview; @@ -19,14 +18,8 @@ public DiffHighlighter( StyleClassedTextArea targetTextview, DiffMethod diffMethod ) { - Objects.requireNonNull( - sourceTextview, - "source text view MUST NOT be null." - ); - Objects.requireNonNull( - targetTextview, - "target text view MUST NOT be null." - ); + Objects.requireNonNull(sourceTextview, "source text view MUST NOT be null."); + Objects.requireNonNull(targetTextview, "target text view MUST NOT be null."); this.sourceTextview = sourceTextview; this.targetTextview = targetTextview; diff --git a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/diffhighlighter/SplitDiffHighlighter.java b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/diffhighlighter/SplitDiffHighlighter.java index 31ea10af885..797f808c8b8 100644 --- a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/diffhighlighter/SplitDiffHighlighter.java +++ b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/diffhighlighter/SplitDiffHighlighter.java @@ -46,9 +46,7 @@ public void highlight() { .map(String::length) .reduce(Integer::sum) .map(value -> - value + - (getSeparator().length() * - (affectedTokensInSource.size() - 1)) + value + (getSeparator().length() * (affectedTokensInSource.size() - 1)) ) .orElse(0); @@ -57,9 +55,7 @@ public void highlight() { .map(String::length) .reduce(Integer::sum) .map(value -> - value + - (getSeparator().length() * - (affectedTokensInTarget.size() - 1)) + value + (getSeparator().length() * (affectedTokensInTarget.size() - 1)) ) .orElse(0); int affectedSourceTokensPositionInText = getPositionInText( @@ -74,37 +70,30 @@ public void highlight() { case CHANGE -> { sourceTextview.setStyleClass( affectedSourceTokensPositionInText, - affectedSourceTokensPositionInText + - joinedSourceTokensLength, + affectedSourceTokensPositionInText + joinedSourceTokensLength, "deletion" ); targetTextview.setStyleClass( affectedTargetTokensPositionInText, - affectedTargetTokensPositionInText + - joinedTargetTokensLength, + affectedTargetTokensPositionInText + joinedTargetTokensLength, "updated" ); } case DELETE -> sourceTextview.setStyleClass( affectedSourceTokensPositionInText, - affectedSourceTokensPositionInText + - joinedSourceTokensLength, + affectedSourceTokensPositionInText + joinedSourceTokensLength, "deletion" ); case INSERT -> targetTextview.setStyleClass( affectedTargetTokensPositionInText, - affectedTargetTokensPositionInText + - joinedTargetTokensLength, + affectedTargetTokensPositionInText + joinedTargetTokensLength, "addition" ); } } } - public int getPositionInText( - int positionInTokenList, - List tokenList - ) { + public int getPositionInText(int positionInTokenList, List tokenList) { if (positionInTokenList == 0) { return 0; } else { @@ -113,9 +102,7 @@ public int getPositionInText( .limit(positionInTokenList) .map(String::length) .reduce(Integer::sum) - .map(value -> - value + (getSeparator().length() * positionInTokenList) - ) + .map(value -> value + (getSeparator().length() * positionInTokenList)) .orElse(0); } } diff --git a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/diffhighlighter/UnifiedDiffHighlighter.java b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/diffhighlighter/UnifiedDiffHighlighter.java index 86bc3a982bc..3dd288456c4 100644 --- a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/diffhighlighter/UnifiedDiffHighlighter.java +++ b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/diffhighlighter/UnifiedDiffHighlighter.java @@ -48,43 +48,26 @@ public void highlight() { int changePosition = delta.getTarget().getPosition(); int deletionPoint = changePosition + deletionCount; int insertionPoint = deletionPoint + 1; - List deltaSourceWords = delta - .getSource() - .getLines(); - List deltaTargetWords = delta - .getTarget() - .getLines(); + List deltaSourceWords = delta.getSource().getLines(); + List deltaTargetWords = delta.getTarget().getLines(); unifiedWords.add(deletionPoint, join(deltaSourceWords)); + changeList.add(new Change(deletionPoint, 1, ChangeType.CHANGE_DELETION)); changeList.add( - new Change(deletionPoint, 1, ChangeType.CHANGE_DELETION) - ); - changeList.add( - new Change( - insertionPoint, - deltaTargetWords.size(), - ChangeType.ADDITION - ) + new Change(insertionPoint, deltaTargetWords.size(), ChangeType.ADDITION) ); deletionCount++; } case DELETE -> { - int deletionPoint = - delta.getTarget().getPosition() + deletionCount; - unifiedWords.add( - deletionPoint, - join(delta.getSource().getLines()) - ); + int deletionPoint = delta.getTarget().getPosition() + deletionCount; + unifiedWords.add(deletionPoint, join(delta.getSource().getLines())); - changeList.add( - new Change(deletionPoint, 1, ChangeType.DELETION) - ); + changeList.add(new Change(deletionPoint, 1, ChangeType.DELETION)); deletionCount++; } case INSERT -> { - int insertionPoint = - delta.getTarget().getPosition() + deletionCount; + int insertionPoint = delta.getTarget().getPosition() + deletionCount; changeList.add( new Change( insertionPoint, @@ -100,16 +83,9 @@ public void highlight() { boolean changeInProgress = false; for (int position = 0; position < unifiedWords.size(); position++) { String word = unifiedWords.get(position); - Optional changeAtPosition = findChange( - position, - changeList - ); + Optional changeAtPosition = findChange(position, changeList); if (changeAtPosition.isEmpty()) { - appendToTextArea( - targetTextview, - getSeparator() + word, - "unchanged" - ); + appendToTextArea(targetTextview, getSeparator() + word, "unchanged"); } else { Change change = changeAtPosition.get(); List changeWords = unifiedWords.subList( @@ -125,11 +101,7 @@ public void highlight() { ); } else if (change.type() == ChangeType.ADDITION) { if (changeInProgress) { - appendToTextArea( - targetTextview, - join(changeWords), - "addition" - ); + appendToTextArea(targetTextview, join(changeWords), "addition"); changeInProgress = false; } else { appendToTextArea( @@ -155,30 +127,20 @@ public void highlight() { } } - private void appendToTextArea( - StyleClassedTextArea textArea, - String text, - String styleClass - ) { + private void appendToTextArea(StyleClassedTextArea textArea, String text, String styleClass) { if (text.isEmpty()) { return; } // Append separator without styling it if (text.startsWith(getSeparator())) { textArea.append(getSeparator(), "unchanged"); - textArea.append( - text.substring(getSeparator().length()), - styleClass - ); + textArea.append(text.substring(getSeparator().length()), styleClass); } else { textArea.append(text, styleClass); } } private Optional findChange(int position, List changeList) { - return changeList - .stream() - .filter(change -> change.position() == position) - .findAny(); + return changeList.stream().filter(change -> change.position() == position).findAny(); } } diff --git a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/fieldsmerger/FieldMergerFactory.java b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/fieldsmerger/FieldMergerFactory.java index dd426f67c93..96ce98241d0 100644 --- a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/fieldsmerger/FieldMergerFactory.java +++ b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/fieldsmerger/FieldMergerFactory.java @@ -23,8 +23,7 @@ public FieldMerger create(Field field) { return new FileMerger(); } else { throw new IllegalArgumentException( - "No implementation found for merging the given field: " + - field.getDisplayName() + "No implementation found for merging the given field: " + field.getDisplayName() ); } } diff --git a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/fieldsmerger/GroupMerger.java b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/fieldsmerger/GroupMerger.java index be6e88af2bf..28047c24840 100644 --- a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/fieldsmerger/GroupMerger.java +++ b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/fieldsmerger/GroupMerger.java @@ -12,9 +12,7 @@ public class GroupMerger implements FieldMerger { public static final String GROUPS_SEPARATOR = ", "; - public static final Pattern GROUPS_SEPARATOR_REGEX = Pattern.compile( - "\s*,\s*" - ); + public static final Pattern GROUPS_SEPARATOR_REGEX = Pattern.compile("\s*,\s*"); @Override public String merge(String groupsA, String groupsB) { @@ -26,11 +24,7 @@ public String merge(String groupsA, String groupsB) { return groupsA; } else { return Arrays - .stream( - GROUPS_SEPARATOR_REGEX.split( - groupsA + GROUPS_SEPARATOR + groupsB - ) - ) + .stream(GROUPS_SEPARATOR_REGEX.split(groupsA + GROUPS_SEPARATOR + groupsB)) .distinct() .collect(Collectors.joining(GROUPS_SEPARATOR)); } diff --git a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/fieldsmerger/KeywordMerger.java b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/fieldsmerger/KeywordMerger.java index 7e30d73bcfd..d735c04e7fc 100644 --- a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/fieldsmerger/KeywordMerger.java +++ b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/fieldsmerger/KeywordMerger.java @@ -20,8 +20,6 @@ public KeywordMerger(BibEntryPreferences bibEntryPreferences) { @Override public String merge(String keywordsA, String keywordsB) { Character delimiter = bibEntryPreferences.getKeywordSeparator(); - return KeywordList - .merge(keywordsA, keywordsB, delimiter) - .getAsString(delimiter); + return KeywordList.merge(keywordsA, keywordsB, delimiter).getAsString(delimiter); } } diff --git a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/toolbar/ThreeWayMergeToolbar.java b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/toolbar/ThreeWayMergeToolbar.java index 9975f1fe6d4..0ebec20f851 100644 --- a/src/main/java/org/jabref/gui/mergeentries/newmergedialog/toolbar/ThreeWayMergeToolbar.java +++ b/src/main/java/org/jabref/gui/mergeentries/newmergedialog/toolbar/ThreeWayMergeToolbar.java @@ -53,10 +53,8 @@ public class ThreeWayMergeToolbar extends AnchorPane { @Inject private PreferencesService preferencesService; - private final ObjectProperty diffHighlightingMethod = - new SimpleObjectProperty<>(); - private final BooleanProperty onlyShowChangedFields = - new SimpleBooleanProperty(); + private final ObjectProperty diffHighlightingMethod = new SimpleObjectProperty<>(); + private final BooleanProperty onlyShowChangedFields = new SimpleBooleanProperty(); private EasyBinding showDiff; public ThreeWayMergeToolbar() { @@ -104,9 +102,7 @@ public DiffView fromString(String string) { ); highlightWordsRadioButton.disableProperty().bind(notShowDiffProperty()); - highlightCharactersRadioButtons - .disableProperty() - .bind(notShowDiffProperty()); + highlightCharactersRadioButtons.disableProperty().bind(notShowDiffProperty()); diffHighlightingMethodToggleGroup .selectedToggleProperty() @@ -127,13 +123,9 @@ public DiffView fromString(String string) { onlyShowChangedFieldsCheck .selectedProperty() .bindBidirectional( - preferencesService - .getGuiPreferences() - .mergeShowChangedFieldOnlyProperty() + preferencesService.getGuiPreferences().mergeShowChangedFieldOnlyProperty() ); - onlyShowChangedFields.bind( - onlyShowChangedFieldsCheck.selectedProperty() - ); + onlyShowChangedFields.bind(onlyShowChangedFieldsCheck.selectedProperty()); loadSavedConfiguration(); } @@ -141,18 +133,14 @@ public DiffView fromString(String string) { private void loadSavedConfiguration() { GuiPreferences guiPreferences = preferencesService.getGuiPreferences(); - PlainTextOrDiff plainTextOrDiffPreference = - guiPreferences.getMergeShouldShowDiff() - ? PlainTextOrDiff.Diff - : PlainTextOrDiff.PLAIN_TEXT; - plainTextOrDiffComboBox - .getSelectionModel() - .select(plainTextOrDiffPreference); + PlainTextOrDiff plainTextOrDiffPreference = guiPreferences.getMergeShouldShowDiff() + ? PlainTextOrDiff.Diff + : PlainTextOrDiff.PLAIN_TEXT; + plainTextOrDiffComboBox.getSelectionModel().select(plainTextOrDiffPreference); - DiffView diffViewPreference = - guiPreferences.getMergeShouldShowUnifiedDiff() - ? DiffView.UNIFIED - : DiffView.SPLIT; + DiffView diffViewPreference = guiPreferences.getMergeShouldShowUnifiedDiff() + ? DiffView.UNIFIED + : DiffView.SPLIT; diffViewComboBox.getSelectionModel().select(diffViewPreference); diffHighlightingMethodToggleGroup.selectToggle( @@ -165,19 +153,14 @@ private void loadSavedConfiguration() { public void saveToolbarConfiguration() { preferencesService .getGuiPreferences() - .setMergeShouldShowDiff( - plainTextOrDiffComboBox.getValue() == PlainTextOrDiff.Diff - ); + .setMergeShouldShowDiff(plainTextOrDiffComboBox.getValue() == PlainTextOrDiff.Diff); preferencesService .getGuiPreferences() - .setMergeShouldShowUnifiedDiff( - diffViewComboBox.getValue() == DiffView.UNIFIED - ); + .setMergeShouldShowUnifiedDiff(diffViewComboBox.getValue() == DiffView.UNIFIED); - boolean highlightWordsRadioButtonValue = - diffHighlightingMethodToggleGroup - .getSelectedToggle() - .equals(highlightWordsRadioButton); + boolean highlightWordsRadioButtonValue = diffHighlightingMethodToggleGroup + .getSelectedToggle() + .equals(highlightWordsRadioButton); preferencesService .getGuiPreferences() .setMergeHighlightWords(highlightWordsRadioButtonValue); diff --git a/src/main/java/org/jabref/gui/openoffice/AdvancedCiteDialogView.java b/src/main/java/org/jabref/gui/openoffice/AdvancedCiteDialogView.java index abb256093a0..938ee42e6bc 100644 --- a/src/main/java/org/jabref/gui/openoffice/AdvancedCiteDialogView.java +++ b/src/main/java/org/jabref/gui/openoffice/AdvancedCiteDialogView.java @@ -9,8 +9,7 @@ import org.jabref.gui.util.BaseDialog; import org.jabref.logic.l10n.Localization; -public class AdvancedCiteDialogView - extends BaseDialog { +public class AdvancedCiteDialogView extends BaseDialog { @FXML private TextField pageInfo; @@ -43,12 +42,8 @@ public AdvancedCiteDialogView() { private void initialize() { viewModel = new AdvancedCiteDialogViewModel(); - inPar - .selectedProperty() - .bindBidirectional(viewModel.citeInParProperty()); - inText - .selectedProperty() - .bindBidirectional(viewModel.citeInTextProperty()); + inPar.selectedProperty().bindBidirectional(viewModel.citeInParProperty()); + inText.selectedProperty().bindBidirectional(viewModel.citeInTextProperty()); pageInfo.textProperty().bindBidirectional(viewModel.pageInfoProperty()); } } diff --git a/src/main/java/org/jabref/gui/openoffice/Bootstrap.java b/src/main/java/org/jabref/gui/openoffice/Bootstrap.java index e2bd4297d2f..4cd743d1476 100644 --- a/src/main/java/org/jabref/gui/openoffice/Bootstrap.java +++ b/src/main/java/org/jabref/gui/openoffice/Bootstrap.java @@ -73,58 +73,29 @@ public class Bootstrap { private static final Random RANDOM_PIPE_NAME = new Random(); private static boolean M_LOADED_JUH = false; - private static void insertBasicFactories( - XSet xSet, - XImplementationLoader xImpLoader - ) throws Exception { + private static void insertBasicFactories(XSet xSet, XImplementationLoader xImpLoader) + throws Exception { // insert the factory of the loader - xSet.insert( - xImpLoader.activate( - "com.sun.star.comp.loader.JavaLoader", - null, - null, - null - ) - ); + xSet.insert(xImpLoader.activate("com.sun.star.comp.loader.JavaLoader", null, null, null)); // insert the factory of the URLResolver xSet.insert( - xImpLoader.activate( - "com.sun.star.comp.urlresolver.UrlResolver", - null, - null, - null - ) + xImpLoader.activate("com.sun.star.comp.urlresolver.UrlResolver", null, null, null) ); // insert the bridgefactory xSet.insert( - xImpLoader.activate( - "com.sun.star.comp.bridgefactory.BridgeFactory", - null, - null, - null - ) + xImpLoader.activate("com.sun.star.comp.bridgefactory.BridgeFactory", null, null, null) ); // insert the connector xSet.insert( - xImpLoader.activate( - "com.sun.star.comp.connections.Connector", - null, - null, - null - ) + xImpLoader.activate("com.sun.star.comp.connections.Connector", null, null, null) ); // insert the acceptor xSet.insert( - xImpLoader.activate( - "com.sun.star.comp.connections.Acceptor", - null, - null, - null - ) + xImpLoader.activate("com.sun.star.comp.connections.Acceptor", null, null, null) ); } @@ -146,12 +117,7 @@ private static void insertBasicFactories( * @since LibreOffice 5.1 */ public static String[] getDefaultOptions() { - return new String[] { - "--nologo", - "--nodefault", - "--norestore", - "--nolockcheck", - }; + return new String[] { "--nologo", "--nodefault", "--norestore", "--nolockcheck" }; } /** @@ -164,9 +130,7 @@ public static String[] getDefaultOptions() { public static XComponentContext createInitialComponentContext( Hashtable context_entries ) throws Exception { - return createInitialComponentContext( - (Map) context_entries - ); + return createInitialComponentContext((Map) context_entries); } /** @@ -185,10 +149,7 @@ public static XComponentContext createInitialComponentContext( XImplementationLoader.class, new JavaLoader() ); - XInitialization xInit = UnoRuntime.queryInterface( - XInitialization.class, - xImpLoader - ); + XInitialization xInit = UnoRuntime.queryInterface(XInitialization.class, xImpLoader); Object[] args = new Object[] { xSMgr }; xInit.initialize(args); @@ -202,10 +163,7 @@ public static XComponentContext createInitialComponentContext( new ComponentContextEntry(null, xSMgr) ); // ... xxx todo: add standard entries - XComponentContext xContext = new ComponentContext( - context_entries, - null - ); + XComponentContext xContext = new ComponentContext(context_entries, null); xSMgr.setDefaultContext(xContext); @@ -224,12 +182,10 @@ public static XComponentContext createInitialComponentContext( * @return a freshly bootstrapped service manager * @throws Exception if things go awry. */ - public static XMultiServiceFactory createSimpleServiceManager() - throws Exception { + public static XMultiServiceFactory createSimpleServiceManager() throws Exception { return UnoRuntime.queryInterface( XMultiServiceFactory.class, - createInitialComponentContext((Map) null) - .getServiceManager() + createInitialComponentContext((Map) null).getServiceManager() ); } @@ -242,12 +198,8 @@ public static XMultiServiceFactory createSimpleServiceManager() * cppuhelper/defaultBootstrap_InitialComponentContext(). * @throws Exception if things go awry. */ - public static XComponentContext defaultBootstrap_InitialComponentContext() - throws Exception { - return defaultBootstrap_InitialComponentContext( - (String) null, - (Map) null - ); + public static XComponentContext defaultBootstrap_InitialComponentContext() throws Exception { + return defaultBootstrap_InitialComponentContext((String) null, (Map) null); } /** @@ -288,19 +240,14 @@ public static XComponentContext defaultBootstrap_InitialComponentContext( if (null != bootstrap_parameters) { pairs = new String[2 * bootstrap_parameters.size()]; int n = 0; - for (Map.Entry< - String, - String - > bootstrap_parameter : bootstrap_parameters.entrySet()) { + for (Map.Entry bootstrap_parameter : bootstrap_parameters.entrySet()) { pairs[n++] = bootstrap_parameter.getKey(); pairs[n++] = bootstrap_parameter.getValue(); } } if (!M_LOADED_JUH) { - if ( - "The Android Project".equals(System.getProperty("java.vendor")) - ) { + if ("The Android Project".equals(System.getProperty("java.vendor"))) { // Find out if we are configured with DISABLE_DYNLOADING or // not. Try to load the lo-bootstrap shared library which // won't exist in the DISABLE_DYNLOADING case. (And which will @@ -318,26 +265,16 @@ public static XComponentContext defaultBootstrap_InitialComponentContext( } if (!disable_dynloading) { - NativeLibraryLoader.loadLibrary( - Bootstrap.class.getClassLoader(), - "juh" - ); + NativeLibraryLoader.loadLibrary(Bootstrap.class.getClassLoader(), "juh"); } } else { - NativeLibraryLoader.loadLibrary( - Bootstrap.class.getClassLoader(), - "juh" - ); + NativeLibraryLoader.loadLibrary(Bootstrap.class.getClassLoader(), "juh"); } M_LOADED_JUH = true; } return UnoRuntime.queryInterface( XComponentContext.class, - cppuhelper_bootstrap( - ini_file, - pairs, - Bootstrap.class.getClassLoader() - ) + cppuhelper_bootstrap(ini_file, pairs, Bootstrap.class.getClassLoader()) ); } @@ -354,8 +291,7 @@ private static native Object cppuhelper_bootstrap( * @throws BootstrapException if things go awry. * @since UDK 3.1.0 */ - public static XComponentContext bootstrap(Path ooPath) - throws BootstrapException { + public static XComponentContext bootstrap(Path ooPath) throws BootstrapException { String[] defaultArgArray = getDefaultOptions(); return bootstrap(defaultArgArray, ooPath); } @@ -396,8 +332,7 @@ public static XComponentContext bootstrap(String[] argArray, Path path) pipe(p.getErrorStream(), System.err, "CE> "); // initial service manager - XMultiComponentFactory xLocalServiceManager = - xLocalContext.getServiceManager(); + XMultiComponentFactory xLocalServiceManager = xLocalContext.getServiceManager(); if (xLocalServiceManager == null) { throw new BootstrapException("no initial service manager!"); } @@ -407,19 +342,14 @@ public static XComponentContext bootstrap(String[] argArray, Path path) // connection string String sConnect = - "uno:socket,host=localhost,port=2083" + - ";urp;StarOffice.ComponentContext"; + "uno:socket,host=localhost,port=2083" + ";urp;StarOffice.ComponentContext"; // wait until office is started for (int i = 0;; ++i) { try { // try to connect to office Object context = xUrlResolver.resolve(sConnect); - xContext = - UnoRuntime.queryInterface( - XComponentContext.class, - context - ); + xContext = UnoRuntime.queryInterface(XComponentContext.class, context); if (xContext == null) { throw new BootstrapException("no component context!"); } @@ -444,11 +374,7 @@ public static XComponentContext bootstrap(String[] argArray, Path path) return xContext; } - private static void pipe( - final InputStream in, - final PrintStream out, - final String prefix - ) { + private static void pipe(final InputStream in, final PrintStream out, final String prefix) { new Thread("Pipe: " + prefix) { @Override public void run() { diff --git a/src/main/java/org/jabref/gui/openoffice/CitationEntryViewModel.java b/src/main/java/org/jabref/gui/openoffice/CitationEntryViewModel.java index fadd14b595f..a8a9c959f18 100644 --- a/src/main/java/org/jabref/gui/openoffice/CitationEntryViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/CitationEntryViewModel.java @@ -7,16 +7,10 @@ public class CitationEntryViewModel { private final StringProperty citation = new SimpleStringProperty(""); - private final StringProperty extraInformation = new SimpleStringProperty( - "" - ); + private final StringProperty extraInformation = new SimpleStringProperty(""); private final String refMarkName; - public CitationEntryViewModel( - String refMarkName, - String citation, - String extraInfo - ) { + public CitationEntryViewModel(String refMarkName, String citation, String extraInfo) { this.refMarkName = refMarkName; this.citation.setValue(citation); this.extraInformation.setValue(extraInfo); @@ -31,11 +25,7 @@ public CitationEntryViewModel(CitationEntry citationEntry) { } public CitationEntry toCitationEntry() { - return new CitationEntry( - refMarkName, - citation.getValue(), - extraInformation.getValue() - ); + return new CitationEntry(refMarkName, citation.getValue(), extraInformation.getValue()); } public StringProperty citationProperty() { diff --git a/src/main/java/org/jabref/gui/openoffice/DetectOpenOfficeInstallation.java b/src/main/java/org/jabref/gui/openoffice/DetectOpenOfficeInstallation.java index 0e7b2dac8d9..59b1c631805 100644 --- a/src/main/java/org/jabref/gui/openoffice/DetectOpenOfficeInstallation.java +++ b/src/main/java/org/jabref/gui/openoffice/DetectOpenOfficeInstallation.java @@ -37,9 +37,7 @@ public Optional selectInstallationPath() { final NativeDesktop nativeDesktop = OS.getNativeDesktop(); dialogService.showInformationDialogAndWait( - Localization.lang( - "Could not find OpenOffice/LibreOffice installation" - ), + Localization.lang("Could not find OpenOffice/LibreOffice installation"), Localization.lang( "Unable to autodetect OpenOffice/LibreOffice installation. Please choose the installation directory manually." ) @@ -48,47 +46,30 @@ public Optional selectInstallationPath() { new DirectoryDialogConfiguration.Builder() .withInitialDirectory(nativeDesktop.getApplicationDirectory()) .build(); - return dialogService.showDirectorySelectionDialog( - dirDialogConfiguration - ); + return dialogService.showDirectorySelectionDialog(dirDialogConfiguration); } /** * Checks whether the executablePath exists */ - private boolean checkAutoDetectedPaths( - OpenOfficePreferences openOfficePreferences - ) { + private boolean checkAutoDetectedPaths(OpenOfficePreferences openOfficePreferences) { String executablePath = openOfficePreferences.getExecutablePath(); if (OS.LINUX && (System.getenv("FLATPAK_SANDBOX_DIR") != null)) { - executablePath = - OpenOfficePreferences.DEFAULT_LINUX_FLATPAK_EXEC_PATH; + executablePath = OpenOfficePreferences.DEFAULT_LINUX_FLATPAK_EXEC_PATH; } - return ( - !StringUtil.isNullOrEmpty(executablePath) && - Files.exists(Path.of(executablePath)) - ); + return (!StringUtil.isNullOrEmpty(executablePath) && Files.exists(Path.of(executablePath))); } public boolean setOpenOfficePreferences(Path installDir) { Optional execPath = Optional.empty(); if (OS.WINDOWS) { - execPath = - FileUtil.find( - OpenOfficePreferences.WINDOWS_EXECUTABLE, - installDir - ); + execPath = FileUtil.find(OpenOfficePreferences.WINDOWS_EXECUTABLE, installDir); } else if (OS.OS_X) { - execPath = - FileUtil.find(OpenOfficePreferences.OSX_EXECUTABLE, installDir); + execPath = FileUtil.find(OpenOfficePreferences.OSX_EXECUTABLE, installDir); } else if (OS.LINUX) { - execPath = - FileUtil.find( - OpenOfficePreferences.LINUX_EXECUTABLE, - installDir - ); + execPath = FileUtil.find(OpenOfficePreferences.LINUX_EXECUTABLE, installDir); } if (execPath.isPresent()) { @@ -110,9 +91,7 @@ public Optional chooseAmongInstallations(List installDirs) { return dialogService.showChoiceDialogAndWait( Localization.lang("Choose OpenOffice/LibreOffice executable"), - Localization.lang( - "Found more than one OpenOffice/LibreOffice executable." - ) + + Localization.lang("Found more than one OpenOffice/LibreOffice executable.") + "\n" + Localization.lang("Please choose which one to connect to:"), Localization.lang("Use selected instance"), diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java index fb7606cd8b6..3b1a106a1b2 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogView.java @@ -57,26 +57,19 @@ public ManageCitationsDialogView(OOBibBase ooBase) { private void initialize() { viewModel = new ManageCitationsDialogViewModel(ooBase, dialogService); - citation.setCellValueFactory(cellData -> - cellData.getValue().citationProperty() - ); + citation.setCellValueFactory(cellData -> cellData.getValue().citationProperty()); new ValueTableCellFactory() .withGraphic(this::getText) .install(citation); - extraInfo.setCellValueFactory(cellData -> - cellData.getValue().extraInformationProperty() - ); + extraInfo.setCellValueFactory(cellData -> cellData.getValue().extraInformationProperty()); extraInfo.setEditable(true); citationsTableView.setEditable(true); - citationsTableView - .itemsProperty() - .bindBidirectional(viewModel.citationsProperty()); + citationsTableView.itemsProperty().bindBidirectional(viewModel.citationsProperty()); - extraInfo.setOnEditCommit( - (CellEditEvent cell) -> + extraInfo.setOnEditCommit((CellEditEvent cell) -> cell.getRowValue().setExtraInfo(cell.getNewValue()) ); extraInfo.setCellFactory(TextFieldTableCell.forTableColumn()); @@ -88,13 +81,9 @@ private Node getText(String citationContext) { HTML_BOLD_START_TAG, HTML_BOLD_END_TAG ); - String start = citationContext.substring( - 0, - citationContext.indexOf(HTML_BOLD_START_TAG) - ); + String start = citationContext.substring(0, citationContext.indexOf(HTML_BOLD_START_TAG)); String end = citationContext.substring( - citationContext.lastIndexOf(HTML_BOLD_END_TAG) + - HTML_BOLD_END_TAG.length() + citationContext.lastIndexOf(HTML_BOLD_END_TAG) + HTML_BOLD_END_TAG.length() ); Text startText = new Text(start); diff --git a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java index 3834714dba3..e50a67fcc5b 100644 --- a/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/ManageCitationsDialogViewModel.java @@ -12,28 +12,24 @@ public class ManageCitationsDialogViewModel { public final boolean failedToGetCitationEntries; - private final ListProperty citations = - new SimpleListProperty<>(FXCollections.observableArrayList()); + private final ListProperty citations = new SimpleListProperty<>( + FXCollections.observableArrayList() + ); private final OOBibBase ooBase; private final DialogService dialogService; - public ManageCitationsDialogViewModel( - OOBibBase ooBase, - DialogService dialogService - ) { + public ManageCitationsDialogViewModel(OOBibBase ooBase, DialogService dialogService) { this.ooBase = ooBase; this.dialogService = dialogService; - Optional> citationEntries = - ooBase.guiActionGetCitationEntries(); + Optional> citationEntries = ooBase.guiActionGetCitationEntries(); this.failedToGetCitationEntries = citationEntries.isEmpty(); if (citationEntries.isEmpty()) { return; } for (CitationEntry entry : citationEntries.get()) { - CitationEntryViewModel itemViewModelEntry = - new CitationEntryViewModel(entry); + CitationEntryViewModel itemViewModelEntry = new CitationEntryViewModel(entry); citations.add(itemViewModelEntry); } } diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java index 0317cdc0140..1dda5bc36a3 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBase.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBase.java @@ -53,9 +53,7 @@ */ class OOBibBase { - private static final Logger LOGGER = LoggerFactory.getLogger( - OOBibBase.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(OOBibBase.class); private final DialogService dialogService; @@ -84,20 +82,10 @@ public void guiActionSelectDocument(boolean autoSelectForSingle) { } catch (NoDocumentFoundException ex) { OOError.from(ex).showErrorDialog(dialogService); } catch (DisposedException ex) { - OOError - .from(ex) - .setTitle(errorTitle) - .showErrorDialog(dialogService); - } catch ( - WrappedTargetException - | IndexOutOfBoundsException - | NoSuchElementException ex - ) { + OOError.from(ex).setTitle(errorTitle).showErrorDialog(dialogService); + } catch (WrappedTargetException | IndexOutOfBoundsException | NoSuchElementException ex) { LOGGER.warn("Problem connecting", ex); - OOError - .fromMisc(ex) - .setTitle(errorTitle) - .showErrorDialog(dialogService); + OOError.fromMisc(ex).setTitle(errorTitle).showErrorDialog(dialogService); } if (this.isConnectedToDocument()) { @@ -153,10 +141,7 @@ void showDialog(String errorTitle, OOError err) { err.setTitle(errorTitle).showErrorDialog(dialogService); } - OOVoidResult collectResults( - String errorTitle, - List> results - ) { + OOVoidResult collectResults(String errorTitle, List> results) { String msg = results .stream() .filter(OOVoidResult::isError) @@ -182,10 +167,7 @@ boolean testDialog(String errorTitle, List> results) { } @SafeVarargs - final boolean testDialog( - String errorTitle, - OOVoidResult... results - ) { + final boolean testDialog(String errorTitle, OOVoidResult... results) { List> resultList = Arrays.asList(results); return testDialog(collectResults(errorTitle, resultList)); } @@ -207,13 +189,10 @@ OOResult getUserCursorForTextInsertion( } catch (com.sun.star.uno.RuntimeException ex) { String msg = Localization.lang( - "Please move the cursor" + - " to the location for the new citation." + "Please move the cursor" + " to the location for the new citation." ) + "\n" + - Localization.lang( - "I cannot insert to the cursor's current location." - ); + Localization.lang("I cannot insert to the cursor's current location."); return OOResult.error(new OOError(errorTitle, msg, ex)); } return OOResult.ok(cursor); @@ -227,23 +206,18 @@ OOResult getFunctionalTextViewCursor( String errorTitle ) { String messageOnFailureToObtain = - Localization.lang( - "Please move the cursor into the document text." - ) + + Localization.lang("Please move the cursor into the document text.") + "\n" + Localization.lang( "To get the visual positions of your citations" + " I need to move the cursor around," + " but could not get it." ); - OOResult result = - FunctionalTextViewCursor.get(doc); + OOResult result = FunctionalTextViewCursor.get(doc); if (result.isError()) { LOGGER.warn(result.getError()); } - return result.mapError(detail -> - new OOError(errorTitle, messageOnFailureToObtain) - ); + return result.mapError(detail -> new OOError(errorTitle, messageOnFailureToObtain)); } private static OOVoidResult checkRangeOverlaps( @@ -255,19 +229,12 @@ private static OOVoidResult checkRangeOverlaps( int maxReportedOverlaps = 10; try { return frontend - .checkRangeOverlaps( - doc, - new ArrayList<>(), - requireSeparation, - maxReportedOverlaps - ) + .checkRangeOverlaps(doc, new ArrayList<>(), requireSeparation, maxReportedOverlaps) .mapError(OOError::from); } catch (NoDocumentException ex) { return OOVoidResult.error(OOError.from(ex).setTitle(errorTitle)); } catch (WrappedTargetException ex) { - return OOVoidResult.error( - OOError.fromMisc(ex).setTitle(errorTitle) - ); + return OOVoidResult.error(OOError.fromMisc(ex).setTitle(errorTitle)); } } @@ -283,29 +250,17 @@ private static OOVoidResult checkRangeOverlapsWithCursor( boolean requireSeparation = false; OOVoidResult res; try { - res = - frontend.checkRangeOverlapsWithCursor( - doc, - userRanges, - requireSeparation - ); + res = frontend.checkRangeOverlapsWithCursor(doc, userRanges, requireSeparation); } catch (NoDocumentException ex) { return OOVoidResult.error(OOError.from(ex).setTitle(errorTitle)); } catch (WrappedTargetException ex) { - return OOVoidResult.error( - OOError.fromMisc(ex).setTitle(errorTitle) - ); + return OOVoidResult.error(OOError.fromMisc(ex).setTitle(errorTitle)); } if (res.isError()) { - final String xtitle = Localization.lang( - "The cursor is in a protected area." - ); + final String xtitle = Localization.lang("The cursor is in a protected area."); return OOVoidResult.error( - new OOError( - xtitle, - xtitle + "\n" + res.getError().getLocalizedMessage() + "\n" - ) + new OOError(xtitle, xtitle + "\n" + res.getError().getLocalizedMessage() + "\n") ); } return res.mapError(OOError::from); @@ -317,12 +272,8 @@ private static OOVoidResult checkRangeOverlapsWithCursor( * * ******************************************************/ - private static OOVoidResult checkIfOpenOfficeIsRecordingChanges( - XTextDocument doc - ) { - String errorTitle = Localization.lang( - "Recording and/or Recorded changes" - ); + private static OOVoidResult checkIfOpenOfficeIsRecordingChanges(XTextDocument doc) { + String errorTitle = Localization.lang("Recording and/or Recorded changes"); try { boolean recordingChanges = UnoRedlines.getRecordChanges(doc); int nRedlines = UnoRedlines.countRedlines(doc); @@ -331,8 +282,7 @@ private static OOVoidResult checkIfOpenOfficeIsRecordingChanges( if (recordingChanges) { msg += Localization.lang( - "Cannot work with" + - " [Edit]/[Track Changes]/[Record] turned on." + "Cannot work with" + " [Edit]/[Track Changes]/[Record] turned on." ); } if (nRedlines > 0) { @@ -347,16 +297,13 @@ private static OOVoidResult checkIfOpenOfficeIsRecordingChanges( ); msg += "\n"; msg += - Localization.lang( - "Use [Edit]/[Track Changes]/[Manage] to resolve them first." - ); + Localization.lang("Use [Edit]/[Track Changes]/[Manage] to resolve them first."); } return OOVoidResult.error(new OOError(errorTitle, msg)); } } catch (WrappedTargetException ex) { String msg = Localization.lang( - "Error while checking if Writer" + - " is recording changes or has recorded changes." + "Error while checking if Writer" + " is recording changes or has recorded changes." ); return OOVoidResult.error(new OOError(errorTitle, msg, ex)); } @@ -382,10 +329,7 @@ OOResult getFrontend(XTextDocument doc) { } } - OOVoidResult databaseIsRequired( - List databases, - Supplier fun - ) { + OOVoidResult databaseIsRequired(List databases, Supplier fun) { if (databases == null || databases.isEmpty()) { return OOVoidResult.error(fun.get()); } else { @@ -414,11 +358,7 @@ private OOVoidResult checkStyleExistsInTheDocument( String labelInJstyleFile, String pathToStyleFile ) throws WrappedTargetException { - Optional internalName = UnoStyle.getInternalNameOfStyle( - doc, - familyName, - styleName - ); + Optional internalName = UnoStyle.getInternalNameOfStyle(doc, familyName, styleName); if (internalName.isEmpty()) { String msg = @@ -442,9 +382,7 @@ private OOVoidResult checkStyleExistsInTheDocument( ); } + "\n" + - Localization.lang( - "Please create it in the document or change in the file:" - ) + + Localization.lang("Please create it in the document or change in the file:") + "\n" + pathToStyleFile; return OOVoidResult.error(new OOError("StyleIsNotKnown", msg)); @@ -480,9 +418,7 @@ private OOVoidResult checkStyleExistsInTheDocument( ) + "\n" + pathToStyleFile; - return OOVoidResult.error( - new OOError("StyleNameIsNotInternal", msg) - ); + return OOVoidResult.error(new OOError("StyleNameIsNotInternal", msg)); } return OOVoidResult.ok(); } @@ -527,11 +463,7 @@ public OOVoidResult checkStylesExistInTheDocument( } catch (WrappedTargetException ex) { results.add( OOVoidResult.error( - new OOError( - "Other error in checkStyleExistsInTheDocument", - ex.getMessage(), - ex - ) + new OOError("Other error in checkStyleExistsInTheDocument", ex.getMessage(), ex) ) ); } @@ -546,9 +478,7 @@ public OOVoidResult checkStylesExistInTheDocument( * ******************************************************/ public Optional> guiActionGetCitationEntries() { final Optional> FAIL = Optional.empty(); - final String errorTitle = Localization.lang( - "Problem collecting citations" - ); + final String errorTitle = Localization.lang("Problem collecting citations"); OOResult odoc = getXTextDocument(); if (testDialog(errorTitle, odoc.asVoidResult())) { @@ -564,23 +494,14 @@ public Optional> guiActionGetCitationEntries() { try { return Optional.of(ManageCitations.getCitationEntries(doc)); } catch (NoDocumentException ex) { - OOError - .from(ex) - .setTitle(errorTitle) - .showErrorDialog(dialogService); + OOError.from(ex).setTitle(errorTitle).showErrorDialog(dialogService); return FAIL; } catch (DisposedException ex) { - OOError - .from(ex) - .setTitle(errorTitle) - .showErrorDialog(dialogService); + OOError.from(ex).setTitle(errorTitle).showErrorDialog(dialogService); return FAIL; } catch (WrappedTargetException ex) { LOGGER.warn(errorTitle, ex); - OOError - .fromMisc(ex) - .setTitle(errorTitle) - .showErrorDialog(dialogService); + OOError.fromMisc(ex).setTitle(errorTitle).showErrorDialog(dialogService); return FAIL; } } @@ -604,12 +525,8 @@ public Optional> guiActionGetCitationEntries() { * citation from the text). * */ - public void guiActionApplyCitationEntries( - List citationEntries - ) { - final String errorTitle = Localization.lang( - "Problem modifying citation" - ); + public void guiActionApplyCitationEntries(List citationEntries) { + final String errorTitle = Localization.lang("Problem modifying citation"); OOResult odoc = getXTextDocument(); if (testDialog(errorTitle, odoc.asVoidResult())) { @@ -620,15 +537,9 @@ public void guiActionApplyCitationEntries( try { ManageCitations.applyCitationEntries(doc, citationEntries); } catch (NoDocumentException ex) { - OOError - .from(ex) - .setTitle(errorTitle) - .showErrorDialog(dialogService); + OOError.from(ex).setTitle(errorTitle).showErrorDialog(dialogService); } catch (DisposedException ex) { - OOError - .from(ex) - .setTitle(errorTitle) - .showErrorDialog(dialogService); + OOError.from(ex).setTitle(errorTitle).showErrorDialog(dialogService); } catch ( PropertyVetoException | IllegalTypeException @@ -636,10 +547,7 @@ public void guiActionApplyCitationEntries( | com.sun.star.lang.IllegalArgumentException ex ) { LOGGER.warn(errorTitle, ex); - OOError - .fromMisc(ex) - .setTitle(errorTitle) - .showErrorDialog(dialogService); + OOError.fromMisc(ex).setTitle(errorTitle).showErrorDialog(dialogService); } } @@ -675,10 +583,7 @@ public void guiActionInsertEntry( errorTitle, odoc.asVoidResult(), styleIsRequired(style), - selectedBibEntryIsRequired( - entries, - OOError::noEntriesSelectedForCitation - ) + selectedBibEntryIsRequired(entries, OOError::noEntriesSelectedForCitation) ) ) { return; @@ -690,20 +595,12 @@ public void guiActionInsertEntry( return; } - OOResult cursor = getUserCursorForTextInsertion( - doc, - errorTitle - ); + OOResult cursor = getUserCursorForTextInsertion(doc, errorTitle); if (testDialog(errorTitle, cursor.asVoidResult())) { return; } - if ( - testDialog( - errorTitle, - checkRangeOverlapsWithCursor(doc, frontend.get()) - ) - ) { + if (testDialog(errorTitle, checkRangeOverlapsWithCursor(doc, frontend.get()))) { return; } @@ -729,11 +626,7 @@ public void guiActionInsertEntry( } syncOptions - .map(e -> - e.setUpdateBibliography( - this.refreshBibliographyDuringSyncWhenCiting - ) - ) + .map(e -> e.setUpdateBibliography(this.refreshBibliographyDuringSyncWhenCiting)) .map(e -> e.setAlwaysAddCitedOnPages(this.alwaysAddCitedOnPages)); if (syncOptions.isPresent()) { @@ -764,23 +657,12 @@ public void guiActionInsertEntry( ); if (syncOptions.isPresent()) { - Update.resyncDocument( - doc, - style, - fcursor.get(), - syncOptions.get() - ); + Update.resyncDocument(doc, style, fcursor.get(), syncOptions.get()); } } catch (NoDocumentException ex) { - OOError - .from(ex) - .setTitle(errorTitle) - .showErrorDialog(dialogService); + OOError.from(ex).setTitle(errorTitle).showErrorDialog(dialogService); } catch (DisposedException ex) { - OOError - .from(ex) - .setTitle(errorTitle) - .showErrorDialog(dialogService); + OOError.from(ex).setTitle(errorTitle).showErrorDialog(dialogService); } catch ( CreationException | IllegalTypeException @@ -789,10 +671,7 @@ public void guiActionInsertEntry( | WrappedTargetException ex ) { LOGGER.warn("Could not insert entry", ex); - OOError - .fromMisc(ex) - .setTitle(errorTitle) - .showErrorDialog(dialogService); + OOError.fromMisc(ex).setTitle(errorTitle).showErrorDialog(dialogService); } finally { UnoUndo.leaveUndoContext(doc); } @@ -801,13 +680,8 @@ public void guiActionInsertEntry( /** * GUI action "Merge citations" */ - public void guiActionMergeCitationGroups( - List databases, - OOBibStyle style - ) { - final String errorTitle = Localization.lang( - "Problem combining cite markers" - ); + public void guiActionMergeCitationGroups(List databases, OOBibStyle style) { + final String errorTitle = Localization.lang("Problem combining cite markers"); OOResult odoc = getXTextDocument(); if ( @@ -822,8 +696,10 @@ public void guiActionMergeCitationGroups( } XTextDocument doc = odoc.get(); - OOResult fcursor = - getFunctionalTextViewCursor(doc, errorTitle); + OOResult fcursor = getFunctionalTextViewCursor( + doc, + errorTitle + ); if ( testDialog( @@ -840,28 +716,16 @@ public void guiActionMergeCitationGroups( UnoUndo.enterUndoContext(doc, "Merge citations"); OOFrontend frontend = new OOFrontend(doc); - boolean madeModifications = EditMerge.mergeCitationGroups( - doc, - frontend, - style - ); + boolean madeModifications = EditMerge.mergeCitationGroups(doc, frontend, style); if (madeModifications) { UnoCrossRef.refresh(doc); - Update.SyncOptions syncOptions = new Update.SyncOptions( - databases - ); + Update.SyncOptions syncOptions = new Update.SyncOptions(databases); Update.resyncDocument(doc, style, fcursor.get(), syncOptions); } } catch (NoDocumentException ex) { - OOError - .from(ex) - .setTitle(errorTitle) - .showErrorDialog(dialogService); + OOError.from(ex).setTitle(errorTitle).showErrorDialog(dialogService); } catch (DisposedException ex) { - OOError - .from(ex) - .setTitle(errorTitle) - .showErrorDialog(dialogService); + OOError.from(ex).setTitle(errorTitle).showErrorDialog(dialogService); } catch ( CreationException | IllegalTypeException @@ -871,10 +735,7 @@ public void guiActionMergeCitationGroups( | com.sun.star.lang.IllegalArgumentException ex ) { LOGGER.warn("Problem combining cite markers", ex); - OOError - .fromMisc(ex) - .setTitle(errorTitle) - .showErrorDialog(dialogService); + OOError.fromMisc(ex).setTitle(errorTitle).showErrorDialog(dialogService); } finally { UnoUndo.leaveUndoContext(doc); fcursor.get().restore(doc); @@ -886,13 +747,8 @@ public void guiActionMergeCitationGroups( *

* Do the opposite of MergeCitationGroups. Combined markers are split, with a space inserted between. */ - public void guiActionSeparateCitations( - List databases, - OOBibStyle style - ) { - final String errorTitle = Localization.lang( - "Problem during separating cite markers" - ); + public void guiActionSeparateCitations(List databases, OOBibStyle style) { + final String errorTitle = Localization.lang("Problem during separating cite markers"); OOResult odoc = getXTextDocument(); if ( @@ -907,8 +763,10 @@ public void guiActionSeparateCitations( } XTextDocument doc = odoc.get(); - OOResult fcursor = - getFunctionalTextViewCursor(doc, errorTitle); + OOResult fcursor = getFunctionalTextViewCursor( + doc, + errorTitle + ); if ( testDialog( @@ -933,21 +791,13 @@ public void guiActionSeparateCitations( ); if (madeModifications) { UnoCrossRef.refresh(doc); - Update.SyncOptions syncOptions = new Update.SyncOptions( - databases - ); + Update.SyncOptions syncOptions = new Update.SyncOptions(databases); Update.resyncDocument(doc, style, fcursor.get(), syncOptions); } } catch (NoDocumentException ex) { - OOError - .from(ex) - .setTitle(errorTitle) - .showErrorDialog(dialogService); + OOError.from(ex).setTitle(errorTitle).showErrorDialog(dialogService); } catch (DisposedException ex) { - OOError - .from(ex) - .setTitle(errorTitle) - .showErrorDialog(dialogService); + OOError.from(ex).setTitle(errorTitle).showErrorDialog(dialogService); } catch ( CreationException | IllegalTypeException @@ -957,10 +807,7 @@ public void guiActionSeparateCitations( | com.sun.star.lang.IllegalArgumentException ex ) { LOGGER.warn("Problem during separating cite markers", ex); - OOError - .fromMisc(ex) - .setTitle(errorTitle) - .showErrorDialog(dialogService); + OOError.fromMisc(ex).setTitle(errorTitle).showErrorDialog(dialogService); } finally { UnoUndo.leaveUndoContext(doc); fcursor.get().restore(doc); @@ -979,19 +826,14 @@ public Optional exportCitedHelper( boolean returnPartialResult ) { final Optional FAIL = Optional.empty(); - final String errorTitle = Localization.lang( - "Unable to generate new library" - ); + final String errorTitle = Localization.lang("Unable to generate new library"); OOResult odoc = getXTextDocument(); if ( testDialog( errorTitle, odoc.asVoidResult(), - databaseIsRequired( - databases, - OOError::noDataBaseIsOpenForExport - ) + databaseIsRequired(databases, OOError::noDataBaseIsOpenForExport) ) ) { return FAIL; @@ -1001,10 +843,7 @@ public Optional exportCitedHelper( try { ExportCited.GenerateDatabaseResult result; try { - UnoUndo.enterUndoContext( - doc, - "Changes during \"Export cited\"" - ); + UnoUndo.enterUndoContext(doc, "Changes during \"Export cited\""); result = ExportCited.generateDatabase(doc, databases); } finally { // There should be no changes, thus no Undo entry should appear @@ -1047,19 +886,10 @@ public Optional exportCitedHelper( } catch (NoDocumentException ex) { OOError.from(ex).showErrorDialog(dialogService); } catch (DisposedException ex) { - OOError - .from(ex) - .setTitle(errorTitle) - .showErrorDialog(dialogService); - } catch ( - WrappedTargetException - | com.sun.star.lang.IllegalArgumentException ex - ) { + OOError.from(ex).setTitle(errorTitle).showErrorDialog(dialogService); + } catch (WrappedTargetException | com.sun.star.lang.IllegalArgumentException ex) { LOGGER.warn("Problem generating new database.", ex); - OOError - .fromMisc(ex) - .setTitle(errorTitle) - .showErrorDialog(dialogService); + OOError.fromMisc(ex).setTitle(errorTitle).showErrorDialog(dialogService); } return FAIL; } @@ -1070,30 +900,21 @@ public Optional exportCitedHelper( * @param databases Must have at least one. * @param style Style. */ - public void guiActionUpdateDocument( - List databases, - OOBibStyle style - ) { - final String errorTitle = Localization.lang( - "Unable to synchronize bibliography" - ); + public void guiActionUpdateDocument(List databases, OOBibStyle style) { + final String errorTitle = Localization.lang("Unable to synchronize bibliography"); try { OOResult odoc = getXTextDocument(); - if ( - testDialog( - errorTitle, - odoc.asVoidResult(), - styleIsRequired(style) - ) - ) { + if (testDialog(errorTitle, odoc.asVoidResult(), styleIsRequired(style))) { return; } XTextDocument doc = odoc.get(); - OOResult fcursor = - getFunctionalTextViewCursor(doc, errorTitle); + OOResult fcursor = getFunctionalTextViewCursor( + doc, + errorTitle + ); if ( testDialog( @@ -1115,21 +936,13 @@ public void guiActionUpdateDocument( try { UnoUndo.enterUndoContext(doc, "Refresh bibliography"); - Update.SyncOptions syncOptions = new Update.SyncOptions( - databases - ); + Update.SyncOptions syncOptions = new Update.SyncOptions(databases); syncOptions .setUpdateBibliography(true) .setAlwaysAddCitedOnPages(this.alwaysAddCitedOnPages); unresolvedKeys = - Update.synchronizeDocument( - doc, - frontend, - style, - fcursor.get(), - syncOptions - ); + Update.synchronizeDocument(doc, frontend, style, fcursor.get(), syncOptions); } finally { UnoUndo.leaveUndoContext(doc); fcursor.get().restore(doc); @@ -1144,25 +957,16 @@ public void guiActionUpdateDocument( dialogService.showErrorDialogAndWait(errorTitle, msg); } } catch (NoDocumentException ex) { - OOError - .from(ex) - .setTitle(errorTitle) - .showErrorDialog(dialogService); + OOError.from(ex).setTitle(errorTitle).showErrorDialog(dialogService); } catch (DisposedException ex) { - OOError - .from(ex) - .setTitle(errorTitle) - .showErrorDialog(dialogService); + OOError.from(ex).setTitle(errorTitle).showErrorDialog(dialogService); } catch ( CreationException | WrappedTargetException | com.sun.star.lang.IllegalArgumentException ex ) { LOGGER.warn("Could not update bibliography", ex); - OOError - .fromMisc(ex) - .setTitle(errorTitle) - .showErrorDialog(dialogService); + OOError.fromMisc(ex).setTitle(errorTitle).showErrorDialog(dialogService); } } } diff --git a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java index 2d63c0df110..9a27d58700e 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java +++ b/src/main/java/org/jabref/gui/openoffice/OOBibBaseConnect.java @@ -35,9 +35,7 @@ */ public class OOBibBaseConnect { - private static final Logger LOGGER = LoggerFactory.getLogger( - OOBibBaseConnect.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(OOBibBaseConnect.class); private final DialogService dialogService; private final XDesktop xDesktop; @@ -55,8 +53,7 @@ public OOBibBaseConnect(Path loPath, DialogService dialogService) this.xDesktop = simpleBootstrap(loPath); } - private XDesktop simpleBootstrap(Path loPath) - throws CreationException, BootstrapException { + private XDesktop simpleBootstrap(Path loPath) throws CreationException, BootstrapException { // Get the office component context: XComponentContext context = Bootstrap.bootstrap(loPath); XMultiComponentFactory sem = context.getServiceManager(); @@ -65,11 +62,7 @@ private XDesktop simpleBootstrap(Path loPath) // hierarchy of frames that contain viewable components: Object desktop; try { - desktop = - sem.createInstanceWithContext( - "com.sun.star.frame.Desktop", - context - ); + desktop = sem.createInstanceWithContext("com.sun.star.frame.Desktop", context); } catch (com.sun.star.uno.Exception e) { throw new CreationException(e.getMessage()); } @@ -96,10 +89,7 @@ public static void closeOfficeConnection() { } } } catch (Exception ex) { - LOGGER.error( - "Exception disposing office process connection bridge", - ex - ); + LOGGER.error("Exception disposing office process connection bridge", ex); } } @@ -113,10 +103,7 @@ private static List getTextDocuments(XDesktop desktop) while (compEnum.hasMoreElements()) { Object next = compEnum.nextElement(); XComponent comp = UnoCast.cast(XComponent.class, next).get(); - Optional doc = UnoCast.cast( - XTextDocument.class, - comp - ); + Optional doc = UnoCast.cast(XTextDocument.class, comp); doc.ifPresent(result::add); } return result; @@ -138,8 +125,7 @@ class DocumentTitleViewModel { public DocumentTitleViewModel(XTextDocument xTextDocument) { this.xTextDocument = xTextDocument; - this.description = - UnoTextDocument.getFrameTitle(xTextDocument).orElse(""); + this.description = UnoTextDocument.getFrameTitle(xTextDocument).orElse(""); } public XTextDocument getXtextDocument() { @@ -160,17 +146,14 @@ public String toString() { // This whole method is part of a background task when // auto-detecting instances, so we need to show dialog in FX // thread - Optional selectedDocument = - dialogService.showChoiceDialogAndWait( - Localization.lang("Select document"), - Localization.lang("Found documents:"), - Localization.lang("Use selected document"), - viewModel - ); - - return selectedDocument - .map(DocumentTitleViewModel::getXtextDocument) - .orElse(null); + Optional selectedDocument = dialogService.showChoiceDialogAndWait( + Localization.lang("Select document"), + Localization.lang("Found documents:"), + Localization.lang("Use selected document"), + viewModel + ); + + return selectedDocument.map(DocumentTitleViewModel::getXtextDocument).orElse(null); } /** @@ -193,11 +176,7 @@ public void selectDocument(boolean autoSelectForSingle) } else if ((textDocumentList.size() == 1) && autoSelectForSingle) { selected = textDocumentList.get(0); // Get the only one } else { // Bring up a dialog - selected = - OOBibBaseConnect.selectDocumentDialog( - textDocumentList, - this.dialogService - ); + selected = OOBibBaseConnect.selectDocumentDialog(textDocumentList, this.dialogService); } if (selected == null) { diff --git a/src/main/java/org/jabref/gui/openoffice/OOError.java b/src/main/java/org/jabref/gui/openoffice/OOError.java index 71575c67a31..773467bd6d7 100644 --- a/src/main/java/org/jabref/gui/openoffice/OOError.java +++ b/src/main/java/org/jabref/gui/openoffice/OOError.java @@ -39,11 +39,7 @@ public void showErrorDialog(DialogService dialogService) { */ public static OOError from(JabRefException err) { - return new OOError( - Localization.lang("JabRefException"), - err.getLocalizedMessage(), - err - ); + return new OOError(Localization.lang("JabRefException"), err.getLocalizedMessage(), err); } // For DisposedException @@ -99,9 +95,7 @@ public static OOError fromMisc(Exception err) { public static OOError noDataBaseIsOpenForCiting() { return new OOError( Localization.lang("No database"), - Localization.lang( - "No bibliography database is open for citation." - ) + + Localization.lang("No bibliography database is open for citation.") + "\n" + Localization.lang("Open one before citing.") ); @@ -110,9 +104,7 @@ public static OOError noDataBaseIsOpenForCiting() { public static OOError noDataBaseIsOpenForSyncingAfterCitation() { return new OOError( Localization.lang("No database"), - Localization.lang( - "No database is open for updating citation markers after citing." - ) + + Localization.lang("No database is open for updating citation markers after citing.") + "\n" + Localization.lang("Open one before citing.") ); @@ -130,9 +122,7 @@ public static OOError noDataBaseIsOpenForExport() { public static OOError noDataBaseIsOpen() { return new OOError( Localization.lang("No database is open"), - Localization.lang( - "This operation requires a bibliography database." - ) + Localization.lang("This operation requires a bibliography database.") ); } @@ -140,15 +130,12 @@ public static OOError noDataBaseIsOpen() { public static OOError noValidStyleSelected() { return new OOError( Localization.lang("No valid style file defined"), - Localization.lang( - "No bibliography style is selected for citation." - ) + + Localization.lang("No bibliography style is selected for citation.") + "\n" + Localization.lang("Select one before citing.") + "\n" + Localization.lang( - "You must select either a valid style file," + - " or use one of the default styles." + "You must select either a valid style file," + " or use one of the default styles." ) ); } @@ -157,9 +144,7 @@ public static OOError noValidStyleSelected() { public static OOError noEntriesSelectedForCitation() { return new OOError( Localization.lang("No entries selected for citation"), - Localization.lang( - "No bibliography entries are selected for citation." - ) + + Localization.lang("No bibliography entries are selected for citation.") + "\n" + Localization.lang("Select some before citing.") ); diff --git a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java index a0ee264bc39..72c129451a0 100644 --- a/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java +++ b/src/main/java/org/jabref/gui/openoffice/OpenOfficePanel.java @@ -65,40 +65,22 @@ */ public class OpenOfficePanel { - private static final Logger LOGGER = LoggerFactory.getLogger( - OpenOfficePanel.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(OpenOfficePanel.class); private final DialogService dialogService; private final Button connect; private final Button manualConnect; private final Button selectDocument; - private final Button setStyleFile = new Button( - Localization.lang("Select style") - ); + private final Button setStyleFile = new Button(Localization.lang("Select style")); private final Button pushEntries = new Button(Localization.lang("Cite")); - private final Button pushEntriesInt = new Button( - Localization.lang("Cite in-text") - ); - private final Button pushEntriesEmpty = new Button( - Localization.lang("Insert empty citation") - ); - private final Button pushEntriesAdvanced = new Button( - Localization.lang("Cite special") - ); + private final Button pushEntriesInt = new Button(Localization.lang("Cite in-text")); + private final Button pushEntriesEmpty = new Button(Localization.lang("Insert empty citation")); + private final Button pushEntriesAdvanced = new Button(Localization.lang("Cite special")); private final Button update; - private final Button merge = new Button( - Localization.lang("Merge citations") - ); - private final Button unmerge = new Button( - Localization.lang("Separate citations") - ); - private final Button manageCitations = new Button( - Localization.lang("Manage citations") - ); - private final Button exportCitations = new Button( - Localization.lang("Export cited") - ); + private final Button merge = new Button(Localization.lang("Merge citations")); + private final Button unmerge = new Button(Localization.lang("Separate citations")); + private final Button manageCitations = new Button(Localization.lang("Manage citations")); + private final Button exportCitations = new Button(Localization.lang("Export cited")); private final Button settingsB = new Button(Localization.lang("Settings")); private final Button help; private final VBox vbox = new VBox(); @@ -137,19 +119,13 @@ public OpenOfficePanel( this.undoManager = undoManager; connect = new Button(); - connect.setGraphic( - IconTheme.JabRefIcons.CONNECT_OPEN_OFFICE.getGraphicNode() - ); + connect.setGraphic(IconTheme.JabRefIcons.CONNECT_OPEN_OFFICE.getGraphicNode()); connect.setTooltip(new Tooltip(Localization.lang("Connect"))); connect.setMaxWidth(Double.MAX_VALUE); manualConnect = new Button(); - manualConnect.setGraphic( - IconTheme.JabRefIcons.CONNECT_OPEN_OFFICE.getGraphicNode() - ); - manualConnect.setTooltip( - new Tooltip(Localization.lang("Manual connect")) - ); + manualConnect.setGraphic(IconTheme.JabRefIcons.CONNECT_OPEN_OFFICE.getGraphicNode()); + manualConnect.setTooltip(new Tooltip(Localization.lang("Manual connect"))); manualConnect.setMaxWidth(Double.MAX_VALUE); help = @@ -165,17 +141,13 @@ public OpenOfficePanel( selectDocument = new Button(); selectDocument.setGraphic(IconTheme.JabRefIcons.OPEN.getGraphicNode()); - selectDocument.setTooltip( - new Tooltip(Localization.lang("Select Writer document")) - ); + selectDocument.setTooltip(new Tooltip(Localization.lang("Select Writer document"))); selectDocument.setMaxWidth(Double.MAX_VALUE); update = new Button(); update.setGraphic(IconTheme.JabRefIcons.REFRESH.getGraphicNode()); update.setTooltip( - new Tooltip( - Localization.lang("Sync OpenOffice/LibreOffice bibliography") - ) + new Tooltip(Localization.lang("Sync OpenOffice/LibreOffice bibliography")) ); update.setMaxWidth(Double.MAX_VALUE); @@ -207,10 +179,7 @@ private boolean getOrUpdateTheStyle(String title) { try { style.ensureUpToDate(); } catch (IOException ex) { - LOGGER.warn( - "Unable to reload style file '" + style.getPath() + "'", - ex - ); + LOGGER.warn("Unable to reload style file '" + style.getPath() + "'", ex); String msg = Localization.lang("Unable to reload style file") + "'" + @@ -230,11 +199,7 @@ private void initPanel() { manualConnect.setOnAction(e -> connectManually()); selectDocument.setTooltip( - new Tooltip( - Localization.lang( - "Select which open Writer document to work on" - ) - ) + new Tooltip(Localization.lang("Select which open Writer document to work on")) ); selectDocument.setOnAction(e -> ooBase.guiActionSelectDocument(false)); @@ -247,39 +212,23 @@ private void initPanel() { try { style.ensureUpToDate(); } catch (IOException e) { - LOGGER.warn( - "Unable to reload style file '" + - style.getPath() + - "'", - e - ); + LOGGER.warn("Unable to reload style file '" + style.getPath() + "'", e); } dialogService.notify( - Localization.lang( - "Current style is '%0'", - style.getName() - ) + Localization.lang("Current style is '%0'", style.getName()) ); }) ); pushEntries.setTooltip( - new Tooltip( - Localization.lang("Cite selected entries between parenthesis") - ) - ); - pushEntries.setOnAction(e -> - pushEntries(CitationType.AUTHORYEAR_PAR, false) + new Tooltip(Localization.lang("Cite selected entries between parenthesis")) ); + pushEntries.setOnAction(e -> pushEntries(CitationType.AUTHORYEAR_PAR, false)); pushEntries.setMaxWidth(Double.MAX_VALUE); pushEntriesInt.setTooltip( - new Tooltip( - Localization.lang("Cite selected entries with in-text citation") - ) - ); - pushEntriesInt.setOnAction(e -> - pushEntries(CitationType.AUTHORYEAR_INTEXT, false) + new Tooltip(Localization.lang("Cite selected entries with in-text citation")) ); + pushEntriesInt.setOnAction(e -> pushEntries(CitationType.AUTHORYEAR_INTEXT, false)); pushEntriesInt.setMaxWidth(Double.MAX_VALUE); pushEntriesEmpty.setTooltip( new Tooltip( @@ -288,26 +237,16 @@ private void initPanel() { ) ) ); - pushEntriesEmpty.setOnAction(e -> - pushEntries(CitationType.INVISIBLE_CIT, false) - ); + pushEntriesEmpty.setOnAction(e -> pushEntries(CitationType.INVISIBLE_CIT, false)); pushEntriesEmpty.setMaxWidth(Double.MAX_VALUE); pushEntriesAdvanced.setTooltip( - new Tooltip( - Localization.lang( - "Cite selected entries with extra information" - ) - ) - ); - pushEntriesAdvanced.setOnAction(e -> - pushEntries(CitationType.AUTHORYEAR_INTEXT, true) + new Tooltip(Localization.lang("Cite selected entries with extra information")) ); + pushEntriesAdvanced.setOnAction(e -> pushEntries(CitationType.AUTHORYEAR_INTEXT, true)); pushEntriesAdvanced.setMaxWidth(Double.MAX_VALUE); update.setTooltip( - new Tooltip( - Localization.lang("Ensure that the bibliography is up-to-date") - ) + new Tooltip(Localization.lang("Ensure that the bibliography is up-to-date")) ); update.setOnAction(event -> { @@ -322,34 +261,22 @@ private void initPanel() { merge.setMaxWidth(Double.MAX_VALUE); merge.setTooltip( new Tooltip( - Localization.lang( - "Combine pairs of citations that are separated by spaces only" - ) + Localization.lang("Combine pairs of citations that are separated by spaces only") ) ); - merge.setOnAction(e -> - ooBase.guiActionMergeCitationGroups(getBaseList(), style) - ); + merge.setOnAction(e -> ooBase.guiActionMergeCitationGroups(getBaseList(), style)); unmerge.setMaxWidth(Double.MAX_VALUE); - unmerge.setTooltip( - new Tooltip(Localization.lang("Separate merged citations")) - ); - unmerge.setOnAction(e -> - ooBase.guiActionSeparateCitations(getBaseList(), style) - ); + unmerge.setTooltip(new Tooltip(Localization.lang("Separate merged citations"))); + unmerge.setOnAction(e -> ooBase.guiActionSeparateCitations(getBaseList(), style)); ContextMenu settingsMenu = createSettingsPopup(); settingsB.setMaxWidth(Double.MAX_VALUE); settingsB.setContextMenu(settingsMenu); - settingsB.setOnAction(e -> - settingsMenu.show(settingsB, Side.BOTTOM, 0, 0) - ); + settingsB.setOnAction(e -> settingsMenu.show(settingsB, Side.BOTTOM, 0, 0)); manageCitations.setMaxWidth(Double.MAX_VALUE); manageCitations.setOnAction(e -> { - ManageCitationsDialogView dialog = new ManageCitationsDialogView( - ooBase - ); + ManageCitationsDialogView dialog = new ManageCitationsDialogView(ooBase); if (dialog.isOkToShowThisDialog()) { dialogService.showCustomDialogAndWait(dialog); } @@ -361,9 +288,7 @@ private void initPanel() { updateButtonAvailability(); HBox hbox = new HBox(); - hbox - .getChildren() - .addAll(connect, manualConnect, selectDocument, update, help); + hbox.getChildren().addAll(connect, manualConnect, selectDocument, update, help); hbox.getChildren().forEach(btn -> HBox.setHgrow(btn, Priority.ALWAYS)); FlowPane flow = new FlowPane(); @@ -372,9 +297,7 @@ private void initPanel() { flow.setHgap(4); flow.setPrefWrapLength(200); flow.getChildren().addAll(setStyleFile, pushEntries, pushEntriesInt); - flow - .getChildren() - .addAll(pushEntriesAdvanced, pushEntriesEmpty, merge, unmerge); + flow.getChildren().addAll(pushEntriesAdvanced, pushEntriesEmpty, merge, unmerge); flow.getChildren().addAll(manageCitations, exportCitations, settingsB); vbox.setFillWidth(true); @@ -389,9 +312,7 @@ private void exportEntries() { returnPartialResult ); if (newDatabase.isPresent()) { - BibDatabaseContext databaseContext = new BibDatabaseContext( - newDatabase.get() - ); + BibDatabaseContext databaseContext = new BibDatabaseContext(newDatabase.get()); LibraryTab libraryTab = LibraryTab.createLibraryTab( databaseContext, JabRefGUI.getMainFrame(), @@ -409,9 +330,7 @@ private void exportEntries() { private List getBaseList() { List databases = new ArrayList<>(); - if ( - preferencesService.getOpenOfficePreferences().getUseAllDatabases() - ) { + if (preferencesService.getOpenOfficePreferences().getUseAllDatabases()) { for (BibDatabaseContext database : stateManager.getOpenDatabases()) { databases.add(database.getDatabase()); } @@ -428,11 +347,10 @@ private List getBaseList() { } private void connectAutomatically() { - DetectOpenOfficeInstallation officeInstallation = - new DetectOpenOfficeInstallation( - preferencesService.getOpenOfficePreferences(), - dialogService - ); + DetectOpenOfficeInstallation officeInstallation = new DetectOpenOfficeInstallation( + preferencesService.getOpenOfficePreferences(), + dialogService + ); if (officeInstallation.isExecutablePathDefined()) { connect(); @@ -445,21 +363,16 @@ protected List call() { }; taskConnectIfInstalled.setOnSucceeded(evt -> { - var installations = new ArrayList<>( - taskConnectIfInstalled.getValue() - ); + var installations = new ArrayList<>(taskConnectIfInstalled.getValue()); if (installations.isEmpty()) { - officeInstallation - .selectInstallationPath() - .ifPresent(installations::add); + officeInstallation.selectInstallationPath().ifPresent(installations::add); } - Optional actualFile = - officeInstallation.chooseAmongInstallations(installations); + Optional actualFile = officeInstallation.chooseAmongInstallations( + installations + ); if ( actualFile.isPresent() && - officeInstallation.setOpenOfficePreferences( - actualFile.get() - ) + officeInstallation.setOpenOfficePreferences(actualFile.get()) ) { connect(); } @@ -486,22 +399,18 @@ private void connectManually() { var fileDialogConfiguration = new DirectoryDialogConfiguration.Builder() .withInitialDirectory(System.getProperty("user.home")) .build(); - Optional selectedPath = - dialogService.showDirectorySelectionDialog(fileDialogConfiguration); + Optional selectedPath = dialogService.showDirectorySelectionDialog( + fileDialogConfiguration + ); - DetectOpenOfficeInstallation officeInstallation = - new DetectOpenOfficeInstallation( - preferencesService.getOpenOfficePreferences(), - dialogService - ); + DetectOpenOfficeInstallation officeInstallation = new DetectOpenOfficeInstallation( + preferencesService.getOpenOfficePreferences(), + dialogService + ); if (selectedPath.isPresent()) { BackgroundTask - .wrap(() -> - officeInstallation.setOpenOfficePreferences( - selectedPath.get() - ) - ) + .wrap(() -> officeInstallation.setOpenOfficePreferences(selectedPath.get())) .withInitialMessage("Searching for executable") .onFailure(dialogService::showErrorDialogAndWait) .onSuccess(value -> { @@ -521,9 +430,7 @@ private void connectManually() { .executeWith(taskExecutor); } else { dialogService.showErrorDialogAndWait( - Localization.lang( - "Could not connect to running OpenOffice/LibreOffice." - ), + Localization.lang("Could not connect to running OpenOffice/LibreOffice."), Localization.lang( "If connecting manually, please verify program and library paths." ) @@ -533,8 +440,7 @@ private void connectManually() { private void updateButtonAvailability() { boolean isConnected = ooBase != null; - boolean isConnectedToDocument = - isConnected && !ooBase.isDocumentConnectionMissing(); + boolean isConnectedToDocument = isConnected && !ooBase.isDocumentConnectionMissing(); // For these, we need to watch something boolean hasStyle = true; // (style != null); @@ -542,12 +448,9 @@ private void updateButtonAvailability() { boolean hasSelectedBibEntry = true; selectDocument.setDisable(!isConnected); - pushEntries.setDisable( - !(isConnectedToDocument && hasStyle && hasDatabase) - ); + pushEntries.setDisable(!(isConnectedToDocument && hasStyle && hasDatabase)); - boolean canCite = - isConnectedToDocument && hasStyle && hasSelectedBibEntry; + boolean canCite = isConnectedToDocument && hasStyle && hasSelectedBibEntry; pushEntriesInt.setDisable(!canCite); pushEntriesEmpty.setDisable(!canCite); pushEntriesAdvanced.setDisable(!canCite); @@ -571,9 +474,7 @@ protected OOBibBase call() throws Exception { ); var path = Path.of( - preferencesService - .getOpenOfficePreferences() - .getExecutablePath() + preferencesService.getOpenOfficePreferences().getExecutablePath() ); return createBibBase(path); } @@ -592,10 +493,7 @@ protected OOBibBase call() throws Exception { Throwable ex = connectTask.getException(); LOGGER.error("autodetect failed", ex); if (ex instanceof UnsatisfiedLinkError) { - LOGGER.warn( - "Could not connect to running OpenOffice/LibreOffice", - ex - ); + LOGGER.warn("Could not connect to running OpenOffice/LibreOffice", ex); dialogService.showErrorDialogAndWait( Localization.lang( @@ -604,18 +502,11 @@ protected OOBibBase call() throws Exception { ) ); } else if (ex instanceof IOException) { - LOGGER.warn( - "Could not connect to running OpenOffice/LibreOffice", - ex - ); + LOGGER.warn("Could not connect to running OpenOffice/LibreOffice", ex); dialogService.showErrorDialogAndWait( - Localization.lang( - "Could not connect to running OpenOffice/LibreOffice." - ), - Localization.lang( - "Could not connect to running OpenOffice/LibreOffice." - ) + + Localization.lang("Could not connect to running OpenOffice/LibreOffice."), + Localization.lang("Could not connect to running OpenOffice/LibreOffice.") + "\n" + Localization.lang( "Make sure you have installed OpenOffice/LibreOffice with Java support." @@ -630,10 +521,7 @@ protected OOBibBase call() throws Exception { ex ); } else if (ex instanceof BootstrapException bootstrapEx) { - LOGGER.error( - "Exception boostrap cause", - bootstrapEx.getTargetException() - ); + LOGGER.error("Exception boostrap cause", bootstrapEx.getTargetException()); dialogService.showErrorDialogAndWait( "Bootstrap error", bootstrapEx.getTargetException() @@ -655,8 +543,7 @@ protected OOBibBase call() throws Exception { taskExecutor.execute(connectTask); } - private OOBibBase createBibBase(Path loPath) - throws BootstrapException, CreationException { + private OOBibBase createBibBase(Path loPath) throws BootstrapException, CreationException { return new OOBibBase(loPath, dialogService); } @@ -666,22 +553,15 @@ private OOBibBase createBibBase(Path loPath) * @param withText False means invisible citation (no text). * @param inParenthesis True means "(Au and Thor 2000)". False means "Au and Thor (2000)". */ - private static CitationType citationTypeFromOptions( - boolean withText, - boolean inParenthesis - ) { + private static CitationType citationTypeFromOptions(boolean withText, boolean inParenthesis) { if (!withText) { return CitationType.INVISIBLE_CIT; } - return inParenthesis - ? CitationType.AUTHORYEAR_PAR - : CitationType.AUTHORYEAR_INTEXT; + return inParenthesis ? CitationType.AUTHORYEAR_PAR : CitationType.AUTHORYEAR_INTEXT; } private void pushEntries(CitationType citationType, boolean addPageInfo) { - final String errorDialogTitle = Localization.lang( - "Error pushing entries" - ); + final String errorDialogTitle = Localization.lang("Error pushing entries"); if ( stateManager.getActiveDatabase().isEmpty() || @@ -694,10 +574,7 @@ private void pushEntries(CitationType citationType, boolean addPageInfo) { return; } - final BibDatabase database = stateManager - .getActiveDatabase() - .get() - .getDatabase(); + final BibDatabase database = stateManager.getActiveDatabase().get().getDatabase(); if (database == null) { OOError .noDataBaseIsOpenForCiting() @@ -724,19 +601,14 @@ private void pushEntries(CitationType citationType, boolean addPageInfo) { boolean withText = citationType.withText(); Optional citeDialogViewModel = - dialogService.showCustomDialogAndWait( - new AdvancedCiteDialogView() - ); + dialogService.showCustomDialogAndWait(new AdvancedCiteDialogView()); if (citeDialogViewModel.isPresent()) { AdvancedCiteDialogViewModel model = citeDialogViewModel.get(); if (!model.pageInfoProperty().getValue().isEmpty()) { pageInfo = model.pageInfoProperty().getValue(); } citationType = - citationTypeFromOptions( - withText, - model.citeInParProperty().getValue() - ); + citationTypeFromOptions(withText, model.citeInParProperty().getValue()); } else { // user canceled return; @@ -754,14 +626,7 @@ private void pushEntries(CitationType citationType, boolean addPageInfo) { ? Optional.of(new Update.SyncOptions(getBaseList())) : Optional.empty(); - ooBase.guiActionInsertEntry( - entries, - database, - style, - citationType, - pageInfo, - syncOptions - ); + ooBase.guiActionInsertEntry(entries, database, style, citationType, pageInfo, syncOptions); } /** @@ -789,30 +654,23 @@ private boolean checkThatEntriesHaveKeys(List entries) { // Ask if keys should be generated boolean citePressed = dialogService.showConfirmationDialogAndWait( Localization.lang("Cite"), - Localization.lang( - "Cannot cite entries without citation keys. Generate keys now?" - ), + Localization.lang("Cannot cite entries without citation keys. Generate keys now?"), Localization.lang("Generate keys"), Localization.lang("Cancel") ); - Optional databaseContext = - stateManager.getActiveDatabase(); + Optional databaseContext = stateManager.getActiveDatabase(); if (citePressed && databaseContext.isPresent()) { // Generate keys CitationKeyPatternPreferences prefs = preferencesService.getCitationKeyPatternPreferences(); - NamedCompound undoCompound = new NamedCompound( - Localization.lang("Cite") - ); + NamedCompound undoCompound = new NamedCompound(Localization.lang("Cite")); for (BibEntry entry : entries) { if (entry.getCitationKey().isEmpty()) { // Generate key new CitationKeyGenerator(databaseContext.get(), prefs) .generateAndSetKey(entry) - .ifPresent(change -> - undoCompound.addEdit(new UndoableKeyChange(change)) - ); + .ifPresent(change -> undoCompound.addEdit(new UndoableKeyChange(change))); } } undoCompound.end(); @@ -827,23 +685,16 @@ private boolean checkThatEntriesHaveKeys(List entries) { } private ContextMenu createSettingsPopup() { - OpenOfficePreferences openOfficePreferences = - preferencesService.getOpenOfficePreferences(); + OpenOfficePreferences openOfficePreferences = preferencesService.getOpenOfficePreferences(); ContextMenu contextMenu = new ContextMenu(); CheckMenuItem autoSync = new CheckMenuItem( - Localization.lang( - "Automatically sync bibliography when inserting citations" - ) + Localization.lang("Automatically sync bibliography when inserting citations") ); autoSync .selectedProperty() - .set( - preferencesService - .getOpenOfficePreferences() - .getSyncWhenCiting() - ); + .set(preferencesService.getOpenOfficePreferences().getSyncWhenCiting()); ToggleGroup toggleGroup = new ToggleGroup(); RadioMenuItem useActiveBase = new RadioMenuItem( @@ -865,22 +716,16 @@ private ContextMenu createSettingsPopup() { useActiveBase.setSelected(true); } - autoSync.setOnAction(e -> - openOfficePreferences.setSyncWhenCiting(autoSync.isSelected()) - ); + autoSync.setOnAction(e -> openOfficePreferences.setSyncWhenCiting(autoSync.isSelected())); useAllBases.setOnAction(e -> openOfficePreferences.setUseAllDatabases(useAllBases.isSelected()) ); useActiveBase.setOnAction(e -> - openOfficePreferences.setUseAllDatabases( - !useActiveBase.isSelected() - ) + openOfficePreferences.setUseAllDatabases(!useActiveBase.isSelected()) ); clearConnectionSettings.setOnAction(e -> { openOfficePreferences.clearConnectionSettings(); - dialogService.notify( - Localization.lang("Cleared connection settings") - ); + dialogService.notify(Localization.lang("Cleared connection settings")); }); contextMenu diff --git a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogView.java b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogView.java index 762bfbb6d6d..b395ffac041 100644 --- a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogView.java +++ b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogView.java @@ -83,10 +83,7 @@ public StyleSelectDialogView(StyleLoader loader) { setResultConverter(button -> { if (button == ButtonType.OK) { viewModel.storePrefs(); - return tvStyles - .getSelectionModel() - .getSelectedItem() - .getStyle(); + return tvStyles.getSelectionModel().getSelectedItem().getStyle(); } return null; }); @@ -95,12 +92,7 @@ public StyleSelectDialogView(StyleLoader loader) { @FXML private void initialize() { - viewModel = - new StyleSelectDialogViewModel( - dialogService, - loader, - preferencesService - ); + viewModel = new StyleSelectDialogViewModel(dialogService, loader, preferencesService); previewArticle = new PreviewViewer( @@ -126,18 +118,10 @@ private void initialize() { previewBook.setEntry(TestEntry.getTestEntryBook()); vbox.getChildren().add(previewBook); - colName.setCellValueFactory(cellData -> - cellData.getValue().nameProperty() - ); - colJournals.setCellValueFactory(cellData -> - cellData.getValue().journalsProperty() - ); - colFile.setCellValueFactory(cellData -> - cellData.getValue().fileProperty() - ); - colDeleteIcon.setCellValueFactory(cellData -> - cellData.getValue().internalStyleProperty() - ); + colName.setCellValueFactory(cellData -> cellData.getValue().nameProperty()); + colJournals.setCellValueFactory(cellData -> cellData.getValue().journalsProperty()); + colFile.setCellValueFactory(cellData -> cellData.getValue().fileProperty()); + colDeleteIcon.setCellValueFactory(cellData -> cellData.getValue().internalStyleProperty()); new ValueTableCellFactory() .withGraphic(internalStyle -> { @@ -182,16 +166,12 @@ private void initialize() { tvStyles.getSelectionModel().select(style); previewArticle.setLayout( new TextBasedPreviewLayout( - style - .getStyle() - .getReferenceFormat(StandardEntryType.Article) + style.getStyle().getReferenceFormat(StandardEntryType.Article) ) ); previewBook.setLayout( new TextBasedPreviewLayout( - style - .getStyle() - .getReferenceFormat(StandardEntryType.Book) + style.getStyle().getReferenceFormat(StandardEntryType.Book) ) ); } diff --git a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java index df0db4b1292..7d52cb903e0 100644 --- a/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/StyleSelectDialogViewModel.java @@ -34,8 +34,9 @@ public class StyleSelectDialogViewModel { private final StyleLoader styleLoader; private final OpenOfficePreferences openOfficePreferences; private final FilePreferences filePreferences; - private final ListProperty styles = - new SimpleListProperty<>(FXCollections.observableArrayList()); + private final ListProperty styles = new SimpleListProperty<>( + FXCollections.observableArrayList() + ); private final ObjectProperty selectedItem = new SimpleObjectProperty<>(); @@ -46,8 +47,7 @@ public StyleSelectDialogViewModel( ) { this.dialogService = dialogService; this.filePreferences = preferencesService.getFilePreferences(); - this.openOfficePreferences = - preferencesService.getOpenOfficePreferences(); + this.openOfficePreferences = preferencesService.getOpenOfficePreferences(); this.styleLoader = styleLoader; styles.addAll(loadStyles()); @@ -60,9 +60,7 @@ public StyleSelectItemViewModel fromOOBibStyle(OOBibStyle style) { return new StyleSelectItemViewModel( style.getName(), String.join(", ", style.getJournals()), - style.isInternalStyle() - ? Localization.lang("Internal style") - : style.getPath(), + style.isInternalStyle() ? Localization.lang("Internal style") : style.getPath(), style ); } @@ -72,21 +70,12 @@ public OOBibStyle toOOBibStyle(StyleSelectItemViewModel item) { } public void addStyleFile() { - FileDialogConfiguration fileDialogConfiguration = - new FileDialogConfiguration.Builder() - .addExtensionFilter( - Localization.lang("Style file"), - StandardFileType.JSTYLE - ) - .withDefaultExtension( - Localization.lang("Style file"), - StandardFileType.JSTYLE - ) - .withInitialDirectory(filePreferences.getWorkingDirectory()) - .build(); - Optional path = dialogService.showFileOpenDialog( - fileDialogConfiguration - ); + FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() + .addExtensionFilter(Localization.lang("Style file"), StandardFileType.JSTYLE) + .withDefaultExtension(Localization.lang("Style file"), StandardFileType.JSTYLE) + .withInitialDirectory(filePreferences.getWorkingDirectory()) + .build(); + Optional path = dialogService.showFileOpenDialog(fileDialogConfiguration); path .map(Path::toAbsolutePath) .map(Path::toString) @@ -127,11 +116,10 @@ public void deleteStyle() { public void editStyle() { OOBibStyle style = selectedItem.getValue().getStyle(); - Optional type = - ExternalFileTypes.getExternalFileTypeByExt( - "jstyle", - filePreferences - ); + Optional type = ExternalFileTypes.getExternalFileTypeByExt( + "jstyle", + filePreferences + ); try { JabRefDesktop.openExternalFileAnyFormat( new BibDatabaseContext(), @@ -152,11 +140,7 @@ public void viewStyle(StyleSelectItemViewModel item) { TextArea styleView = new TextArea(item.getStyle().getLocalCopy()); scrollPane.setContent(styleView); pane.setContent(scrollPane); - dialogService.showCustomDialogAndWait( - item.getStyle().getName(), - pane, - ButtonType.OK - ); + dialogService.showCustomDialogAndWait(item.getStyle().getName(), pane, ButtonType.OK); } public ObjectProperty selectedItemProperty() { @@ -171,9 +155,7 @@ public void storePrefs() { .map(OOBibStyle::getPath) .collect(Collectors.toList()); openOfficePreferences.setExternalStyles(externalStyles); - openOfficePreferences.setCurrentStyle( - selectedItem.getValue().getStylePath() - ); + openOfficePreferences.setCurrentStyle(selectedItem.getValue().getStylePath()); } private StyleSelectItemViewModel getStyleOrDefault(String stylePath) { diff --git a/src/main/java/org/jabref/gui/openoffice/StyleSelectItemViewModel.java b/src/main/java/org/jabref/gui/openoffice/StyleSelectItemViewModel.java index 80ac7148cbb..8890f246c0c 100644 --- a/src/main/java/org/jabref/gui/openoffice/StyleSelectItemViewModel.java +++ b/src/main/java/org/jabref/gui/openoffice/StyleSelectItemViewModel.java @@ -21,12 +21,7 @@ public class StyleSelectItemViewModel { private final OOBibStyle style; private final BooleanProperty internalStyle = new SimpleBooleanProperty(); - public StyleSelectItemViewModel( - String name, - String journals, - String file, - OOBibStyle style - ) { + public StyleSelectItemViewModel(String name, String journals, String file, OOBibStyle style) { this.name.setValue(name); this.journals.setValue(journals); this.file.setValue(file); diff --git a/src/main/java/org/jabref/gui/preferences/AbstractPreferenceTabView.java b/src/main/java/org/jabref/gui/preferences/AbstractPreferenceTabView.java index 26cee411fda..2ce9d3906e0 100644 --- a/src/main/java/org/jabref/gui/preferences/AbstractPreferenceTabView.java +++ b/src/main/java/org/jabref/gui/preferences/AbstractPreferenceTabView.java @@ -8,9 +8,7 @@ import org.jabref.gui.util.TaskExecutor; import org.jabref.preferences.PreferencesService; -public abstract class AbstractPreferenceTabView< - T extends PreferenceTabViewModel -> +public abstract class AbstractPreferenceTabView extends VBox implements PreferencesTab { diff --git a/src/main/java/org/jabref/gui/preferences/PreferencesDialogView.java b/src/main/java/org/jabref/gui/preferences/PreferencesDialogView.java index 929dcbd0065..ede1a3bba84 100644 --- a/src/main/java/org/jabref/gui/preferences/PreferencesDialogView.java +++ b/src/main/java/org/jabref/gui/preferences/PreferencesDialogView.java @@ -27,8 +27,7 @@ * PreferencesTab interface, since this dialog will call the storeSettings() method of all tabs when the user presses * ok. */ -public class PreferencesDialogView - extends BaseDialog { +public class PreferencesDialogView extends BaseDialog { @FXML private CustomTextField searchBox; @@ -85,16 +84,9 @@ public PreferencesDialogViewModel getViewModel() { @FXML private void initialize() { - viewModel = - new PreferencesDialogViewModel( - dialogService, - preferencesService, - frame - ); + viewModel = new PreferencesDialogViewModel(dialogService, preferencesService, frame); - preferenceTabList - .itemsProperty() - .setValue(viewModel.getPreferenceTabs()); + preferenceTabList.itemsProperty().setValue(viewModel.getPreferenceTabs()); // The list view does not respect the listener for the dialog and needs its own preferenceTabList.setOnKeyReleased(key -> { @@ -126,17 +118,11 @@ private void initialize() { EasyBind.subscribe( preferenceTabList.getSelectionModel().selectedItemProperty(), tab -> { - if ( - tab instanceof AbstractPreferenceTabView preferencesTab - ) { - preferencesContainer.setContent( - preferencesTab.getBuilder() - ); + if (tab instanceof AbstractPreferenceTabView preferencesTab) { + preferencesContainer.setContent(preferencesTab.getBuilder()); preferencesTab .prefWidthProperty() - .bind( - preferencesContainer.widthProperty().subtract(10d) - ); + .bind(preferencesContainer.widthProperty().subtract(10d)); preferencesTab.getStyleClass().add("preferencesTab"); } else { preferencesContainer.setContent(null); @@ -149,9 +135,7 @@ private void initialize() { .withText(PreferencesTab::getTabName) .install(preferenceTabList); - memoryStickMode - .selectedProperty() - .bindBidirectional(viewModel.getMemoryStickProperty()); + memoryStickMode.selectedProperty().bindBidirectional(viewModel.getMemoryStickProperty()); viewModel.setValues(); } diff --git a/src/main/java/org/jabref/gui/preferences/PreferencesDialogViewModel.java b/src/main/java/org/jabref/gui/preferences/PreferencesDialogViewModel.java index ac19f497d89..363f0adfdd7 100644 --- a/src/main/java/org/jabref/gui/preferences/PreferencesDialogViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/PreferencesDialogViewModel.java @@ -45,12 +45,9 @@ public class PreferencesDialogViewModel extends AbstractViewModel { - private static final Logger LOGGER = LoggerFactory.getLogger( - PreferencesDialogViewModel.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(PreferencesDialogViewModel.class); - private final SimpleBooleanProperty memoryStickProperty = - new SimpleBooleanProperty(); + private final SimpleBooleanProperty memoryStickProperty = new SimpleBooleanProperty(); private final DialogService dialogService; private final PreferencesService preferences; @@ -98,16 +95,13 @@ public ObservableList getPreferenceTabs() { } public void importPreferences() { - FileDialogConfiguration fileDialogConfiguration = - new FileDialogConfiguration.Builder() - .addExtensionFilter(StandardFileType.XML) - .withDefaultExtension(StandardFileType.XML) - .withInitialDirectory( - preferences - .getInternalPreferences() - .getLastPreferencesExportPath() - ) - .build(); + FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() + .addExtensionFilter(StandardFileType.XML) + .withDefaultExtension(StandardFileType.XML) + .withInitialDirectory( + preferences.getInternalPreferences().getLastPreferencesExportPath() + ) + .build(); dialogService .showFileOpenDialog(fileDialogConfiguration) @@ -118,9 +112,7 @@ public void importPreferences() { dialogService.showWarningDialogAndWait( Localization.lang("Import preferences"), - Localization.lang( - "You must restart JabRef for this to come into effect." - ) + Localization.lang("You must restart JabRef for this to come into effect.") ); } catch (JabRefException ex) { LOGGER.error("Error while importing preferences", ex); @@ -133,16 +125,13 @@ public void importPreferences() { } public void exportPreferences() { - FileDialogConfiguration fileDialogConfiguration = - new FileDialogConfiguration.Builder() - .addExtensionFilter(StandardFileType.XML) - .withDefaultExtension(StandardFileType.XML) - .withInitialDirectory( - preferences - .getInternalPreferences() - .getLastPreferencesExportPath() - ) - .build(); + FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() + .addExtensionFilter(StandardFileType.XML) + .withDefaultExtension(StandardFileType.XML) + .withInitialDirectory( + preferences.getInternalPreferences().getLastPreferencesExportPath() + ) + .build(); dialogService .showFileSaveDialog(fileDialogConfiguration) @@ -150,9 +139,7 @@ public void exportPreferences() { try { storeAllSettings(); preferences.exportPreferences(exportFile); - preferences - .getInternalPreferences() - .setLastPreferencesExportPath(exportFile); + preferences.getInternalPreferences().setLastPreferencesExportPath(exportFile); } catch (JabRefException ex) { LOGGER.warn(ex.getMessage(), ex); dialogService.showErrorDialogAndWait( @@ -170,31 +157,23 @@ public void showPreferences() { } public void resetPreferences() { - boolean resetPreferencesConfirmed = - dialogService.showConfirmationDialogAndWait( - Localization.lang("Reset preferences"), - Localization.lang( - "Are you sure you want to reset all settings to default values?" - ), - Localization.lang("Reset preferences"), - Localization.lang("Cancel") - ); + boolean resetPreferencesConfirmed = dialogService.showConfirmationDialogAndWait( + Localization.lang("Reset preferences"), + Localization.lang("Are you sure you want to reset all settings to default values?"), + Localization.lang("Reset preferences"), + Localization.lang("Cancel") + ); if (resetPreferencesConfirmed) { try { preferences.clear(); dialogService.showWarningDialogAndWait( Localization.lang("Reset preferences"), - Localization.lang( - "You must restart JabRef for this to come into effect." - ) + Localization.lang("You must restart JabRef for this to come into effect.") ); } catch (BackingStoreException ex) { LOGGER.error("Error while resetting preferences", ex); - dialogService.showErrorDialogAndWait( - Localization.lang("Reset preferences"), - ex - ); + dialogService.showErrorDialogAndWait(Localization.lang("Reset preferences"), ex); } updateAfterPreferenceChanges(); @@ -207,9 +186,7 @@ public void resetPreferences() { private void updateAfterPreferenceChanges() { setValues(); - frame - .getLibraryTabs() - .forEach(panel -> panel.getMainTable().getTableModel().refresh()); + frame.getLibraryTabs().forEach(panel -> panel.getMainTable().getTableModel().refresh()); } /** @@ -233,9 +210,7 @@ public void storeAllSettings() { } // Store settings - preferences - .getInternalPreferences() - .setMemoryStickMode(memoryStickProperty.get()); + preferences.getInternalPreferences().setMemoryStickMode(memoryStickProperty.get()); for (PreferencesTab tab : preferenceTabs) { tab.storeSettings(); @@ -248,9 +223,7 @@ public void storeAllSettings() { Localization.lang("Restart required"), String.join(",\n", restartWarnings) + "\n\n" + - Localization.lang( - "You must restart JabRef for this to come into effect." - ) + Localization.lang("You must restart JabRef for this to come into effect.") ); } @@ -266,9 +239,7 @@ public void storeAllSettings() { * Inserts the preference values into the Properties of the ViewModel */ public void setValues() { - memoryStickProperty.setValue( - preferences.getInternalPreferences().isMemoryStickMode() - ); + memoryStickProperty.setValue(preferences.getInternalPreferences().isMemoryStickMode()); for (PreferencesTab preferencesTab : preferenceTabs) { preferencesTab.setValues(); diff --git a/src/main/java/org/jabref/gui/preferences/PreferencesFilterDialog.java b/src/main/java/org/jabref/gui/preferences/PreferencesFilterDialog.java index a2827ac2d75..b04abecf894 100644 --- a/src/main/java/org/jabref/gui/preferences/PreferencesFilterDialog.java +++ b/src/main/java/org/jabref/gui/preferences/PreferencesFilterDialog.java @@ -23,12 +23,8 @@ public class PreferencesFilterDialog extends BaseDialog { private final PreferencesFilter preferencesFilter; - private final ObservableList< - PreferencesFilter.PreferenceOption - > preferenceOptions; - private final FilteredList< - PreferencesFilter.PreferenceOption - > filteredOptions; + private final ObservableList preferenceOptions; + private final FilteredList filteredOptions; @FXML private TableView table; @@ -46,10 +42,7 @@ public class PreferencesFilterDialog extends BaseDialog { private TableColumn columnValue; @FXML - private TableColumn< - PreferencesFilter.PreferenceOption, - Object - > columnDefaultValue; + private TableColumn columnDefaultValue; @FXML private CheckBox showOnlyDeviatingPreferenceOptions; @@ -82,43 +75,30 @@ private void initialize() { if ((searchText == null) || searchText.isEmpty()) { return null; } - String lowerCaseSearchText = searchText.toLowerCase( - Locale.ROOT - ); + String lowerCaseSearchText = searchText.toLowerCase(Locale.ROOT); return option -> - option - .getKey() - .toLowerCase(Locale.ROOT) - .contains(lowerCaseSearchText); + option.getKey().toLowerCase(Locale.ROOT).contains(lowerCaseSearchText); } ) ); columnType.setCellValueFactory(data -> new ReadOnlyObjectWrapper<>(data.getValue().getType()) ); - columnKey.setCellValueFactory(data -> - new ReadOnlyStringWrapper(data.getValue().getKey()) - ); + columnKey.setCellValueFactory(data -> new ReadOnlyStringWrapper(data.getValue().getKey())); columnValue.setCellValueFactory(data -> new ReadOnlyObjectWrapper<>(data.getValue().getValue()) ); columnDefaultValue.setCellValueFactory(data -> - new ReadOnlyObjectWrapper<>( - data.getValue().getDefaultValue().orElse("") - ) + new ReadOnlyObjectWrapper<>(data.getValue().getDefaultValue().orElse("")) ); table.setItems(filteredOptions); - count - .textProperty() - .bind(Bindings.size(table.getItems()).asString("(%d)")); + count.textProperty().bind(Bindings.size(table.getItems()).asString("(%d)")); updateModel(); } private void updateModel() { if (showOnlyDeviatingPreferenceOptions.isSelected()) { - preferenceOptions.setAll( - preferencesFilter.getDeviatingPreferences() - ); + preferenceOptions.setAll(preferencesFilter.getDeviatingPreferences()); } else { preferenceOptions.setAll(preferencesFilter.getPreferenceOptions()); } diff --git a/src/main/java/org/jabref/gui/preferences/PreferencesSearchHandler.java b/src/main/java/org/jabref/gui/preferences/PreferencesSearchHandler.java index 1e9d5ede8ea..bae2be79147 100644 --- a/src/main/java/org/jabref/gui/preferences/PreferencesSearchHandler.java +++ b/src/main/java/org/jabref/gui/preferences/PreferencesSearchHandler.java @@ -14,24 +14,17 @@ class PreferencesSearchHandler { - private static PseudoClass labelHighlight = PseudoClass.getPseudoClass( - "search-highlight" - ); + private static PseudoClass labelHighlight = PseudoClass.getPseudoClass("search-highlight"); private final List preferenceTabs; private final ListProperty filteredPreferenceTabs; - private final ArrayListMultimap< - PreferencesTab, - Labeled - > preferenceTabsLabelNames; + private final ArrayListMultimap preferenceTabsLabelNames; private final ArrayList highlightedLabels = new ArrayList<>(); PreferencesSearchHandler(List preferenceTabs) { this.preferenceTabs = preferenceTabs; this.preferenceTabsLabelNames = getPrefsTabLabelMap(); this.filteredPreferenceTabs = - new SimpleListProperty<>( - FXCollections.observableArrayList(preferenceTabs) - ); + new SimpleListProperty<>(FXCollections.observableArrayList(preferenceTabs)); } public void filterTabs(String text) { @@ -70,8 +63,7 @@ private void highlightLabel(Labeled labeled) { } private void clearHighlights() { - highlightedLabels.forEach(labeled -> - labeled.pseudoClassStateChanged(labelHighlight, false) + highlightedLabels.forEach(labeled -> labeled.pseudoClassStateChanged(labelHighlight, false) ); } @@ -84,17 +76,12 @@ private void clearSearch() { * mapping from PreferencesTab to all its Labeled type nodes. */ private ArrayListMultimap getPrefsTabLabelMap() { - ArrayListMultimap prefsTabLabelMap = - ArrayListMultimap.create(); + ArrayListMultimap prefsTabLabelMap = ArrayListMultimap.create(); for (PreferencesTab preferencesTab : preferenceTabs) { Node builder = preferencesTab.getBuilder(); if (builder instanceof Parent) { Parent parentBuilder = (Parent) builder; - scanLabeledControls( - parentBuilder, - prefsTabLabelMap, - preferencesTab - ); + scanLabeledControls(parentBuilder, prefsTabLabelMap, preferencesTab); } } return prefsTabLabelMap; @@ -111,11 +98,7 @@ private static void scanLabeledControls( ) { for (Node child : parent.getChildrenUnmodifiable()) { if (!(child instanceof Labeled)) { - scanLabeledControls( - (Parent) child, - prefsTabLabelMap, - preferencesTab - ); + scanLabeledControls((Parent) child, prefsTabLabelMap, preferencesTab); } else { Labeled labeled = (Labeled) child; if (!labeled.getText().isEmpty()) { diff --git a/src/main/java/org/jabref/gui/preferences/ShowPreferencesAction.java b/src/main/java/org/jabref/gui/preferences/ShowPreferencesAction.java index 0e494c680e6..ce209954b47 100644 --- a/src/main/java/org/jabref/gui/preferences/ShowPreferencesAction.java +++ b/src/main/java/org/jabref/gui/preferences/ShowPreferencesAction.java @@ -11,19 +11,14 @@ public class ShowPreferencesAction extends SimpleCommand { private final JabRefFrame jabRefFrame; private final TaskExecutor taskExecutor; - public ShowPreferencesAction( - JabRefFrame jabRefFrame, - TaskExecutor taskExecutor - ) { + public ShowPreferencesAction(JabRefFrame jabRefFrame, TaskExecutor taskExecutor) { this.jabRefFrame = jabRefFrame; this.taskExecutor = taskExecutor; } @Override public void execute() { - DialogService dialogService = Injector.instantiateModelOrService( - DialogService.class - ); + DialogService dialogService = Injector.instantiateModelOrService(DialogService.class); dialogService.showCustomDialog(new PreferencesDialogView(jabRefFrame)); } } diff --git a/src/main/java/org/jabref/gui/preferences/autocompletion/AutoCompletionTab.java b/src/main/java/org/jabref/gui/preferences/autocompletion/AutoCompletionTab.java index bbe08a23a9f..8335e19aa1f 100644 --- a/src/main/java/org/jabref/gui/preferences/autocompletion/AutoCompletionTab.java +++ b/src/main/java/org/jabref/gui/preferences/autocompletion/AutoCompletionTab.java @@ -47,26 +47,19 @@ public String getTabName() { } public void initialize() { - viewModel = - new AutoCompletionTabViewModel( - preferencesService.getAutoCompletePreferences() - ); + viewModel = new AutoCompletionTabViewModel(preferencesService.getAutoCompletePreferences()); enableAutoComplete .selectedProperty() .bindBidirectional(viewModel.enableAutoCompleteProperty()); - autoCompleteFields - .textProperty() - .bindBidirectional(viewModel.autoCompleteFieldsProperty()); + autoCompleteFields.textProperty().bindBidirectional(viewModel.autoCompleteFieldsProperty()); autoCompleteFirstLast .selectedProperty() .bindBidirectional(viewModel.autoCompleteFirstLastProperty()); autoCompleteLastFirst .selectedProperty() .bindBidirectional(viewModel.autoCompleteLastFirstProperty()); - autoCompleteBoth - .selectedProperty() - .bindBidirectional(viewModel.autoCompleteBothProperty()); + autoCompleteBoth.selectedProperty().bindBidirectional(viewModel.autoCompleteBothProperty()); firstNameModeAbbreviated .selectedProperty() .bindBidirectional(viewModel.firstNameModeAbbreviatedProperty()); diff --git a/src/main/java/org/jabref/gui/preferences/autocompletion/AutoCompletionTabViewModel.java b/src/main/java/org/jabref/gui/preferences/autocompletion/AutoCompletionTabViewModel.java index 47229ac276d..e27000fb7f5 100644 --- a/src/main/java/org/jabref/gui/preferences/autocompletion/AutoCompletionTabViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/autocompletion/AutoCompletionTabViewModel.java @@ -14,50 +14,34 @@ public class AutoCompletionTabViewModel implements PreferenceTabViewModel { - private final BooleanProperty enableAutoCompleteProperty = - new SimpleBooleanProperty(); - private final StringProperty autoCompleteFieldsProperty = - new SimpleStringProperty(); - private final BooleanProperty autoCompleteFirstLastProperty = - new SimpleBooleanProperty(); - private final BooleanProperty autoCompleteLastFirstProperty = - new SimpleBooleanProperty(); - private final BooleanProperty autoCompleteBothProperty = - new SimpleBooleanProperty(); - private final BooleanProperty firstNameModeAbbreviatedProperty = - new SimpleBooleanProperty(); - private final BooleanProperty firstNameModeFullProperty = - new SimpleBooleanProperty(); - private final BooleanProperty firstNameModeBothProperty = - new SimpleBooleanProperty(); + private final BooleanProperty enableAutoCompleteProperty = new SimpleBooleanProperty(); + private final StringProperty autoCompleteFieldsProperty = new SimpleStringProperty(); + private final BooleanProperty autoCompleteFirstLastProperty = new SimpleBooleanProperty(); + private final BooleanProperty autoCompleteLastFirstProperty = new SimpleBooleanProperty(); + private final BooleanProperty autoCompleteBothProperty = new SimpleBooleanProperty(); + private final BooleanProperty firstNameModeAbbreviatedProperty = new SimpleBooleanProperty(); + private final BooleanProperty firstNameModeFullProperty = new SimpleBooleanProperty(); + private final BooleanProperty firstNameModeBothProperty = new SimpleBooleanProperty(); private final AutoCompletePreferences autoCompletePreferences; private final List restartWarnings = new ArrayList<>(); - public AutoCompletionTabViewModel( - AutoCompletePreferences autoCompletePreferences - ) { + public AutoCompletionTabViewModel(AutoCompletePreferences autoCompletePreferences) { this.autoCompletePreferences = autoCompletePreferences; } @Override public void setValues() { - enableAutoCompleteProperty.setValue( - autoCompletePreferences.shouldAutoComplete() - ); - autoCompleteFieldsProperty.setValue( - autoCompletePreferences.getCompleteNamesAsString() - ); + enableAutoCompleteProperty.setValue(autoCompletePreferences.shouldAutoComplete()); + autoCompleteFieldsProperty.setValue(autoCompletePreferences.getCompleteNamesAsString()); if ( - autoCompletePreferences.getNameFormat() == - AutoCompletePreferences.NameFormat.FIRST_LAST + autoCompletePreferences.getNameFormat() == AutoCompletePreferences.NameFormat.FIRST_LAST ) { autoCompleteFirstLastProperty.setValue(true); } else if ( - autoCompletePreferences.getNameFormat() == - AutoCompletePreferences.NameFormat.LAST_FIRST + autoCompletePreferences.getNameFormat() == AutoCompletePreferences.NameFormat.LAST_FIRST ) { autoCompleteLastFirstProperty.setValue(true); } else { @@ -65,9 +49,7 @@ public void setValues() { } switch (autoCompletePreferences.getFirstNameMode()) { - case ONLY_ABBREVIATED -> firstNameModeAbbreviatedProperty.setValue( - true - ); + case ONLY_ABBREVIATED -> firstNameModeAbbreviatedProperty.setValue(true); case ONLY_FULL -> firstNameModeFullProperty.setValue(true); default -> firstNameModeBothProperty.setValue(true); } @@ -75,61 +57,36 @@ public void setValues() { @Override public void storeSettings() { - autoCompletePreferences.setAutoComplete( - enableAutoCompleteProperty.getValue() - ); + autoCompletePreferences.setAutoComplete(enableAutoCompleteProperty.getValue()); if (autoCompleteBothProperty.getValue()) { - autoCompletePreferences.setNameFormat( - AutoCompletePreferences.NameFormat.BOTH - ); + autoCompletePreferences.setNameFormat(AutoCompletePreferences.NameFormat.BOTH); } else if (autoCompleteFirstLastProperty.getValue()) { - autoCompletePreferences.setNameFormat( - AutoCompletePreferences.NameFormat.FIRST_LAST - ); + autoCompletePreferences.setNameFormat(AutoCompletePreferences.NameFormat.FIRST_LAST); } else if (autoCompleteLastFirstProperty.getValue()) { - autoCompletePreferences.setNameFormat( - AutoCompletePreferences.NameFormat.LAST_FIRST - ); + autoCompletePreferences.setNameFormat(AutoCompletePreferences.NameFormat.LAST_FIRST); } if (firstNameModeBothProperty.getValue()) { - autoCompletePreferences.setFirstNameMode( - AutoCompleteFirstNameMode.BOTH - ); + autoCompletePreferences.setFirstNameMode(AutoCompleteFirstNameMode.BOTH); } else if (firstNameModeAbbreviatedProperty.getValue()) { - autoCompletePreferences.setFirstNameMode( - AutoCompleteFirstNameMode.ONLY_ABBREVIATED - ); + autoCompletePreferences.setFirstNameMode(AutoCompleteFirstNameMode.ONLY_ABBREVIATED); } else if (firstNameModeFullProperty.getValue()) { - autoCompletePreferences.setFirstNameMode( - AutoCompleteFirstNameMode.ONLY_FULL - ); + autoCompletePreferences.setFirstNameMode(AutoCompleteFirstNameMode.ONLY_FULL); } - if ( - autoCompletePreferences.shouldAutoComplete() != - enableAutoCompleteProperty.getValue() - ) { + if (autoCompletePreferences.shouldAutoComplete() != enableAutoCompleteProperty.getValue()) { if (enableAutoCompleteProperty.getValue()) { - restartWarnings.add( - Localization.lang("Auto complete enabled.") - ); + restartWarnings.add(Localization.lang("Auto complete enabled.")); } else { - restartWarnings.add( - Localization.lang("Auto complete disabled.") - ); + restartWarnings.add(Localization.lang("Auto complete disabled.")); } } autoCompletePreferences.getCompleteFields().clear(); autoCompletePreferences .getCompleteFields() - .addAll( - FieldFactory.parseFieldList( - autoCompleteFieldsProperty.getValue() - ) - ); + .addAll(FieldFactory.parseFieldList(autoCompleteFieldsProperty.getValue())); } @Override diff --git a/src/main/java/org/jabref/gui/preferences/citationkeypattern/CitationKeyPatternTab.java b/src/main/java/org/jabref/gui/preferences/citationkeypattern/CitationKeyPatternTab.java index be7628c1df4..fecd1a3d250 100644 --- a/src/main/java/org/jabref/gui/preferences/citationkeypattern/CitationKeyPatternTab.java +++ b/src/main/java/org/jabref/gui/preferences/citationkeypattern/CitationKeyPatternTab.java @@ -68,33 +68,17 @@ public void initialize() { preferencesService.getCitationKeyPatternPreferences() ); - overwriteAllow - .selectedProperty() - .bindBidirectional(viewModel.overwriteAllowProperty()); - overwriteWarning - .selectedProperty() - .bindBidirectional(viewModel.overwriteWarningProperty()); - generateOnSave - .selectedProperty() - .bindBidirectional(viewModel.generateOnSaveProperty()); - letterStartA - .selectedProperty() - .bindBidirectional(viewModel.letterStartAProperty()); - letterStartB - .selectedProperty() - .bindBidirectional(viewModel.letterStartBProperty()); - letterAlwaysAdd - .selectedProperty() - .bindBidirectional(viewModel.letterAlwaysAddProperty()); - keyPatternRegex - .textProperty() - .bindBidirectional(viewModel.keyPatternRegexProperty()); + overwriteAllow.selectedProperty().bindBidirectional(viewModel.overwriteAllowProperty()); + overwriteWarning.selectedProperty().bindBidirectional(viewModel.overwriteWarningProperty()); + generateOnSave.selectedProperty().bindBidirectional(viewModel.generateOnSaveProperty()); + letterStartA.selectedProperty().bindBidirectional(viewModel.letterStartAProperty()); + letterStartB.selectedProperty().bindBidirectional(viewModel.letterStartBProperty()); + letterAlwaysAdd.selectedProperty().bindBidirectional(viewModel.letterAlwaysAddProperty()); + keyPatternRegex.textProperty().bindBidirectional(viewModel.keyPatternRegexProperty()); keyPatternReplacement .textProperty() .bindBidirectional(viewModel.keyPatternReplacementProperty()); - unwantedCharacters - .textProperty() - .bindBidirectional(viewModel.unwantedCharactersProperty()); + unwantedCharacters.textProperty().bindBidirectional(viewModel.unwantedCharactersProperty()); bibtexKeyPatternTable .patternListProperty() @@ -120,13 +104,9 @@ public void setValues() { viewModel.setValues(); bibtexKeyPatternTable.setValues( Globals.entryTypesManager.getAllTypes( - preferencesService - .getLibraryPreferences() - .getDefaultBibDatabaseMode() + preferencesService.getLibraryPreferences().getDefaultBibDatabaseMode() ), - preferencesService - .getCitationKeyPatternPreferences() - .getKeyPattern() + preferencesService.getCitationKeyPatternPreferences().getKeyPattern() ); } diff --git a/src/main/java/org/jabref/gui/preferences/citationkeypattern/CitationKeyPatternTabViewModel.java b/src/main/java/org/jabref/gui/preferences/citationkeypattern/CitationKeyPatternTabViewModel.java index 52c6dad18ad..3982b97bb44 100644 --- a/src/main/java/org/jabref/gui/preferences/citationkeypattern/CitationKeyPatternTabViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/citationkeypattern/CitationKeyPatternTabViewModel.java @@ -17,64 +17,42 @@ public class CitationKeyPatternTabViewModel implements PreferenceTabViewModel { - private final BooleanProperty overwriteAllowProperty = - new SimpleBooleanProperty(); - private final BooleanProperty overwriteWarningProperty = - new SimpleBooleanProperty(); - private final BooleanProperty generateOnSaveProperty = - new SimpleBooleanProperty(); - private final BooleanProperty letterStartAProperty = - new SimpleBooleanProperty(); - private final BooleanProperty letterStartBProperty = - new SimpleBooleanProperty(); - private final BooleanProperty letterAlwaysAddProperty = - new SimpleBooleanProperty(); - private final StringProperty keyPatternRegexProperty = - new SimpleStringProperty(); - private final StringProperty keyPatternReplacementProperty = - new SimpleStringProperty(); - private final StringProperty unwantedCharactersProperty = - new SimpleStringProperty(); + private final BooleanProperty overwriteAllowProperty = new SimpleBooleanProperty(); + private final BooleanProperty overwriteWarningProperty = new SimpleBooleanProperty(); + private final BooleanProperty generateOnSaveProperty = new SimpleBooleanProperty(); + private final BooleanProperty letterStartAProperty = new SimpleBooleanProperty(); + private final BooleanProperty letterStartBProperty = new SimpleBooleanProperty(); + private final BooleanProperty letterAlwaysAddProperty = new SimpleBooleanProperty(); + private final StringProperty keyPatternRegexProperty = new SimpleStringProperty(); + private final StringProperty keyPatternReplacementProperty = new SimpleStringProperty(); + private final StringProperty unwantedCharactersProperty = new SimpleStringProperty(); // The list and the default properties are being overwritten by the bound properties of the tableView, but to // prevent an NPE on storing the preferences before lazy-loading of the setValues, they need to be initialized. - private final ListProperty< - CitationKeyPatternPanelItemModel - > patternListProperty = new SimpleListProperty<>( - FXCollections.observableArrayList() - ); - private final ObjectProperty< - CitationKeyPatternPanelItemModel - > defaultKeyPatternProperty = new SimpleObjectProperty<>( - new CitationKeyPatternPanelItemModel( - new CitationKeyPatternPanelViewModel.DefaultEntryType(), - "" - ) - ); + private final ListProperty patternListProperty = + new SimpleListProperty<>(FXCollections.observableArrayList()); + private final ObjectProperty defaultKeyPatternProperty = + new SimpleObjectProperty<>( + new CitationKeyPatternPanelItemModel( + new CitationKeyPatternPanelViewModel.DefaultEntryType(), + "" + ) + ); private final CitationKeyPatternPreferences keyPatternPreferences; - public CitationKeyPatternTabViewModel( - CitationKeyPatternPreferences keyPatternPreferences - ) { + public CitationKeyPatternTabViewModel(CitationKeyPatternPreferences keyPatternPreferences) { this.keyPatternPreferences = keyPatternPreferences; } @Override public void setValues() { - overwriteAllowProperty.setValue( - !keyPatternPreferences.shouldAvoidOverwriteCiteKey() - ); - overwriteWarningProperty.setValue( - keyPatternPreferences.shouldWarnBeforeOverwriteCiteKey() - ); - generateOnSaveProperty.setValue( - keyPatternPreferences.shouldGenerateCiteKeysBeforeSaving() - ); + overwriteAllowProperty.setValue(!keyPatternPreferences.shouldAvoidOverwriteCiteKey()); + overwriteWarningProperty.setValue(keyPatternPreferences.shouldWarnBeforeOverwriteCiteKey()); + generateOnSaveProperty.setValue(keyPatternPreferences.shouldGenerateCiteKeysBeforeSaving()); if ( - keyPatternPreferences.getKeySuffix() == - CitationKeyPatternPreferences.KeySuffix.ALWAYS + keyPatternPreferences.getKeySuffix() == CitationKeyPatternPreferences.KeySuffix.ALWAYS ) { letterAlwaysAddProperty.setValue(true); letterStartAProperty.setValue(false); @@ -92,15 +70,9 @@ public void setValues() { letterStartBProperty.setValue(true); } - keyPatternRegexProperty.setValue( - keyPatternPreferences.getKeyPatternRegex() - ); - keyPatternReplacementProperty.setValue( - keyPatternPreferences.getKeyPatternReplacement() - ); - unwantedCharactersProperty.setValue( - keyPatternPreferences.getUnwantedCharacters() - ); + keyPatternRegexProperty.setValue(keyPatternPreferences.getKeyPatternRegex()); + keyPatternReplacementProperty.setValue(keyPatternPreferences.getKeyPatternReplacement()); + unwantedCharactersProperty.setValue(keyPatternPreferences.getUnwantedCharacters()); } @Override @@ -112,22 +84,15 @@ public void storeSettings() { String patternString = item.getPattern(); if (!item.getEntryType().getName().equals("default")) { if (!patternString.trim().isEmpty()) { - newKeyPattern.addCitationKeyPattern( - item.getEntryType(), - patternString - ); + newKeyPattern.addCitationKeyPattern(item.getEntryType(), patternString); } } }); - if ( - !defaultKeyPatternProperty.getValue().getPattern().trim().isEmpty() - ) { + if (!defaultKeyPatternProperty.getValue().getPattern().trim().isEmpty()) { // we do not trim the value at the assignment to enable users to have spaces at the beginning and // at the end of the pattern - newKeyPattern.setDefaultValue( - defaultKeyPatternProperty.getValue().getPattern() - ); + newKeyPattern.setDefaultValue(defaultKeyPatternProperty.getValue().getPattern()); } CitationKeyPatternPreferences.KeySuffix keySuffix = @@ -139,25 +104,13 @@ public void storeSettings() { keySuffix = CitationKeyPatternPreferences.KeySuffix.SECOND_WITH_B; } - keyPatternPreferences.setAvoidOverwriteCiteKey( - !overwriteAllowProperty.getValue() - ); - keyPatternPreferences.setWarnBeforeOverwriteCiteKey( - overwriteWarningProperty.getValue() - ); - keyPatternPreferences.setGenerateCiteKeysBeforeSaving( - generateOnSaveProperty.getValue() - ); + keyPatternPreferences.setAvoidOverwriteCiteKey(!overwriteAllowProperty.getValue()); + keyPatternPreferences.setWarnBeforeOverwriteCiteKey(overwriteWarningProperty.getValue()); + keyPatternPreferences.setGenerateCiteKeysBeforeSaving(generateOnSaveProperty.getValue()); keyPatternPreferences.setKeySuffix(keySuffix); - keyPatternPreferences.setKeyPatternRegex( - keyPatternRegexProperty.getValue() - ); - keyPatternPreferences.setKeyPatternReplacement( - keyPatternReplacementProperty.getValue() - ); - keyPatternPreferences.setUnwantedCharacters( - unwantedCharactersProperty.getValue() - ); + keyPatternPreferences.setKeyPatternRegex(keyPatternRegexProperty.getValue()); + keyPatternPreferences.setKeyPatternReplacement(keyPatternReplacementProperty.getValue()); + keyPatternPreferences.setUnwantedCharacters(unwantedCharactersProperty.getValue()); keyPatternPreferences.setKeyPattern(newKeyPattern); } @@ -193,15 +146,11 @@ public StringProperty keyPatternReplacementProperty() { return keyPatternReplacementProperty; } - public ListProperty< - CitationKeyPatternPanelItemModel - > patternListProperty() { + public ListProperty patternListProperty() { return patternListProperty; } - public ObjectProperty< - CitationKeyPatternPanelItemModel - > defaultKeyPatternProperty() { + public ObjectProperty defaultKeyPatternProperty() { return defaultKeyPatternProperty; } diff --git a/src/main/java/org/jabref/gui/preferences/customentrytypes/CustomEntryTypeViewModel.java b/src/main/java/org/jabref/gui/preferences/customentrytypes/CustomEntryTypeViewModel.java index 49210d85955..a708fdfc52d 100644 --- a/src/main/java/org/jabref/gui/preferences/customentrytypes/CustomEntryTypeViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/customentrytypes/CustomEntryTypeViewModel.java @@ -6,10 +6,7 @@ public class CustomEntryTypeViewModel extends EntryTypeViewModel { - public CustomEntryTypeViewModel( - BibEntryType entryType, - Predicate isMultiline - ) { + public CustomEntryTypeViewModel(BibEntryType entryType, Predicate isMultiline) { super(entryType, isMultiline); } } diff --git a/src/main/java/org/jabref/gui/preferences/customentrytypes/CustomEntryTypesTab.java b/src/main/java/org/jabref/gui/preferences/customentrytypes/CustomEntryTypesTab.java index 93c95c930d1..e2b184ee769 100644 --- a/src/main/java/org/jabref/gui/preferences/customentrytypes/CustomEntryTypesTab.java +++ b/src/main/java/org/jabref/gui/preferences/customentrytypes/CustomEntryTypesTab.java @@ -99,11 +99,7 @@ public void initialize() { BibDatabaseMode mode = stateManager .getActiveDatabase() .map(BibDatabaseContext::getMode) - .orElse( - preferencesService - .getLibraryPreferences() - .getDefaultBibDatabaseMode() - ); + .orElse(preferencesService.getLibraryPreferences().getDefaultBibDatabaseMode()); BibEntryTypesManager entryTypesRepository = preferencesService.getCustomEntryTypesRepository(); @@ -134,11 +130,7 @@ public void initialize() { addNewEntryType, true ); - visualizer.initVisualization( - viewModel.fieldValidationStatus(), - addNewField, - true - ); + visualizer.initVisualization(viewModel.fieldValidationStatus(), addNewField, true); }); } @@ -179,9 +171,7 @@ private void setupEntryTypesTable() { if (type instanceof CustomEntryTypeViewModel) { return evt -> viewModel.removeEntryType( - entryTypesTable - .getSelectionModel() - .getSelectedItem() + entryTypesTable.getSelectionModel().getSelectedItem() ); } else { return evt -> {}; @@ -192,9 +182,7 @@ private void setupEntryTypesTable() { viewModel .selectedEntryTypeProperty() .bind(entryTypesTable.getSelectionModel().selectedItemProperty()); - viewModel - .entryTypeToAddProperty() - .bindBidirectional(addNewEntryType.textProperty()); + viewModel.entryTypeToAddProperty().bindBidirectional(addNewEntryType.textProperty()); EasyBind.subscribe( viewModel.selectedEntryTypeProperty(), @@ -210,32 +198,23 @@ private void setupEntryTypesTable() { } private void setupFieldsTable() { - fieldNameColumn.setCellValueFactory(item -> - item.getValue().displayNameProperty() - ); + fieldNameColumn.setCellValueFactory(item -> item.getValue().displayNameProperty()); fieldNameColumn.setCellFactory(TextFieldTableCell.forTableColumn()); fieldNameColumn.setEditable(true); fieldNameColumn.setOnEditCommit( (TableColumn.CellEditEvent event) -> { String newDisplayName = event.getNewValue(); if (newDisplayName.isBlank()) { - dialogService.notify( - Localization.lang("Name cannot be empty") - ); + dialogService.notify(Localization.lang("Name cannot be empty")); event.getTableView().edit(-1, null); event.getTableView().refresh(); return; } FieldViewModel fieldViewModel = event.getRowValue(); - String currentDisplayName = fieldViewModel - .displayNameProperty() - .getValue(); - EntryTypeViewModel selectedEntryType = viewModel - .selectedEntryTypeProperty() - .get(); - ObservableList entryFields = - selectedEntryType.fields(); + String currentDisplayName = fieldViewModel.displayNameProperty().getValue(); + EntryTypeViewModel selectedEntryType = viewModel.selectedEntryTypeProperty().get(); + ObservableList entryFields = selectedEntryType.fields(); // The first predicate will check if the user input the original field name or doesn't edit anything after double click boolean fieldExists = !newDisplayName.equals(currentDisplayName) && @@ -249,32 +228,21 @@ private void setupFieldsTable() { ); event.getTableView().edit(-1, null); } else { - fieldViewModel - .displayNameProperty() - .setValue(newDisplayName); + fieldViewModel.displayNameProperty().setValue(newDisplayName); } event.getTableView().refresh(); } ); - fieldTypeColumn.setCellFactory( - CheckBoxTableCell.forTableColumn(fieldTypeColumn) - ); - fieldTypeColumn.setCellValueFactory(item -> - item.getValue().requiredProperty() - ); + fieldTypeColumn.setCellFactory(CheckBoxTableCell.forTableColumn(fieldTypeColumn)); + fieldTypeColumn.setCellValueFactory(item -> item.getValue().requiredProperty()); makeRotatedColumnHeader(fieldTypeColumn, Localization.lang("Required")); fieldTypeMultilineColumn.setCellFactory( CheckBoxTableCell.forTableColumn(fieldTypeMultilineColumn) ); - fieldTypeMultilineColumn.setCellValueFactory(item -> - item.getValue().multilineProperty() - ); - makeRotatedColumnHeader( - fieldTypeMultilineColumn, - Localization.lang("Multiline") - ); + fieldTypeMultilineColumn.setCellValueFactory(item -> item.getValue().multilineProperty()); + makeRotatedColumnHeader(fieldTypeMultilineColumn, Localization.lang("Multiline")); fieldTypeActionColumn.setSortable(false); fieldTypeActionColumn.setReorderable(false); @@ -284,20 +252,12 @@ private void setupFieldsTable() { ); new ValueTableCellFactory() - .withGraphic(item -> - IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode() - ) + .withGraphic(item -> IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode()) .withTooltip(name -> - Localization.lang( - "Remove field %0 from currently selected entry type", - name - ) + Localization.lang("Remove field %0 from currently selected entry type", name) ) .withOnMouseClickedEvent(item -> - evt -> - viewModel.removeField( - fields.getSelectionModel().getSelectedItem() - ) + evt -> viewModel.removeField(fields.getSelectionModel().getSelectedItem()) ) .install(fieldTypeActionColumn); @@ -311,24 +271,16 @@ private void setupFieldsTable() { addNewField.setItems(viewModel.fieldsForAdding()); addNewField.setConverter(FieldsUtil.FIELD_STRING_CONVERTER); - viewModel - .newFieldToAddProperty() - .bindBidirectional(addNewField.valueProperty()); + viewModel.newFieldToAddProperty().bindBidirectional(addNewField.valueProperty()); // The valueProperty() of addNewField ComboBox needs to be updated by typing text in the ComboBox textfield, // since the enabled/disabled state of addNewFieldButton won't update otherwise EasyBind.subscribe( addNewField.getEditor().textProperty(), - text -> - addNewField.setValue( - FieldsUtil.FIELD_STRING_CONVERTER.fromString(text) - ) + text -> addNewField.setValue(FieldsUtil.FIELD_STRING_CONVERTER.fromString(text)) ); } - private void makeRotatedColumnHeader( - TableColumn column, - String text - ) { + private void makeRotatedColumnHeader(TableColumn column, String text) { Label label = new Label(); label.setText(text); label.setRotate(-90); @@ -373,9 +325,7 @@ private void handleOnDragDropped( DragEvent event ) { if (localDragboard.hasType(FieldViewModel.class)) { - FieldViewModel field = localDragboard.getValue( - FieldViewModel.class - ); + FieldViewModel field = localDragboard.getValue(FieldViewModel.class); fields.getItems().remove(field); if (row.isEmpty()) { diff --git a/src/main/java/org/jabref/gui/preferences/customentrytypes/CustomEntryTypesTabViewModel.java b/src/main/java/org/jabref/gui/preferences/customentrytypes/CustomEntryTypesTabViewModel.java index 1e61a2ed752..40b7b1e2634 100644 --- a/src/main/java/org/jabref/gui/preferences/customentrytypes/CustomEntryTypesTabViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/customentrytypes/CustomEntryTypesTabViewModel.java @@ -38,15 +38,13 @@ public class CustomEntryTypesTabViewModel implements PreferenceTabViewModel { - private final ObservableList fieldsForAdding = - FXCollections.observableArrayList( - FieldFactory.getStandardFieldsWithCitationKey() - ); + private final ObservableList fieldsForAdding = FXCollections.observableArrayList( + FieldFactory.getStandardFieldsWithCitationKey() + ); private final ObjectProperty selectedEntryType = new SimpleObjectProperty<>(); private final StringProperty entryTypeToAdd = new SimpleStringProperty(""); - private final ObjectProperty newFieldToAdd = - new SimpleObjectProperty<>(); + private final ObjectProperty newFieldToAdd = new SimpleObjectProperty<>(); private final ObservableList entryTypesWithFields = FXCollections.observableArrayList(extractor -> new Observable[] { extractor.entryType(), extractor.fields() } @@ -86,21 +84,15 @@ public CustomEntryTypesTabViewModel( entryTypeToAdd, StringUtil::isNotBlank, ValidationMessage.error( - Localization.lang( - "Entry type cannot be empty. Please enter a name." - ) + Localization.lang("Entry type cannot be empty. Please enter a name.") ) ); fieldValidator = new FunctionBasedValidator<>( newFieldToAdd, - input -> - (input != null) && - StringUtil.isNotBlank(input.getDisplayName()), + input -> (input != null) && StringUtil.isNotBlank(input.getDisplayName()), ValidationMessage.error( - Localization.lang( - "Field cannot be empty. Please enter a name." - ) + Localization.lang("Field cannot be empty. Please enter a name.") ) ); } @@ -110,20 +102,12 @@ public void setValues() { if (!this.entryTypesWithFields.isEmpty()) { this.entryTypesWithFields.clear(); } - Collection allTypes = entryTypesManager.getAllTypes( - bibDatabaseMode - ); + Collection allTypes = entryTypesManager.getAllTypes(bibDatabaseMode); for (BibEntryType entryType : allTypes) { EntryTypeViewModel viewModel; - if ( - entryTypesManager.isCustomType( - entryType.getType(), - bibDatabaseMode - ) - ) { - viewModel = - new CustomEntryTypeViewModel(entryType, isMultiline); + if (entryTypesManager.isCustomType(entryType.getType(), bibDatabaseMode)) { + viewModel = new CustomEntryTypeViewModel(entryType, isMultiline); } else { viewModel = new EntryTypeViewModel(entryType, isMultiline); } @@ -157,40 +141,26 @@ public void storeSettings() { .map(FieldViewModel::toBibField) .collect(Collectors.toList()); - BibEntryType newType = new BibEntryType( - type.getType(), - fields, - required - ); + BibEntryType newType = new BibEntryType(type.getType(), fields, required); entryTypesManager.addCustomOrModifiedType(newType, bibDatabaseMode); } for (var entryType : entryTypesToDelete) { - entryTypesManager.removeCustomOrModifiedEntryType( - entryType, - bibDatabaseMode - ); + entryTypesManager.removeCustomOrModifiedEntryType(entryType, bibDatabaseMode); } - preferencesService - .getFieldPreferences() - .setNonWrappableFields(multilineFields); + preferencesService.getFieldPreferences().setNonWrappableFields(multilineFields); preferencesService.storeCustomEntryTypesRepository(entryTypesManager); } public EntryTypeViewModel addNewCustomEntryType() { - EntryType newentryType = new UnknownEntryType( - entryTypeToAdd.getValue() - ); + EntryType newentryType = new UnknownEntryType(entryTypeToAdd.getValue()); BibEntryType type = new BibEntryType( newentryType, new ArrayList<>(), Collections.emptyList() ); - EntryTypeViewModel viewModel = new CustomEntryTypeViewModel( - type, - isMultiline - ); + EntryTypeViewModel viewModel = new CustomEntryTypeViewModel(type, isMultiline); this.entryTypesWithFields.add(viewModel); this.entryTypeToAdd.setValue(""); @@ -229,15 +199,11 @@ public void addNewField() { } public boolean displayNameExists(String displayName) { - ObservableList entryFields = - this.selectedEntryType.getValue().fields(); + ObservableList entryFields = this.selectedEntryType.getValue().fields(); return entryFields .stream() .anyMatch(fieldViewModel -> - fieldViewModel - .displayNameProperty() - .getValue() - .equals(displayName) + fieldViewModel.displayNameProperty().getValue().equals(displayName) ); } diff --git a/src/main/java/org/jabref/gui/preferences/customentrytypes/EntryTypeViewModel.java b/src/main/java/org/jabref/gui/preferences/customentrytypes/EntryTypeViewModel.java index 17f430b7684..c4b51401c29 100644 --- a/src/main/java/org/jabref/gui/preferences/customentrytypes/EntryTypeViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/customentrytypes/EntryTypeViewModel.java @@ -15,14 +15,10 @@ public class EntryTypeViewModel { - private final ObjectProperty entryType = - new SimpleObjectProperty<>(); + private final ObjectProperty entryType = new SimpleObjectProperty<>(); private final ObservableList fields; - public EntryTypeViewModel( - BibEntryType entryType, - Predicate isMultiline - ) { + public EntryTypeViewModel(BibEntryType entryType, Predicate isMultiline) { this.entryType.set(entryType); List allFieldsForType = entryType .getAllBibFields() @@ -55,10 +51,7 @@ public boolean equals(Object obj) { return false; } EntryTypeViewModel other = (EntryTypeViewModel) obj; - return ( - Objects.equals(entryType, other.entryType) && - Objects.equals(fields, other.fields) - ); + return (Objects.equals(entryType, other.entryType) && Objects.equals(fields, other.fields)); } public void addField(FieldViewModel field) { @@ -79,12 +72,6 @@ public void removeField(FieldViewModel focusedItem) { @Override public String toString() { - return ( - "CustomEntryTypeViewModel [entryType=" + - entryType + - ", fields=" + - fields + - "]" - ); + return ("CustomEntryTypeViewModel [entryType=" + entryType + ", fields=" + fields + "]"); } } diff --git a/src/main/java/org/jabref/gui/preferences/customentrytypes/FieldViewModel.java b/src/main/java/org/jabref/gui/preferences/customentrytypes/FieldViewModel.java index a66833ab368..5b29230c8cd 100644 --- a/src/main/java/org/jabref/gui/preferences/customentrytypes/FieldViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/customentrytypes/FieldViewModel.java @@ -18,8 +18,7 @@ public class FieldViewModel { private final StringProperty displayName = new SimpleStringProperty(""); private final BooleanProperty required = new SimpleBooleanProperty(); private final BooleanProperty multiline = new SimpleBooleanProperty(); - private final ObjectProperty priorityProperty = - new SimpleObjectProperty<>(); + private final ObjectProperty priorityProperty = new SimpleObjectProperty<>(); public FieldViewModel( Field field, diff --git a/src/main/java/org/jabref/gui/preferences/customexporter/CustomExporterTab.java b/src/main/java/org/jabref/gui/preferences/customexporter/CustomExporterTab.java index b7a0aba6d2c..0ed93d3045f 100644 --- a/src/main/java/org/jabref/gui/preferences/customexporter/CustomExporterTab.java +++ b/src/main/java/org/jabref/gui/preferences/customexporter/CustomExporterTab.java @@ -38,24 +38,17 @@ public String getTabName() { @FXML private void initialize() { - viewModel = - new CustomExporterTabViewModel(preferencesService, dialogService); + viewModel = new CustomExporterTabViewModel(preferencesService, dialogService); - exporterTable - .getSelectionModel() - .setSelectionMode(SelectionMode.MULTIPLE); + exporterTable.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); exporterTable.itemsProperty().bind(viewModel.exportersProperty()); EasyBind.bindContent( viewModel.selectedExportersProperty(), exporterTable.getSelectionModel().getSelectedItems() ); nameColumn.setCellValueFactory(cellData -> cellData.getValue().name()); - layoutColumn.setCellValueFactory(cellData -> - cellData.getValue().layoutFileName() - ); - extensionColumn.setCellValueFactory(cellData -> - cellData.getValue().extension() - ); + layoutColumn.setCellValueFactory(cellData -> cellData.getValue().layoutFileName()); + extensionColumn.setCellValueFactory(cellData -> cellData.getValue().extension()); } @FXML diff --git a/src/main/java/org/jabref/gui/preferences/customexporter/CustomExporterTabViewModel.java b/src/main/java/org/jabref/gui/preferences/customexporter/CustomExporterTabViewModel.java index b1621c45f3a..da6d79b4192 100644 --- a/src/main/java/org/jabref/gui/preferences/customexporter/CustomExporterTabViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/customexporter/CustomExporterTabViewModel.java @@ -15,18 +15,17 @@ public class CustomExporterTabViewModel implements PreferenceTabViewModel { - private final ListProperty exporters = - new SimpleListProperty<>(FXCollections.observableArrayList()); - private final ListProperty selectedExporters = - new SimpleListProperty<>(FXCollections.observableArrayList()); + private final ListProperty exporters = new SimpleListProperty<>( + FXCollections.observableArrayList() + ); + private final ListProperty selectedExporters = new SimpleListProperty<>( + FXCollections.observableArrayList() + ); private final PreferencesService preferences; private final DialogService dialogService; - public CustomExporterTabViewModel( - PreferencesService preferences, - DialogService dialogService - ) { + public CustomExporterTabViewModel(PreferencesService preferences, DialogService dialogService) { this.preferences = preferences; this.dialogService = dialogService; } @@ -52,10 +51,8 @@ public void storeSettings() { } public void addExporter() { - CreateModifyExporterDialogView dialog = - new CreateModifyExporterDialogView(null); - Optional exporter = - dialogService.showCustomDialogAndWait(dialog); + CreateModifyExporterDialogView dialog = new CreateModifyExporterDialogView(null); + Optional exporter = dialogService.showCustomDialogAndWait(dialog); if ((exporter != null) && exporter.isPresent()) { exporters.add(exporter.get()); } @@ -67,10 +64,10 @@ public void modifyExporter() { } ExporterViewModel exporterToModify = selectedExporters.get(0); - CreateModifyExporterDialogView dialog = - new CreateModifyExporterDialogView(exporterToModify); - Optional exporter = - dialogService.showCustomDialogAndWait(dialog); + CreateModifyExporterDialogView dialog = new CreateModifyExporterDialogView( + exporterToModify + ); + Optional exporter = dialogService.showCustomDialogAndWait(dialog); if ((exporter != null) && exporter.isPresent()) { exporters.remove(exporterToModify); exporters.add(exporter.get()); diff --git a/src/main/java/org/jabref/gui/preferences/customimporter/CustomImporterTab.java b/src/main/java/org/jabref/gui/preferences/customimporter/CustomImporterTab.java index 9b127f85662..75dbc4108cf 100644 --- a/src/main/java/org/jabref/gui/preferences/customimporter/CustomImporterTab.java +++ b/src/main/java/org/jabref/gui/preferences/customimporter/CustomImporterTab.java @@ -44,37 +44,26 @@ public String getTabName() { @FXML private void initialize() { - viewModel = - new CustomImporterTabViewModel(preferencesService, dialogService); + viewModel = new CustomImporterTabViewModel(preferencesService, dialogService); - importerTable - .getSelectionModel() - .setSelectionMode(SelectionMode.MULTIPLE); + importerTable.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); importerTable.itemsProperty().bind(viewModel.importersProperty()); EasyBind.bindContent( viewModel.selectedImportersProperty(), importerTable.getSelectionModel().getSelectedItems() ); nameColumn.setCellValueFactory(cellData -> cellData.getValue().name()); - classColumn.setCellValueFactory(cellData -> - cellData.getValue().className() - ); - basePathColumn.setCellValueFactory(cellData -> - cellData.getValue().basePath() - ); + classColumn.setCellValueFactory(cellData -> cellData.getValue().className()); + basePathColumn.setCellValueFactory(cellData -> cellData.getValue().basePath()); new ViewModelTableRowFactory() .withTooltip(importer -> importer.getLogic().getDescription()) .install(importerTable); addButton.setTooltip( new Tooltip( - Localization.lang( - "Add a (compiled) custom Importer class from a class path." - ) + + Localization.lang("Add a (compiled) custom Importer class from a class path.") + "\n" + - Localization.lang( - "The path need not be on the classpath of JabRef." - ) + Localization.lang("The path need not be on the classpath of JabRef.") ) ); } diff --git a/src/main/java/org/jabref/gui/preferences/customimporter/CustomImporterTabViewModel.java b/src/main/java/org/jabref/gui/preferences/customimporter/CustomImporterTabViewModel.java index 71fc7e5d112..b75d8daa330 100644 --- a/src/main/java/org/jabref/gui/preferences/customimporter/CustomImporterTabViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/customimporter/CustomImporterTabViewModel.java @@ -24,22 +24,19 @@ public class CustomImporterTabViewModel implements PreferenceTabViewModel { - private static final Logger LOGGER = LoggerFactory.getLogger( - CustomImporterTabViewModel.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(CustomImporterTabViewModel.class); - private final ListProperty importers = - new SimpleListProperty<>(FXCollections.observableArrayList()); - private final ListProperty selectedImporters = - new SimpleListProperty<>(FXCollections.observableArrayList()); + private final ListProperty importers = new SimpleListProperty<>( + FXCollections.observableArrayList() + ); + private final ListProperty selectedImporters = new SimpleListProperty<>( + FXCollections.observableArrayList() + ); private final PreferencesService preferences; private final DialogService dialogService; - public CustomImporterTabViewModel( - PreferencesService preferences, - DialogService dialogService - ) { + public CustomImporterTabViewModel(PreferencesService preferences, DialogService dialogService) { this.preferences = preferences; this.dialogService = dialogService; } @@ -60,10 +57,7 @@ public void storeSettings() { preferences .getImporterPreferences() .setCustomImporters( - importers - .stream() - .map(ImporterViewModel::getLogic) - .collect(Collectors.toSet()) + importers.stream().map(ImporterViewModel::getLogic).collect(Collectors.toSet()) ); } @@ -89,51 +83,31 @@ private static String pathToClass(String basePath, Path path) { } public void addImporter() { - FileDialogConfiguration fileDialogConfiguration = - new FileDialogConfiguration.Builder() - .addExtensionFilter( - StandardFileType.CLASS, - StandardFileType.JAR, - StandardFileType.ZIP - ) - .withDefaultExtension(StandardFileType.CLASS) - .withInitialDirectory( - preferences.getFilePreferences().getWorkingDirectory() - ) - .build(); + FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() + .addExtensionFilter(StandardFileType.CLASS, StandardFileType.JAR, StandardFileType.ZIP) + .withDefaultExtension(StandardFileType.CLASS) + .withInitialDirectory(preferences.getFilePreferences().getWorkingDirectory()) + .build(); - Optional selectedFile = dialogService.showFileOpenDialog( - fileDialogConfiguration - ); + Optional selectedFile = dialogService.showFileOpenDialog(fileDialogConfiguration); - if ( - selectedFile.isPresent() && (selectedFile.get().getParent() != null) - ) { + if (selectedFile.isPresent() && (selectedFile.get().getParent() != null)) { boolean isArchive = FileUtil .getFileExtension(selectedFile.get()) .filter(extension -> - "jar".equalsIgnoreCase(extension) || - "zip".equalsIgnoreCase(extension) + "jar".equalsIgnoreCase(extension) || "zip".equalsIgnoreCase(extension) ) .isPresent(); if (isArchive) { try { Optional selectedFileInArchive = - dialogService.showFileOpenFromArchiveDialog( - selectedFile.get() - ); + dialogService.showFileOpenFromArchiveDialog(selectedFile.get()); if (selectedFileInArchive.isPresent()) { String className = selectedFileInArchive .get() .toString() - .substring( - 0, - selectedFileInArchive - .get() - .toString() - .lastIndexOf('.') - ) + .substring(0, selectedFileInArchive.get().toString().lastIndexOf('.')) .replace("/", "."); CustomImporter importer = new CustomImporter( selectedFile.get().toAbsolutePath().toString(), @@ -144,37 +118,23 @@ public void addImporter() { } catch (IOException exc) { LOGGER.error("Could not open ZIP-archive.", exc); dialogService.showErrorDialogAndWait( - Localization.lang( - "Could not open %0", - selectedFile.get().toString() - ) + + Localization.lang("Could not open %0", selectedFile.get().toString()) + "\n" + - Localization.lang( - "Have you chosen the correct package path?" - ), + Localization.lang("Have you chosen the correct package path?"), exc ); } catch (ImportException exc) { LOGGER.error("Could not instantiate importer", exc); dialogService.showErrorDialogAndWait( - Localization.lang( - "Could not instantiate %0 %1", - "importer" - ), + Localization.lang("Could not instantiate %0 %1", "importer"), exc ); } } else { try { String basePath = selectedFile.get().getParent().toString(); - String className = pathToClass( - basePath, - selectedFile.get() - ); - CustomImporter importer = new CustomImporter( - basePath, - className - ); + String className = pathToClass(basePath, selectedFile.get()); + CustomImporter importer = new CustomImporter(basePath, className); importers.add(new ImporterViewModel(importer)); } catch (Exception exc) { @@ -187,10 +147,7 @@ public void addImporter() { exc ); } catch (NoClassDefFoundError exc) { - LOGGER.error( - "Could not find class while instantiating importer", - exc - ); + LOGGER.error("Could not find class while instantiating importer", exc); dialogService.showErrorDialogAndWait( Localization.lang( "Could not instantiate %0. Have you chosen the correct package path?", diff --git a/src/main/java/org/jabref/gui/preferences/entry/EntryTab.java b/src/main/java/org/jabref/gui/preferences/entry/EntryTab.java index d681a5694a1..62cc7a01dbc 100644 --- a/src/main/java/org/jabref/gui/preferences/entry/EntryTab.java +++ b/src/main/java/org/jabref/gui/preferences/entry/EntryTab.java @@ -61,9 +61,7 @@ public EntryTab() { public void initialize() { this.viewModel = new EntryTabViewModel(preferencesService); - keywordSeparator - .textProperty() - .bindBidirectional(viewModel.keywordSeparatorProperty()); + keywordSeparator.textProperty().bindBidirectional(viewModel.keywordSeparatorProperty()); // Use TextFormatter to limit the length of the Input of keywordSeparator to 1 character only. UnaryOperator singleCharacterFilter = change -> { @@ -72,41 +70,25 @@ public void initialize() { } return null; // null means the change is rejected }; - TextFormatter formatter = new TextFormatter<>( - singleCharacterFilter - ); + TextFormatter formatter = new TextFormatter<>(singleCharacterFilter); keywordSeparator.setTextFormatter(formatter); - resolveStrings - .selectedProperty() - .bindBidirectional(viewModel.resolveStringsProperty()); + resolveStrings.selectedProperty().bindBidirectional(viewModel.resolveStringsProperty()); resolveStringsForFields .textProperty() .bindBidirectional(viewModel.resolveStringsForFieldsProperty()); - nonWrappableFields - .textProperty() - .bindBidirectional(viewModel.nonWrappableFieldsProperty()); + nonWrappableFields.textProperty().bindBidirectional(viewModel.nonWrappableFieldsProperty()); - markOwner - .selectedProperty() - .bindBidirectional(viewModel.markOwnerProperty()); - markOwnerName - .textProperty() - .bindBidirectional(viewModel.markOwnerNameProperty()); - markOwnerName - .disableProperty() - .bind(markOwner.selectedProperty().not()); + markOwner.selectedProperty().bindBidirectional(viewModel.markOwnerProperty()); + markOwnerName.textProperty().bindBidirectional(viewModel.markOwnerNameProperty()); + markOwnerName.disableProperty().bind(markOwner.selectedProperty().not()); markOwnerOverwrite .selectedProperty() .bindBidirectional(viewModel.markOwnerOverwriteProperty()); - markOwnerOverwrite - .disableProperty() - .bind(markOwner.selectedProperty().not()); + markOwnerOverwrite.disableProperty().bind(markOwner.selectedProperty().not()); - addCreationDate - .selectedProperty() - .bindBidirectional(viewModel.addCreationDateProperty()); + addCreationDate.selectedProperty().bindBidirectional(viewModel.addCreationDateProperty()); addModificationDate .selectedProperty() .bindBidirectional(viewModel.addModificationDateProperty()); @@ -114,11 +96,7 @@ public void initialize() { ActionFactory actionFactory = new ActionFactory(keyBindingRepository); actionFactory.configureIconButton( StandardActions.HELP, - new HelpAction( - HelpFile.OWNER, - dialogService, - preferencesService.getFilePreferences() - ), + new HelpAction(HelpFile.OWNER, dialogService, preferencesService.getFilePreferences()), markOwnerHelp ); } diff --git a/src/main/java/org/jabref/gui/preferences/entry/EntryTabViewModel.java b/src/main/java/org/jabref/gui/preferences/entry/EntryTabViewModel.java index dfed9652b0a..a3e791b51b9 100644 --- a/src/main/java/org/jabref/gui/preferences/entry/EntryTabViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/entry/EntryTabViewModel.java @@ -14,26 +14,17 @@ public class EntryTabViewModel implements PreferenceTabViewModel { - private final StringProperty keywordSeparatorProperty = - new SimpleStringProperty(""); - - private final BooleanProperty resolveStringsProperty = - new SimpleBooleanProperty(); - private final StringProperty resolveStringsForFieldsProperty = - new SimpleStringProperty(""); - private final StringProperty nonWrappableFieldsProperty = - new SimpleStringProperty(""); - - private final BooleanProperty markOwnerProperty = - new SimpleBooleanProperty(); - private final StringProperty markOwnerNameProperty = - new SimpleStringProperty(""); - private final BooleanProperty markOwnerOverwriteProperty = - new SimpleBooleanProperty(); - private final BooleanProperty addCreationDateProperty = - new SimpleBooleanProperty(); - private final BooleanProperty addModificationDateProperty = - new SimpleBooleanProperty(); + private final StringProperty keywordSeparatorProperty = new SimpleStringProperty(""); + + private final BooleanProperty resolveStringsProperty = new SimpleBooleanProperty(); + private final StringProperty resolveStringsForFieldsProperty = new SimpleStringProperty(""); + private final StringProperty nonWrappableFieldsProperty = new SimpleStringProperty(""); + + private final BooleanProperty markOwnerProperty = new SimpleBooleanProperty(); + private final StringProperty markOwnerNameProperty = new SimpleStringProperty(""); + private final BooleanProperty markOwnerOverwriteProperty = new SimpleBooleanProperty(); + private final BooleanProperty addCreationDateProperty = new SimpleBooleanProperty(); + private final BooleanProperty addModificationDateProperty = new SimpleBooleanProperty(); private final FieldPreferences fieldPreferences; private final BibEntryPreferences bibEntryPreferences; @@ -44,42 +35,27 @@ public EntryTabViewModel(PreferencesService preferencesService) { this.bibEntryPreferences = preferencesService.getBibEntryPreferences(); this.fieldPreferences = preferencesService.getFieldPreferences(); this.ownerPreferences = preferencesService.getOwnerPreferences(); - this.timestampPreferences = - preferencesService.getTimestampPreferences(); + this.timestampPreferences = preferencesService.getTimestampPreferences(); } @Override public void setValues() { - keywordSeparatorProperty.setValue( - bibEntryPreferences.getKeywordSeparator().toString() - ); + keywordSeparatorProperty.setValue(bibEntryPreferences.getKeywordSeparator().toString()); - resolveStringsProperty.setValue( - fieldPreferences.shouldResolveStrings() - ); + resolveStringsProperty.setValue(fieldPreferences.shouldResolveStrings()); resolveStringsForFieldsProperty.setValue( - FieldFactory.serializeFieldsList( - fieldPreferences.getResolvableFields() - ) + FieldFactory.serializeFieldsList(fieldPreferences.getResolvableFields()) ); nonWrappableFieldsProperty.setValue( - FieldFactory.serializeFieldsList( - fieldPreferences.getNonWrappableFields() - ) + FieldFactory.serializeFieldsList(fieldPreferences.getNonWrappableFields()) ); markOwnerProperty.setValue(ownerPreferences.isUseOwner()); markOwnerNameProperty.setValue(ownerPreferences.getDefaultOwner()); - markOwnerOverwriteProperty.setValue( - ownerPreferences.isOverwriteOwner() - ); + markOwnerOverwriteProperty.setValue(ownerPreferences.isOverwriteOwner()); - addCreationDateProperty.setValue( - timestampPreferences.shouldAddCreationDate() - ); - addModificationDateProperty.setValue( - timestampPreferences.shouldAddModificationDate() - ); + addCreationDateProperty.setValue(timestampPreferences.shouldAddCreationDate()); + addModificationDateProperty.setValue(timestampPreferences.shouldAddModificationDate()); } @Override @@ -90,28 +66,18 @@ public void storeSettings() { fieldPreferences.setResolveStrings(resolveStringsProperty.getValue()); fieldPreferences.setResolvableFields( - FieldFactory.parseFieldList( - resolveStringsForFieldsProperty.getValue().trim() - ) + FieldFactory.parseFieldList(resolveStringsForFieldsProperty.getValue().trim()) ); fieldPreferences.setNonWrappableFields( - FieldFactory.parseFieldList( - nonWrappableFieldsProperty.getValue().trim() - ) + FieldFactory.parseFieldList(nonWrappableFieldsProperty.getValue().trim()) ); ownerPreferences.setUseOwner(markOwnerProperty.getValue()); ownerPreferences.setDefaultOwner(markOwnerNameProperty.getValue()); - ownerPreferences.setOverwriteOwner( - markOwnerOverwriteProperty.getValue() - ); + ownerPreferences.setOverwriteOwner(markOwnerOverwriteProperty.getValue()); - timestampPreferences.setAddCreationDate( - addCreationDateProperty.getValue() - ); - timestampPreferences.setAddModificationDate( - addModificationDateProperty.getValue() - ); + timestampPreferences.setAddCreationDate(addCreationDateProperty.getValue()); + timestampPreferences.setAddModificationDate(addModificationDateProperty.getValue()); } public StringProperty keywordSeparatorProperty() { diff --git a/src/main/java/org/jabref/gui/preferences/entryeditor/EntryEditorTab.java b/src/main/java/org/jabref/gui/preferences/entryeditor/EntryEditorTab.java index af35eb447bb..079b89927e2 100644 --- a/src/main/java/org/jabref/gui/preferences/entryeditor/EntryEditorTab.java +++ b/src/main/java/org/jabref/gui/preferences/entryeditor/EntryEditorTab.java @@ -68,15 +68,10 @@ public String getTabName() { } public void initialize() { - this.viewModel = - new EntryEditorTabViewModel(dialogService, preferencesService); + this.viewModel = new EntryEditorTabViewModel(dialogService, preferencesService); - openOnNewEntry - .selectedProperty() - .bindBidirectional(viewModel.openOnNewEntryProperty()); - defaultSource - .selectedProperty() - .bindBidirectional(viewModel.defaultSourceProperty()); + openOnNewEntry.selectedProperty().bindBidirectional(viewModel.openOnNewEntryProperty()); + defaultSource.selectedProperty().bindBidirectional(viewModel.defaultSourceProperty()); enableRelatedArticlesTab .selectedProperty() .bindBidirectional(viewModel.enableRelatedArticlesTabProperty()); @@ -86,25 +81,17 @@ public void initialize() { enableLatexCitationsTab .selectedProperty() .bindBidirectional(viewModel.enableLatexCitationsTabProperty()); - enableValidation - .selectedProperty() - .bindBidirectional(viewModel.enableValidationProperty()); + enableValidation.selectedProperty().bindBidirectional(viewModel.enableValidationProperty()); allowIntegerEdition .selectedProperty() .bindBidirectional(viewModel.allowIntegerEditionProperty()); - journalPopupEnabled - .selectedProperty() - .bindBidirectional(viewModel.journalPopupProperty()); + journalPopupEnabled.selectedProperty().bindBidirectional(viewModel.journalPopupProperty()); autoLinkFilesEnabled .selectedProperty() .bindBidirectional(viewModel.autoLinkFilesEnabledProperty()); - enableSciteTab - .selectedProperty() - .bindBidirectional(viewModel.enableSciteTabProperty()); + enableSciteTab.selectedProperty().bindBidirectional(viewModel.enableSciteTabProperty()); - fieldsTextArea - .textProperty() - .bindBidirectional(viewModel.fieldsProperty()); + fieldsTextArea.textProperty().bindBidirectional(viewModel.fieldsProperty()); ActionFactory actionFactory = new ActionFactory(keyBindingRepository); actionFactory.configureIconButton( diff --git a/src/main/java/org/jabref/gui/preferences/entryeditor/EntryEditorTabViewModel.java b/src/main/java/org/jabref/gui/preferences/entryeditor/EntryEditorTabViewModel.java index 9f5b3178e6b..f66256a5b59 100644 --- a/src/main/java/org/jabref/gui/preferences/entryeditor/EntryEditorTabViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/entryeditor/EntryEditorTabViewModel.java @@ -19,26 +19,16 @@ public class EntryEditorTabViewModel implements PreferenceTabViewModel { - private final BooleanProperty openOnNewEntryProperty = - new SimpleBooleanProperty(); - private final BooleanProperty defaultSourceProperty = - new SimpleBooleanProperty(); - private final BooleanProperty enableRelatedArticlesTabProperty = - new SimpleBooleanProperty(); - private final BooleanProperty acceptRecommendationsProperty = - new SimpleBooleanProperty(); - private final BooleanProperty enableLatexCitationsTabProperty = - new SimpleBooleanProperty(); - private final BooleanProperty enableValidationProperty = - new SimpleBooleanProperty(); - private final BooleanProperty allowIntegerEditionProperty = - new SimpleBooleanProperty(); - private final BooleanProperty journalPopupProperty = - new SimpleBooleanProperty(); - private final BooleanProperty autoLinkEnabledProperty = - new SimpleBooleanProperty(); - private final BooleanProperty enableSciteTabProperty = - new SimpleBooleanProperty(); + private final BooleanProperty openOnNewEntryProperty = new SimpleBooleanProperty(); + private final BooleanProperty defaultSourceProperty = new SimpleBooleanProperty(); + private final BooleanProperty enableRelatedArticlesTabProperty = new SimpleBooleanProperty(); + private final BooleanProperty acceptRecommendationsProperty = new SimpleBooleanProperty(); + private final BooleanProperty enableLatexCitationsTabProperty = new SimpleBooleanProperty(); + private final BooleanProperty enableValidationProperty = new SimpleBooleanProperty(); + private final BooleanProperty allowIntegerEditionProperty = new SimpleBooleanProperty(); + private final BooleanProperty journalPopupProperty = new SimpleBooleanProperty(); + private final BooleanProperty autoLinkEnabledProperty = new SimpleBooleanProperty(); + private final BooleanProperty enableSciteTabProperty = new SimpleBooleanProperty(); private final StringProperty fieldsProperty = new SimpleStringProperty(); @@ -53,8 +43,7 @@ public EntryEditorTabViewModel( ) { this.dialogService = dialogService; this.preferencesService = preferencesService; - this.entryEditorPreferences = - preferencesService.getEntryEditorPreferences(); + this.entryEditorPreferences = preferencesService.getEntryEditorPreferences(); this.mrDlibPreferences = preferencesService.getMrDlibPreferences(); } @@ -63,24 +52,16 @@ public void setValues() { // ToDo: Include CustomizeGeneralFieldsDialog in PreferencesDialog // therefore yet unused: entryEditorPreferences.getEntryEditorTabList(); - openOnNewEntryProperty.setValue( - entryEditorPreferences.shouldOpenOnNewEntry() - ); - defaultSourceProperty.setValue( - entryEditorPreferences.showSourceTabByDefault() - ); + openOnNewEntryProperty.setValue(entryEditorPreferences.shouldOpenOnNewEntry()); + defaultSourceProperty.setValue(entryEditorPreferences.showSourceTabByDefault()); enableRelatedArticlesTabProperty.setValue( entryEditorPreferences.shouldShowRecommendationsTab() ); - acceptRecommendationsProperty.setValue( - mrDlibPreferences.shouldAcceptRecommendations() - ); + acceptRecommendationsProperty.setValue(mrDlibPreferences.shouldAcceptRecommendations()); enableLatexCitationsTabProperty.setValue( entryEditorPreferences.shouldShowLatexCitationsTab() ); - enableValidationProperty.setValue( - entryEditorPreferences.shouldEnableValidation() - ); + enableValidationProperty.setValue(entryEditorPreferences.shouldEnableValidation()); allowIntegerEditionProperty.setValue( entryEditorPreferences.shouldAllowIntegerEditionBibtex() ); @@ -88,22 +69,14 @@ public void setValues() { entryEditorPreferences.shouldEnableJournalPopup() == EntryEditorPreferences.JournalPopupEnabled.ENABLED ); - autoLinkEnabledProperty.setValue( - entryEditorPreferences.autoLinkFilesEnabled() - ); - enableSciteTabProperty.setValue( - entryEditorPreferences.shouldShowSciteTab() - ); + autoLinkEnabledProperty.setValue(entryEditorPreferences.autoLinkFilesEnabled()); + enableSciteTabProperty.setValue(entryEditorPreferences.shouldShowSciteTab()); setFields(entryEditorPreferences.getEntryEditorTabs()); } public void resetToDefaults() { - setFields( - preferencesService - .getEntryEditorPreferences() - .getDefaultEntryEditorTabs() - ); + setFields(preferencesService.getEntryEditorPreferences().getDefaultEntryEditorTabs()); } private void setFields(Map> tabNamesAndFields) { @@ -122,39 +95,25 @@ private void setFields(Map> tabNamesAndFields) { @Override public void storeSettings() { // entryEditorPreferences.setEntryEditorTabList(); - entryEditorPreferences.setShouldOpenOnNewEntry( - openOnNewEntryProperty.getValue() - ); + entryEditorPreferences.setShouldOpenOnNewEntry(openOnNewEntryProperty.getValue()); entryEditorPreferences.setShouldShowRecommendationsTab( enableRelatedArticlesTabProperty.getValue() ); - mrDlibPreferences.setAcceptRecommendations( - acceptRecommendationsProperty.getValue() - ); + mrDlibPreferences.setAcceptRecommendations(acceptRecommendationsProperty.getValue()); entryEditorPreferences.setShouldShowLatexCitationsTab( enableLatexCitationsTabProperty.getValue() ); - entryEditorPreferences.setShowSourceTabByDefault( - defaultSourceProperty.getValue() - ); - entryEditorPreferences.setEnableValidation( - enableValidationProperty.getValue() - ); - entryEditorPreferences.setAllowIntegerEditionBibtex( - allowIntegerEditionProperty.getValue() - ); + entryEditorPreferences.setShowSourceTabByDefault(defaultSourceProperty.getValue()); + entryEditorPreferences.setEnableValidation(enableValidationProperty.getValue()); + entryEditorPreferences.setAllowIntegerEditionBibtex(allowIntegerEditionProperty.getValue()); entryEditorPreferences.setEnableJournalPopup( journalPopupProperty.getValue() ? EntryEditorPreferences.JournalPopupEnabled.ENABLED : EntryEditorPreferences.JournalPopupEnabled.DISABLED ); // entryEditorPreferences.setDividerPosition(); - entryEditorPreferences.setAutoLinkFilesEnabled( - autoLinkEnabledProperty.getValue() - ); - entryEditorPreferences.setShouldShowSciteTab( - enableSciteTabProperty.getValue() - ); + entryEditorPreferences.setAutoLinkFilesEnabled(autoLinkEnabledProperty.getValue()); + entryEditorPreferences.setShouldShowSciteTab(enableSciteTabProperty.getValue()); Map> customTabsMap = new LinkedHashMap<>(); String[] lines = fieldsProperty.get().split("\n"); @@ -175,10 +134,7 @@ public void storeSettings() { // from preferences because the list of allowable characters in this particular differs // i.e. ';' character is allowed in this window, but it's on the list of unwanted chars in preferences String unwantedChars = "#{}()~,^&-\"'`ʹ\\"; - String testString = CitationKeyGenerator.cleanKey( - parts[1], - unwantedChars - ); + String testString = CitationKeyGenerator.cleanKey(parts[1], unwantedChars); if (!testString.equals(parts[1])) { dialogService.showInformationDialogAndWait( Localization.lang("Error"), diff --git a/src/main/java/org/jabref/gui/preferences/export/ExportTab.java b/src/main/java/org/jabref/gui/preferences/export/ExportTab.java index 2454f3ece4e..7f7b6bf7c3a 100644 --- a/src/main/java/org/jabref/gui/preferences/export/ExportTab.java +++ b/src/main/java/org/jabref/gui/preferences/export/ExportTab.java @@ -24,8 +24,7 @@ public String getTabName() { } public void initialize() { - this.viewModel = - new ExportTabViewModel(preferencesService.getExportPreferences()); + this.viewModel = new ExportTabViewModel(preferencesService.getExportPreferences()); exportOrderPanel .saveInOriginalProperty() @@ -36,12 +35,8 @@ public void initialize() { exportOrderPanel .saveInSpecifiedOrderProperty() .bindBidirectional(viewModel.saveInSpecifiedOrderProperty()); - exportOrderPanel - .sortableFieldsProperty() - .bind(viewModel.sortableFieldsProperty()); - exportOrderPanel - .sortCriteriaProperty() - .bindBidirectional(viewModel.sortCriteriaProperty()); + exportOrderPanel.sortableFieldsProperty().bind(viewModel.sortableFieldsProperty()); + exportOrderPanel.sortCriteriaProperty().bindBidirectional(viewModel.sortCriteriaProperty()); exportOrderPanel.setCriteriaLimit(3); } } diff --git a/src/main/java/org/jabref/gui/preferences/export/ExportTabViewModel.java b/src/main/java/org/jabref/gui/preferences/export/ExportTabViewModel.java index 30c0879aa37..a3e89dfe8b9 100644 --- a/src/main/java/org/jabref/gui/preferences/export/ExportTabViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/export/ExportTabViewModel.java @@ -18,18 +18,14 @@ public class ExportTabViewModel implements PreferenceTabViewModel { // SaveOrderConfigPanel - private final BooleanProperty exportInOriginalProperty = - new SimpleBooleanProperty(); - private final BooleanProperty exportInTableOrderProperty = - new SimpleBooleanProperty(); - private final BooleanProperty exportInSpecifiedOrderProperty = - new SimpleBooleanProperty(); - private final ListProperty sortableFieldsProperty = - new SimpleListProperty<>(FXCollections.observableArrayList()); + private final BooleanProperty exportInOriginalProperty = new SimpleBooleanProperty(); + private final BooleanProperty exportInTableOrderProperty = new SimpleBooleanProperty(); + private final BooleanProperty exportInSpecifiedOrderProperty = new SimpleBooleanProperty(); + private final ListProperty sortableFieldsProperty = new SimpleListProperty<>( + FXCollections.observableArrayList() + ); private final ListProperty sortCriteriaProperty = - new SimpleListProperty<>( - FXCollections.observableArrayList(new ArrayList<>()) - ); + new SimpleListProperty<>(FXCollections.observableArrayList(new ArrayList<>())); private final ExportPreferences exportPreferences; @@ -46,11 +42,7 @@ public void setValues() { case TABLE -> exportInTableOrderProperty.setValue(true); } sortCriteriaProperty.addAll( - exportSaveOrder - .getSortCriteria() - .stream() - .map(SortCriterionViewModel::new) - .toList() + exportSaveOrder.getSortCriteria().stream().map(SortCriterionViewModel::new).toList() ); Set fields = FieldFactory.getAllFieldsWithOutInternal(); @@ -58,9 +50,7 @@ public void setValues() { fields.add(InternalField.INTERNAL_ALL_TEXT_FIELDS_FIELD); fields.add(InternalField.KEY_FIELD); fields.add(InternalField.TYPE_HEADER); - sortableFieldsProperty.addAll( - FieldFactory.getStandardFieldsWithCitationKey() - ); + sortableFieldsProperty.addAll(FieldFactory.getStandardFieldsWithCitationKey()); } @Override @@ -70,10 +60,7 @@ public void storeSettings() { exportInSpecifiedOrderProperty.getValue(), exportInOriginalProperty.getValue() ), - sortCriteriaProperty - .stream() - .map(SortCriterionViewModel::getCriterion) - .toList() + sortCriteriaProperty.stream().map(SortCriterionViewModel::getCriterion).toList() ); exportPreferences.setExportSaveOrder(newSaveOrder); } diff --git a/src/main/java/org/jabref/gui/preferences/external/ExternalTab.java b/src/main/java/org/jabref/gui/preferences/external/ExternalTab.java index 7c1e3371e04..0f23b481d34 100644 --- a/src/main/java/org/jabref/gui/preferences/external/ExternalTab.java +++ b/src/main/java/org/jabref/gui/preferences/external/ExternalTab.java @@ -59,8 +59,7 @@ public class ExternalTab @FXML private TextField kindleEmail; - private final ControlsFxVisualizer validationVisualizer = - new ControlsFxVisualizer(); + private final ControlsFxVisualizer validationVisualizer = new ControlsFxVisualizer(); public ExternalTab() { ViewLoader.view(this).root(this).load(); @@ -72,8 +71,7 @@ public String getTabName() { } public void initialize() { - this.viewModel = - new ExternalTabViewModel(dialogService, preferencesService); + this.viewModel = new ExternalTabViewModel(dialogService, preferencesService); new ViewModelListCellFactory() .withText(PushToApplication::getDisplayName) @@ -87,15 +85,11 @@ public void initialize() { .selectedProperty() .bindBidirectional(viewModel.autoOpenAttachedFoldersProperty()); - pushToApplicationCombo - .itemsProperty() - .bind(viewModel.pushToApplicationsListProperty()); + pushToApplicationCombo.itemsProperty().bind(viewModel.pushToApplicationsListProperty()); pushToApplicationCombo .valueProperty() .bindBidirectional(viewModel.selectedPushToApplication()); - citeCommand - .textProperty() - .bindBidirectional(viewModel.citeCommandProperty()); + citeCommand.textProperty().bindBidirectional(viewModel.citeCommandProperty()); useCustomTerminal .selectedProperty() @@ -103,12 +97,8 @@ public void initialize() { customTerminalCommand .textProperty() .bindBidirectional(viewModel.customTerminalCommandProperty()); - customTerminalCommand - .disableProperty() - .bind(useCustomTerminal.selectedProperty().not()); - customTerminalBrowse - .disableProperty() - .bind(useCustomTerminal.selectedProperty().not()); + customTerminalCommand.disableProperty().bind(useCustomTerminal.selectedProperty().not()); + customTerminalBrowse.disableProperty().bind(useCustomTerminal.selectedProperty().not()); useCustomFileBrowser .selectedProperty() @@ -123,9 +113,7 @@ public void initialize() { .disableProperty() .bind(useCustomFileBrowser.selectedProperty().not()); - kindleEmail - .textProperty() - .bindBidirectional(viewModel.kindleEmailProperty()); + kindleEmail.textProperty().bindBidirectional(viewModel.kindleEmailProperty()); validationVisualizer.setDecoration(new IconValidationDecorator()); Platform.runLater(() -> { diff --git a/src/main/java/org/jabref/gui/preferences/external/ExternalTabViewModel.java b/src/main/java/org/jabref/gui/preferences/external/ExternalTabViewModel.java index 884509dce83..f3941a7f486 100644 --- a/src/main/java/org/jabref/gui/preferences/external/ExternalTabViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/external/ExternalTabViewModel.java @@ -32,30 +32,18 @@ public class ExternalTabViewModel implements PreferenceTabViewModel { - private final StringProperty eMailReferenceSubjectProperty = - new SimpleStringProperty(""); - private final BooleanProperty autoOpenAttachedFoldersProperty = - new SimpleBooleanProperty(); - private final ListProperty< - PushToApplication - > pushToApplicationsListProperty = new SimpleListProperty<>(); - private final ObjectProperty< - PushToApplication - > selectedPushToApplicationProperty = new SimpleObjectProperty<>(); - private final StringProperty citeCommandProperty = new SimpleStringProperty( - "" - ); - private final BooleanProperty useCustomTerminalProperty = - new SimpleBooleanProperty(); - private final StringProperty customTerminalCommandProperty = - new SimpleStringProperty(""); - private final BooleanProperty useCustomFileBrowserProperty = - new SimpleBooleanProperty(); - private final StringProperty customFileBrowserCommandProperty = - new SimpleStringProperty(""); - private final StringProperty kindleEmailProperty = new SimpleStringProperty( - "" - ); + private final StringProperty eMailReferenceSubjectProperty = new SimpleStringProperty(""); + private final BooleanProperty autoOpenAttachedFoldersProperty = new SimpleBooleanProperty(); + private final ListProperty pushToApplicationsListProperty = + new SimpleListProperty<>(); + private final ObjectProperty selectedPushToApplicationProperty = + new SimpleObjectProperty<>(); + private final StringProperty citeCommandProperty = new SimpleStringProperty(""); + private final BooleanProperty useCustomTerminalProperty = new SimpleBooleanProperty(); + private final StringProperty customTerminalCommandProperty = new SimpleStringProperty(""); + private final BooleanProperty useCustomFileBrowserProperty = new SimpleBooleanProperty(); + private final StringProperty customFileBrowserCommandProperty = new SimpleStringProperty(""); + private final StringProperty kindleEmailProperty = new SimpleStringProperty(""); private final Validator terminalCommandValidator; private final Validator fileBrowserCommandValidator; @@ -78,14 +66,11 @@ public ExternalTabViewModel( this.preferences = preferencesService; this.initialExternalApplicationPreferences = preferences.getExternalApplicationsPreferences(); - this.initialPushToApplicationPreferences = - preferences.getPushToApplicationPreferences(); + this.initialPushToApplicationPreferences = preferences.getPushToApplicationPreferences(); this.workingPushToApplicationPreferences = new PushToApplicationPreferences( initialPushToApplicationPreferences.getActiveApplicationName(), - new HashMap<>( - initialPushToApplicationPreferences.getCommandPaths() - ), + new HashMap<>(initialPushToApplicationPreferences.getCommandPaths()), initialPushToApplicationPreferences.getEmacsArguments(), initialPushToApplicationPreferences.getVimServer() ); @@ -99,9 +84,7 @@ public ExternalTabViewModel( "%s > %s %n %n %s", Localization.lang("External programs"), Localization.lang("Custom applications"), - Localization.lang( - "Please specify a terminal application." - ) + Localization.lang("Please specify a terminal application.") ) ) ); @@ -132,10 +115,7 @@ public void setValues() { pushToApplicationsListProperty.setValue( FXCollections.observableArrayList( - PushToApplications.getAllApplications( - dialogService, - preferences - ) + PushToApplications.getAllApplications(dialogService, preferences) ) ); selectedPushToApplicationProperty.setValue( @@ -148,9 +128,7 @@ public void setValues() { .orElse(new PushToEmacs(dialogService, preferences)) ); - citeCommandProperty.setValue( - initialExternalApplicationPreferences.getCiteCommand() - ); + citeCommandProperty.setValue(initialExternalApplicationPreferences.getCiteCommand()); useCustomTerminalProperty.setValue( initialExternalApplicationPreferences.useCustomTerminal() ); @@ -163,31 +141,21 @@ public void setValues() { customFileBrowserCommandProperty.setValue( initialExternalApplicationPreferences.getCustomFileBrowserCommand() ); - kindleEmailProperty.setValue( - initialExternalApplicationPreferences.getKindleEmail() - ); + kindleEmailProperty.setValue(initialExternalApplicationPreferences.getKindleEmail()); } @Override public void storeSettings() { ExternalApplicationsPreferences externalPreferences = preferences.getExternalApplicationsPreferences(); - externalPreferences.setEMailSubject( - eMailReferenceSubjectProperty.getValue() - ); + externalPreferences.setEMailSubject(eMailReferenceSubjectProperty.getValue()); externalPreferences.setAutoOpenEmailAttachmentsFolder( autoOpenAttachedFoldersProperty.getValue() ); externalPreferences.setCiteCommand(citeCommandProperty.getValue()); - externalPreferences.setUseCustomTerminal( - useCustomTerminalProperty.getValue() - ); - externalPreferences.setCustomTerminalCommand( - customTerminalCommandProperty.getValue() - ); - externalPreferences.setUseCustomFileBrowser( - useCustomFileBrowserProperty.getValue() - ); + externalPreferences.setUseCustomTerminal(useCustomTerminalProperty.getValue()); + externalPreferences.setCustomTerminalCommand(customTerminalCommandProperty.getValue()); + externalPreferences.setUseCustomFileBrowser(useCustomFileBrowserProperty.getValue()); externalPreferences.setCustomFileBrowserCommand( customFileBrowserCommandProperty.getValue() ); @@ -198,15 +166,9 @@ public void storeSettings() { pushPreferences.setActiveApplicationName( selectedPushToApplicationProperty.getValue().getDisplayName() ); - pushPreferences.setCommandPaths( - workingPushToApplicationPreferences.getCommandPaths() - ); - pushPreferences.setEmacsArguments( - workingPushToApplicationPreferences.getEmacsArguments() - ); - pushPreferences.setVimServer( - workingPushToApplicationPreferences.getVimServer() - ); + pushPreferences.setCommandPaths(workingPushToApplicationPreferences.getCommandPaths()); + pushPreferences.setEmacsArguments(workingPushToApplicationPreferences.getEmacsArguments()); + pushPreferences.setVimServer(workingPushToApplicationPreferences.getVimServer()); } public ValidationStatus terminalCommandValidationStatus() { @@ -233,17 +195,14 @@ public boolean validateSettings() { if (!validationStatus.isValid()) { validationStatus .getHighestMessage() - .ifPresent(message -> - dialogService.showErrorDialogAndWait(message.getMessage()) - ); + .ifPresent(message -> dialogService.showErrorDialogAndWait(message.getMessage())); return false; } return true; } public void pushToApplicationSettings() { - PushToApplication selectedApplication = - selectedPushToApplicationProperty.getValue(); + PushToApplication selectedApplication = selectedPushToApplicationProperty.getValue(); PushToApplicationSettings settings = selectedApplication.getSettings( selectedApplication, workingPushToApplicationPreferences @@ -270,9 +229,7 @@ public void customTerminalBrowse() { dialogService .showFileOpenDialog(fileDialogConfiguration) .ifPresent(file -> - customTerminalCommandProperty.setValue( - file.toAbsolutePath().toString() - ) + customTerminalCommandProperty.setValue(file.toAbsolutePath().toString()) ); } @@ -280,9 +237,7 @@ public void customFileBrowserBrowse() { dialogService .showFileOpenDialog(fileDialogConfiguration) .ifPresent(file -> - customFileBrowserCommandProperty.setValue( - file.toAbsolutePath().toString() - ) + customFileBrowserCommandProperty.setValue(file.toAbsolutePath().toString()) ); } @@ -334,9 +289,7 @@ public StringProperty customFileBrowserCommandProperty() { public void resetCiteCommandToDefault() { this.citeCommandProperty.setValue( - preferences - .getExternalApplicationsPreferences() - .getDefaultCiteCommand() + preferences.getExternalApplicationsPreferences().getDefaultCiteCommand() ); } } diff --git a/src/main/java/org/jabref/gui/preferences/externalfiletypes/EditExternalFileTypeEntryDialog.java b/src/main/java/org/jabref/gui/preferences/externalfiletypes/EditExternalFileTypeEntryDialog.java index 5972414ad92..7c2635e3e45 100644 --- a/src/main/java/org/jabref/gui/preferences/externalfiletypes/EditExternalFileTypeEntryDialog.java +++ b/src/main/java/org/jabref/gui/preferences/externalfiletypes/EditExternalFileTypeEntryDialog.java @@ -58,10 +58,7 @@ public class EditExternalFileTypeEntryDialog extends BaseDialog { private EditExternalFileTypeViewModel viewModel; - public EditExternalFileTypeEntryDialog( - ExternalFileTypeItemViewModel item, - String dialogTitle - ) { + public EditExternalFileTypeEntryDialog(ExternalFileTypeItemViewModel item, String dialogTitle) { this.item = item; this.setTitle(dialogTitle); @@ -88,16 +85,10 @@ public void initialize() { customApplication .selectedProperty() .bindBidirectional(viewModel.customApplicationSelectedProperty()); - selectedApplication - .disableProperty() - .bind(viewModel.defaultApplicationSelectedProperty()); - btnBrowse - .disableProperty() - .bind(viewModel.defaultApplicationSelectedProperty()); + selectedApplication.disableProperty().bind(viewModel.defaultApplicationSelectedProperty()); + btnBrowse.disableProperty().bind(viewModel.defaultApplicationSelectedProperty()); - extension - .textProperty() - .bindBidirectional(viewModel.extensionProperty()); + extension.textProperty().bindBidirectional(viewModel.extensionProperty()); name.textProperty().bindBidirectional(viewModel.nameProperty()); mimeType.textProperty().bindBidirectional(viewModel.mimeTypeProperty()); selectedApplication @@ -110,9 +101,7 @@ private void openFileChooser(ActionEvent event) { dialogService .showFileOpenDialog(fileDialogConfiguration) .ifPresent(path -> - viewModel - .selectedApplicationProperty() - .setValue(path.toAbsolutePath().toString()) + viewModel.selectedApplicationProperty().setValue(path.toAbsolutePath().toString()) ); } } diff --git a/src/main/java/org/jabref/gui/preferences/externalfiletypes/EditExternalFileTypeViewModel.java b/src/main/java/org/jabref/gui/preferences/externalfiletypes/EditExternalFileTypeViewModel.java index d46c26d5448..b67657c3177 100644 --- a/src/main/java/org/jabref/gui/preferences/externalfiletypes/EditExternalFileTypeViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/externalfiletypes/EditExternalFileTypeViewModel.java @@ -11,31 +11,22 @@ public class EditExternalFileTypeViewModel { private final ExternalFileTypeItemViewModel fileTypeViewModel; private final StringProperty nameProperty = new SimpleStringProperty(""); - private final StringProperty mimeTypeProperty = new SimpleStringProperty( - "" + private final StringProperty mimeTypeProperty = new SimpleStringProperty(""); + private final StringProperty extensionProperty = new SimpleStringProperty(""); + private final StringProperty selectedApplicationProperty = new SimpleStringProperty(""); + private final BooleanProperty defaultApplicationSelectedProperty = new SimpleBooleanProperty( + false ); - private final StringProperty extensionProperty = new SimpleStringProperty( - "" + private final BooleanProperty customApplicationSelectedProperty = new SimpleBooleanProperty( + false ); - private final StringProperty selectedApplicationProperty = - new SimpleStringProperty(""); - private final BooleanProperty defaultApplicationSelectedProperty = - new SimpleBooleanProperty(false); - private final BooleanProperty customApplicationSelectedProperty = - new SimpleBooleanProperty(false); - - public EditExternalFileTypeViewModel( - ExternalFileTypeItemViewModel fileTypeViewModel - ) { + + public EditExternalFileTypeViewModel(ExternalFileTypeItemViewModel fileTypeViewModel) { this.fileTypeViewModel = fileTypeViewModel; - extensionProperty.setValue( - fileTypeViewModel.extensionProperty().getValue() - ); + extensionProperty.setValue(fileTypeViewModel.extensionProperty().getValue()); nameProperty.setValue(fileTypeViewModel.nameProperty().getValue()); - mimeTypeProperty.setValue( - fileTypeViewModel.mimetypeProperty().getValue() - ); + mimeTypeProperty.setValue(fileTypeViewModel.mimetypeProperty().getValue()); if (fileTypeViewModel.applicationProperty().getValue().isEmpty()) { defaultApplicationSelectedProperty.setValue(true); @@ -76,12 +67,8 @@ public BooleanProperty customApplicationSelectedProperty() { } public void storeSettings() { - fileTypeViewModel - .nameProperty() - .setValue(nameProperty.getValue().trim()); - fileTypeViewModel - .mimetypeProperty() - .setValue(mimeTypeProperty.getValue().trim()); + fileTypeViewModel.nameProperty().setValue(nameProperty.getValue().trim()); + fileTypeViewModel.mimetypeProperty().setValue(mimeTypeProperty.getValue().trim()); String ext = extensionProperty.getValue().trim(); if (!ext.isEmpty() && (ext.charAt(0) == '.')) { @@ -93,10 +80,7 @@ public void storeSettings() { String application = selectedApplicationProperty.getValue().trim(); // store application as empty if the "Default" option is selected, or if the application name is empty: - if ( - defaultApplicationSelectedProperty.getValue() || - application.isEmpty() - ) { + if (defaultApplicationSelectedProperty.getValue() || application.isEmpty()) { fileTypeViewModel.applicationProperty().setValue(""); selectedApplicationProperty.setValue(""); } else { diff --git a/src/main/java/org/jabref/gui/preferences/externalfiletypes/ExternalFileTypeItemViewModel.java b/src/main/java/org/jabref/gui/preferences/externalfiletypes/ExternalFileTypeItemViewModel.java index 495d4bc9d58..35a5eca90ba 100644 --- a/src/main/java/org/jabref/gui/preferences/externalfiletypes/ExternalFileTypeItemViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/externalfiletypes/ExternalFileTypeItemViewModel.java @@ -11,8 +11,7 @@ public class ExternalFileTypeItemViewModel { - private final ObjectProperty icon = - new SimpleObjectProperty<>(); + private final ObjectProperty icon = new SimpleObjectProperty<>(); private final StringProperty name = new SimpleStringProperty(); private final StringProperty extension = new SimpleStringProperty(); private final StringProperty mimetype = new SimpleStringProperty(); @@ -27,16 +26,7 @@ public ExternalFileTypeItemViewModel(ExternalFileType fileType) { } public ExternalFileTypeItemViewModel() { - this( - new CustomExternalFileType( - "", - "", - "", - "", - "new", - IconTheme.JabRefIcons.FILE - ) - ); + this(new CustomExternalFileType("", "", "", "", "new", IconTheme.JabRefIcons.FILE)); } public ObjectProperty iconProperty() { diff --git a/src/main/java/org/jabref/gui/preferences/externalfiletypes/ExternalFileTypesTab.java b/src/main/java/org/jabref/gui/preferences/externalfiletypes/ExternalFileTypesTab.java index 1672a1ca6cf..0512c317519 100644 --- a/src/main/java/org/jabref/gui/preferences/externalfiletypes/ExternalFileTypesTab.java +++ b/src/main/java/org/jabref/gui/preferences/externalfiletypes/ExternalFileTypesTab.java @@ -20,46 +20,25 @@ public class ExternalFileTypesTab implements PreferencesTab { @FXML - private TableColumn< - ExternalFileTypeItemViewModel, - JabRefIcon - > fileTypesTableIconColumn; + private TableColumn fileTypesTableIconColumn; @FXML - private TableColumn< - ExternalFileTypeItemViewModel, - String - > fileTypesTableNameColumn; + private TableColumn fileTypesTableNameColumn; @FXML - private TableColumn< - ExternalFileTypeItemViewModel, - String - > fileTypesTableExtensionColumn; + private TableColumn fileTypesTableExtensionColumn; @FXML - private TableColumn< - ExternalFileTypeItemViewModel, - String - > fileTypesTableMimeTypeColumn; + private TableColumn fileTypesTableMimeTypeColumn; @FXML - private TableColumn< - ExternalFileTypeItemViewModel, - String - > fileTypesTableApplicationColumn; + private TableColumn fileTypesTableApplicationColumn; @FXML - private TableColumn< - ExternalFileTypeItemViewModel, - Boolean - > fileTypesTableEditColumn; + private TableColumn fileTypesTableEditColumn; @FXML - private TableColumn< - ExternalFileTypeItemViewModel, - Boolean - > fileTypesTableDeleteColumn; + private TableColumn fileTypesTableDeleteColumn; @FXML private TableView fileTypesTable; @@ -83,15 +62,13 @@ public void initialize() { fileTypesTable.setItems(viewModel.getFileTypes()); - fileTypesTableIconColumn.setCellValueFactory(cellData -> - cellData.getValue().iconProperty() + fileTypesTableIconColumn.setCellValueFactory(cellData -> cellData.getValue().iconProperty() ); new ValueTableCellFactory() .withGraphic(JabRefIcon::getGraphicNode) .install(fileTypesTableIconColumn); - fileTypesTableNameColumn.setCellValueFactory(cellData -> - cellData.getValue().nameProperty() + fileTypesTableNameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty() ); new ValueTableCellFactory() .withText(name -> name) @@ -118,29 +95,19 @@ public void initialize() { .withText(extension -> extension) .install(fileTypesTableApplicationColumn); - fileTypesTableEditColumn.setCellValueFactory(data -> - BindingsHelper.constantOf(true) - ); - fileTypesTableDeleteColumn.setCellValueFactory(data -> - BindingsHelper.constantOf(true) - ); + fileTypesTableEditColumn.setCellValueFactory(data -> BindingsHelper.constantOf(true)); + fileTypesTableDeleteColumn.setCellValueFactory(data -> BindingsHelper.constantOf(true)); new ValueTableCellFactory() .withGraphic(JabRefIcon::getGraphicNode) .install(fileTypesTableIconColumn); new ValueTableCellFactory() .withGraphic(none -> IconTheme.JabRefIcons.EDIT.getGraphicNode()) - .withOnMouseClickedEvent((type, none) -> - event -> viewModel.edit(type) - ) + .withOnMouseClickedEvent((type, none) -> event -> viewModel.edit(type)) .install(fileTypesTableEditColumn); new ValueTableCellFactory() - .withGraphic(none -> - IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode() - ) - .withOnMouseClickedEvent((type, none) -> - event -> viewModel.remove(type) - ) + .withGraphic(none -> IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode()) + .withOnMouseClickedEvent((type, none) -> event -> viewModel.remove(type)) .install(fileTypesTableDeleteColumn); } diff --git a/src/main/java/org/jabref/gui/preferences/externalfiletypes/ExternalFileTypesTabViewModel.java b/src/main/java/org/jabref/gui/preferences/externalfiletypes/ExternalFileTypesTabViewModel.java index 6a71ddad79f..e39591d3499 100644 --- a/src/main/java/org/jabref/gui/preferences/externalfiletypes/ExternalFileTypesTabViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/externalfiletypes/ExternalFileTypesTabViewModel.java @@ -38,9 +38,7 @@ public void setValues() { .map(ExternalFileTypeItemViewModel::new) .toList() ); - fileTypes.sort( - Comparator.comparing(ExternalFileTypeItemViewModel::getName) - ); + fileTypes.sort(Comparator.comparing(ExternalFileTypeItemViewModel::getName)); } public void storeSettings() { @@ -70,14 +68,11 @@ public void resetToDefaults() { .map(ExternalFileTypeItemViewModel::new) .toList() ); - fileTypes.sort( - Comparator.comparing(ExternalFileTypeItemViewModel::getName) - ); + fileTypes.sort(Comparator.comparing(ExternalFileTypeItemViewModel::getName)); } public void addNewType() { - ExternalFileTypeItemViewModel item = - new ExternalFileTypeItemViewModel(); + ExternalFileTypeItemViewModel item = new ExternalFileTypeItemViewModel(); fileTypes.add(item); showEditDialog(item, Localization.lang("Add new file type")); } @@ -86,10 +81,7 @@ public ObservableList getFileTypes() { return fileTypes; } - private void showEditDialog( - ExternalFileTypeItemViewModel item, - String dialogTitle - ) { + private void showEditDialog(ExternalFileTypeItemViewModel item, String dialogTitle) { dialogService.showCustomDialogAndWait( new EditExternalFileTypeEntryDialog(item, dialogTitle) ); diff --git a/src/main/java/org/jabref/gui/preferences/general/GeneralTab.java b/src/main/java/org/jabref/gui/preferences/general/GeneralTab.java index d3159df5af9..58fcc93fbd4 100644 --- a/src/main/java/org/jabref/gui/preferences/general/GeneralTab.java +++ b/src/main/java/org/jabref/gui/preferences/general/GeneralTab.java @@ -103,22 +103,20 @@ public class GeneralTab @Inject private BibEntryTypesManager entryTypesManager; - private final ControlsFxVisualizer validationVisualizer = - new ControlsFxVisualizer(); + private final ControlsFxVisualizer validationVisualizer = new ControlsFxVisualizer(); // The fontSizeFormatter formats the input given to the fontSize spinner so that non valid values cannot be entered. - private final TextFormatter fontSizeFormatter = - new TextFormatter<>( - new IntegerStringConverter(), - 9, - c -> { - if (Pattern.matches("\\d*", c.getText())) { - return c; - } - c.setText("0"); + private final TextFormatter fontSizeFormatter = new TextFormatter<>( + new IntegerStringConverter(), + 9, + c -> { + if (Pattern.matches("\\d*", c.getText())) { return c; } - ); + c.setText("0"); + return c; + } + ); public GeneralTab() { ViewLoader.view(this).root(this).load(); @@ -142,37 +140,24 @@ public void initialize() { .withText(Language::getDisplayName) .install(language); language.itemsProperty().bind(viewModel.languagesListProperty()); - language - .valueProperty() - .bindBidirectional(viewModel.selectedLanguageProperty()); + language.valueProperty().bindBidirectional(viewModel.selectedLanguageProperty()); - fontOverride - .selectedProperty() - .bindBidirectional(viewModel.fontOverrideProperty()); + fontOverride.selectedProperty().bindBidirectional(viewModel.fontOverrideProperty()); // Spinner does neither support alignment nor disableProperty in FXML fontSize.disableProperty().bind(fontOverride.selectedProperty().not()); fontSize.getEditor().setAlignment(Pos.CENTER_RIGHT); fontSize.setValueFactory(GeneralTabViewModel.fontSizeValueFactory); - fontSize - .getEditor() - .textProperty() - .bindBidirectional(viewModel.fontSizeProperty()); + fontSize.getEditor().textProperty().bindBidirectional(viewModel.fontSizeProperty()); fontSize.getEditor().setTextFormatter(fontSizeFormatter); new ViewModelListCellFactory() .withText(ThemeTypes::getDisplayName) .install(theme); theme.itemsProperty().bind(viewModel.themesListProperty()); - theme - .valueProperty() - .bindBidirectional(viewModel.selectedThemeProperty()); - themeSyncOs - .selectedProperty() - .bindBidirectional(viewModel.themeSyncOsProperty()); - customThemePath - .textProperty() - .bindBidirectional(viewModel.customPathToThemeProperty()); + theme.valueProperty().bindBidirectional(viewModel.selectedThemeProperty()); + themeSyncOs.selectedProperty().bindBidirectional(viewModel.themeSyncOsProperty()); + customThemePath.textProperty().bindBidirectional(viewModel.customPathToThemeProperty()); EasyBind.subscribe( viewModel.selectedThemeProperty(), theme -> { @@ -184,30 +169,22 @@ public void initialize() { validationVisualizer.setDecoration(new IconValidationDecorator()); - openLastStartup - .selectedProperty() - .bindBidirectional(viewModel.openLastStartupProperty()); + openLastStartup.selectedProperty().bindBidirectional(viewModel.openLastStartupProperty()); showAdvancedHints .selectedProperty() .bindBidirectional(viewModel.showAdvancedHintsProperty()); inspectionWarningDuplicate .selectedProperty() .bindBidirectional(viewModel.inspectionWarningDuplicateProperty()); - confirmDelete - .selectedProperty() - .bindBidirectional(viewModel.confirmDeleteProperty()); + confirmDelete.selectedProperty().bindBidirectional(viewModel.confirmDeleteProperty()); - collectTelemetry - .selectedProperty() - .bindBidirectional(viewModel.collectTelemetryProperty()); + collectTelemetry.selectedProperty().bindBidirectional(viewModel.collectTelemetryProperty()); new ViewModelListCellFactory() .withText(BibDatabaseMode::getFormattedName) .install(biblatexMode); biblatexMode.itemsProperty().bind(viewModel.biblatexModeListProperty()); - biblatexMode - .valueProperty() - .bindBidirectional(viewModel.selectedBiblatexModeProperty()); + biblatexMode.valueProperty().bindBidirectional(viewModel.selectedBiblatexModeProperty()); alwaysReformatBib .selectedProperty() @@ -229,48 +206,29 @@ public void initialize() { ); actionFactory.configureIconButton( StandardActions.HELP, - new HelpAction( - HelpFile.REMOTE, - dialogService, - preferencesService.getFilePreferences() - ), + new HelpAction(HelpFile.REMOTE, dialogService, preferencesService.getFilePreferences()), remoteHelp ); - createBackup - .selectedProperty() - .bindBidirectional(viewModel.createBackupProperty()); - backupDirectory - .textProperty() - .bindBidirectional(viewModel.backupDirectoryProperty()); - backupDirectory - .disableProperty() - .bind(viewModel.createBackupProperty().not()); + createBackup.selectedProperty().bindBidirectional(viewModel.createBackupProperty()); + backupDirectory.textProperty().bindBidirectional(viewModel.backupDirectoryProperty()); + backupDirectory.disableProperty().bind(viewModel.createBackupProperty().not()); Platform.runLater(() -> { validationVisualizer.initVisualization( viewModel.remotePortValidationStatus(), remotePort ); - validationVisualizer.initVisualization( - viewModel.fontSizeValidationStatus(), - fontSize - ); + validationVisualizer.initVisualization(viewModel.fontSizeValidationStatus(), fontSize); validationVisualizer.initVisualization( viewModel.customPathToThemeValidationStatus(), customThemePath ); }); - remoteServer - .selectedProperty() - .bindBidirectional(viewModel.remoteServerProperty()); - remotePort - .textProperty() - .bindBidirectional(viewModel.remotePortProperty()); - remotePort - .disableProperty() - .bind(remoteServer.selectedProperty().not()); + remoteServer.selectedProperty().bindBidirectional(viewModel.remoteServerProperty()); + remotePort.textProperty().bindBidirectional(viewModel.remotePortProperty()); + remotePort.disableProperty().bind(remoteServer.selectedProperty().not()); } @FXML diff --git a/src/main/java/org/jabref/gui/preferences/general/GeneralTabViewModel.java b/src/main/java/org/jabref/gui/preferences/general/GeneralTabViewModel.java index 7f74cdb7c5c..22f73432901 100644 --- a/src/main/java/org/jabref/gui/preferences/general/GeneralTabViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/general/GeneralTabViewModel.java @@ -51,61 +51,42 @@ public class GeneralTabViewModel implements PreferenceTabViewModel { protected static SpinnerValueFactory fontSizeValueFactory = - new SpinnerValueFactory.IntegerSpinnerValueFactory( - 9, - Integer.MAX_VALUE - ); + new SpinnerValueFactory.IntegerSpinnerValueFactory(9, Integer.MAX_VALUE); - private final ReadOnlyListProperty languagesListProperty = - new ReadOnlyListWrapper<>( - FXCollections.observableArrayList(Language.values()) - ); - private final ObjectProperty selectedLanguageProperty = - new SimpleObjectProperty<>(); + private final ReadOnlyListProperty languagesListProperty = new ReadOnlyListWrapper<>( + FXCollections.observableArrayList(Language.values()) + ); + private final ObjectProperty selectedLanguageProperty = new SimpleObjectProperty<>(); - private final ReadOnlyListProperty themesListProperty = - new ReadOnlyListWrapper<>( - FXCollections.observableArrayList(ThemeTypes.values()) - ); - private final ObjectProperty selectedThemeProperty = - new SimpleObjectProperty<>(); + private final ReadOnlyListProperty themesListProperty = new ReadOnlyListWrapper<>( + FXCollections.observableArrayList(ThemeTypes.values()) + ); + private final ObjectProperty selectedThemeProperty = new SimpleObjectProperty<>(); - private final BooleanProperty themeSyncOsProperty = - new SimpleBooleanProperty(); + private final BooleanProperty themeSyncOsProperty = new SimpleBooleanProperty(); - private final StringProperty customPathToThemeProperty = - new SimpleStringProperty(); + private final StringProperty customPathToThemeProperty = new SimpleStringProperty(); - private final BooleanProperty fontOverrideProperty = - new SimpleBooleanProperty(); + private final BooleanProperty fontOverrideProperty = new SimpleBooleanProperty(); private final StringProperty fontSizeProperty = new SimpleStringProperty(); - private final BooleanProperty openLastStartupProperty = - new SimpleBooleanProperty(); - private final BooleanProperty showAdvancedHintsProperty = - new SimpleBooleanProperty(); - private final BooleanProperty inspectionWarningDuplicateProperty = - new SimpleBooleanProperty(); - private final BooleanProperty confirmDeleteProperty = - new SimpleBooleanProperty(); + private final BooleanProperty openLastStartupProperty = new SimpleBooleanProperty(); + private final BooleanProperty showAdvancedHintsProperty = new SimpleBooleanProperty(); + private final BooleanProperty inspectionWarningDuplicateProperty = new SimpleBooleanProperty(); + private final BooleanProperty confirmDeleteProperty = new SimpleBooleanProperty(); - private final BooleanProperty collectTelemetryProperty = - new SimpleBooleanProperty(); + private final BooleanProperty collectTelemetryProperty = new SimpleBooleanProperty(); private final ListProperty bibliographyModeListProperty = new SimpleListProperty<>(); private final ObjectProperty selectedBiblatexModeProperty = new SimpleObjectProperty<>(); - private final BooleanProperty alwaysReformatBibProperty = - new SimpleBooleanProperty(); - private final BooleanProperty autosaveLocalLibraries = - new SimpleBooleanProperty(); + private final BooleanProperty alwaysReformatBibProperty = new SimpleBooleanProperty(); + private final BooleanProperty autosaveLocalLibraries = new SimpleBooleanProperty(); - private final BooleanProperty createBackupProperty = - new SimpleBooleanProperty(); - private final StringProperty backupDirectoryProperty = - new SimpleStringProperty(""); + private final BooleanProperty createBackupProperty = new SimpleBooleanProperty(); + private final StringProperty backupDirectoryProperty = new SimpleStringProperty(""); private final DialogService dialogService; private final PreferencesService preferences; @@ -119,15 +100,11 @@ public class GeneralTabViewModel implements PreferenceTabViewModel { private final Validator customPathToThemeValidator; private final List restartWarning = new ArrayList<>(); - private final BooleanProperty remoteServerProperty = - new SimpleBooleanProperty(); - private final StringProperty remotePortProperty = new SimpleStringProperty( - "" - ); + private final BooleanProperty remoteServerProperty = new SimpleBooleanProperty(); + private final StringProperty remotePortProperty = new SimpleStringProperty(""); private final Validator remotePortValidator; private final InternalPreferences internalPreferences; - private final BooleanProperty versionCheckProperty = - new SimpleBooleanProperty(); + private final BooleanProperty versionCheckProperty = new SimpleBooleanProperty(); private final FileUpdateMonitor fileUpdateMonitor; private final BibEntryTypesManager entryTypesManager; private TrustStoreManager trustStoreManager; @@ -155,9 +132,7 @@ public GeneralTabViewModel( fontSizeProperty, input -> { try { - return ( - Integer.parseInt(fontSizeProperty().getValue()) > 8 - ); + return (Integer.parseInt(fontSizeProperty().getValue()) > 8); } catch (NumberFormatException ex) { return false; } @@ -167,9 +142,7 @@ public GeneralTabViewModel( "%s > %s %n %n %s", Localization.lang("General"), Localization.lang("Font settings"), - Localization.lang( - "You must enter an integer value higher than 8." - ) + Localization.lang("You must enter an integer value higher than 8.") ) ) ); @@ -193,9 +166,7 @@ public GeneralTabViewModel( remotePortProperty, input -> { try { - int portNumber = Integer.parseInt( - remotePortProperty().getValue() - ); + int portNumber = Integer.parseInt(remotePortProperty().getValue()); return RemoteUtil.isUserPort(portNumber); } catch (NumberFormatException ex) { return false; @@ -214,9 +185,7 @@ public GeneralTabViewModel( ); this.trustStoreManager = - new TrustStoreManager( - Path.of(preferences.getSSLPreferences().getTruststorePath()) - ); + new TrustStoreManager(Path.of(preferences.getSSLPreferences().getTruststorePath())); } public ValidationStatus remotePortValidationStatus() { @@ -234,58 +203,36 @@ public void setValues() { case EMBEDDED -> selectedThemeProperty.setValue(ThemeTypes.DARK); case CUSTOM -> { selectedThemeProperty.setValue(ThemeTypes.CUSTOM); - customPathToThemeProperty.setValue( - workspacePreferences.getTheme().getName() - ); + customPathToThemeProperty.setValue(workspacePreferences.getTheme().getName()); } } themeSyncOsProperty.setValue(workspacePreferences.shouldThemeSyncOs()); - fontOverrideProperty.setValue( - workspacePreferences.shouldOverrideDefaultFontSize() - ); - fontSizeProperty.setValue( - String.valueOf(workspacePreferences.getMainFontSize()) - ); + fontOverrideProperty.setValue(workspacePreferences.shouldOverrideDefaultFontSize()); + fontSizeProperty.setValue(String.valueOf(workspacePreferences.getMainFontSize())); - openLastStartupProperty.setValue( - workspacePreferences.shouldOpenLastEdited() - ); - showAdvancedHintsProperty.setValue( - workspacePreferences.shouldShowAdvancedHints() - ); + openLastStartupProperty.setValue(workspacePreferences.shouldOpenLastEdited()); + showAdvancedHintsProperty.setValue(workspacePreferences.shouldShowAdvancedHints()); inspectionWarningDuplicateProperty.setValue( workspacePreferences.shouldWarnAboutDuplicatesInInspection() ); - confirmDeleteProperty.setValue( - workspacePreferences.shouldConfirmDelete() - ); + confirmDeleteProperty.setValue(workspacePreferences.shouldConfirmDelete()); - collectTelemetryProperty.setValue( - telemetryPreferences.shouldCollectTelemetry() - ); + collectTelemetryProperty.setValue(telemetryPreferences.shouldCollectTelemetry()); bibliographyModeListProperty.setValue( FXCollections.observableArrayList(BibDatabaseMode.values()) ); - selectedBiblatexModeProperty.setValue( - libraryPreferences.getDefaultBibDatabaseMode() - ); + selectedBiblatexModeProperty.setValue(libraryPreferences.getDefaultBibDatabaseMode()); - alwaysReformatBibProperty.setValue( - libraryPreferences.shouldAlwaysReformatOnSave() - ); + alwaysReformatBibProperty.setValue(libraryPreferences.shouldAlwaysReformatOnSave()); autosaveLocalLibraries.setValue(libraryPreferences.shouldAutoSave()); createBackupProperty.setValue(filePreferences.shouldCreateBackup()); - backupDirectoryProperty.setValue( - filePreferences.getBackupDirectory().toString() - ); + backupDirectoryProperty.setValue(filePreferences.getBackupDirectory().toString()); remoteServerProperty.setValue(remotePreferences.useRemoteServer()); - remotePortProperty.setValue( - String.valueOf(remotePreferences.getPort()) - ); + remotePortProperty.setValue(String.valueOf(remotePreferences.getPort())); } @Override @@ -295,18 +242,12 @@ public void storeSettings() { workspacePreferences.setLanguage(newLanguage); Localization.setLanguage(newLanguage); restartWarning.add( - Localization.lang("Changed language") + - ": " + - newLanguage.getDisplayName() + Localization.lang("Changed language") + ": " + newLanguage.getDisplayName() ); } - workspacePreferences.setShouldOverrideDefaultFontSize( - fontOverrideProperty.getValue() - ); - workspacePreferences.setMainFontSize( - Integer.parseInt(fontSizeProperty.getValue()) - ); + workspacePreferences.setShouldOverrideDefaultFontSize(fontOverrideProperty.getValue()); + workspacePreferences.setMainFontSize(Integer.parseInt(fontSizeProperty.getValue())); switch (selectedThemeProperty.get()) { case LIGHT -> workspacePreferences.setTheme(Theme.light()); @@ -317,33 +258,21 @@ public void storeSettings() { } workspacePreferences.setThemeSyncOs(themeSyncOsProperty.getValue()); - workspacePreferences.setOpenLastEdited( - openLastStartupProperty.getValue() - ); - workspacePreferences.setShowAdvancedHints( - showAdvancedHintsProperty.getValue() - ); + workspacePreferences.setOpenLastEdited(openLastStartupProperty.getValue()); + workspacePreferences.setShowAdvancedHints(showAdvancedHintsProperty.getValue()); workspacePreferences.setWarnAboutDuplicatesInInspection( inspectionWarningDuplicateProperty.getValue() ); workspacePreferences.setConfirmDelete(confirmDeleteProperty.getValue()); - telemetryPreferences.setCollectTelemetry( - collectTelemetryProperty.getValue() - ); + telemetryPreferences.setCollectTelemetry(collectTelemetryProperty.getValue()); - libraryPreferences.setDefaultBibDatabaseMode( - selectedBiblatexModeProperty.getValue() - ); + libraryPreferences.setDefaultBibDatabaseMode(selectedBiblatexModeProperty.getValue()); - libraryPreferences.setAlwaysReformatOnSave( - alwaysReformatBibProperty.getValue() - ); + libraryPreferences.setAlwaysReformatOnSave(alwaysReformatBibProperty.getValue()); libraryPreferences.setAutoSave(autosaveLocalLibraries.getValue()); - filePreferences - .createBackupProperty() - .setValue(createBackupProperty.getValue()); + filePreferences.createBackupProperty().setValue(createBackupProperty.getValue()); filePreferences .backupDirectoryProperty() .setValue(Path.of(backupDirectoryProperty.getValue())); @@ -355,9 +284,7 @@ public void storeSettings() { } }); - internalPreferences.setVersionCheckEnabled( - versionCheckProperty.getValue() - ); + internalPreferences.setVersionCheckEnabled(versionCheckProperty.getValue()); getPortAsInt(remotePortProperty.getValue()) .ifPresent(newPort -> { @@ -369,11 +296,7 @@ public void storeSettings() { if (remoteServerProperty.getValue()) { remotePreferences.setUseRemoteServer(true); Globals.REMOTE_LISTENER.openAndStart( - new CLIMessageHandler( - preferences, - fileUpdateMonitor, - entryTypesManager - ), + new CLIMessageHandler(preferences, fileUpdateMonitor, entryTypesManager), remotePreferences.getPort() ); } else { @@ -385,11 +308,7 @@ public void storeSettings() { if (remoteServerProperty.getValue()) { remotePreferences.setUseRemoteServer(true); Globals.REMOTE_LISTENER.openAndStart( - new CLIMessageHandler( - preferences, - fileUpdateMonitor, - entryTypesManager - ), + new CLIMessageHandler(preferences, fileUpdateMonitor, entryTypesManager), remotePreferences.getPort() ); } else { @@ -427,9 +346,7 @@ public boolean validateSettings() { if (!validationStatus.isValid()) { validationStatus .getHighestMessage() - .ifPresent(message -> - dialogService.showErrorDialogAndWait(message.getMessage()) - ); + .ifPresent(message -> dialogService.showErrorDialogAndWait(message.getMessage())); return false; } return true; @@ -465,23 +382,17 @@ public StringProperty customPathToThemeProperty() { } public void importCSSFile() { - FileDialogConfiguration fileDialogConfiguration = - new FileDialogConfiguration.Builder() - .addExtensionFilter(StandardFileType.CSS) - .withDefaultExtension(StandardFileType.CSS) - .withInitialDirectory( - preferences - .getInternalPreferences() - .getLastPreferencesExportPath() - ) - .build(); + FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() + .addExtensionFilter(StandardFileType.CSS) + .withDefaultExtension(StandardFileType.CSS) + .withInitialDirectory( + preferences.getInternalPreferences().getLastPreferencesExportPath() + ) + .build(); dialogService .showFileOpenDialog(fileDialogConfiguration) - .ifPresent(file -> - customPathToThemeProperty.setValue( - file.toAbsolutePath().toString() - ) + .ifPresent(file -> customPathToThemeProperty.setValue(file.toAbsolutePath().toString()) ); } @@ -540,9 +451,7 @@ public StringProperty backupDirectoryProperty() { public void backupFileDirBrowse() { DirectoryDialogConfiguration dirDialogConfiguration = new DirectoryDialogConfiguration.Builder() - .withInitialDirectory( - Path.of(backupDirectoryProperty().getValue()) - ) + .withInitialDirectory(Path.of(backupDirectoryProperty().getValue())) .build(); dialogService .showDirectorySelectionDialog(dirDialogConfiguration) @@ -562,10 +471,7 @@ public void openBrowser() { try { JabRefDesktop.openBrowser(url, preferences.getFilePreferences()); } catch (IOException e) { - dialogService.showErrorDialogAndWait( - Localization.lang("Could not open website."), - e - ); + dialogService.showErrorDialogAndWait(Localization.lang("Could not open website."), e); } } diff --git a/src/main/java/org/jabref/gui/preferences/groups/GroupsTab.java b/src/main/java/org/jabref/gui/preferences/groups/GroupsTab.java index 183dab0b4fe..fd38fc67e52 100644 --- a/src/main/java/org/jabref/gui/preferences/groups/GroupsTab.java +++ b/src/main/java/org/jabref/gui/preferences/groups/GroupsTab.java @@ -34,8 +34,7 @@ public String getTabName() { } public void initialize() { - this.viewModel = - new GroupsTabViewModel(preferencesService.getGroupsPreferences()); + this.viewModel = new GroupsTabViewModel(preferencesService.getGroupsPreferences()); groupViewModeIntersection .selectedProperty() @@ -43,11 +42,7 @@ public void initialize() { groupViewModeUnion .selectedProperty() .bindBidirectional(viewModel.groupViewModeUnionProperty()); - autoAssignGroup - .selectedProperty() - .bindBidirectional(viewModel.autoAssignGroupProperty()); - displayGroupCount - .selectedProperty() - .bindBidirectional(viewModel.displayGroupCount()); + autoAssignGroup.selectedProperty().bindBidirectional(viewModel.autoAssignGroupProperty()); + displayGroupCount.selectedProperty().bindBidirectional(viewModel.displayGroupCount()); } } diff --git a/src/main/java/org/jabref/gui/preferences/groups/GroupsTabViewModel.java b/src/main/java/org/jabref/gui/preferences/groups/GroupsTabViewModel.java index bcc123e634c..e45ce8f145b 100644 --- a/src/main/java/org/jabref/gui/preferences/groups/GroupsTabViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/groups/GroupsTabViewModel.java @@ -8,14 +8,10 @@ public class GroupsTabViewModel implements PreferenceTabViewModel { - private final BooleanProperty groupViewModeIntersectionProperty = - new SimpleBooleanProperty(); - private final BooleanProperty groupViewModeUnionProperty = - new SimpleBooleanProperty(); - private final BooleanProperty autoAssignGroupProperty = - new SimpleBooleanProperty(); - private final BooleanProperty displayGroupCountProperty = - new SimpleBooleanProperty(); + private final BooleanProperty groupViewModeIntersectionProperty = new SimpleBooleanProperty(); + private final BooleanProperty groupViewModeUnionProperty = new SimpleBooleanProperty(); + private final BooleanProperty autoAssignGroupProperty = new SimpleBooleanProperty(); + private final BooleanProperty displayGroupCountProperty = new SimpleBooleanProperty(); private final GroupsPreferences groupsPreferences; @@ -35,12 +31,8 @@ public void setValues() { groupViewModeUnionProperty.setValue(true); } } - autoAssignGroupProperty.setValue( - groupsPreferences.shouldAutoAssignGroup() - ); - displayGroupCountProperty.setValue( - groupsPreferences.shouldDisplayGroupCount() - ); + autoAssignGroupProperty.setValue(groupsPreferences.shouldAutoAssignGroup()); + displayGroupCountProperty.setValue(groupsPreferences.shouldDisplayGroupCount()); } @Override @@ -50,12 +42,8 @@ public void storeSettings() { ? GroupViewMode.INTERSECTION : GroupViewMode.UNION ); - groupsPreferences.setAutoAssignGroup( - autoAssignGroupProperty.getValue() - ); - groupsPreferences.setDisplayGroupCount( - displayGroupCountProperty.getValue() - ); + groupsPreferences.setAutoAssignGroup(autoAssignGroupProperty.getValue()); + groupsPreferences.setDisplayGroupCount(displayGroupCountProperty.getValue()); } public BooleanProperty groupViewModeIntersectionProperty() { diff --git a/src/main/java/org/jabref/gui/preferences/journals/AbbreviationViewModel.java b/src/main/java/org/jabref/gui/preferences/journals/AbbreviationViewModel.java index 0dde9ac7f39..5c5a1c790c7 100644 --- a/src/main/java/org/jabref/gui/preferences/journals/AbbreviationViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/journals/AbbreviationViewModel.java @@ -16,12 +16,10 @@ public class AbbreviationViewModel { private final StringProperty name = new SimpleStringProperty(""); private final StringProperty abbreviation = new SimpleStringProperty(""); - private final StringProperty shortestUniqueAbbreviation = - new SimpleStringProperty(""); + private final StringProperty shortestUniqueAbbreviation = new SimpleStringProperty(""); // Used when a "null" abbreviation object is added - private final BooleanProperty pseudoAbbreviation = - new SimpleBooleanProperty(); + private final BooleanProperty pseudoAbbreviation = new SimpleBooleanProperty(); public AbbreviationViewModel(Abbreviation abbreviationObject) { this.pseudoAbbreviation.set(abbreviationObject == null); @@ -39,19 +37,13 @@ public AbbreviationViewModel(Abbreviation abbreviationObject) { if (shortestUniqueAbbreviationIsDefaultValue) { this.shortestUniqueAbbreviation.set(""); } else { - this.shortestUniqueAbbreviation.setValue( - shortestUniqueAbbreviationOfAbbreviation - ); + this.shortestUniqueAbbreviation.setValue(shortestUniqueAbbreviationOfAbbreviation); } } } public Abbreviation getAbbreviationObject() { - return new Abbreviation( - getName(), - getAbbreviation(), - getShortestUniqueAbbreviation() - ); + return new Abbreviation(getName(), getAbbreviation(), getShortestUniqueAbbreviation()); } public String getName() { @@ -74,9 +66,7 @@ public String getShortestUniqueAbbreviation() { return shortestUniqueAbbreviation.get(); } - public void setShortestUniqueAbbreviation( - String shortestUniqueAbbreviation - ) { + public void setShortestUniqueAbbreviation(String shortestUniqueAbbreviation) { this.shortestUniqueAbbreviation.set(shortestUniqueAbbreviation); } @@ -112,8 +102,7 @@ public boolean equals(Object o) { return ( getName().equals(that.getName()) && getAbbreviation().equals(that.getAbbreviation()) && - getShortestUniqueAbbreviation() - .equals(that.getShortestUniqueAbbreviation()) && + getShortestUniqueAbbreviation().equals(that.getShortestUniqueAbbreviation()) && (isPseudoAbbreviation() == that.isPseudoAbbreviation()) ); } @@ -131,13 +120,9 @@ public int hashCode() { public boolean containsCaseIndependent(String searchTerm) { searchTerm = searchTerm.toLowerCase(Locale.ROOT); return ( - this.abbreviation.get() - .toLowerCase(Locale.ROOT) - .contains(searchTerm) || + this.abbreviation.get().toLowerCase(Locale.ROOT).contains(searchTerm) || this.name.get().toLowerCase(Locale.ROOT).contains(searchTerm) || - this.shortestUniqueAbbreviation.get() - .toLowerCase(Locale.ROOT) - .contains(searchTerm) + this.shortestUniqueAbbreviation.get().toLowerCase(Locale.ROOT).contains(searchTerm) ); } } diff --git a/src/main/java/org/jabref/gui/preferences/journals/AbbreviationsFileViewModel.java b/src/main/java/org/jabref/gui/preferences/journals/AbbreviationsFileViewModel.java index 6dbbfb196de..d19dd1656cc 100644 --- a/src/main/java/org/jabref/gui/preferences/journals/AbbreviationsFileViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/journals/AbbreviationsFileViewModel.java @@ -40,10 +40,7 @@ public AbbreviationsFileViewModel(Path filePath) { * a placeholder and its path will be null meaning it has no place on the filesystem. Its isPseudoFile property * will therefore be set to true. */ - public AbbreviationsFileViewModel( - List abbreviations, - String name - ) { + public AbbreviationsFileViewModel(List abbreviations, String name) { this.abbreviations.addAll(abbreviations); this.name = name; this.path = Optional.empty(); @@ -53,9 +50,7 @@ public AbbreviationsFileViewModel( public void readAbbreviations() throws IOException { if (path.isPresent()) { Collection abbreviationList = - JournalAbbreviationLoader.readAbbreviationsFromCsvFile( - path.get() - ); + JournalAbbreviationLoader.readAbbreviationsFromCsvFile(path.get()); abbreviationList.forEach(abbreviation -> abbreviations.addAll(new AbbreviationViewModel(abbreviation)) ); diff --git a/src/main/java/org/jabref/gui/preferences/journals/JournalAbbreviationsTab.java b/src/main/java/org/jabref/gui/preferences/journals/JournalAbbreviationsTab.java index 4a93a2f4ffc..3185880a1d0 100644 --- a/src/main/java/org/jabref/gui/preferences/journals/JournalAbbreviationsTab.java +++ b/src/main/java/org/jabref/gui/preferences/journals/JournalAbbreviationsTab.java @@ -55,16 +55,10 @@ public class JournalAbbreviationsTab private TableColumn journalTableNameColumn; @FXML - private TableColumn< - AbbreviationViewModel, - String - > journalTableAbbreviationColumn; + private TableColumn journalTableAbbreviationColumn; @FXML - private TableColumn< - AbbreviationViewModel, - String - > journalTableShortestUniqueAbbreviationColumn; + private TableColumn journalTableShortestUniqueAbbreviationColumn; @FXML private TableColumn actionsColumn; @@ -108,8 +102,7 @@ private void initialize() { abbreviationRepository ); - filteredAbbreviations = - new FilteredList<>(viewModel.abbreviationsProperty()); + filteredAbbreviations = new FilteredList<>(viewModel.abbreviationsProperty()); setUpTable(); setBindings(); @@ -120,19 +113,13 @@ private void initialize() { } private void setUpTable() { - journalTableNameColumn.setCellValueFactory(cellData -> - cellData.getValue().nameProperty() - ); - journalTableNameColumn.setCellFactory( - TextFieldTableCell.forTableColumn() - ); + journalTableNameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty()); + journalTableNameColumn.setCellFactory(TextFieldTableCell.forTableColumn()); journalTableAbbreviationColumn.setCellValueFactory(cellData -> cellData.getValue().abbreviationProperty() ); - journalTableAbbreviationColumn.setCellFactory( - TextFieldTableCell.forTableColumn() - ); + journalTableAbbreviationColumn.setCellFactory(TextFieldTableCell.forTableColumn()); journalTableShortestUniqueAbbreviationColumn.setCellValueFactory(cellData -> cellData.getValue().shortestUniqueAbbreviationProperty() @@ -141,26 +128,16 @@ private void setUpTable() { TextFieldTableCell.forTableColumn() ); - actionsColumn.setCellValueFactory(cellData -> - cellData.getValue().nameProperty() - ); + actionsColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty()); new ValueTableCellFactory() - .withGraphic(name -> - IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode() - ) + .withGraphic(name -> IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode()) .withTooltip(name -> Localization.lang("Remove journal '%0'", name)) - .withDisableExpression(item -> - viewModel.isEditableAndRemovableProperty().not() - ) - .withVisibleExpression(item -> - viewModel.isEditableAndRemovableProperty() - ) + .withDisableExpression(item -> viewModel.isEditableAndRemovableProperty().not()) + .withVisibleExpression(item -> viewModel.isEditableAndRemovableProperty()) .withOnMouseClickedEvent(item -> evt -> viewModel.removeAbbreviation( - journalAbbreviationsTable - .getFocusModel() - .getFocusedItem() + journalAbbreviationsTable.getFocusModel().getFocusedItem() ) ) .install(actionsColumn); @@ -170,15 +147,12 @@ private void setBindings() { journalAbbreviationsTable.setItems(filteredAbbreviations); EasyBind.subscribe( - journalAbbreviationsTable - .getSelectionModel() - .selectedItemProperty(), + journalAbbreviationsTable.getSelectionModel().selectedItemProperty(), newValue -> viewModel.currentAbbreviationProperty().set(newValue) ); EasyBind.subscribe( viewModel.currentAbbreviationProperty(), - newValue -> - journalAbbreviationsTable.getSelectionModel().select(newValue) + newValue -> journalAbbreviationsTable.getSelectionModel().select(newValue) ); journalTableNameColumn @@ -194,12 +168,8 @@ private void setBindings() { removeAbbreviationListButton .disableProperty() .bind(viewModel.isFileRemovableProperty().not()); - journalFilesBox - .itemsProperty() - .bindBidirectional(viewModel.journalFilesProperty()); - journalFilesBox - .valueProperty() - .bindBidirectional(viewModel.currentFileProperty()); + journalFilesBox.itemsProperty().bindBidirectional(viewModel.journalFilesProperty()); + journalFilesBox.valueProperty().bindBidirectional(viewModel.currentFileProperty()); addAbbreviationButton .disableProperty() @@ -212,22 +182,18 @@ private void setBindings() { .textProperty() .addListener((observable, previousText, searchTerm) -> filteredAbbreviations.setPredicate(abbreviation -> - searchTerm.isEmpty() || - abbreviation.containsCaseIndependent(searchTerm) + searchTerm.isEmpty() || abbreviation.containsCaseIndependent(searchTerm) ) ); - useFJournal - .selectedProperty() - .bindBidirectional(viewModel.useFJournalProperty()); + useFJournal.selectedProperty().bindBidirectional(viewModel.useFJournalProperty()); } private void setAnimations() { - ObjectProperty flashingColor = new SimpleObjectProperty<>( - Color.TRANSPARENT + ObjectProperty flashingColor = new SimpleObjectProperty<>(Color.TRANSPARENT); + StringProperty flashingColorStringProperty = createFlashingColorStringProperty( + flashingColor ); - StringProperty flashingColorStringProperty = - createFlashingColorStringProperty(flashingColor); searchBox .styleProperty() @@ -240,11 +206,7 @@ private void setAnimations() { new Timeline( new KeyFrame( Duration.seconds(0), - new KeyValue( - flashingColor, - Color.TRANSPARENT, - Interpolator.LINEAR - ) + new KeyValue(flashingColor, Color.TRANSPARENT, Interpolator.LINEAR) ), new KeyFrame( Duration.seconds(0.25), @@ -252,11 +214,7 @@ private void setAnimations() { ), new KeyFrame( Duration.seconds(0.25), - new KeyValue( - searchBox.textProperty(), - "", - Interpolator.DISCRETE - ) + new KeyValue(searchBox.textProperty(), "", Interpolator.DISCRETE) ), new KeyFrame( Duration.seconds(0.25), @@ -264,11 +222,7 @@ private void setAnimations() { ), new KeyFrame( Duration.seconds(0.5), - new KeyValue( - flashingColor, - Color.TRANSPARENT, - Interpolator.LINEAR - ) + new KeyValue(flashingColor, Color.TRANSPARENT, Interpolator.LINEAR) ) ); } @@ -306,8 +260,7 @@ private void addAbbreviationActions() { private static StringProperty createFlashingColorStringProperty( final ObjectProperty flashingColor ) { - final StringProperty flashingColorStringProperty = - new SimpleStringProperty(); + final StringProperty flashingColorStringProperty = new SimpleStringProperty(); setColorStringFromColor(flashingColorStringProperty, flashingColor); flashingColor.addListener((observable, oldValue, newValue) -> setColorStringFromColor(flashingColorStringProperty, flashingColor) @@ -334,9 +287,7 @@ private void selectNewAbbreviation() { int lastRow = viewModel.abbreviationsCountProperty().get() - 1; journalAbbreviationsTable.scrollTo(lastRow); journalAbbreviationsTable.getSelectionModel().select(lastRow); - journalAbbreviationsTable - .getFocusModel() - .focus(lastRow, journalTableNameColumn); + journalAbbreviationsTable.getFocusModel().focus(lastRow, journalTableNameColumn); } @Override diff --git a/src/main/java/org/jabref/gui/preferences/journals/JournalAbbreviationsTabViewModel.java b/src/main/java/org/jabref/gui/preferences/journals/JournalAbbreviationsTabViewModel.java index 96928ae3bb5..34142765ef1 100644 --- a/src/main/java/org/jabref/gui/preferences/journals/JournalAbbreviationsTabViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/journals/JournalAbbreviationsTabViewModel.java @@ -30,38 +30,27 @@ * This class provides a model for managing journal abbreviation lists. It provides all necessary methods to create, * modify or delete journal abbreviations and files. To visualize the model one can bind the properties to UI elements. */ -public class JournalAbbreviationsTabViewModel - implements PreferenceTabViewModel { +public class JournalAbbreviationsTabViewModel implements PreferenceTabViewModel { - private final Logger LOGGER = LoggerFactory.getLogger( - JournalAbbreviationsTabViewModel.class - ); + private final Logger LOGGER = LoggerFactory.getLogger(JournalAbbreviationsTabViewModel.class); private final SimpleListProperty journalFiles = new SimpleListProperty<>(FXCollections.observableArrayList()); private final SimpleListProperty abbreviations = new SimpleListProperty<>(FXCollections.observableArrayList()); - private final SimpleIntegerProperty abbreviationsCount = - new SimpleIntegerProperty(); + private final SimpleIntegerProperty abbreviationsCount = new SimpleIntegerProperty(); private final SimpleObjectProperty currentFile = new SimpleObjectProperty<>(); - private final SimpleObjectProperty< - AbbreviationViewModel - > currentAbbreviation = new SimpleObjectProperty<>(); - - private final SimpleBooleanProperty isFileRemovable = - new SimpleBooleanProperty(); - private final SimpleBooleanProperty isLoading = new SimpleBooleanProperty( - false - ); - private final SimpleBooleanProperty isEditableAndRemovable = - new SimpleBooleanProperty(false); + private final SimpleObjectProperty currentAbbreviation = + new SimpleObjectProperty<>(); + + private final SimpleBooleanProperty isFileRemovable = new SimpleBooleanProperty(); + private final SimpleBooleanProperty isLoading = new SimpleBooleanProperty(false); + private final SimpleBooleanProperty isEditableAndRemovable = new SimpleBooleanProperty(false); private final SimpleBooleanProperty isAbbreviationEditableAndRemovable = new SimpleBooleanProperty(false); - private final SimpleBooleanProperty useFJournal = new SimpleBooleanProperty( - true - ); + private final SimpleBooleanProperty useFJournal = new SimpleBooleanProperty(true); private final DialogService dialogService; private final TaskExecutor taskExecutor; @@ -78,38 +67,27 @@ public JournalAbbreviationsTabViewModel( ) { this.dialogService = Objects.requireNonNull(dialogService); this.taskExecutor = Objects.requireNonNull(taskExecutor); - this.journalAbbreviationRepository = - Objects.requireNonNull(journalAbbreviationRepository); + this.journalAbbreviationRepository = Objects.requireNonNull(journalAbbreviationRepository); this.abbreviationsPreferences = abbreviationsPreferences; abbreviationsCount.bind(abbreviations.sizeProperty()); currentAbbreviation.addListener((observable, oldValue, newValue) -> { - boolean isAbbreviation = - (newValue != null) && !newValue.isPseudoAbbreviation(); + boolean isAbbreviation = (newValue != null) && !newValue.isPseudoAbbreviation(); boolean isEditableFile = - (currentFile.get() != null) && - !currentFile.get().isBuiltInListProperty().get(); + (currentFile.get() != null) && !currentFile.get().isBuiltInListProperty().get(); isEditableAndRemovable.set(isEditableFile); - isAbbreviationEditableAndRemovable.set( - isAbbreviation && isEditableFile - ); + isAbbreviationEditableAndRemovable.set(isAbbreviation && isEditableFile); }); currentFile.addListener((observable, oldValue, newValue) -> { if (oldValue != null) { - abbreviations.unbindBidirectional( - oldValue.abbreviationsProperty() - ); + abbreviations.unbindBidirectional(oldValue.abbreviationsProperty()); currentAbbreviation.set(null); } if (newValue != null) { isFileRemovable.set(!newValue.isBuiltInListProperty().get()); - abbreviations.bindBidirectional( - newValue.abbreviationsProperty() - ); + abbreviations.bindBidirectional(newValue.abbreviationsProperty()); if (!abbreviations.isEmpty()) { - currentAbbreviation.set( - abbreviations.get(abbreviations.size() - 1) - ); + currentAbbreviation.set(abbreviations.get(abbreviations.size() - 1)); } } else { isFileRemovable.set(false); @@ -127,11 +105,7 @@ public JournalAbbreviationsTabViewModel( if (!lcl.wasReplaced()) { if ( lcl.wasAdded() && - !lcl - .getAddedSubList() - .get(0) - .isBuiltInListProperty() - .get() + !lcl.getAddedSubList().get(0).isBuiltInListProperty().get() ) { currentFile.set(lcl.getAddedSubList().get(0)); } @@ -154,8 +128,7 @@ public void setValues() { * Read all saved file paths and read their abbreviations. */ public void createFileObjects() { - List externalFiles = - abbreviationsPreferences.getExternalJournalLists(); + List externalFiles = abbreviationsPreferences.getExternalJournalLists(); externalFiles.forEach(name -> openFile(Path.of(name))); } @@ -166,9 +139,7 @@ public void createFileObjects() { */ public void selectLastJournalFile() { if (!journalFiles.isEmpty()) { - currentFile.set( - journalFilesProperty().get(journalFilesProperty().size() - 1) - ); + currentFile.set(journalFilesProperty().get(journalFilesProperty().size() - 1)); } } @@ -202,14 +173,11 @@ public void addBuiltInList() { * basically just calls the {@link #openFile(Path)}} method. */ public void addNewFile() { - FileDialogConfiguration fileDialogConfiguration = - new FileDialogConfiguration.Builder() - .addExtensionFilter(StandardFileType.CSV) - .build(); - - dialogService - .showFileSaveDialog(fileDialogConfiguration) - .ifPresent(this::openFile); + FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() + .addExtensionFilter(StandardFileType.CSV) + .build(); + + dialogService.showFileSaveDialog(fileDialogConfiguration).ifPresent(this::openFile); } /** @@ -220,15 +188,11 @@ public void addNewFile() { * @param filePath path to the file */ private void openFile(Path filePath) { - AbbreviationsFileViewModel abbreviationsFile = - new AbbreviationsFileViewModel(filePath); + AbbreviationsFileViewModel abbreviationsFile = new AbbreviationsFileViewModel(filePath); if (journalFiles.contains(abbreviationsFile)) { dialogService.showErrorDialogAndWait( Localization.lang("Duplicated Journal File"), - Localization.lang( - "Journal file %s already added", - filePath.toString() - ) + Localization.lang("Journal file %s already added", filePath.toString()) ); return; } @@ -243,14 +207,11 @@ private void openFile(Path filePath) { } public void openFile() { - FileDialogConfiguration fileDialogConfiguration = - new FileDialogConfiguration.Builder() - .addExtensionFilter(StandardFileType.CSV) - .build(); - - dialogService - .showFileOpenDialog(fileDialogConfiguration) - .ifPresent(this::openFile); + FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() + .addExtensionFilter(StandardFileType.CSV) + .build(); + + dialogService.showFileOpenDialog(fileDialogConfiguration).ifPresent(this::openFile); } /** @@ -273,9 +234,7 @@ public void removeCurrentFile() { * property to the new abbreviation. */ public void addAbbreviation(Abbreviation abbreviationObject) { - AbbreviationViewModel abbreviationViewModel = new AbbreviationViewModel( - abbreviationObject - ); + AbbreviationViewModel abbreviationViewModel = new AbbreviationViewModel(abbreviationObject); if (abbreviations.contains(abbreviationViewModel)) { dialogService.showErrorDialogAndWait( Localization.lang("Duplicated Journal Abbreviation"), @@ -307,14 +266,10 @@ public void addAbbreviation() { */ void editAbbreviation(Abbreviation abbreviationObject) { if (isEditableAndRemovable.get()) { - AbbreviationViewModel abbViewModel = new AbbreviationViewModel( - abbreviationObject - ); + AbbreviationViewModel abbViewModel = new AbbreviationViewModel(abbreviationObject); if (abbreviations.contains(abbViewModel)) { if (abbViewModel.equals(currentAbbreviation.get())) { - setCurrentAbbreviationNameAndAbbreviationIfValid( - abbreviationObject - ); + setCurrentAbbreviationNameAndAbbreviationIfValid(abbreviationObject); } else { dialogService.showErrorDialogAndWait( Localization.lang("Duplicated Journal Abbreviation"), @@ -326,33 +281,23 @@ void editAbbreviation(Abbreviation abbreviationObject) { ); } } else { - setCurrentAbbreviationNameAndAbbreviationIfValid( - abbreviationObject - ); + setCurrentAbbreviationNameAndAbbreviationIfValid(abbreviationObject); } } } - private void setCurrentAbbreviationNameAndAbbreviationIfValid( - Abbreviation abbreviationObject - ) { + private void setCurrentAbbreviationNameAndAbbreviationIfValid(Abbreviation abbreviationObject) { if (abbreviationObject.getName().trim().isEmpty()) { - dialogService.showErrorDialogAndWait( - Localization.lang("Name cannot be empty") - ); + dialogService.showErrorDialogAndWait(Localization.lang("Name cannot be empty")); return; } if (abbreviationObject.getAbbreviation().trim().isEmpty()) { - dialogService.showErrorDialogAndWait( - Localization.lang("Abbreviation cannot be empty") - ); + dialogService.showErrorDialogAndWait(Localization.lang("Abbreviation cannot be empty")); return; } AbbreviationViewModel abbreviationViewModel = currentAbbreviation.get(); abbreviationViewModel.setName(abbreviationObject.getName()); - abbreviationViewModel.setAbbreviation( - abbreviationObject.getAbbreviation() - ); + abbreviationViewModel.setAbbreviation(abbreviationObject.getAbbreviation()); if (abbreviationObject.isDefaultShortestUniqueAbbreviation()) { abbreviationViewModel.setShortestUniqueAbbreviation(""); } else { @@ -370,8 +315,7 @@ private void setCurrentAbbreviationNameAndAbbreviationIfValid( */ public void deleteAbbreviation() { if ( - (currentAbbreviation.get() != null) && - !currentAbbreviation.get().isPseudoAbbreviation() + (currentAbbreviation.get() != null) && !currentAbbreviation.get().isPseudoAbbreviation() ) { int index = abbreviations.indexOf(currentAbbreviation.get()); if (index > 1) { @@ -424,14 +368,10 @@ public void storeSettings() { .stream() .filter(path -> !path.isBuiltInListProperty().get()) .filter(path -> path.getAbsolutePath().isPresent()) - .map(path -> - path.getAbsolutePath().get().toAbsolutePath().toString() - ) + .map(path -> path.getAbsolutePath().get().toAbsolutePath().toString()) .collect(Collectors.toList()); - abbreviationsPreferences.setExternalJournalLists( - journalStringList - ); + abbreviationsPreferences.setExternalJournalLists(journalStringList); abbreviationsPreferences.setUseFJournalField(useFJournal.get()); if (shouldWriteLists) { @@ -441,13 +381,9 @@ public void storeSettings() { }) .onSuccess(success -> Globals.journalAbbreviationRepository = - JournalAbbreviationLoader.loadRepository( - abbreviationsPreferences - ) - ) - .onFailure(exception -> - LOGGER.error("Failed to store journal preferences.", exception) + JournalAbbreviationLoader.loadRepository(abbreviationsPreferences) ) + .onFailure(exception -> LOGGER.error("Failed to store journal preferences.", exception)) .executeWith(taskExecutor); } @@ -455,9 +391,7 @@ public SimpleBooleanProperty isLoadingProperty() { return isLoading; } - public SimpleListProperty< - AbbreviationsFileViewModel - > journalFilesProperty() { + public SimpleListProperty journalFilesProperty() { return journalFiles; } @@ -469,15 +403,11 @@ public SimpleIntegerProperty abbreviationsCountProperty() { return abbreviationsCount; } - public SimpleObjectProperty< - AbbreviationsFileViewModel - > currentFileProperty() { + public SimpleObjectProperty currentFileProperty() { return currentFile; } - public SimpleObjectProperty< - AbbreviationViewModel - > currentAbbreviationProperty() { + public SimpleObjectProperty currentAbbreviationProperty() { return currentAbbreviation; } diff --git a/src/main/java/org/jabref/gui/preferences/keybindings/KeyBindingViewModel.java b/src/main/java/org/jabref/gui/preferences/keybindings/KeyBindingViewModel.java index cd459e2c2e1..dc8484c842f 100644 --- a/src/main/java/org/jabref/gui/preferences/keybindings/KeyBindingViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/keybindings/KeyBindingViewModel.java @@ -29,8 +29,7 @@ public class KeyBindingViewModel { FXCollections.observableArrayList(); private final KeyBindingRepository keyBindingRepository; private final SimpleStringProperty displayName = new SimpleStringProperty(); - private final SimpleStringProperty shownBinding = - new SimpleStringProperty(); + private final SimpleStringProperty shownBinding = new SimpleStringProperty(); private final KeyBindingCategory category; @@ -75,20 +74,14 @@ private void setBinding(String bind) { String[] parts = bind.split(" "); StringBuilder displayBind = new StringBuilder(); for (String part : parts) { - displayBind - .append(CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, part)) - .append(" "); + displayBind.append(CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, part)).append(" "); } - this.shownBinding.set( - displayBind.toString().trim().replace(" ", " + ") - ); + this.shownBinding.set(displayBind.toString().trim().replace(" ", " + ")); } private void setDisplayName() { this.displayName.set( - keyBinding == null - ? this.category.getName() - : keyBinding.getLocalization() + keyBinding == null ? this.category.getName() : keyBinding.getLocalization() ); } @@ -136,11 +129,7 @@ public boolean setNewBinding(KeyEvent evt) { // if no modifier keys are pressed, only special keys can be shortcuts if (modifiers.isEmpty()) { - if ( - !(code.isFunctionKey() || - (code == KeyCode.ESCAPE) || - (code == KeyCode.DELETE)) - ) { + if (!(code.isFunctionKey() || (code == KeyCode.ESCAPE) || (code == KeyCode.DELETE))) { return false; } } @@ -171,14 +160,10 @@ public void clear() { } public Optional getResetIcon() { - return isCategory() - ? Optional.empty() - : Optional.of(IconTheme.JabRefIcons.REFRESH); + return isCategory() ? Optional.empty() : Optional.of(IconTheme.JabRefIcons.REFRESH); } public Optional getClearIcon() { - return isCategory() - ? Optional.empty() - : Optional.of(IconTheme.JabRefIcons.CLEANUP_ENTRIES); + return isCategory() ? Optional.empty() : Optional.of(IconTheme.JabRefIcons.CLEANUP_ENTRIES); } } diff --git a/src/main/java/org/jabref/gui/preferences/keybindings/KeyBindingsTab.java b/src/main/java/org/jabref/gui/preferences/keybindings/KeyBindingsTab.java index 0264e4edb45..740716afab3 100644 --- a/src/main/java/org/jabref/gui/preferences/keybindings/KeyBindingsTab.java +++ b/src/main/java/org/jabref/gui/preferences/keybindings/KeyBindingsTab.java @@ -34,16 +34,10 @@ public class KeyBindingsTab private TreeTableColumn shortcutColumn; @FXML - private TreeTableColumn< - KeyBindingViewModel, - KeyBindingViewModel - > resetColumn; + private TreeTableColumn resetColumn; @FXML - private TreeTableColumn< - KeyBindingViewModel, - KeyBindingViewModel - > clearColumn; + private TreeTableColumn clearColumn; @FXML private MenuButton presetsButton; @@ -63,15 +57,9 @@ public String getTabName() { @FXML private void initialize() { viewModel = - new KeyBindingsTabViewModel( - keyBindingRepository, - dialogService, - preferencesService - ); + new KeyBindingsTabViewModel(keyBindingRepository, dialogService, preferencesService); - keyBindingsTable - .getSelectionModel() - .setSelectionMode(SelectionMode.SINGLE); + keyBindingsTable.getSelectionModel().setSelectionMode(SelectionMode.SINGLE); viewModel .selectedKeyBindingProperty() .bind( @@ -87,44 +75,29 @@ private void initialize() { EasyBind.map( viewModel.rootKeyBindingProperty(), keybinding -> - new RecursiveTreeItem<>( - keybinding, - KeyBindingViewModel::getChildren - ) + new RecursiveTreeItem<>(keybinding, KeyBindingViewModel::getChildren) ) ); - actionColumn.setCellValueFactory(cellData -> - cellData.getValue().getValue().nameProperty() - ); + actionColumn.setCellValueFactory(cellData -> cellData.getValue().getValue().nameProperty()); shortcutColumn.setCellValueFactory(cellData -> cellData.getValue().getValue().shownBindingProperty() ); new ViewModelTreeTableCellFactory() .withGraphic(keyBinding -> - keyBinding - .getResetIcon() - .map(JabRefIcon::getGraphicNode) - .orElse(null) - ) - .withOnMouseClickedEvent(keyBinding -> - evt -> keyBinding.resetToDefault() + keyBinding.getResetIcon().map(JabRefIcon::getGraphicNode).orElse(null) ) + .withOnMouseClickedEvent(keyBinding -> evt -> keyBinding.resetToDefault()) .install(resetColumn); new ViewModelTreeTableCellFactory() .withGraphic(keyBinding -> - keyBinding - .getClearIcon() - .map(JabRefIcon::getGraphicNode) - .orElse(null) + keyBinding.getClearIcon().map(JabRefIcon::getGraphicNode).orElse(null) ) .withOnMouseClickedEvent(keyBinding -> evt -> keyBinding.clear()) .install(clearColumn); viewModel .keyBindingPresets() - .forEach(preset -> - presetsButton.getItems().add(createMenuItem(preset)) - ); + .forEach(preset -> presetsButton.getItems().add(createMenuItem(preset))); } private MenuItem createMenuItem(KeyBindingPreset preset) { diff --git a/src/main/java/org/jabref/gui/preferences/keybindings/KeyBindingsTabViewModel.java b/src/main/java/org/jabref/gui/preferences/keybindings/KeyBindingsTabViewModel.java index dce2ba7fa59..6af529ed5f1 100644 --- a/src/main/java/org/jabref/gui/preferences/keybindings/KeyBindingsTabViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/keybindings/KeyBindingsTabViewModel.java @@ -29,13 +29,12 @@ public class KeyBindingsTabViewModel implements PreferenceTabViewModel { private final KeyBindingRepository keyBindingRepository; private final KeyBindingRepository initialKeyBindingRepository; private final PreferencesService preferences; - private final OptionalObjectProperty< - KeyBindingViewModel - > selectedKeyBinding = OptionalObjectProperty.empty(); - private final ObjectProperty rootKeyBinding = - new SimpleObjectProperty<>(); - private final ListProperty keyBindingPresets = - new SimpleListProperty<>(FXCollections.observableArrayList()); + private final OptionalObjectProperty selectedKeyBinding = + OptionalObjectProperty.empty(); + private final ObjectProperty rootKeyBinding = new SimpleObjectProperty<>(); + private final ListProperty keyBindingPresets = new SimpleListProperty<>( + FXCollections.observableArrayList() + ); private final DialogService dialogService; @@ -46,8 +45,7 @@ public KeyBindingsTabViewModel( DialogService dialogService, PreferencesService preferences ) { - this.keyBindingRepository = - Objects.requireNonNull(keyBindingRepository); + this.keyBindingRepository = Objects.requireNonNull(keyBindingRepository); this.initialKeyBindingRepository = new KeyBindingRepository(keyBindingRepository.getKeyBindings()); this.dialogService = Objects.requireNonNull(dialogService); @@ -75,12 +73,11 @@ public void setValues() { .getKeyBindings() .forEach((keyBinding, bind) -> { if (keyBinding.getCategory() == category) { - KeyBindingViewModel keyBindViewModel = - new KeyBindingViewModel( - keyBindingRepository, - keyBinding, - bind - ); + KeyBindingViewModel keyBindViewModel = new KeyBindingViewModel( + keyBindingRepository, + keyBinding, + bind + ); categoryItem.getChildren().add(keyBindViewModel); } }); @@ -90,8 +87,7 @@ public void setValues() { } public void setNewBindingForCurrent(KeyEvent event) { - Optional selectedKeyBindingValue = - selectedKeyBinding.getValue(); + Optional selectedKeyBindingValue = selectedKeyBinding.getValue(); if (selectedKeyBindingValue.isEmpty()) { return; } @@ -102,10 +98,7 @@ public void setNewBindingForCurrent(KeyEvent event) { } if (selectedEntry.setNewBinding(event)) { - keyBindingRepository.put( - selectedEntry.getKeyBinding(), - selectedEntry.getBinding() - ); + keyBindingRepository.put(selectedEntry.getKeyBinding(), selectedEntry.getBinding()); } } @@ -119,13 +112,8 @@ public void storeSettings() { public void resetToDefault() { String title = Localization.lang("Resetting all key bindings"); - String content = Localization.lang( - "All key bindings will be reset to their defaults." - ); - ButtonType resetButtonType = new ButtonType( - "Reset", - ButtonBar.ButtonData.OK_DONE - ); + String content = Localization.lang("All key bindings will be reset to their defaults."); + ButtonType resetButtonType = new ButtonType("Reset", ButtonBar.ButtonData.OK_DONE); dialogService .showCustomButtonDialogAndWait( Alert.AlertType.INFORMATION, @@ -160,9 +148,7 @@ public List getRestartWarnings() { return restartWarning; } - public OptionalObjectProperty< - KeyBindingViewModel - > selectedKeyBindingProperty() { + public OptionalObjectProperty selectedKeyBindingProperty() { return selectedKeyBinding; } diff --git a/src/main/java/org/jabref/gui/preferences/linkedfiles/LinkedFilesTab.java b/src/main/java/org/jabref/gui/preferences/linkedfiles/LinkedFilesTab.java index 0ef99d6166b..ddfce199ae9 100644 --- a/src/main/java/org/jabref/gui/preferences/linkedfiles/LinkedFilesTab.java +++ b/src/main/java/org/jabref/gui/preferences/linkedfiles/LinkedFilesTab.java @@ -59,8 +59,7 @@ public class LinkedFilesTab @FXML private TextField fileDirectoryPattern; - private final ControlsFxVisualizer validationVisualizer = - new ControlsFxVisualizer(); + private final ControlsFxVisualizer validationVisualizer = new ControlsFxVisualizer(); public LinkedFilesTab() { ViewLoader.view(this).root(this).load(); @@ -72,18 +71,11 @@ public String getTabName() { } public void initialize() { - this.viewModel = - new LinkedFilesTabViewModel(dialogService, preferencesService); + this.viewModel = new LinkedFilesTabViewModel(dialogService, preferencesService); - mainFileDirectory - .textProperty() - .bindBidirectional(viewModel.mainFileDirectoryProperty()); - mainFileDirectory - .disableProperty() - .bind(viewModel.useBibLocationAsPrimaryProperty()); - browseDirectory - .disableProperty() - .bind(viewModel.useBibLocationAsPrimaryProperty()); + mainFileDirectory.textProperty().bindBidirectional(viewModel.mainFileDirectoryProperty()); + mainFileDirectory.disableProperty().bind(viewModel.useBibLocationAsPrimaryProperty()); + browseDirectory.disableProperty().bind(viewModel.useBibLocationAsPrimaryProperty()); useBibLocationAsPrimary .selectedProperty() .bindBidirectional(viewModel.useBibLocationAsPrimaryProperty()); @@ -97,24 +89,12 @@ public void initialize() { autolinkFileExactBibtex .selectedProperty() .bindBidirectional(viewModel.autolinkFileExactBibtexProperty()); - autolinkUseRegex - .selectedProperty() - .bindBidirectional(viewModel.autolinkUseRegexProperty()); - autolinkRegexKey - .textProperty() - .bindBidirectional(viewModel.autolinkRegexKeyProperty()); - autolinkRegexKey - .disableProperty() - .bind(autolinkUseRegex.selectedProperty().not()); - fulltextIndex - .selectedProperty() - .bindBidirectional(viewModel.fulltextIndexProperty()); - fileNamePattern - .valueProperty() - .bindBidirectional(viewModel.fileNamePatternProperty()); - fileNamePattern - .itemsProperty() - .bind(viewModel.defaultFileNamePatternsProperty()); + autolinkUseRegex.selectedProperty().bindBidirectional(viewModel.autolinkUseRegexProperty()); + autolinkRegexKey.textProperty().bindBidirectional(viewModel.autolinkRegexKeyProperty()); + autolinkRegexKey.disableProperty().bind(autolinkUseRegex.selectedProperty().not()); + fulltextIndex.selectedProperty().bindBidirectional(viewModel.fulltextIndexProperty()); + fileNamePattern.valueProperty().bindBidirectional(viewModel.fileNamePatternProperty()); + fileNamePattern.itemsProperty().bind(viewModel.defaultFileNamePatternsProperty()); fileDirectoryPattern .textProperty() .bindBidirectional(viewModel.fileDirectoryPatternProperty()); diff --git a/src/main/java/org/jabref/gui/preferences/linkedfiles/LinkedFilesTabViewModel.java b/src/main/java/org/jabref/gui/preferences/linkedfiles/LinkedFilesTabViewModel.java index 2088032e599..ebfb6a3276d 100644 --- a/src/main/java/org/jabref/gui/preferences/linkedfiles/LinkedFilesTabViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/linkedfiles/LinkedFilesTabViewModel.java @@ -24,31 +24,19 @@ public class LinkedFilesTabViewModel implements PreferenceTabViewModel { - private final StringProperty mainFileDirectoryProperty = - new SimpleStringProperty(""); - private final BooleanProperty useMainFileDirectoryProperty = - new SimpleBooleanProperty(); - private final BooleanProperty useBibLocationAsPrimaryProperty = - new SimpleBooleanProperty(); - private final BooleanProperty autolinkFileStartsBibtexProperty = - new SimpleBooleanProperty(); - private final BooleanProperty autolinkFileExactBibtexProperty = - new SimpleBooleanProperty(); - private final BooleanProperty autolinkUseRegexProperty = - new SimpleBooleanProperty(); - private final StringProperty autolinkRegexKeyProperty = - new SimpleStringProperty(""); - private final ListProperty defaultFileNamePatternsProperty = - new SimpleListProperty<>( - FXCollections.observableArrayList( - FilePreferences.DEFAULT_FILENAME_PATTERNS - ) - ); + private final StringProperty mainFileDirectoryProperty = new SimpleStringProperty(""); + private final BooleanProperty useMainFileDirectoryProperty = new SimpleBooleanProperty(); + private final BooleanProperty useBibLocationAsPrimaryProperty = new SimpleBooleanProperty(); + private final BooleanProperty autolinkFileStartsBibtexProperty = new SimpleBooleanProperty(); + private final BooleanProperty autolinkFileExactBibtexProperty = new SimpleBooleanProperty(); + private final BooleanProperty autolinkUseRegexProperty = new SimpleBooleanProperty(); + private final StringProperty autolinkRegexKeyProperty = new SimpleStringProperty(""); + private final ListProperty defaultFileNamePatternsProperty = new SimpleListProperty<>( + FXCollections.observableArrayList(FilePreferences.DEFAULT_FILENAME_PATTERNS) + ); private final BooleanProperty fulltextIndex = new SimpleBooleanProperty(); - private final StringProperty fileNamePatternProperty = - new SimpleStringProperty(); - private final StringProperty fileDirectoryPatternProperty = - new SimpleStringProperty(); + private final StringProperty fileNamePatternProperty = new SimpleStringProperty(); + private final StringProperty fileDirectoryPatternProperty = new SimpleStringProperty(); private final Validator mainFileDirValidator; @@ -56,10 +44,7 @@ public class LinkedFilesTabViewModel implements PreferenceTabViewModel { private final FilePreferences filePreferences; private final AutoLinkPreferences autoLinkPreferences; - public LinkedFilesTabViewModel( - DialogService dialogService, - PreferencesService preferences - ) { + public LinkedFilesTabViewModel(DialogService dialogService, PreferencesService preferences) { this.dialogService = dialogService; this.filePreferences = preferences.getFilePreferences(); this.autoLinkPreferences = preferences.getAutoLinkPreferences(); @@ -92,24 +77,15 @@ public LinkedFilesTabViewModel( public void setValues() { // External files preferences / Attached files preferences / File preferences mainFileDirectoryProperty.setValue( - filePreferences - .getMainFileDirectory() - .orElse(Path.of("")) - .toString() - ); - useMainFileDirectoryProperty.setValue( - !filePreferences.shouldStoreFilesRelativeToBibFile() + filePreferences.getMainFileDirectory().orElse(Path.of("")).toString() ); + useMainFileDirectoryProperty.setValue(!filePreferences.shouldStoreFilesRelativeToBibFile()); useBibLocationAsPrimaryProperty.setValue( filePreferences.shouldStoreFilesRelativeToBibFile() ); - fulltextIndex.setValue( - filePreferences.shouldFulltextIndexLinkedFiles() - ); + fulltextIndex.setValue(filePreferences.shouldFulltextIndexLinkedFiles()); fileNamePatternProperty.setValue(filePreferences.getFileNamePattern()); - fileDirectoryPatternProperty.setValue( - filePreferences.getFileDirectoryPattern() - ); + fileDirectoryPatternProperty.setValue(filePreferences.getFileDirectoryPattern()); // Autolink preferences switch (autoLinkPreferences.getCitationKeyDependency()) { @@ -118,24 +94,16 @@ public void setValues() { case REGEX -> autolinkUseRegexProperty.setValue(true); } - autolinkRegexKeyProperty.setValue( - autoLinkPreferences.getRegularExpression() - ); + autolinkRegexKeyProperty.setValue(autoLinkPreferences.getRegularExpression()); } @Override public void storeSettings() { // External files preferences / Attached files preferences / File preferences - filePreferences.setMainFileDirectory( - mainFileDirectoryProperty.getValue() - ); - filePreferences.setStoreFilesRelativeToBibFile( - useBibLocationAsPrimaryProperty.getValue() - ); + filePreferences.setMainFileDirectory(mainFileDirectoryProperty.getValue()); + filePreferences.setStoreFilesRelativeToBibFile(useBibLocationAsPrimaryProperty.getValue()); filePreferences.setFileNamePattern(fileNamePatternProperty.getValue()); - filePreferences.setFileDirectoryPattern( - fileDirectoryPatternProperty.getValue() - ); + filePreferences.setFileDirectoryPattern(fileDirectoryPatternProperty.getValue()); filePreferences.setFulltextIndexLinkedFiles(fulltextIndex.getValue()); // Autolink preferences @@ -153,9 +121,7 @@ public void storeSettings() { ); } - autoLinkPreferences.setRegularExpression( - autolinkRegexKeyProperty.getValue() - ); + autoLinkPreferences.setRegularExpression(autolinkRegexKeyProperty.getValue()); } ValidationStatus mainFileDirValidationStatus() { @@ -165,14 +131,10 @@ ValidationStatus mainFileDirValidationStatus() { @Override public boolean validateSettings() { ValidationStatus validationStatus = mainFileDirValidationStatus(); - if ( - !validationStatus.isValid() && useMainFileDirectoryProperty().get() - ) { + if (!validationStatus.isValid() && useMainFileDirectoryProperty().get()) { validationStatus .getHighestMessage() - .ifPresent(message -> - dialogService.showErrorDialogAndWait(message.getMessage()) - ); + .ifPresent(message -> dialogService.showErrorDialogAndWait(message.getMessage())); return false; } return true; @@ -181,9 +143,7 @@ public boolean validateSettings() { public void mainFileDirBrowse() { DirectoryDialogConfiguration dirDialogConfiguration = new DirectoryDialogConfiguration.Builder() - .withInitialDirectory( - Path.of(mainFileDirectoryProperty.getValue()) - ) + .withInitialDirectory(Path.of(mainFileDirectoryProperty.getValue())) .build(); dialogService .showDirectorySelectionDialog(dirDialogConfiguration) diff --git a/src/main/java/org/jabref/gui/preferences/nameformatter/NameFormatterTab.java b/src/main/java/org/jabref/gui/preferences/nameformatter/NameFormatterTab.java index d741d0e50ae..3784e15952c 100644 --- a/src/main/java/org/jabref/gui/preferences/nameformatter/NameFormatterTab.java +++ b/src/main/java/org/jabref/gui/preferences/nameformatter/NameFormatterTab.java @@ -56,63 +56,36 @@ public String getTabName() { public void initialize() { this.viewModel = - new NameFormatterTabViewModel( - preferencesService.getNameFormatterPreferences() - ); + new NameFormatterTabViewModel(preferencesService.getNameFormatterPreferences()); formatterNameColumn.setSortable(true); formatterNameColumn.setReorderable(false); - formatterNameColumn.setCellValueFactory(cellData -> - cellData.getValue().nameProperty() - ); + formatterNameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty()); formatterNameColumn.setCellFactory(TextFieldTableCell.forTableColumn()); formatterNameColumn.setEditable(true); formatterNameColumn.setOnEditCommit( - ( - TableColumn.CellEditEvent< - NameFormatterItemModel, - String - > event - ) -> + (TableColumn.CellEditEvent event) -> event.getRowValue().setName(event.getNewValue()) ); formatterStringColumn.setSortable(true); formatterStringColumn.setReorderable(false); - formatterStringColumn.setCellValueFactory(cellData -> - cellData.getValue().formatProperty() - ); - formatterStringColumn.setCellFactory( - TextFieldTableCell.forTableColumn() - ); + formatterStringColumn.setCellValueFactory(cellData -> cellData.getValue().formatProperty()); + formatterStringColumn.setCellFactory(TextFieldTableCell.forTableColumn()); formatterStringColumn.setEditable(true); formatterStringColumn.setOnEditCommit( - ( - TableColumn.CellEditEvent< - NameFormatterItemModel, - String - > event - ) -> + (TableColumn.CellEditEvent event) -> event.getRowValue().setFormat(event.getNewValue()) ); actionsColumn.setSortable(false); actionsColumn.setReorderable(false); - actionsColumn.setCellValueFactory(cellData -> - cellData.getValue().nameProperty() - ); + actionsColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty()); new ValueTableCellFactory() - .withGraphic(name -> - IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode() - ) - .withTooltip(name -> - Localization.lang("Remove formatter '%0'", name) - ) + .withGraphic(name -> IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode()) + .withTooltip(name -> Localization.lang("Remove formatter '%0'", name)) .withOnMouseClickedEvent(item -> - evt -> - viewModel.removeFormatter( - formatterList.getFocusModel().getFocusedItem() - ) + evt -> viewModel.removeFormatter(formatterList.getFocusModel().getFocusedItem()) ) .install(actionsColumn); @@ -120,22 +93,16 @@ public void initialize() { KeyEvent.KEY_PRESSED, event -> { if (event.getCode() == KeyCode.DELETE) { - viewModel.removeFormatter( - formatterList.getSelectionModel().getSelectedItem() - ); + viewModel.removeFormatter(formatterList.getSelectionModel().getSelectedItem()); event.consume(); } } ); formatterList.setEditable(true); - formatterList - .itemsProperty() - .bindBidirectional(viewModel.formatterListProperty()); + formatterList.itemsProperty().bindBidirectional(viewModel.formatterListProperty()); - addFormatterName - .textProperty() - .bindBidirectional(viewModel.addFormatterNameProperty()); + addFormatterName.textProperty().bindBidirectional(viewModel.addFormatterNameProperty()); addFormatterName.addEventFilter( KeyEvent.KEY_PRESSED, event -> { @@ -147,9 +114,7 @@ public void initialize() { } ); - addFormatterString - .textProperty() - .bindBidirectional(viewModel.addFormatterStringProperty()); + addFormatterString.textProperty().bindBidirectional(viewModel.addFormatterStringProperty()); addFormatterString.addEventFilter( KeyEvent.KEY_PRESSED, event -> { diff --git a/src/main/java/org/jabref/gui/preferences/nameformatter/NameFormatterTabViewModel.java b/src/main/java/org/jabref/gui/preferences/nameformatter/NameFormatterTabViewModel.java index 53b5bfb58fa..4cd8b83c119 100644 --- a/src/main/java/org/jabref/gui/preferences/nameformatter/NameFormatterTabViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/nameformatter/NameFormatterTabViewModel.java @@ -15,10 +15,8 @@ public class NameFormatterTabViewModel implements PreferenceTabViewModel { private final ListProperty formatterListProperty = new SimpleListProperty<>(FXCollections.observableArrayList()); - private final StringProperty addFormatterNameProperty = - new SimpleStringProperty(); - private final StringProperty addFormatterStringProperty = - new SimpleStringProperty(); + private final StringProperty addFormatterNameProperty = new SimpleStringProperty(); + private final StringProperty addFormatterStringProperty = new SimpleStringProperty(); private final NameFormatterPreferences nameFormatterPreferences; @@ -34,22 +32,16 @@ public void setValues() { for (int i = 0; i < names.size(); i++) { if (i < formats.size()) { - formatterListProperty.add( - new NameFormatterItemModel(names.get(i), formats.get(i)) - ); + formatterListProperty.add(new NameFormatterItemModel(names.get(i), formats.get(i))); } else { - formatterListProperty.add( - new NameFormatterItemModel(names.get(i)) - ); + formatterListProperty.add(new NameFormatterItemModel(names.get(i))); } } } @Override public void storeSettings() { - formatterListProperty.removeIf(formatter -> - formatter.getName().isEmpty() - ); + formatterListProperty.removeIf(formatter -> formatter.getName().isEmpty()); List names = new ArrayList<>(formatterListProperty.size()); List formats = new ArrayList<>(formatterListProperty.size()); diff --git a/src/main/java/org/jabref/gui/preferences/network/CustomCertificateViewModel.java b/src/main/java/org/jabref/gui/preferences/network/CustomCertificateViewModel.java index 90419bfea7f..23db69515f2 100644 --- a/src/main/java/org/jabref/gui/preferences/network/CustomCertificateViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/network/CustomCertificateViewModel.java @@ -13,19 +13,13 @@ public class CustomCertificateViewModel extends AbstractViewModel { - private final StringProperty serialNumberProperty = - new SimpleStringProperty(""); + private final StringProperty serialNumberProperty = new SimpleStringProperty(""); private final StringProperty issuerProperty = new SimpleStringProperty(""); - private final ObjectProperty validFromProperty = - new SimpleObjectProperty<>(); - private final ObjectProperty validToProperty = - new SimpleObjectProperty<>(); - private final StringProperty signatureAlgorithmProperty = - new SimpleStringProperty(""); + private final ObjectProperty validFromProperty = new SimpleObjectProperty<>(); + private final ObjectProperty validToProperty = new SimpleObjectProperty<>(); + private final StringProperty signatureAlgorithmProperty = new SimpleStringProperty(""); private final StringProperty versionProperty = new SimpleStringProperty(""); - private final StringProperty thumbprintProperty = new SimpleStringProperty( - "" - ); + private final StringProperty thumbprintProperty = new SimpleStringProperty(""); private final StringProperty pathProperty = new SimpleStringProperty(""); public CustomCertificateViewModel( @@ -91,9 +85,7 @@ public StringProperty pathPropertyProperty() { } public Optional getPath() { - if ( - pathProperty.getValue() == null || pathProperty.getValue().isEmpty() - ) { + if (pathProperty.getValue() == null || pathProperty.getValue().isEmpty()) { return Optional.empty(); } else { return Optional.of(pathProperty.getValue()); @@ -117,9 +109,7 @@ public String getSignatureAlgorithm() { return signatureAlgorithmProperty.getValue(); } - public static CustomCertificateViewModel fromSSLCertificate( - SSLCertificate sslCertificate - ) { + public static CustomCertificateViewModel fromSSLCertificate(SSLCertificate sslCertificate) { return new CustomCertificateViewModel( sslCertificate.getSHA256Thumbprint(), sslCertificate.getSerialNumber(), diff --git a/src/main/java/org/jabref/gui/preferences/network/NetworkTab.java b/src/main/java/org/jabref/gui/preferences/network/NetworkTab.java index fc5283dca24..2933364a5b2 100644 --- a/src/main/java/org/jabref/gui/preferences/network/NetworkTab.java +++ b/src/main/java/org/jabref/gui/preferences/network/NetworkTab.java @@ -82,10 +82,7 @@ public class NetworkTab private TableColumn certSerialNumber; @FXML - private TableColumn< - CustomCertificateViewModel, - String - > certSignatureAlgorithm; + private TableColumn certSignatureAlgorithm; @FXML private TableColumn certValidFrom; @@ -102,8 +99,7 @@ public class NetworkTab private String proxyPasswordText = ""; private int proxyPasswordCaretPosition = 0; - private final ControlsFxVisualizer validationVisualizer = - new ControlsFxVisualizer(); + private final ControlsFxVisualizer validationVisualizer = new ControlsFxVisualizer(); public NetworkTab() { ViewLoader.view(this).root(this).load(); @@ -115,76 +111,43 @@ public String getTabName() { } public void initialize() { - this.viewModel = - new NetworkTabViewModel(dialogService, preferencesService); + this.viewModel = new NetworkTabViewModel(dialogService, preferencesService); - versionCheck - .selectedProperty() - .bindBidirectional(viewModel.versionCheckProperty()); + versionCheck.selectedProperty().bindBidirectional(viewModel.versionCheckProperty()); - proxyUse - .selectedProperty() - .bindBidirectional(viewModel.proxyUseProperty()); - proxyHostnameLabel - .disableProperty() - .bind(proxyUse.selectedProperty().not()); - proxyHostname - .textProperty() - .bindBidirectional(viewModel.proxyHostnameProperty()); + proxyUse.selectedProperty().bindBidirectional(viewModel.proxyUseProperty()); + proxyHostnameLabel.disableProperty().bind(proxyUse.selectedProperty().not()); + proxyHostname.textProperty().bindBidirectional(viewModel.proxyHostnameProperty()); proxyHostname.disableProperty().bind(proxyUse.selectedProperty().not()); - proxyPortLabel - .disableProperty() - .bind(proxyUse.selectedProperty().not()); - proxyPort - .textProperty() - .bindBidirectional(viewModel.proxyPortProperty()); + proxyPortLabel.disableProperty().bind(proxyUse.selectedProperty().not()); + proxyPort.textProperty().bindBidirectional(viewModel.proxyPortProperty()); proxyPort.disableProperty().bind(proxyUse.selectedProperty().not()); proxyUseAuthentication .selectedProperty() .bindBidirectional(viewModel.proxyUseAuthenticationProperty()); - proxyUseAuthentication - .disableProperty() - .bind(proxyUse.selectedProperty().not()); + proxyUseAuthentication.disableProperty().bind(proxyUse.selectedProperty().not()); BooleanBinding proxyCustomAndAuthentication = proxyUse .selectedProperty() .and(proxyUseAuthentication.selectedProperty()); - proxyUsernameLabel - .disableProperty() - .bind(proxyCustomAndAuthentication.not()); - proxyUsername - .textProperty() - .bindBidirectional(viewModel.proxyUsernameProperty()); - proxyUsername - .disableProperty() - .bind(proxyCustomAndAuthentication.not()); - proxyPasswordLabel - .disableProperty() - .bind(proxyCustomAndAuthentication.not()); - proxyPassword - .textProperty() - .bindBidirectional(viewModel.proxyPasswordProperty()); - proxyPassword - .disableProperty() - .bind(proxyCustomAndAuthentication.not()); + proxyUsernameLabel.disableProperty().bind(proxyCustomAndAuthentication.not()); + proxyUsername.textProperty().bindBidirectional(viewModel.proxyUsernameProperty()); + proxyUsername.disableProperty().bind(proxyCustomAndAuthentication.not()); + proxyPasswordLabel.disableProperty().bind(proxyCustomAndAuthentication.not()); + proxyPassword.textProperty().bindBidirectional(viewModel.proxyPasswordProperty()); + proxyPassword.disableProperty().bind(proxyCustomAndAuthentication.not()); proxyPersistPassword .selectedProperty() .bindBidirectional(viewModel.proxyPersistPasswordProperty()); proxyPersistPassword .disableProperty() - .bind( - proxyCustomAndAuthentication - .and(viewModel.passwordPersistAvailable()) - .not() - ); + .bind(proxyCustomAndAuthentication.and(viewModel.passwordPersistAvailable()).not()); EasyBind.subscribe( viewModel.passwordPersistAvailable(), available -> { if (!available) { persistentTooltipWrapper.setTooltip( - new Tooltip( - Localization.lang("Credential store not available.") - ) + new Tooltip(Localization.lang("Credential store not available.")) ); } else { persistentTooltipWrapper.setTooltip(null); @@ -192,21 +155,12 @@ public void initialize() { } ); - proxyPassword.setRight( - IconTheme.JabRefIcons.PASSWORD_REVEALED.getGraphicNode() - ); - proxyPassword - .getRight() - .addEventFilter( - MouseEvent.MOUSE_PRESSED, - this::proxyPasswordReveal - ); + proxyPassword.setRight(IconTheme.JabRefIcons.PASSWORD_REVEALED.getGraphicNode()); proxyPassword .getRight() - .addEventFilter(MouseEvent.MOUSE_RELEASED, this::proxyPasswordMask); - proxyPassword - .getRight() - .addEventFilter(MouseEvent.MOUSE_EXITED, this::proxyPasswordMask); + .addEventFilter(MouseEvent.MOUSE_PRESSED, this::proxyPasswordReveal); + proxyPassword.getRight().addEventFilter(MouseEvent.MOUSE_RELEASED, this::proxyPasswordMask); + proxyPassword.getRight().addEventFilter(MouseEvent.MOUSE_EXITED, this::proxyPasswordMask); validationVisualizer.setDecoration(new IconValidationDecorator()); Platform.runLater(() -> { @@ -228,11 +182,8 @@ public void initialize() { ); }); - certSerialNumber.setCellValueFactory(data -> - data.getValue().serialNumberProperty() - ); - certIssuer.setCellValueFactory(data -> data.getValue().issuerProperty() - ); + certSerialNumber.setCellValueFactory(data -> data.getValue().serialNumberProperty()); + certIssuer.setCellValueFactory(data -> data.getValue().issuerProperty()); certSignatureAlgorithm.setCellValueFactory(data -> data.getValue().signatureAlgorithmProperty() ); @@ -247,27 +198,19 @@ public void initialize() { EasyBind.map(data.getValue().validToProperty(), this::formatDate) ); - customCertificatesTable - .itemsProperty() - .set(viewModel.customCertificateListProperty()); + customCertificatesTable.itemsProperty().set(viewModel.customCertificateListProperty()); actionsColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getThumbprint()) ); new ValueTableCellFactory() - .withGraphic(name -> - IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode() - ) - .withTooltip(name -> - Localization.lang("Remove formatter '%0'", name) - ) + .withGraphic(name -> IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode()) + .withTooltip(name -> Localization.lang("Remove formatter '%0'", name)) .withOnMouseClickedEvent(thumbprint -> evt -> viewModel .customCertificateListProperty() - .removeIf(cert -> - cert.getThumbprint().equals(thumbprint) - ) + .removeIf(cert -> cert.getThumbprint().equals(thumbprint)) ) .install(actionsColumn); } diff --git a/src/main/java/org/jabref/gui/preferences/network/NetworkTabViewModel.java b/src/main/java/org/jabref/gui/preferences/network/NetworkTabViewModel.java index 847530a93de..9435988a531 100644 --- a/src/main/java/org/jabref/gui/preferences/network/NetworkTabViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/network/NetworkTabViewModel.java @@ -39,30 +39,17 @@ public class NetworkTabViewModel implements PreferenceTabViewModel { - private final BooleanProperty versionCheckProperty = - new SimpleBooleanProperty(); - private final BooleanProperty proxyUseProperty = - new SimpleBooleanProperty(); - private final StringProperty proxyHostnameProperty = - new SimpleStringProperty(""); - private final StringProperty proxyPortProperty = new SimpleStringProperty( - "" - ); - private final BooleanProperty proxyUseAuthenticationProperty = - new SimpleBooleanProperty(); - private final StringProperty proxyUsernameProperty = - new SimpleStringProperty(""); - private final StringProperty proxyPasswordProperty = - new SimpleStringProperty(""); - private final BooleanProperty proxyPersistPasswordProperty = - new SimpleBooleanProperty(); - private final BooleanProperty passwordPersistAvailable = - new SimpleBooleanProperty(); - private final ListProperty< - CustomCertificateViewModel - > customCertificateListProperty = new SimpleListProperty<>( - FXCollections.observableArrayList() - ); + private final BooleanProperty versionCheckProperty = new SimpleBooleanProperty(); + private final BooleanProperty proxyUseProperty = new SimpleBooleanProperty(); + private final StringProperty proxyHostnameProperty = new SimpleStringProperty(""); + private final StringProperty proxyPortProperty = new SimpleStringProperty(""); + private final BooleanProperty proxyUseAuthenticationProperty = new SimpleBooleanProperty(); + private final StringProperty proxyUsernameProperty = new SimpleStringProperty(""); + private final StringProperty proxyPasswordProperty = new SimpleStringProperty(""); + private final BooleanProperty proxyPersistPasswordProperty = new SimpleBooleanProperty(); + private final BooleanProperty passwordPersistAvailable = new SimpleBooleanProperty(); + private final ListProperty customCertificateListProperty = + new SimpleListProperty<>(FXCollections.observableArrayList()); private final Validator proxyHostnameValidator; private final Validator proxyPortValidator; @@ -78,14 +65,9 @@ public class NetworkTabViewModel implements PreferenceTabViewModel { private final TrustStoreManager trustStoreManager; - private final AtomicBoolean sslCertificatesChanged = new AtomicBoolean( - false - ); + private final AtomicBoolean sslCertificatesChanged = new AtomicBoolean(false); - public NetworkTabViewModel( - DialogService dialogService, - PreferencesService preferences - ) { + public NetworkTabViewModel(DialogService dialogService, PreferencesService preferences) { this.dialogService = dialogService; this.preferences = preferences; this.proxyPreferences = preferences.getProxyPreferences(); @@ -159,16 +141,12 @@ public NetworkTabViewModel( ); this.trustStoreManager = - new TrustStoreManager( - Path.of(preferences.getSSLPreferences().getTruststorePath()) - ); + new TrustStoreManager(Path.of(preferences.getSSLPreferences().getTruststorePath())); } @Override public void setValues() { - versionCheckProperty.setValue( - internalPreferences.isVersionCheckEnabled() - ); + versionCheckProperty.setValue(internalPreferences.isVersionCheckEnabled()); setProxyValues(); setSSLValues(); @@ -178,14 +156,10 @@ private void setProxyValues() { proxyUseProperty.setValue(proxyPreferences.shouldUseProxy()); proxyHostnameProperty.setValue(proxyPreferences.getHostname()); proxyPortProperty.setValue(proxyPreferences.getPort()); - proxyUseAuthenticationProperty.setValue( - proxyPreferences.shouldUseAuthentication() - ); + proxyUseAuthenticationProperty.setValue(proxyPreferences.shouldUseAuthentication()); proxyUsernameProperty.setValue(proxyPreferences.getUsername()); proxyPasswordProperty.setValue(proxyPreferences.getPassword()); - proxyPersistPasswordProperty.setValue( - proxyPreferences.shouldPersistPassword() - ); + proxyPersistPasswordProperty.setValue(proxyPreferences.shouldPersistPassword()); passwordPersistAvailable.setValue(OS.isKeyringAvailable()); } @@ -203,23 +177,17 @@ private void setSSLValues() { sslCertificatesChanged.set(true); while (c.next()) { if (c.wasAdded()) { - CustomCertificateViewModel certificate = c - .getAddedSubList() - .get(0); + CustomCertificateViewModel certificate = c.getAddedSubList().get(0); certificate .getPath() .ifPresent(path -> trustStoreManager.addCertificate( - formatCustomAlias( - certificate.getThumbprint() - ), + formatCustomAlias(certificate.getThumbprint()), Path.of(path) ) ); } else if (c.wasRemoved()) { - CustomCertificateViewModel certificate = c - .getRemoved() - .get(0); + CustomCertificateViewModel certificate = c.getRemoved().get(0); trustStoreManager.deleteCertificate( formatCustomAlias(certificate.getThumbprint()) ); @@ -234,13 +202,9 @@ public void storeSettings() { proxyPreferences.setUseProxy(proxyUseProperty.getValue()); proxyPreferences.setHostname(proxyHostnameProperty.getValue().trim()); proxyPreferences.setPort(proxyPortProperty.getValue().trim()); - proxyPreferences.setUseAuthentication( - proxyUseAuthenticationProperty.getValue() - ); + proxyPreferences.setUseAuthentication(proxyUseAuthenticationProperty.getValue()); proxyPreferences.setUsername(proxyUsernameProperty.getValue().trim()); - proxyPreferences.setPersistPassword( - proxyPersistPasswordProperty.getValue() - ); // Set before the password to actually persist + proxyPreferences.setPersistPassword(proxyPersistPasswordProperty.getValue()); // Set before the password to actually persist proxyPreferences.setPassword(proxyPasswordProperty.getValue()); ProxyRegisterer.register(proxyPreferences); @@ -289,9 +253,7 @@ public boolean validateSettings() { if (!validationStatus.isValid()) { validationStatus .getHighestMessage() - .ifPresent(message -> - dialogService.showErrorDialogAndWait(message.getMessage()) - ); + .ifPresent(message -> dialogService.showErrorDialogAndWait(message.getMessage())); return false; } return true; @@ -301,12 +263,8 @@ public boolean validateSettings() { * Check the connection by using the given url. Used for validating the http proxy. The checking result will be appear when request finished. The checking result could be either success or fail, if fail, the cause will be displayed. */ public void checkConnection() { - final String connectionSuccessText = Localization.lang( - "Connection successful!" - ); - final String connectionFailedText = Localization.lang( - "Connection failed!" - ); + final String connectionSuccessText = Localization.lang("Connection successful!"); + final String connectionFailedText = Localization.lang("Connection failed!"); final String dialogTitle = Localization.lang("Check Proxy Setting"); final String testUrl = "http://jabref.org"; @@ -327,23 +285,14 @@ public void checkConnection() { try { urlDownload = new URLDownload(testUrl); if (urlDownload.canBeReached()) { - dialogService.showInformationDialogAndWait( - dialogTitle, - connectionSuccessText - ); + dialogService.showInformationDialogAndWait(dialogTitle, connectionSuccessText); } else { - dialogService.showErrorDialogAndWait( - dialogTitle, - connectionFailedText - ); + dialogService.showErrorDialogAndWait(dialogTitle, connectionFailedText); } } catch (MalformedURLException e) { // Why would that happen? Because one of developers inserted a failing url in testUrl... } catch (UnirestException e) { - dialogService.showErrorDialogAndWait( - dialogTitle, - connectionFailedText - ); + dialogService.showErrorDialogAndWait(dialogTitle, connectionFailedText); } ProxyRegisterer.register(backupProxyPreferences); @@ -394,30 +343,22 @@ public ReadOnlyBooleanProperty passwordPersistAvailable() { return passwordPersistAvailable; } - public ListProperty< - CustomCertificateViewModel - > customCertificateListProperty() { + public ListProperty customCertificateListProperty() { return customCertificateListProperty; } public void addCertificateFile() { - FileDialogConfiguration fileDialogConfiguration = - new FileDialogConfiguration.Builder() - .addExtensionFilter( - new FileChooser.ExtensionFilter( - Localization.lang("SSL certificate file"), - "*.crt", - "*.cer" - ) - ) - .withDefaultExtension( + FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() + .addExtensionFilter( + new FileChooser.ExtensionFilter( Localization.lang("SSL certificate file"), - StandardFileType.CER - ) - .withInitialDirectory( - preferences.getFilePreferences().getWorkingDirectory() + "*.crt", + "*.cer" ) - .build(); + ) + .withDefaultExtension(Localization.lang("SSL certificate file"), StandardFileType.CER) + .withInitialDirectory(preferences.getFilePreferences().getWorkingDirectory()) + .build(); dialogService .showFileOpenDialog(fileDialogConfiguration) @@ -427,24 +368,18 @@ public void addCertificateFile() { .ifPresent(sslCertificate -> { if ( !trustStoreManager.certificateExists( - formatCustomAlias( - sslCertificate.getSHA256Thumbprint() - ) + formatCustomAlias(sslCertificate.getSHA256Thumbprint()) ) ) { customCertificateListProperty.add( CustomCertificateViewModel .fromSSLCertificate(sslCertificate) - .setPath( - certPath.toAbsolutePath().toString() - ) + .setPath(certPath.toAbsolutePath().toString()) ); } else { dialogService.showWarningDialogAndWait( Localization.lang("Duplicate Certificates"), - Localization.lang( - "You already added this certificate" - ) + Localization.lang("You already added this certificate") ); } }) diff --git a/src/main/java/org/jabref/gui/preferences/preview/PreviewTab.java b/src/main/java/org/jabref/gui/preferences/preview/PreviewTab.java index c1cd365ea7b..76402d53b0d 100644 --- a/src/main/java/org/jabref/gui/preferences/preview/PreviewTab.java +++ b/src/main/java/org/jabref/gui/preferences/preview/PreviewTab.java @@ -93,8 +93,7 @@ public class PreviewTab private long lastKeyPressTime; private String listSearchTerm; - private final ControlsFxVisualizer validationVisualizer = - new ControlsFxVisualizer(); + private final ControlsFxVisualizer validationVisualizer = new ControlsFxVisualizer(); public PreviewTab() { ViewLoader.view(this).root(this).load(); @@ -137,9 +136,7 @@ public void initialize() { ); lastKeyPressTime = System.currentTimeMillis(); - showAsTabCheckBox - .selectedProperty() - .bindBidirectional(viewModel.showAsExtraTabProperty()); + showAsTabCheckBox.selectedProperty().bindBidirectional(viewModel.showAsExtraTabProperty()); searchBox.setPromptText(Localization.lang("Search") + "..."); searchBox.setLeft(IconTheme.JabRefIcons.SEARCH.getGraphicNode()); @@ -148,14 +145,8 @@ public void initialize() { contextMenu .getItems() .addAll( - factory.createMenuItem( - StandardActions.CUT, - new EditAction(StandardActions.CUT) - ), - factory.createMenuItem( - StandardActions.COPY, - new EditAction(StandardActions.COPY) - ), + factory.createMenuItem(StandardActions.CUT, new EditAction(StandardActions.CUT)), + factory.createMenuItem(StandardActions.COPY, new EditAction(StandardActions.COPY)), factory.createMenuItem( StandardActions.PASTE, new EditAction(StandardActions.PASTE) @@ -169,9 +160,7 @@ public void initialize() { contextMenu.getStyleClass().add("context-menu"); availableListView.setItems(viewModel.getFilteredAvailableLayouts()); - viewModel - .availableSelectionModelProperty() - .setValue(availableListView.getSelectionModel()); + viewModel.availableSelectionModelProperty().setValue(availableListView.getSelectionModel()); new ViewModelListCellFactory() .withText(PreviewLayout::getDisplayName) .install(availableListView); @@ -180,50 +169,33 @@ public void initialize() { availableListView.setOnDragDropped(event -> dragDropped(viewModel.availableListProperty(), event) ); - availableListView.setOnKeyTyped(event -> - jumpToSearchKey(availableListView, event) - ); + availableListView.setOnKeyTyped(event -> jumpToSearchKey(availableListView, event)); availableListView.setOnMouseClicked(this::mouseClickedAvailable); - availableListView - .getSelectionModel() - .setSelectionMode(SelectionMode.MULTIPLE); + availableListView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); availableListView .selectionModelProperty() .getValue() .selectedItemProperty() - .addListener((observable, oldValue, newValue) -> - viewModel.setPreviewLayout(newValue) - ); + .addListener((observable, oldValue, newValue) -> viewModel.setPreviewLayout(newValue)); - chosenListView - .itemsProperty() - .bindBidirectional(viewModel.chosenListProperty()); - viewModel - .chosenSelectionModelProperty() - .setValue(chosenListView.getSelectionModel()); + chosenListView.itemsProperty().bindBidirectional(viewModel.chosenListProperty()); + viewModel.chosenSelectionModelProperty().setValue(chosenListView.getSelectionModel()); new ViewModelListCellFactory() .withText(PreviewLayout::getDisplayName) .setOnDragDropped(this::dragDroppedInChosenCell) .install(chosenListView); chosenListView.setOnDragOver(this::dragOver); chosenListView.setOnDragDetected(this::dragDetectedInChosen); - chosenListView.setOnDragDropped(event -> - dragDropped(viewModel.chosenListProperty(), event) - ); - chosenListView.setOnKeyTyped(event -> - jumpToSearchKey(chosenListView, event) + chosenListView.setOnDragDropped(event -> dragDropped(viewModel.chosenListProperty(), event) ); + chosenListView.setOnKeyTyped(event -> jumpToSearchKey(chosenListView, event)); chosenListView.setOnMouseClicked(this::mouseClickedChosen); - chosenListView - .getSelectionModel() - .setSelectionMode(SelectionMode.MULTIPLE); + chosenListView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); chosenListView .selectionModelProperty() .getValue() .selectedItemProperty() - .addListener((observable, oldValue, newValue) -> - viewModel.setPreviewLayout(newValue) - ); + .addListener((observable, oldValue, newValue) -> viewModel.setPreviewLayout(newValue)); toRightButton .disableProperty() @@ -237,29 +209,17 @@ public void initialize() { toLeftButton .disableProperty() .bind( - viewModel - .chosenSelectionModelProperty() - .getValue() - .selectedItemProperty() - .isNull() + viewModel.chosenSelectionModelProperty().getValue().selectedItemProperty().isNull() ); sortUpButton .disableProperty() .bind( - viewModel - .chosenSelectionModelProperty() - .getValue() - .selectedItemProperty() - .isNull() + viewModel.chosenSelectionModelProperty().getValue().selectedItemProperty().isNull() ); sortDownButton .disableProperty() .bind( - viewModel - .chosenSelectionModelProperty() - .getValue() - .selectedItemProperty() - .isNull() + viewModel.chosenSelectionModelProperty().getValue().selectedItemProperty().isNull() ); PreviewViewer previewViewer = new PreviewViewer( @@ -271,10 +231,7 @@ public void initialize() { taskExecutor ); previewViewer.setEntry(TestEntry.getTestEntry()); - EasyBind.subscribe( - viewModel.selectedLayoutProperty(), - previewViewer::setLayout - ); + EasyBind.subscribe(viewModel.selectedLayoutProperty(), previewViewer::setLayout); previewViewer .visibleProperty() .bind( @@ -326,10 +283,7 @@ public void initialize() { editArea .textProperty() .addListener((obs, oldValue, newValue) -> - editArea.setStyleSpans( - 0, - viewModel.computeHighlighting(newValue) - ) + editArea.setStyleSpans(0, viewModel.computeHighlighting(newValue)) ); editArea @@ -346,12 +300,8 @@ public void initialize() { viewModel.setAvailableFilter(searchTerm) ); - readOnlyLabel - .visibleProperty() - .bind(viewModel.selectedIsEditableProperty().not()); - resetDefaultButton - .disableProperty() - .bind(viewModel.selectedIsEditableProperty().not()); + readOnlyLabel.visibleProperty().bind(viewModel.selectedIsEditableProperty().not()); + resetDefaultButton.disableProperty().bind(viewModel.selectedIsEditableProperty().not()); contextMenu .getItems() .get(0) @@ -362,9 +312,7 @@ public void initialize() { .get(2) .disableProperty() .bind(viewModel.selectedIsEditableProperty().not()); - editArea - .editableProperty() - .bind(viewModel.selectedIsEditableProperty()); + editArea.editableProperty().bind(viewModel.selectedIsEditableProperty()); validationVisualizer.setDecoration(new IconValidationDecorator()); Platform.runLater(() -> @@ -383,10 +331,7 @@ public void initialize() { * @param keypressed The pressed character */ - private void jumpToSearchKey( - ListView list, - KeyEvent keypressed - ) { + private void jumpToSearchKey(ListView list, KeyEvent keypressed) { if (keypressed.getCharacter() == null) { return; } @@ -402,9 +347,7 @@ private void jumpToSearchKey( list .getItems() .stream() - .filter(item -> - item.getDisplayName().toLowerCase().startsWith(listSearchTerm) - ) + .filter(item -> item.getDisplayName().toLowerCase().startsWith(listSearchTerm)) .findFirst() .ifPresent(list::scrollTo); } @@ -415,10 +358,7 @@ private void dragOver(DragEvent event) { private void dragDetectedInAvailable(MouseEvent event) { List selectedLayouts = new ArrayList<>( - viewModel - .availableSelectionModelProperty() - .getValue() - .getSelectedItems() + viewModel.availableSelectionModelProperty().getValue().getSelectedItems() ); if (!selectedLayouts.isEmpty()) { Dragboard dragboard = startDragAndDrop(TransferMode.MOVE); @@ -434,10 +374,7 @@ private void dragDetectedInAvailable(MouseEvent event) { private void dragDetectedInChosen(MouseEvent event) { List selectedLayouts = new ArrayList<>( - viewModel - .chosenSelectionModelProperty() - .getValue() - .getSelectedItems() + viewModel.chosenSelectionModelProperty().getValue().getSelectedItems() ); if (!selectedLayouts.isEmpty()) { Dragboard dragboard = startDragAndDrop(TransferMode.MOVE); @@ -451,26 +388,14 @@ private void dragDetectedInChosen(MouseEvent event) { event.consume(); } - private void dragDropped( - ListProperty targetList, - DragEvent event - ) { - boolean success = viewModel.dragDropped( - targetList, - event.getDragboard() - ); + private void dragDropped(ListProperty targetList, DragEvent event) { + boolean success = viewModel.dragDropped(targetList, event.getDragboard()); event.setDropCompleted(success); event.consume(); } - private void dragDroppedInChosenCell( - PreviewLayout targetLayout, - DragEvent event - ) { - boolean success = viewModel.dragDroppedInChosenCell( - targetLayout, - event.getDragboard() - ); + private void dragDroppedInChosenCell(PreviewLayout targetLayout, DragEvent event) { + boolean success = viewModel.dragDroppedInChosenCell(targetLayout, event.getDragboard()); event.setDropCompleted(success); event.consume(); } diff --git a/src/main/java/org/jabref/gui/preferences/preview/PreviewTabViewModel.java b/src/main/java/org/jabref/gui/preferences/preview/PreviewTabViewModel.java index 8a0984efd8a..4a29705642a 100644 --- a/src/main/java/org/jabref/gui/preferences/preview/PreviewTabViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/preview/PreviewTabViewModel.java @@ -56,37 +56,30 @@ * */ public class PreviewTabViewModel implements PreferenceTabViewModel { - private static final Logger LOGGER = LoggerFactory.getLogger( - PreviewTabViewModel.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(PreviewTabViewModel.class); - private final BooleanProperty showAsExtraTabProperty = - new SimpleBooleanProperty(false); + private final BooleanProperty showAsExtraTabProperty = new SimpleBooleanProperty(false); - private final ListProperty availableListProperty = - new SimpleListProperty<>(FXCollections.observableArrayList()); + private final ListProperty availableListProperty = new SimpleListProperty<>( + FXCollections.observableArrayList() + ); private final ObjectProperty< MultipleSelectionModel - > availableSelectionModelProperty = new SimpleObjectProperty<>( - new NoSelectionModel<>() + > availableSelectionModelProperty = new SimpleObjectProperty<>(new NoSelectionModel<>()); + private final FilteredList filteredAvailableLayouts = new FilteredList<>( + this.availableListProperty() + ); + private final ListProperty chosenListProperty = new SimpleListProperty<>( + FXCollections.observableArrayList() ); - private final FilteredList filteredAvailableLayouts = - new FilteredList<>(this.availableListProperty()); - private final ListProperty chosenListProperty = - new SimpleListProperty<>(FXCollections.observableArrayList()); private final ObjectProperty< MultipleSelectionModel - > chosenSelectionModelProperty = new SimpleObjectProperty<>( - new NoSelectionModel<>() - ); + > chosenSelectionModelProperty = new SimpleObjectProperty<>(new NoSelectionModel<>()); - private final BooleanProperty selectedIsEditableProperty = - new SimpleBooleanProperty(false); + private final BooleanProperty selectedIsEditableProperty = new SimpleBooleanProperty(false); private final ObjectProperty selectedLayoutProperty = new SimpleObjectProperty<>(); - private final StringProperty sourceTextProperty = new SimpleStringProperty( - "" - ); + private final StringProperty sourceTextProperty = new SimpleStringProperty(""); private final DialogService dialogService; private final PreviewPreferences previewPreferences; @@ -96,9 +89,7 @@ public class PreviewTabViewModel implements PreferenceTabViewModel { private final CustomLocalDragboard localDragboard; private ListProperty dragSourceList = null; - private ObjectProperty< - MultipleSelectionModel - > dragSourceSelectionModel = null; + private ObjectProperty> dragSourceSelectionModel = null; public PreviewTabViewModel( DialogService dialogService, @@ -112,10 +103,7 @@ public PreviewTabViewModel( this.previewPreferences = previewPreferences; sourceTextProperty.addListener((observable, oldValue, newValue) -> { - if ( - selectedLayoutProperty.getValue() instanceof - TextBasedPreviewLayout layout - ) { + if (selectedLayoutProperty.getValue() instanceof TextBasedPreviewLayout layout) { layout.setText(sourceTextProperty.getValue()); } }); @@ -137,23 +125,13 @@ public PreviewTabViewModel( @Override public void setValues() { - showAsExtraTabProperty.set( - previewPreferences.shouldShowPreviewAsExtraTab() - ); + showAsExtraTabProperty.set(previewPreferences.shouldShowPreviewAsExtraTab()); chosenListProperty().getValue().clear(); - chosenListProperty - .getValue() - .addAll(previewPreferences.getLayoutCycle()); + chosenListProperty.getValue().addAll(previewPreferences.getLayoutCycle()); availableListProperty.clear(); - if ( - chosenListProperty - .stream() - .noneMatch(TextBasedPreviewLayout.class::isInstance) - ) { - availableListProperty - .getValue() - .add(previewPreferences.getCustomPreviewLayout()); + if (chosenListProperty.stream().noneMatch(TextBasedPreviewLayout.class::isInstance)) { + availableListProperty.getValue().add(previewPreferences.getCustomPreviewLayout()); } BackgroundTask @@ -161,18 +139,11 @@ public void setValues() { .onSuccess(styles -> styles .stream() - .map(style -> - new CitationStylePreviewLayout( - style, - Globals.entryTypesManager - ) - ) + .map(style -> new CitationStylePreviewLayout(style, Globals.entryTypesManager)) .filter(style -> chosenListProperty .getValue() - .filtered(item -> - item.getName().equals(style.getName()) - ) + .filtered(item -> item.getName().equals(style.getName())) .isEmpty() ) .sorted(Comparator.comparing(PreviewLayout::getName)) @@ -212,23 +183,17 @@ public void setPreviewLayout(PreviewLayout selectedLayout) { } if (selectedLayout instanceof TextBasedPreviewLayout layout) { - sourceTextProperty.setValue( - layout.getText().replace("__NEWLINE__", "\n") - ); + sourceTextProperty.setValue(layout.getText().replace("__NEWLINE__", "\n")); selectedIsEditableProperty.setValue(true); } else { - sourceTextProperty.setValue( - ((CitationStylePreviewLayout) selectedLayout).getSource() - ); + sourceTextProperty.setValue(((CitationStylePreviewLayout) selectedLayout).getSource()); selectedIsEditableProperty.setValue(false); } } public void refreshPreview() { setPreviewLayout(null); - setPreviewLayout( - chosenSelectionModelProperty.getValue().getSelectedItem() - ); + setPreviewLayout(chosenSelectionModelProperty.getValue().getSelectedItem()); } private PreviewLayout findLayoutByName(String name) { @@ -256,37 +221,21 @@ public void storeSettings() { chosenListProperty.add(previewPreferences.getCustomPreviewLayout()); } - PreviewLayout customLayout = findLayoutByName( - TextBasedPreviewLayout.NAME - ); + PreviewLayout customLayout = findLayoutByName(TextBasedPreviewLayout.NAME); if (customLayout == null) { customLayout = previewPreferences.getCustomPreviewLayout(); } previewPreferences.getLayoutCycle().clear(); previewPreferences.getLayoutCycle().addAll(chosenListProperty); - previewPreferences.setShowPreviewAsExtraTab( - showAsExtraTabProperty.getValue() - ); - previewPreferences.setCustomPreviewLayout( - (TextBasedPreviewLayout) customLayout - ); + previewPreferences.setShowPreviewAsExtraTab(showAsExtraTabProperty.getValue()); + previewPreferences.setCustomPreviewLayout((TextBasedPreviewLayout) customLayout); - if ( - !chosenSelectionModelProperty - .getValue() - .getSelectedItems() - .isEmpty() - ) { + if (!chosenSelectionModelProperty.getValue().getSelectedItems().isEmpty()) { previewPreferences.setLayoutCyclePosition( chosenListProperty .getValue() - .indexOf( - chosenSelectionModelProperty - .getValue() - .getSelectedItems() - .get(0) - ) + .indexOf(chosenSelectionModelProperty.getValue().getSelectedItems().get(0)) ); } } @@ -302,10 +251,7 @@ public boolean validateSettings() { if (validationStatus.getHighestMessage().isPresent()) { validationStatus .getHighestMessage() - .ifPresent(message -> - dialogService.showErrorDialogAndWait( - message.getMessage() - ) + .ifPresent(message -> dialogService.showErrorDialogAndWait(message.getMessage()) ); } return false; @@ -347,19 +293,12 @@ public void selectedInChosenUp() { for (int oldIndex : selected) { boolean alreadyTaken = newIndices.contains(oldIndex - 1); - int newIndex = (oldIndex > 0) && !alreadyTaken - ? oldIndex - 1 - : oldIndex; - chosenListProperty.add( - newIndex, - chosenListProperty.remove(oldIndex) - ); + int newIndex = (oldIndex > 0) && !alreadyTaken ? oldIndex - 1 : oldIndex; + chosenListProperty.add(newIndex, chosenListProperty.remove(oldIndex)); newIndices.add(newIndex); } - newIndices.forEach(index -> - chosenSelectionModelProperty.getValue().select(index) - ); + newIndices.forEach(index -> chosenSelectionModelProperty.getValue().select(index)); chosenSelectionModelProperty.getValue().select(newIndices.get(0)); refreshPreview(); } @@ -378,28 +317,20 @@ public void selectedInChosenDown() { for (int i = selected.size() - 1; i >= 0; i--) { int oldIndex = selected.get(i); boolean alreadyTaken = newIndices.contains(oldIndex + 1); - int newIndex = (oldIndex < (chosenListProperty.size() - 1)) && - !alreadyTaken + int newIndex = (oldIndex < (chosenListProperty.size() - 1)) && !alreadyTaken ? oldIndex + 1 : oldIndex; - chosenListProperty.add( - newIndex, - chosenListProperty.remove(oldIndex) - ); + chosenListProperty.add(newIndex, chosenListProperty.remove(oldIndex)); newIndices.add(newIndex); } - newIndices.forEach(index -> - chosenSelectionModelProperty.getValue().select(index) - ); + newIndices.forEach(index -> chosenSelectionModelProperty.getValue().select(index)); chosenSelectionModelProperty.getValue().select(newIndices.get(0)); refreshPreview(); } public void resetDefaultLayout() { - PreviewLayout defaultLayout = findLayoutByName( - TextBasedPreviewLayout.NAME - ); + PreviewLayout defaultLayout = findLayoutByName(TextBasedPreviewLayout.NAME); if (defaultLayout instanceof TextBasedPreviewLayout layout) { layout.setText(previewPreferences.getDefaultCustomPreviewLayout()); } @@ -420,12 +351,9 @@ public void resetDefaultLayout() { */ public StyleSpans> computeHighlighting(String text) { final Pattern XML_TAG = Pattern.compile( - "(?(]*)(\\h*/?>))" + - "|(?)" - ); - final Pattern ATTRIBUTES = Pattern.compile( - "(\\w+\\h*)(=)(\\h*\"[^\"]+\")" + "(?(]*)(\\h*/?>))" + "|(?)" ); + final Pattern ATTRIBUTES = Pattern.compile("(\\w+\\h*)(=)(\\h*\"[^\"]+\")"); final int GROUP_OPEN_BRACKET = 2; final int GROUP_ELEMENT_NAME = 3; @@ -437,41 +365,28 @@ public StyleSpans> computeHighlighting(String text) { Matcher matcher = XML_TAG.matcher(text); int lastKeywordEnd = 0; - StyleSpansBuilder> spansBuilder = - new StyleSpansBuilder<>(); + StyleSpansBuilder> spansBuilder = new StyleSpansBuilder<>(); while (matcher.find()) { - spansBuilder.add( - Collections.emptyList(), - matcher.start() - lastKeywordEnd - ); + spansBuilder.add(Collections.emptyList(), matcher.start() - lastKeywordEnd); if (matcher.group("COMMENT") != null) { - spansBuilder.add( - Collections.singleton("comment"), - matcher.end() - matcher.start() - ); + spansBuilder.add(Collections.singleton("comment"), matcher.end() - matcher.start()); } else { if (matcher.group("ELEMENT") != null) { - String attributesText = matcher.group( - GROUP_ATTRIBUTES_SECTION - ); + String attributesText = matcher.group(GROUP_ATTRIBUTES_SECTION); spansBuilder.add( Collections.singleton("tagmark"), - matcher.end(GROUP_OPEN_BRACKET) - - matcher.start(GROUP_OPEN_BRACKET) + matcher.end(GROUP_OPEN_BRACKET) - matcher.start(GROUP_OPEN_BRACKET) ); spansBuilder.add( Collections.singleton("anytag"), - matcher.end(GROUP_ELEMENT_NAME) - - matcher.end(GROUP_OPEN_BRACKET) + matcher.end(GROUP_ELEMENT_NAME) - matcher.end(GROUP_OPEN_BRACKET) ); if (!attributesText.isEmpty()) { lastKeywordEnd = 0; - Matcher attributesMatcher = ATTRIBUTES.matcher( - attributesText - ); + Matcher attributesMatcher = ATTRIBUTES.matcher(attributesText); while (attributesMatcher.find()) { spansBuilder.add( Collections.emptyList(), @@ -512,28 +427,19 @@ public StyleSpans> computeHighlighting(String text) { } lastKeywordEnd = matcher.end(); } - spansBuilder.add( - Collections.emptyList(), - text.length() - lastKeywordEnd - ); + spansBuilder.add(Collections.emptyList(), text.length() - lastKeywordEnd); return spansBuilder.create(); } public void dragOver(DragEvent event) { - if ( - event - .getDragboard() - .hasContent(DragAndDropDataFormats.PREVIEWLAYOUTS) - ) { + if (event.getDragboard().hasContent(DragAndDropDataFormats.PREVIEWLAYOUTS)) { event.acceptTransferModes(TransferMode.MOVE); } } public void dragDetected( ListProperty sourceList, - ObjectProperty< - MultipleSelectionModel - > sourceSelectionModel, + ObjectProperty> sourceSelectionModel, List selectedLayouts, Dragboard dragboard ) { @@ -551,15 +457,11 @@ public void dragDetected( * @param targetList either availableListView or chosenListView */ - public boolean dragDropped( - ListProperty targetList, - Dragboard dragboard - ) { + public boolean dragDropped(ListProperty targetList, Dragboard dragboard) { boolean success = false; if (dragboard.hasContent(DragAndDropDataFormats.PREVIEWLAYOUTS)) { - List draggedLayouts = - localDragboard.getPreviewLayouts(); + List draggedLayouts = localDragboard.getPreviewLayouts(); if (!draggedLayouts.isEmpty()) { dragSourceSelectionModel.getValue().clearSelection(); dragSourceList.getValue().removeAll(draggedLayouts); @@ -569,11 +471,7 @@ public boolean dragDropped( if (targetList == availableListProperty) { targetList .getValue() - .sort((a, b) -> - a - .getDisplayName() - .compareToIgnoreCase(b.getDisplayName()) - ); + .sort((a, b) -> a.getDisplayName().compareToIgnoreCase(b.getDisplayName())); } } } @@ -587,10 +485,7 @@ public boolean dragDropped( * @param targetLayout the Layout, the user drops a layout on */ - public boolean dragDroppedInChosenCell( - PreviewLayout targetLayout, - Dragboard dragboard - ) { + public boolean dragDroppedInChosenCell(PreviewLayout targetLayout, Dragboard dragboard) { boolean success = false; if (dragboard.hasContent(DragAndDropDataFormats.PREVIEWLAYOUTS)) { @@ -599,9 +494,7 @@ public boolean dragDroppedInChosenCell( ); if (!draggedSelectedLayouts.isEmpty()) { chosenSelectionModelProperty.getValue().clearSelection(); - int targetId = chosenListProperty - .getValue() - .indexOf(targetLayout); + int targetId = chosenListProperty.getValue().indexOf(targetLayout); // see https://stackoverflow.com/questions/28603224/sort-tableview-with-drag-and-drop-rows int onSelectedDelta = 0; @@ -620,15 +513,12 @@ public boolean dragDroppedInChosenCell( if (targetLayout != null) { targetId = - chosenListProperty.getValue().indexOf(targetLayout) + - onSelectedDelta; + chosenListProperty.getValue().indexOf(targetLayout) + onSelectedDelta; } else if (targetId != 0) { targetId = chosenListProperty.getValue().size(); } - chosenListProperty - .getValue() - .addAll(targetId, draggedSelectedLayouts); + chosenListProperty.getValue().addAll(targetId, draggedSelectedLayouts); draggedSelectedLayouts.forEach(layout -> chosenSelectionModelProperty.getValue().select(layout) @@ -655,14 +545,11 @@ public FilteredList getFilteredAvailableLayouts() { public void setAvailableFilter(String searchTerm) { this.filteredAvailableLayouts.setPredicate(preview -> - searchTerm.isEmpty() || - preview.containsCaseIndependent(searchTerm) + searchTerm.isEmpty() || preview.containsCaseIndependent(searchTerm) ); } - public ObjectProperty< - MultipleSelectionModel - > availableSelectionModelProperty() { + public ObjectProperty> availableSelectionModelProperty() { return availableSelectionModelProperty; } @@ -670,9 +557,7 @@ public ListProperty chosenListProperty() { return chosenListProperty; } - public ObjectProperty< - MultipleSelectionModel - > chosenSelectionModelProperty() { + public ObjectProperty> chosenSelectionModelProperty() { return chosenSelectionModelProperty; } diff --git a/src/main/java/org/jabref/gui/preferences/protectedterms/NewProtectedTermsFileDialog.java b/src/main/java/org/jabref/gui/preferences/protectedterms/NewProtectedTermsFileDialog.java index 7d41eb85700..1a90fc6836c 100644 --- a/src/main/java/org/jabref/gui/preferences/protectedterms/NewProtectedTermsFileDialog.java +++ b/src/main/java/org/jabref/gui/preferences/protectedterms/NewProtectedTermsFileDialog.java @@ -30,46 +30,27 @@ public NewProtectedTermsFileDialog( this.setTitle(Localization.lang("New protected terms file")); - FileDialogConfiguration fileDialogConfiguration = - new FileDialogConfiguration.Builder() - .addExtensionFilter( - Localization.lang("Protected terms file"), - StandardFileType.TERMS - ) - .withDefaultExtension( - Localization.lang("Protected terms file"), - StandardFileType.TERMS - ) - .withInitialDirectory(filePreferences.getWorkingDirectory()) - .build(); + FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() + .addExtensionFilter(Localization.lang("Protected terms file"), StandardFileType.TERMS) + .withDefaultExtension(Localization.lang("Protected terms file"), StandardFileType.TERMS) + .withInitialDirectory(filePreferences.getWorkingDirectory()) + .build(); Button browse = new Button(Localization.lang("Browse")); browse.setOnAction(event -> this.dialogService.showFileSaveDialog(fileDialogConfiguration) - .ifPresent(file -> - newFile.setText(file.toAbsolutePath().toString()) - ) + .ifPresent(file -> newFile.setText(file.toAbsolutePath().toString())) ); TextField newDescription = new TextField(); VBox container = new VBox( 10, - new VBox( - 5, - new Label(Localization.lang("Description")), - newDescription - ), - new VBox( - 5, - new Label(Localization.lang("File")), - new HBox(10, newFile, browse) - ) + new VBox(5, new Label(Localization.lang("Description")), newDescription), + new VBox(5, new Label(Localization.lang("File")), new HBox(10, newFile, browse)) ); getDialogPane().setContent(container); - getDialogPane() - .getButtonTypes() - .setAll(ButtonType.OK, ButtonType.CANCEL); + getDialogPane().getButtonTypes().setAll(ButtonType.OK, ButtonType.CANCEL); setResultConverter(button -> { if (button == ButtonType.OK) { diff --git a/src/main/java/org/jabref/gui/preferences/protectedterms/ProtectedTermsTab.java b/src/main/java/org/jabref/gui/preferences/protectedterms/ProtectedTermsTab.java index 97b29c8623b..ad953523009 100644 --- a/src/main/java/org/jabref/gui/preferences/protectedterms/ProtectedTermsTab.java +++ b/src/main/java/org/jabref/gui/preferences/protectedterms/ProtectedTermsTab.java @@ -33,34 +33,19 @@ public class ProtectedTermsTab private TableView filesTable; @FXML - private TableColumn< - ProtectedTermsListItemModel, - Boolean - > filesTableEnabledColumn; + private TableColumn filesTableEnabledColumn; @FXML - private TableColumn< - ProtectedTermsListItemModel, - String - > filesTableDescriptionColumn; + private TableColumn filesTableDescriptionColumn; @FXML - private TableColumn< - ProtectedTermsListItemModel, - String - > filesTableFileColumn; + private TableColumn filesTableFileColumn; @FXML - private TableColumn< - ProtectedTermsListItemModel, - Boolean - > filesTableEditColumn; + private TableColumn filesTableEditColumn; @FXML - private TableColumn< - ProtectedTermsListItemModel, - Boolean - > filesTableDeleteColumn; + private TableColumn filesTableDeleteColumn; @Inject private ProtectedTermsLoader termsLoader; @@ -79,12 +64,7 @@ public String getTabName() { @FXML public void initialize() { - viewModel = - new ProtectedTermsTabViewModel( - termsLoader, - dialogService, - preferencesService - ); + viewModel = new ProtectedTermsTabViewModel(termsLoader, dialogService, preferencesService); new ViewModelTableRowFactory() .withContextMenu(this::createContextMenu) @@ -92,51 +72,34 @@ public void initialize() { filesTableEnabledColumn.setCellFactory( CheckBoxTableCell.forTableColumn(filesTableEnabledColumn) ); - filesTableEnabledColumn.setCellValueFactory(data -> - data.getValue().enabledProperty() - ); + filesTableEnabledColumn.setCellValueFactory(data -> data.getValue().enabledProperty()); filesTableDescriptionColumn.setCellValueFactory(data -> - BindingsHelper.constantOf( - data.getValue().getTermsList().getDescription() - ) + BindingsHelper.constantOf(data.getValue().getTermsList().getDescription()) ); filesTableFileColumn.setCellValueFactory(data -> { ProtectedTermsList list = data.getValue().getTermsList(); if (list.isInternalList()) { - return BindingsHelper.constantOf( - Localization.lang("Internal list") - ); + return BindingsHelper.constantOf(Localization.lang("Internal list")); } else { return BindingsHelper.constantOf(list.getLocation()); } }); - filesTableEditColumn.setCellValueFactory(data -> - data.getValue().internalProperty().not() - ); + filesTableEditColumn.setCellValueFactory(data -> data.getValue().internalProperty().not()); new ValueTableCellFactory() .withGraphic(none -> IconTheme.JabRefIcons.EDIT.getGraphicNode()) .withVisibleExpression(ReadOnlyBooleanWrapper::new) - .withOnMouseClickedEvent((item, none) -> - event -> viewModel.edit(item) - ) + .withOnMouseClickedEvent((item, none) -> event -> viewModel.edit(item)) .install(filesTableEditColumn); - filesTableDeleteColumn.setCellValueFactory(data -> - data.getValue().internalProperty().not() + filesTableDeleteColumn.setCellValueFactory(data -> data.getValue().internalProperty().not() ); new ValueTableCellFactory() - .withGraphic(none -> - IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode() - ) + .withGraphic(none -> IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode()) .withVisibleExpression(ReadOnlyBooleanWrapper::new) - .withTooltip(none -> - Localization.lang("Remove protected terms file") - ) - .withOnMouseClickedEvent((item, none) -> - event -> viewModel.removeList(item) - ) + .withTooltip(none -> Localization.lang("Remove protected terms file")) + .withOnMouseClickedEvent((item, none) -> event -> viewModel.removeList(item)) .install(filesTableDeleteColumn); filesTable.itemsProperty().set(viewModel.termsFilesProperty()); @@ -150,31 +113,19 @@ private ContextMenu createContextMenu(ProtectedTermsListItemModel file) { .addAll( factory.createMenuItem( StandardActions.EDIT_LIST, - new ProtectedTermsTab.ContextAction( - StandardActions.EDIT_LIST, - file - ) + new ProtectedTermsTab.ContextAction(StandardActions.EDIT_LIST, file) ), factory.createMenuItem( StandardActions.VIEW_LIST, - new ProtectedTermsTab.ContextAction( - StandardActions.VIEW_LIST, - file - ) + new ProtectedTermsTab.ContextAction(StandardActions.VIEW_LIST, file) ), factory.createMenuItem( StandardActions.REMOVE_LIST, - new ProtectedTermsTab.ContextAction( - StandardActions.REMOVE_LIST, - file - ) + new ProtectedTermsTab.ContextAction(StandardActions.REMOVE_LIST, file) ), factory.createMenuItem( StandardActions.RELOAD_LIST, - new ProtectedTermsTab.ContextAction( - StandardActions.RELOAD_LIST, - file - ) + new ProtectedTermsTab.ContextAction(StandardActions.RELOAD_LIST, file) ) ); contextMenu.getItems().forEach(item -> item.setGraphic(null)); @@ -198,19 +149,14 @@ private class ContextAction extends SimpleCommand { private final StandardActions command; private final ProtectedTermsListItemModel itemModel; - public ContextAction( - StandardActions command, - ProtectedTermsListItemModel itemModel - ) { + public ContextAction(StandardActions command, ProtectedTermsListItemModel itemModel) { this.command = command; this.itemModel = itemModel; this.executable.bind( BindingsHelper.constantOf( switch (command) { - case EDIT_LIST, - REMOVE_LIST, - RELOAD_LIST -> !itemModel + case EDIT_LIST, REMOVE_LIST, RELOAD_LIST -> !itemModel .getTermsList() .isInternalList(); default -> true; diff --git a/src/main/java/org/jabref/gui/preferences/protectedterms/ProtectedTermsTabViewModel.java b/src/main/java/org/jabref/gui/preferences/protectedterms/ProtectedTermsTabViewModel.java index 2793415290f..d428fdd011f 100644 --- a/src/main/java/org/jabref/gui/preferences/protectedterms/ProtectedTermsTabViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/protectedterms/ProtectedTermsTabViewModel.java @@ -32,9 +32,7 @@ public class ProtectedTermsTabViewModel implements PreferenceTabViewModel { - private static final Logger LOGGER = LoggerFactory.getLogger( - ProtectedTermsTabViewModel.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(ProtectedTermsTabViewModel.class); private final ProtectedTermsLoader termsLoader; private final ListProperty termsFilesProperty = @@ -51,8 +49,7 @@ public ProtectedTermsTabViewModel( this.termsLoader = termsLoader; this.dialogService = dialogService; this.filePreferences = preferencesService.getFilePreferences(); - this.protectedTermsPreferences = - preferencesService.getProtectedTermsPreferences(); + this.protectedTermsPreferences = preferencesService.getProtectedTermsPreferences(); } @Override @@ -94,35 +91,20 @@ public void storeSettings() { } } - protectedTermsPreferences.setEnabledInternalTermLists( - enabledInternalList - ); - protectedTermsPreferences.setEnabledExternalTermLists( - enabledExternalList - ); - protectedTermsPreferences.setDisabledInternalTermLists( - disabledInternalList - ); - protectedTermsPreferences.setDisabledExternalTermLists( - disabledExternalList - ); + protectedTermsPreferences.setEnabledInternalTermLists(enabledInternalList); + protectedTermsPreferences.setEnabledExternalTermLists(enabledExternalList); + protectedTermsPreferences.setDisabledInternalTermLists(disabledInternalList); + protectedTermsPreferences.setDisabledExternalTermLists(disabledExternalList); termsLoader.update(protectedTermsPreferences); } public void addFile() { - FileDialogConfiguration fileDialogConfiguration = - new FileDialogConfiguration.Builder() - .addExtensionFilter( - Localization.lang("Protected terms file"), - StandardFileType.TERMS - ) - .withDefaultExtension( - Localization.lang("Protected terms file"), - StandardFileType.TERMS - ) - .withInitialDirectory(filePreferences.getWorkingDirectory()) - .build(); + FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() + .addExtensionFilter(Localization.lang("Protected terms file"), StandardFileType.TERMS) + .withDefaultExtension(Localization.lang("Protected terms file"), StandardFileType.TERMS) + .withInitialDirectory(filePreferences.getWorkingDirectory()) + .build(); dialogService .showFileOpenDialog(fileDialogConfiguration) @@ -130,10 +112,7 @@ public void addFile() { Path fileName = file.toAbsolutePath(); termsFilesProperty.add( new ProtectedTermsListItemModel( - ProtectedTermsLoader.readProtectedTermsListFromFile( - fileName, - true - ) + ProtectedTermsLoader.readProtectedTermsListFromFile(fileName, true) ) ); }); @@ -145,9 +124,7 @@ public void removeList(ProtectedTermsListItemModel itemModel) { !list.isInternalList() && dialogService.showConfirmationDialogAndWait( Localization.lang("Remove protected terms file"), - Localization.lang( - "Are you sure you want to remove the protected terms file?" - ), + Localization.lang("Are you sure you want to remove the protected terms file?"), Localization.lang("Remove protected terms file"), Localization.lang("Cancel") ) @@ -161,22 +138,13 @@ public void removeList(ProtectedTermsListItemModel itemModel) { public void createNewFile() { dialogService.showCustomDialogAndWait( - new NewProtectedTermsFileDialog( - termsFilesProperty, - dialogService, - filePreferences - ) + new NewProtectedTermsFileDialog(termsFilesProperty, dialogService, filePreferences) ); } public void edit(ProtectedTermsListItemModel file) { - Optional termsFileType = OptionalUtil.< - ExternalFileType - >orElse( - ExternalFileTypes.getExternalFileTypeByExt( - "terms", - filePreferences - ), + Optional termsFileType = OptionalUtil.orElse( + ExternalFileTypes.getExternalFileTypeByExt("terms", filePreferences), ExternalFileTypes.getExternalFileTypeByExt("txt", filePreferences) ); @@ -215,22 +183,15 @@ public void displayContent(ProtectedTermsListItemModel itemModel) { public void reloadList(ProtectedTermsListItemModel oldItemModel) { ProtectedTermsList oldList = oldItemModel.getTermsList(); - ProtectedTermsList newList = - ProtectedTermsLoader.readProtectedTermsListFromFile( - Path.of(oldList.getLocation()), - oldList.isEnabled() - ); + ProtectedTermsList newList = ProtectedTermsLoader.readProtectedTermsListFromFile( + Path.of(oldList.getLocation()), + oldList.isEnabled() + ); int index = termsFilesProperty.indexOf(oldItemModel); if (index >= 0) { - termsFilesProperty.set( - index, - new ProtectedTermsListItemModel(newList) - ); + termsFilesProperty.set(index, new ProtectedTermsListItemModel(newList)); } else { - LOGGER.warn( - "Problem reloading protected terms file {}.", - oldList.getLocation() - ); + LOGGER.warn("Problem reloading protected terms file {}.", oldList.getLocation()); } } diff --git a/src/main/java/org/jabref/gui/preferences/table/TableTab.java b/src/main/java/org/jabref/gui/preferences/table/TableTab.java index 4b20b976890..07bc2156bca 100644 --- a/src/main/java/org/jabref/gui/preferences/table/TableTab.java +++ b/src/main/java/org/jabref/gui/preferences/table/TableTab.java @@ -74,8 +74,7 @@ public class TableTab @FXML private RadioButton abbreviationLastNameOnly; - private final ControlsFxVisualizer validationVisualizer = - new ControlsFxVisualizer(); + private final ControlsFxVisualizer validationVisualizer = new ControlsFxVisualizer(); public TableTab() { ViewLoader.view(this).root(this).load(); @@ -87,8 +86,7 @@ public String getTabName() { } public void initialize() { - this.viewModel = - new TableTabViewModel(dialogService, preferencesService); + this.viewModel = new TableTabViewModel(dialogService, preferencesService); setupTable(); setupBindings(); @@ -110,42 +108,28 @@ public void initialize() { private void setupTable() { nameColumn.setSortable(false); nameColumn.setReorderable(false); - nameColumn.setCellValueFactory(cellData -> - cellData.getValue().nameProperty() - ); + nameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty()); new ValueTableCellFactory() .withText(name -> name) .install(nameColumn); actionsColumn.setSortable(false); actionsColumn.setReorderable(false); - actionsColumn.setCellValueFactory(cellData -> - cellData.getValue().nameProperty() - ); + actionsColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty()); new ValueTableCellFactory() - .withGraphic(item -> - IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode() - ) - .withTooltip(name -> Localization.lang("Remove column") + " " + name - ) + .withGraphic(item -> IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode()) + .withTooltip(name -> Localization.lang("Remove column") + " " + name) .withOnMouseClickedEvent(item -> - evt -> - viewModel.removeColumn( - columnsList.getFocusModel().getFocusedItem() - ) + evt -> viewModel.removeColumn(columnsList.getFocusModel().getFocusedItem()) ) .install(actionsColumn); - viewModel - .selectedColumnModelProperty() - .setValue(columnsList.getSelectionModel()); + viewModel.selectedColumnModelProperty().setValue(columnsList.getSelectionModel()); columnsList.addEventFilter( KeyEvent.KEY_PRESSED, event -> { if (event.getCode() == KeyCode.DELETE) { - viewModel.removeColumn( - columnsList.getSelectionModel().getSelectedItem() - ); + viewModel.removeColumn(columnsList.getSelectionModel().getSelectedItem()); event.consume(); } } @@ -156,12 +140,8 @@ private void setupTable() { new ViewModelListCellFactory() .withText(MainTableColumnModel::getDisplayName) .install(addColumnName); - addColumnName - .itemsProperty() - .bind(viewModel.availableColumnsProperty()); - addColumnName - .valueProperty() - .bindBidirectional(viewModel.addColumnProperty()); + addColumnName.itemsProperty().bind(viewModel.availableColumnsProperty()); + addColumnName.valueProperty().bindBidirectional(viewModel.addColumnProperty()); addColumnName.setConverter(TableTabViewModel.columnNameStringConverter); addColumnName.addEventFilter( KeyEvent.KEY_PRESSED, @@ -193,43 +173,29 @@ private void setupBindings() { .selectedProperty() .bindBidirectional(viewModel.autoResizeColumnsProperty()); - namesNatbib - .selectedProperty() - .bindBidirectional(viewModel.namesNatbibProperty()); - nameAsIs - .selectedProperty() - .bindBidirectional(viewModel.nameAsIsProperty()); - nameFirstLast - .selectedProperty() - .bindBidirectional(viewModel.nameFirstLastProperty()); - nameLastFirst - .selectedProperty() - .bindBidirectional(viewModel.nameLastFirstProperty()); + namesNatbib.selectedProperty().bindBidirectional(viewModel.namesNatbibProperty()); + nameAsIs.selectedProperty().bindBidirectional(viewModel.nameAsIsProperty()); + nameFirstLast.selectedProperty().bindBidirectional(viewModel.nameFirstLastProperty()); + nameLastFirst.selectedProperty().bindBidirectional(viewModel.nameLastFirstProperty()); abbreviationDisabled .selectedProperty() .bindBidirectional(viewModel.abbreviationDisabledProperty()); abbreviationDisabled .disableProperty() - .bind( - namesNatbib.selectedProperty().or(nameAsIs.selectedProperty()) - ); + .bind(namesNatbib.selectedProperty().or(nameAsIs.selectedProperty())); abbreviationEnabled .selectedProperty() .bindBidirectional(viewModel.abbreviationEnabledProperty()); abbreviationEnabled .disableProperty() - .bind( - namesNatbib.selectedProperty().or(nameAsIs.selectedProperty()) - ); + .bind(namesNatbib.selectedProperty().or(nameAsIs.selectedProperty())); abbreviationLastNameOnly .selectedProperty() .bindBidirectional(viewModel.abbreviationLastNameOnlyProperty()); abbreviationLastNameOnly .disableProperty() - .bind( - namesNatbib.selectedProperty().or(nameAsIs.selectedProperty()) - ); + .bind(namesNatbib.selectedProperty().or(nameAsIs.selectedProperty())); } public void updateToCurrentColumnOrder() { diff --git a/src/main/java/org/jabref/gui/preferences/table/TableTabViewModel.java b/src/main/java/org/jabref/gui/preferences/table/TableTabViewModel.java index 433c14515cf..86f85607354 100644 --- a/src/main/java/org/jabref/gui/preferences/table/TableTabViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/table/TableTabViewModel.java @@ -51,38 +51,26 @@ public MainTableColumnModel fromString(String string) { } }; - private final ListProperty columnsListProperty = - new SimpleListProperty<>(FXCollections.observableArrayList()); - private final ObjectProperty< - SelectionModel - > selectedColumnModelProperty = new SimpleObjectProperty<>( - new NoSelectionModel<>() + private final ListProperty columnsListProperty = new SimpleListProperty<>( + FXCollections.observableArrayList() ); + private final ObjectProperty> selectedColumnModelProperty = + new SimpleObjectProperty<>(new NoSelectionModel<>()); private final ListProperty availableColumnsProperty = new SimpleListProperty<>(FXCollections.observableArrayList()); private final ObjectProperty addColumnProperty = new SimpleObjectProperty<>(); - private final BooleanProperty specialFieldsEnabledProperty = - new SimpleBooleanProperty(); - private final BooleanProperty extraFileColumnsEnabledProperty = - new SimpleBooleanProperty(); - private final BooleanProperty autoResizeColumnsProperty = - new SimpleBooleanProperty(); - - private final BooleanProperty namesNatbibProperty = - new SimpleBooleanProperty(); - private final BooleanProperty nameAsIsProperty = - new SimpleBooleanProperty(); - private final BooleanProperty nameFirstLastProperty = - new SimpleBooleanProperty(); - private final BooleanProperty nameLastFirstProperty = - new SimpleBooleanProperty(); - private final BooleanProperty abbreviationDisabledProperty = - new SimpleBooleanProperty(); - private final BooleanProperty abbreviationEnabledProperty = - new SimpleBooleanProperty(); - private final BooleanProperty abbreviationLastNameOnlyProperty = - new SimpleBooleanProperty(); + private final BooleanProperty specialFieldsEnabledProperty = new SimpleBooleanProperty(); + private final BooleanProperty extraFileColumnsEnabledProperty = new SimpleBooleanProperty(); + private final BooleanProperty autoResizeColumnsProperty = new SimpleBooleanProperty(); + + private final BooleanProperty namesNatbibProperty = new SimpleBooleanProperty(); + private final BooleanProperty nameAsIsProperty = new SimpleBooleanProperty(); + private final BooleanProperty nameFirstLastProperty = new SimpleBooleanProperty(); + private final BooleanProperty nameLastFirstProperty = new SimpleBooleanProperty(); + private final BooleanProperty abbreviationDisabledProperty = new SimpleBooleanProperty(); + private final BooleanProperty abbreviationEnabledProperty = new SimpleBooleanProperty(); + private final BooleanProperty abbreviationLastNameOnlyProperty = new SimpleBooleanProperty(); private final Validator columnsNotEmptyValidator; @@ -94,36 +82,28 @@ public MainTableColumnModel fromString(String string) { private final NameDisplayPreferences nameDisplayPreferences; private final MainTablePreferences mainTablePreferences; - public TableTabViewModel( - DialogService dialogService, - PreferencesService preferences - ) { + public TableTabViewModel(DialogService dialogService, PreferencesService preferences) { this.dialogService = dialogService; this.preferences = preferences; - this.specialFieldsPreferences = - preferences.getSpecialFieldsPreferences(); + this.specialFieldsPreferences = preferences.getSpecialFieldsPreferences(); this.nameDisplayPreferences = preferences.getNameDisplayPreferences(); this.mainTablePreferences = preferences.getMainTablePreferences(); - specialFieldsEnabledProperty.addListener( - (observable, oldValue, newValue) -> { - if (newValue) { - insertSpecialFieldColumns(); - } else { - removeSpecialFieldColumns(); - } + specialFieldsEnabledProperty.addListener((observable, oldValue, newValue) -> { + if (newValue) { + insertSpecialFieldColumns(); + } else { + removeSpecialFieldColumns(); } - ); + }); - extraFileColumnsEnabledProperty.addListener( - (observable, oldValue, newValue) -> { - if (newValue) { - insertExtraFileColumns(); - } else { - removeExtraFileColumns(); - } + extraFileColumnsEnabledProperty.addListener((observable, oldValue, newValue) -> { + if (newValue) { + insertExtraFileColumns(); + } else { + removeExtraFileColumns(); } - ); + }); columnsNotEmptyValidator = new FunctionBasedValidator<>( @@ -144,24 +124,16 @@ public TableTabViewModel( public void setValues() { initialColumnPreferences = mainTablePreferences.getColumnPreferences(); - specialFieldsEnabledProperty.setValue( - specialFieldsPreferences.isSpecialFieldsEnabled() - ); - extraFileColumnsEnabledProperty.setValue( - mainTablePreferences.getExtraFileColumnsEnabled() - ); - autoResizeColumnsProperty.setValue( - mainTablePreferences.getResizeColumnsToFit() - ); + specialFieldsEnabledProperty.setValue(specialFieldsPreferences.isSpecialFieldsEnabled()); + extraFileColumnsEnabledProperty.setValue(mainTablePreferences.getExtraFileColumnsEnabled()); + autoResizeColumnsProperty.setValue(mainTablePreferences.getResizeColumnsToFit()); fillColumnList(); availableColumnsProperty.clear(); availableColumnsProperty.addAll( new MainTableColumnModel(MainTableColumnModel.Type.INDEX), - new MainTableColumnModel( - MainTableColumnModel.Type.LINKED_IDENTIFIER - ), + new MainTableColumnModel(MainTableColumnModel.Type.LINKED_IDENTIFIER), new MainTableColumnModel(MainTableColumnModel.Type.GROUPS), new MainTableColumnModel(MainTableColumnModel.Type.FILES), new MainTableColumnModel( @@ -190,12 +162,7 @@ public void setValues() { .allOf(StandardField.class) .stream() .map(Field::getName) - .map(name -> - new MainTableColumnModel( - MainTableColumnModel.Type.NORMALFIELD, - name - ) - ) + .map(name -> new MainTableColumnModel(MainTableColumnModel.Type.NORMALFIELD, name)) .forEach(item -> availableColumnsProperty.getValue().add(item)); if (specialFieldsEnabledProperty.getValue()) { @@ -215,9 +182,7 @@ public void setValues() { switch (nameDisplayPreferences.getAbbreviationStyle()) { case FULL -> abbreviationEnabledProperty.setValue(true); - case LASTNAME_ONLY -> abbreviationLastNameOnlyProperty.setValue( - true - ); + case LASTNAME_ONLY -> abbreviationLastNameOnlyProperty.setValue(true); case NONE -> abbreviationDisabledProperty.setValue(true); } } @@ -225,9 +190,7 @@ public void setValues() { public void fillColumnList() { columnsListProperty.getValue().clear(); if (initialColumnPreferences != null) { - initialColumnPreferences - .getColumns() - .forEach(columnsListProperty.getValue()::add); + initialColumnPreferences.getColumns().forEach(columnsListProperty.getValue()::add); } } @@ -236,26 +199,17 @@ private void insertSpecialFieldColumns() { .allOf(SpecialField.class) .stream() .map(Field::getName) - .map(name -> - new MainTableColumnModel( - MainTableColumnModel.Type.SPECIALFIELD, - name - ) - ) + .map(name -> new MainTableColumnModel(MainTableColumnModel.Type.SPECIALFIELD, name)) .forEach(item -> availableColumnsProperty.getValue().add(0, item)); } private void removeSpecialFieldColumns() { columnsListProperty .getValue() - .removeIf(column -> - column.getType().equals(MainTableColumnModel.Type.SPECIALFIELD) - ); + .removeIf(column -> column.getType().equals(MainTableColumnModel.Type.SPECIALFIELD)); availableColumnsProperty .getValue() - .removeIf(column -> - column.getType().equals(MainTableColumnModel.Type.SPECIALFIELD) - ); + .removeIf(column -> column.getType().equals(MainTableColumnModel.Type.SPECIALFIELD)); } private void insertExtraFileColumns() { @@ -264,26 +218,17 @@ private void insertExtraFileColumns() { .getExternalFileTypes() .stream() .map(ExternalFileType::getName) - .map(name -> - new MainTableColumnModel( - MainTableColumnModel.Type.EXTRAFILE, - name - ) - ) + .map(name -> new MainTableColumnModel(MainTableColumnModel.Type.EXTRAFILE, name)) .forEach(item -> availableColumnsProperty.getValue().add(item)); } private void removeExtraFileColumns() { columnsListProperty .getValue() - .removeIf(column -> - column.getType().equals(MainTableColumnModel.Type.EXTRAFILE) - ); + .removeIf(column -> column.getType().equals(MainTableColumnModel.Type.EXTRAFILE)); availableColumnsProperty .getValue() - .removeIf(column -> - column.getType().equals(MainTableColumnModel.Type.EXTRAFILE) - ); + .removeIf(column -> column.getType().equals(MainTableColumnModel.Type.EXTRAFILE)); } public void insertColumnInList() { @@ -327,10 +272,7 @@ public void moveColumnDown() { .getValue() .getSelectedItem(); int row = columnsListProperty.getValue().indexOf(selectedColumn); - if ( - (selectedColumn == null) || - (row > (columnsListProperty.getValue().size() - 2)) - ) { + if ((selectedColumn == null) || (row > (columnsListProperty.getValue().size() - 2))) { return; } @@ -341,32 +283,20 @@ public void moveColumnDown() { @Override public void storeSettings() { - mainTablePreferences - .getColumnPreferences() - .setColumns(columnsListProperty.getValue()); - mainTablePreferences.setResizeColumnsToFit( - autoResizeColumnsProperty.getValue() - ); - mainTablePreferences.setExtraFileColumnsEnabled( - extraFileColumnsEnabledProperty.getValue() - ); + mainTablePreferences.getColumnPreferences().setColumns(columnsListProperty.getValue()); + mainTablePreferences.setResizeColumnsToFit(autoResizeColumnsProperty.getValue()); + mainTablePreferences.setExtraFileColumnsEnabled(extraFileColumnsEnabledProperty.getValue()); - specialFieldsPreferences.setSpecialFieldsEnabled( - specialFieldsEnabledProperty.getValue() - ); + specialFieldsPreferences.setSpecialFieldsEnabled(specialFieldsEnabledProperty.getValue()); if (nameLastFirstProperty.getValue()) { - nameDisplayPreferences.setDisplayStyle( - DisplayStyle.LASTNAME_FIRSTNAME - ); + nameDisplayPreferences.setDisplayStyle(DisplayStyle.LASTNAME_FIRSTNAME); } else if (namesNatbibProperty.getValue()) { nameDisplayPreferences.setDisplayStyle(DisplayStyle.NATBIB); } else if (nameAsIsProperty.getValue()) { nameDisplayPreferences.setDisplayStyle(DisplayStyle.AS_IS); } else if (nameFirstLastProperty.getValue()) { - nameDisplayPreferences.setDisplayStyle( - DisplayStyle.FIRSTNAME_LASTNAME - ); + nameDisplayPreferences.setDisplayStyle(DisplayStyle.FIRSTNAME_LASTNAME); } if (abbreviationDisabledProperty.getValue()) { @@ -374,9 +304,7 @@ public void storeSettings() { } else if (abbreviationEnabledProperty.getValue()) { nameDisplayPreferences.setAbbreviationStyle(AbbreviationStyle.FULL); } else if (abbreviationLastNameOnlyProperty.getValue()) { - nameDisplayPreferences.setAbbreviationStyle( - AbbreviationStyle.LASTNAME_ONLY - ); + nameDisplayPreferences.setAbbreviationStyle(AbbreviationStyle.LASTNAME_ONLY); } } @@ -390,9 +318,7 @@ public boolean validateSettings() { if (!validationStatus.isValid()) { validationStatus .getHighestMessage() - .ifPresent(message -> - dialogService.showErrorDialogAndWait(message.getMessage()) - ); + .ifPresent(message -> dialogService.showErrorDialogAndWait(message.getMessage())); return false; } return true; @@ -402,9 +328,7 @@ public ListProperty columnsListProperty() { return this.columnsListProperty; } - public ObjectProperty< - SelectionModel - > selectedColumnModelProperty() { + public ObjectProperty> selectedColumnModelProperty() { return selectedColumnModelProperty; } diff --git a/src/main/java/org/jabref/gui/preferences/websearch/WebSearchTab.java b/src/main/java/org/jabref/gui/preferences/websearch/WebSearchTab.java index c74328845d3..5a52b7a4ef2 100644 --- a/src/main/java/org/jabref/gui/preferences/websearch/WebSearchTab.java +++ b/src/main/java/org/jabref/gui/preferences/websearch/WebSearchTab.java @@ -88,12 +88,9 @@ public String getTabName() { } public void initialize() { - this.viewModel = - new WebSearchTabViewModel(preferencesService, dialogService); + this.viewModel = new WebSearchTabViewModel(preferencesService, dialogService); - enableWebSearch - .selectedProperty() - .bindBidirectional(viewModel.enableWebSearchProperty()); + enableWebSearch.selectedProperty().bindBidirectional(viewModel.enableWebSearchProperty()); generateNewKeyOnImport .selectedProperty() .bindBidirectional(viewModel.generateKeyOnImportProperty()); @@ -104,25 +101,13 @@ public void initialize() { .selectedProperty() .bindBidirectional(viewModel.shouldDownloadLinkedOnlineFiles()); - grobidEnabled - .selectedProperty() - .bindBidirectional(viewModel.grobidEnabledProperty()); - grobidURL - .textProperty() - .bindBidirectional(viewModel.grobidURLProperty()); - grobidURL - .disableProperty() - .bind(grobidEnabled.selectedProperty().not()); + grobidEnabled.selectedProperty().bindBidirectional(viewModel.grobidEnabledProperty()); + grobidURL.textProperty().bindBidirectional(viewModel.grobidURLProperty()); + grobidURL.disableProperty().bind(grobidEnabled.selectedProperty().not()); - useCustomDOI - .selectedProperty() - .bindBidirectional(viewModel.useCustomDOIProperty()); - useCustomDOIName - .textProperty() - .bindBidirectional(viewModel.useCustomDOINameProperty()); - useCustomDOIName - .disableProperty() - .bind(useCustomDOI.selectedProperty().not()); + useCustomDOI.selectedProperty().bindBidirectional(viewModel.useCustomDOIProperty()); + useCustomDOIName.textProperty().bindBidirectional(viewModel.useCustomDOINameProperty()); + useCustomDOIName.disableProperty().bind(useCustomDOI.selectedProperty().not()); new ViewModelTableRowFactory() .withOnMouseClickedEvent((entry, event) -> { @@ -137,17 +122,11 @@ public void initialize() { catalogEnabledColumn.setResizable(false); catalogEnabledColumn.setReorderable(false); - catalogEnabledColumn.setCellFactory( - CheckBoxTableCell.forTableColumn(catalogEnabledColumn) - ); - catalogEnabledColumn.setCellValueFactory(param -> - param.getValue().enabledProperty() - ); + catalogEnabledColumn.setCellFactory(CheckBoxTableCell.forTableColumn(catalogEnabledColumn)); + catalogEnabledColumn.setCellValueFactory(param -> param.getValue().enabledProperty()); catalogColumn.setEditable(false); - catalogColumn.setCellValueFactory(param -> - param.getValue().nameProperty() - ); + catalogColumn.setCellValueFactory(param -> param.getValue().nameProperty()); catalogTable.setItems(viewModel.getCatalogs()); new ViewModelListCellFactory() @@ -167,31 +146,19 @@ public void initialize() { }); customApiKey .textProperty() - .addListener(listener -> - updateFetcherApiKey(apiKeySelector.valueProperty().get()) - ); + .addListener(listener -> updateFetcherApiKey(apiKeySelector.valueProperty().get())); - customApiKey - .disableProperty() - .bind(useCustomApiKey.selectedProperty().not()); - testCustomApiKey - .disableProperty() - .bind(useCustomApiKey.selectedProperty().not()); + customApiKey.disableProperty().bind(useCustomApiKey.selectedProperty().not()); + testCustomApiKey.disableProperty().bind(useCustomApiKey.selectedProperty().not()); - persistApiKeys - .selectedProperty() - .bindBidirectional(viewModel.getApikeyPersistProperty()); - persistApiKeys - .disableProperty() - .bind(viewModel.apiKeyPersistAvailable().not()); + persistApiKeys.selectedProperty().bindBidirectional(viewModel.getApikeyPersistProperty()); + persistApiKeys.disableProperty().bind(viewModel.apiKeyPersistAvailable().not()); EasyBind.subscribe( viewModel.apiKeyPersistAvailable(), available -> { if (!available) { persistentTooltipWrapper.setTooltip( - new Tooltip( - Localization.lang("Credential store not available.") - ) + new Tooltip(Localization.lang("Credential store not available.")) ); } else { persistentTooltipWrapper.setTooltip(null); @@ -206,8 +173,7 @@ public void initialize() { viewModel .fetcherApiKeys() .addListener( - (InvalidationListener) change -> - apiKeySelector.getSelectionModel().selectFirst() + (InvalidationListener) change -> apiKeySelector.getSelectionModel().selectFirst() ); } diff --git a/src/main/java/org/jabref/gui/preferences/websearch/WebSearchTabViewModel.java b/src/main/java/org/jabref/gui/preferences/websearch/WebSearchTabViewModel.java index b028210bc5f..52f903a4215 100644 --- a/src/main/java/org/jabref/gui/preferences/websearch/WebSearchTabViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/websearch/WebSearchTabViewModel.java @@ -39,36 +39,23 @@ public class WebSearchTabViewModel implements PreferenceTabViewModel { - private final BooleanProperty enableWebSearchProperty = - new SimpleBooleanProperty(); - private final BooleanProperty generateKeyOnImportProperty = - new SimpleBooleanProperty(); - private final BooleanProperty warnAboutDuplicatesOnImportProperty = - new SimpleBooleanProperty(); - private final BooleanProperty shouldDownloadLinkedOnlineFiles = - new SimpleBooleanProperty(); - - private final BooleanProperty useCustomDOIProperty = - new SimpleBooleanProperty(); - private final StringProperty useCustomDOINameProperty = - new SimpleStringProperty(""); - - private final ObservableList catalogs = - FXCollections.observableArrayList(); - private final BooleanProperty grobidEnabledProperty = - new SimpleBooleanProperty(); - private final StringProperty grobidURLProperty = new SimpleStringProperty( - "" - ); - - private final ListProperty apiKeys = - new SimpleListProperty<>(); + private final BooleanProperty enableWebSearchProperty = new SimpleBooleanProperty(); + private final BooleanProperty generateKeyOnImportProperty = new SimpleBooleanProperty(); + private final BooleanProperty warnAboutDuplicatesOnImportProperty = new SimpleBooleanProperty(); + private final BooleanProperty shouldDownloadLinkedOnlineFiles = new SimpleBooleanProperty(); + + private final BooleanProperty useCustomDOIProperty = new SimpleBooleanProperty(); + private final StringProperty useCustomDOINameProperty = new SimpleStringProperty(""); + + private final ObservableList catalogs = FXCollections.observableArrayList(); + private final BooleanProperty grobidEnabledProperty = new SimpleBooleanProperty(); + private final StringProperty grobidURLProperty = new SimpleStringProperty(""); + + private final ListProperty apiKeys = new SimpleListProperty<>(); private final ObjectProperty selectedApiKeyProperty = new SimpleObjectProperty<>(); - private final BooleanProperty apikeyPersistProperty = - new SimpleBooleanProperty(); - private final BooleanProperty apikeyPersistAvailableProperty = - new SimpleBooleanProperty(); + private final BooleanProperty apikeyPersistProperty = new SimpleBooleanProperty(); + private final BooleanProperty apikeyPersistAvailableProperty = new SimpleBooleanProperty(); private final DialogService dialogService; private final PreferencesService preferencesService; @@ -88,24 +75,17 @@ public WebSearchTabViewModel( this.grobidPreferences = preferencesService.getGrobidPreferences(); this.doiPreferences = preferencesService.getDOIPreferences(); this.filePreferences = preferencesService.getFilePreferences(); - this.importFormatPreferences = - preferencesService.getImportFormatPreferences(); + this.importFormatPreferences = preferencesService.getImportFormatPreferences(); } @Override public void setValues() { - enableWebSearchProperty.setValue( - importerPreferences.areImporterEnabled() - ); - generateKeyOnImportProperty.setValue( - importerPreferences.isGenerateNewKeyOnImport() - ); + enableWebSearchProperty.setValue(importerPreferences.areImporterEnabled()); + generateKeyOnImportProperty.setValue(importerPreferences.isGenerateNewKeyOnImport()); warnAboutDuplicatesOnImportProperty.setValue( importerPreferences.shouldWarnAboutDuplicatesOnImport() ); - shouldDownloadLinkedOnlineFiles.setValue( - filePreferences.shouldDownloadLinkedFiles() - ); + shouldDownloadLinkedOnlineFiles.setValue(filePreferences.shouldDownloadLinkedFiles()); useCustomDOIProperty.setValue(doiPreferences.isUseCustom()); useCustomDOINameProperty.setValue(doiPreferences.getDefaultBaseURI()); @@ -120,25 +100,16 @@ public void setValues() { ); apikeyPersistAvailableProperty.setValue(OS.isKeyringAvailable()); apikeyPersistProperty.setValue( - preferencesService - .getImporterPreferences() - .shouldPersistCustomKeys() + preferencesService.getImporterPreferences().shouldPersistCustomKeys() ); catalogs.addAll( WebFetchers - .getSearchBasedFetchers( - importFormatPreferences, - importerPreferences - ) + .getSearchBasedFetchers(importFormatPreferences, importerPreferences) .stream() .map(SearchBasedFetcher::getName) - .filter(name -> - !name.equals(CompositeSearchBasedFetcher.FETCHER_NAME) - ) + .filter(name -> !name.equals(CompositeSearchBasedFetcher.FETCHER_NAME)) .map(name -> { - boolean enabled = importerPreferences - .getCatalogs() - .contains(name); + boolean enabled = importerPreferences.getCatalogs().contains(name); return new StudyCatalogItem(name, enabled); }) .toList() @@ -147,26 +118,18 @@ public void setValues() { @Override public void storeSettings() { - importerPreferences.setImporterEnabled( - enableWebSearchProperty.getValue() - ); - importerPreferences.setGenerateNewKeyOnImport( - generateKeyOnImportProperty.getValue() - ); + importerPreferences.setImporterEnabled(enableWebSearchProperty.getValue()); + importerPreferences.setGenerateNewKeyOnImport(generateKeyOnImportProperty.getValue()); importerPreferences.setWarnAboutDuplicatesOnImport( warnAboutDuplicatesOnImportProperty.getValue() ); - filePreferences.setDownloadLinkedFiles( - shouldDownloadLinkedOnlineFiles.getValue() - ); + filePreferences.setDownloadLinkedFiles(shouldDownloadLinkedOnlineFiles.getValue()); grobidPreferences.setGrobidEnabled(grobidEnabledProperty.getValue()); grobidPreferences.setGrobidOptOut(grobidPreferences.isGrobidOptOut()); grobidPreferences.setGrobidURL(grobidURLProperty.getValue()); doiPreferences.setUseCustom(useCustomDOIProperty.get()); - doiPreferences.setDefaultBaseURI( - useCustomDOINameProperty.getValue().trim() - ); + doiPreferences.setDefaultBaseURI(useCustomDOINameProperty.getValue().trim()); importerPreferences.setCatalogs( FXCollections.observableList( catalogs @@ -179,10 +142,7 @@ public void storeSettings() { importerPreferences.setPersistCustomKeys(apikeyPersistProperty.get()); preferencesService.getImporterPreferences().getApiKeys().clear(); if (apikeyPersistAvailableProperty.get()) { - preferencesService - .getImporterPreferences() - .getApiKeys() - .addAll(apiKeys); + preferencesService.getImporterPreferences().getApiKeys().addAll(apiKeys); } } @@ -286,10 +246,7 @@ public void checkCustomApiKey() { .openConnection()).getResponseCode(); keyValid = (statusCode >= 200) && (statusCode < 300); - URLDownload.setSSLVerification( - defaultSslSocketFactory, - defaultHostnameVerifier - ); + URLDownload.setSSLVerification(defaultSslSocketFactory, defaultHostnameVerifier); } catch (IOException | UnirestException e) { keyValid = false; } diff --git a/src/main/java/org/jabref/gui/preferences/xmp/XmpPrivacyTab.java b/src/main/java/org/jabref/gui/preferences/xmp/XmpPrivacyTab.java index 2bfc6905d3f..13bcdc66f92 100644 --- a/src/main/java/org/jabref/gui/preferences/xmp/XmpPrivacyTab.java +++ b/src/main/java/org/jabref/gui/preferences/xmp/XmpPrivacyTab.java @@ -44,8 +44,7 @@ public class XmpPrivacyTab @FXML private Button addField; - private final ControlsFxVisualizer validationVisualizer = - new ControlsFxVisualizer(); + private final ControlsFxVisualizer validationVisualizer = new ControlsFxVisualizer(); public XmpPrivacyTab() { ViewLoader.view(this).root(this).load(); @@ -58,50 +57,29 @@ public String getTabName() { public void initialize() { this.viewModel = - new XmpPrivacyTabViewModel( - dialogService, - preferencesService.getXmpPreferences() - ); - - enableXmpFilter - .selectedProperty() - .bindBidirectional(viewModel.xmpFilterEnabledProperty()); - filterList - .disableProperty() - .bind(viewModel.xmpFilterEnabledProperty().not()); - addFieldName - .disableProperty() - .bind(viewModel.xmpFilterEnabledProperty().not()); - addField - .disableProperty() - .bind(viewModel.xmpFilterEnabledProperty().not()); + new XmpPrivacyTabViewModel(dialogService, preferencesService.getXmpPreferences()); + + enableXmpFilter.selectedProperty().bindBidirectional(viewModel.xmpFilterEnabledProperty()); + filterList.disableProperty().bind(viewModel.xmpFilterEnabledProperty().not()); + addFieldName.disableProperty().bind(viewModel.xmpFilterEnabledProperty().not()); + addField.disableProperty().bind(viewModel.xmpFilterEnabledProperty().not()); fieldColumn.setSortable(true); fieldColumn.setReorderable(false); - fieldColumn.setCellValueFactory(cellData -> - BindingsHelper.constantOf(cellData.getValue()) - ); + fieldColumn.setCellValueFactory(cellData -> BindingsHelper.constantOf(cellData.getValue())); new ValueTableCellFactory() .withText(FieldsUtil::getNameWithType) .install(fieldColumn); actionsColumn.setSortable(false); actionsColumn.setReorderable(false); - actionsColumn.setCellValueFactory(cellData -> - BindingsHelper.constantOf(cellData.getValue()) + actionsColumn.setCellValueFactory(cellData -> BindingsHelper.constantOf(cellData.getValue()) ); new ValueTableCellFactory() - .withGraphic(item -> - IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode() - ) - .withTooltip(item -> - Localization.lang("Remove") + " " + item.getName() - ) + .withGraphic(item -> IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode()) + .withTooltip(item -> Localization.lang("Remove") + " " + item.getName()) .withOnMouseClickedEvent(item -> - evt -> - viewModel.removeFilter( - filterList.getFocusModel().getFocusedItem() - ) + evt -> viewModel.removeFilter(filterList.getFocusModel().getFocusedItem()) ) .install(actionsColumn); @@ -109,9 +87,7 @@ public void initialize() { KeyEvent.KEY_PRESSED, event -> { if (event.getCode() == KeyCode.DELETE) { - viewModel.removeFilter( - filterList.getSelectionModel().getSelectedItem() - ); + viewModel.removeFilter(filterList.getSelectionModel().getSelectedItem()); event.consume(); } } @@ -124,9 +100,7 @@ public void initialize() { .withText(FieldsUtil::getNameWithType) .install(addFieldName); addFieldName.itemsProperty().bind(viewModel.availableFieldsProperty()); - addFieldName - .valueProperty() - .bindBidirectional(viewModel.addFieldNameProperty()); + addFieldName.valueProperty().bindBidirectional(viewModel.addFieldNameProperty()); addFieldName.setConverter(FieldsUtil.FIELD_STRING_CONVERTER); addFieldName.addEventFilter( KeyEvent.KEY_PRESSED, diff --git a/src/main/java/org/jabref/gui/preferences/xmp/XmpPrivacyTabViewModel.java b/src/main/java/org/jabref/gui/preferences/xmp/XmpPrivacyTabViewModel.java index b6a5eac0bb7..8821b8eecd8 100644 --- a/src/main/java/org/jabref/gui/preferences/xmp/XmpPrivacyTabViewModel.java +++ b/src/main/java/org/jabref/gui/preferences/xmp/XmpPrivacyTabViewModel.java @@ -21,24 +21,21 @@ public class XmpPrivacyTabViewModel implements PreferenceTabViewModel { - private final BooleanProperty xmpFilterEnabledProperty = - new SimpleBooleanProperty(); - private final ListProperty xmpFilterListProperty = - new SimpleListProperty<>(FXCollections.observableArrayList()); - private final ListProperty availableFieldsProperty = - new SimpleListProperty<>(FXCollections.observableArrayList()); - private final ObjectProperty addFieldProperty = - new SimpleObjectProperty<>(); + private final BooleanProperty xmpFilterEnabledProperty = new SimpleBooleanProperty(); + private final ListProperty xmpFilterListProperty = new SimpleListProperty<>( + FXCollections.observableArrayList() + ); + private final ListProperty availableFieldsProperty = new SimpleListProperty<>( + FXCollections.observableArrayList() + ); + private final ObjectProperty addFieldProperty = new SimpleObjectProperty<>(); private final DialogService dialogService; private final XmpPreferences xmpPreferences; private final Validator xmpFilterListValidator; - XmpPrivacyTabViewModel( - DialogService dialogService, - XmpPreferences xmpPreferences - ) { + XmpPrivacyTabViewModel(DialogService dialogService, XmpPreferences xmpPreferences) { this.dialogService = dialogService; this.xmpPreferences = xmpPreferences; @@ -59,29 +56,21 @@ public class XmpPrivacyTabViewModel implements PreferenceTabViewModel { @Override public void setValues() { - xmpFilterEnabledProperty.setValue( - xmpPreferences.shouldUseXmpPrivacyFilter() - ); + xmpFilterEnabledProperty.setValue(xmpPreferences.shouldUseXmpPrivacyFilter()); xmpFilterListProperty.clear(); xmpFilterListProperty.addAll(xmpPreferences.getXmpPrivacyFilter()); availableFieldsProperty.clear(); availableFieldsProperty.addAll(FieldFactory.getCommonFields()); - availableFieldsProperty.sort( - (Comparator.comparing(Field::getDisplayName)) - ); + availableFieldsProperty.sort((Comparator.comparing(Field::getDisplayName))); } @Override public void storeSettings() { - xmpPreferences.setUseXmpPrivacyFilter( - xmpFilterEnabledProperty.getValue() - ); + xmpPreferences.setUseXmpPrivacyFilter(xmpFilterEnabledProperty.getValue()); xmpPreferences.getXmpPrivacyFilter().clear(); - xmpPreferences - .getXmpPrivacyFilter() - .addAll(xmpFilterListProperty.getValue()); + xmpPreferences.getXmpPrivacyFilter().addAll(xmpFilterListProperty.getValue()); } public void addField() { @@ -113,14 +102,10 @@ public ValidationStatus xmpFilterListValidationStatus() { @Override public boolean validateSettings() { ValidationStatus validationStatus = xmpFilterListValidationStatus(); - if ( - xmpFilterEnabledProperty.getValue() && !validationStatus.isValid() - ) { + if (xmpFilterEnabledProperty.getValue() && !validationStatus.isValid()) { validationStatus .getHighestMessage() - .ifPresent(message -> - dialogService.showErrorDialogAndWait(message.getMessage()) - ); + .ifPresent(message -> dialogService.showErrorDialogAndWait(message.getMessage())); return false; } return true; diff --git a/src/main/java/org/jabref/gui/preview/CopyCitationAction.java b/src/main/java/org/jabref/gui/preview/CopyCitationAction.java index a33a3dfcb99..03948fabb4d 100644 --- a/src/main/java/org/jabref/gui/preview/CopyCitationAction.java +++ b/src/main/java/org/jabref/gui/preview/CopyCitationAction.java @@ -34,9 +34,7 @@ */ public class CopyCitationAction extends SimpleCommand { - private static final Logger LOGGER = LoggerFactory.getLogger( - CopyCitationAction.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(CopyCitationAction.class); private final List selectedEntries; private final CitationStyleOutputFormat outputFormat; @@ -73,12 +71,7 @@ public CopyCitationAction( public void execute() { BackgroundTask .wrap(this::generateCitations) - .onFailure(ex -> - LOGGER.error( - "Error while copying citations to the clipboard", - ex - ) - ) + .onFailure(ex -> LOGGER.error("Error while copying citations to the clipboard", ex)) .onSuccess(this::setClipBoardContent) .executeWith(taskExecutor); } @@ -91,10 +84,7 @@ private List generateCitations() throws IOException { .getPreviewPreferences() .getSelectedPreviewLayout(); - if ( - previewLayout instanceof - CitationStylePreviewLayout citationStyleLayout - ) { + if (previewLayout instanceof CitationStylePreviewLayout citationStyleLayout) { styleSource = citationStyleLayout.getSource(); } @@ -111,8 +101,7 @@ private List generateCitations() throws IOException { } } - private List generateTextBasedPreviewLayoutCitations() - throws IOException { + private List generateTextBasedPreviewLayoutCitations() throws IOException { if (stateManager.getActiveDatabase().isEmpty()) { return Collections.emptyList(); } @@ -133,10 +122,7 @@ private List generateTextBasedPreviewLayoutCitations() List citations = new ArrayList<>(selectedEntries.size()); for (BibEntry entry : selectedEntries) { citations.add( - layout.doLayout( - entry, - stateManager.getActiveDatabase().get().getDatabase() - ) + layout.doLayout(entry, stateManager.getActiveDatabase().get().getDatabase()) ); } return citations; @@ -147,17 +133,9 @@ private List generateTextBasedPreviewLayoutCitations() */ protected static ClipboardContent processPreview(List citations) { ClipboardContent content = new ClipboardContent(); - content.putHtml( - String.join( - CitationStyleOutputFormat.HTML.getLineSeparator(), - citations - ) - ); + content.putHtml(String.join(CitationStyleOutputFormat.HTML.getLineSeparator(), citations)); content.putString( - String.join( - CitationStyleOutputFormat.HTML.getLineSeparator(), - citations - ) + String.join(CitationStyleOutputFormat.HTML.getLineSeparator(), citations) ); return content; } @@ -168,10 +146,7 @@ protected static ClipboardContent processPreview(List citations) { protected static ClipboardContent processText(List citations) { ClipboardContent content = new ClipboardContent(); content.putString( - String.join( - CitationStyleOutputFormat.TEXT.getLineSeparator(), - citations - ) + String.join(CitationStyleOutputFormat.TEXT.getLineSeparator(), citations) ); return content; } @@ -195,13 +170,8 @@ protected static ClipboardContent processHtml(List citations) { OS.NEWLINE + OS.NEWLINE; - result += - String.join( - CitationStyleOutputFormat.HTML.getLineSeparator(), - citations - ); - result += - OS.NEWLINE + " " + OS.NEWLINE + "" + OS.NEWLINE; + result += String.join(CitationStyleOutputFormat.HTML.getLineSeparator(), citations); + result += OS.NEWLINE + " " + OS.NEWLINE + "" + OS.NEWLINE; ClipboardContent content = new ClipboardContent(); content.putString(result); @@ -236,10 +206,7 @@ private void setClipBoardContent(List citations) { } dialogService.notify( - Localization.lang( - "Copied %0 citations.", - String.valueOf(selectedEntries.size()) - ) + Localization.lang("Copied %0 citations.", String.valueOf(selectedEntries.size())) ); } } diff --git a/src/main/java/org/jabref/gui/preview/PreviewPanel.java b/src/main/java/org/jabref/gui/preview/PreviewPanel.java index 35e681d7f6b..aaf6a8b27e7 100644 --- a/src/main/java/org/jabref/gui/preview/PreviewPanel.java +++ b/src/main/java/org/jabref/gui/preview/PreviewPanel.java @@ -34,9 +34,7 @@ public class PreviewPanel extends VBox { - private static final Logger LOGGER = LoggerFactory.getLogger( - PreviewPanel.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(PreviewPanel.class); private final ExternalFilesEntryLinker fileLinker; private final KeyBindingRepository keyBindingRepository; @@ -69,8 +67,7 @@ public PreviewPanel( dialogService ); - PreviewPreferences previewPreferences = - preferencesService.getPreviewPreferences(); + PreviewPreferences previewPreferences = preferencesService.getPreviewPreferences(); previewView = new PreviewViewer( database, @@ -85,9 +82,7 @@ public PreviewPanel( previewView.setOnDragDetected(event -> { previewView.startFullDrag(); - Dragboard dragboard = previewView.startDragAndDrop( - TransferMode.COPY - ); + Dragboard dragboard = previewView.startDragAndDrop(TransferMode.COPY); ClipboardContent content = new ClipboardContent(); content.putHtml(previewView.getSelectionHtmlContent()); dragboard.setContent(content); @@ -97,11 +92,7 @@ public PreviewPanel( previewView.setOnDragOver(event -> { if (event.getDragboard().hasFiles()) { - event.acceptTransferModes( - TransferMode.COPY, - TransferMode.MOVE, - TransferMode.LINK - ); + event.acceptTransferModes(TransferMode.COPY, TransferMode.MOVE, TransferMode.LINK); } event.consume(); }); @@ -130,11 +121,7 @@ public PreviewPanel( } if (event.getTransferMode() == TransferMode.COPY) { LOGGER.debug("Mode Copy"); // ctrl on win, no modifier on Xubuntu - fileLinker.copyFilesToFileDirAndAddToEntry( - entry, - files, - indexingTaskManager - ); + fileLinker.copyFilesToFileDirAndAddToEntry(entry, files, indexingTaskManager); } success = true; } @@ -152,8 +139,7 @@ private void createKeyBindings() { previewView.addEventFilter( KeyEvent.KEY_PRESSED, event -> { - Optional keyBinding = - keyBindingRepository.mapToKeyBinding(event); + Optional keyBinding = keyBindingRepository.mapToKeyBinding(event); if (keyBinding.isPresent()) { switch (keyBinding.get()) { case COPY_PREVIEW: @@ -176,27 +162,19 @@ private ContextMenu createPopupMenu() { .getKeyCombination(KeyBinding.COPY_PREVIEW) .ifPresent(copyPreview::setAccelerator); copyPreview.setOnAction(event -> previewView.copyPreviewToClipBoard()); - MenuItem copySelection = new MenuItem( - Localization.lang("Copy selection") - ); - copySelection.setOnAction(event -> - previewView.copySelectionToClipBoard() - ); + MenuItem copySelection = new MenuItem(Localization.lang("Copy selection")); + copySelection.setOnAction(event -> previewView.copySelectionToClipBoard()); MenuItem printEntryPreview = new MenuItem( Localization.lang("Print entry preview"), IconTheme.JabRefIcons.PRINTED.getGraphicNode() ); printEntryPreview.setOnAction(event -> previewView.print()); - MenuItem previousPreviewLayout = new MenuItem( - Localization.lang("Previous preview layout") - ); + MenuItem previousPreviewLayout = new MenuItem(Localization.lang("Previous preview layout")); keyBindingRepository .getKeyCombination(KeyBinding.PREVIOUS_PREVIEW_LAYOUT) .ifPresent(previousPreviewLayout::setAccelerator); previousPreviewLayout.setOnAction(event -> this.previousPreviewStyle()); - MenuItem nextPreviewLayout = new MenuItem( - Localization.lang("Next preview layout") - ); + MenuItem nextPreviewLayout = new MenuItem(Localization.lang("Next preview layout")); keyBindingRepository .getKeyCombination(KeyBinding.NEXT_PREVIEW_LAYOUT) .ifPresent(nextPreviewLayout::setAccelerator); @@ -236,10 +214,7 @@ private void cyclePreview(int newPosition) { PreviewLayout layout = previewPreferences.getSelectedPreviewLayout(); previewView.setLayout(layout); dialogService.notify( - Localization.lang( - "Preview style changed to: %0", - layout.getDisplayName() - ) + Localization.lang("Preview style changed to: %0", layout.getDisplayName()) ); } } diff --git a/src/main/java/org/jabref/gui/preview/PreviewViewer.java b/src/main/java/org/jabref/gui/preview/PreviewViewer.java index 76a67918a0b..ce73d3b78e1 100644 --- a/src/main/java/org/jabref/gui/preview/PreviewViewer.java +++ b/src/main/java/org/jabref/gui/preview/PreviewViewer.java @@ -42,9 +42,7 @@ */ public class PreviewViewer extends ScrollPane implements InvalidationListener { - private static final Logger LOGGER = LoggerFactory.getLogger( - PreviewViewer.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(PreviewViewer.class); // https://stackoverflow.com/questions/5669448/get-selected-texts-html-in-div/5670825#5670825 private static final String JS_GET_SELECTION_HTML_SCRIPT = @@ -116,9 +114,7 @@ function getSelectionHtml() { """ var markInstance = new Mark(document.getElementById("content")); markInstance.unmark(%s);"""; - private static final Pattern UNESCAPED_FORWARD_SLASH = Pattern.compile( - "(? { - searchHighlightPattern = - queryNewValue.flatMap(SearchQuery::getJavaScriptPatternForWords); + searchHighlightPattern = queryNewValue.flatMap(SearchQuery::getJavaScriptPatternForWords); highlightSearchPattern(); }; @@ -179,9 +174,7 @@ public PreviewViewer( return; } if (!registered) { - stateManager - .activeSearchQueryProperty() - .addListener(listener); + stateManager.activeSearchQueryProperty().addListener(listener); registered = true; } highlightSearchPattern(); @@ -198,8 +191,7 @@ public PreviewViewer( "click", evt -> { EventTarget target = evt.getCurrentTarget(); - HTMLAnchorElement anchorElement = - (HTMLAnchorElement) target; + HTMLAnchorElement anchorElement = (HTMLAnchorElement) target; String href = anchorElement.getHref(); if (href != null) { try { @@ -210,10 +202,7 @@ public PreviewViewer( } catch (MalformedURLException exception) { LOGGER.error("Invalid URL", exception); } catch (IOException exception) { - LOGGER.error( - "Invalid URL Input", - exception - ); + LOGGER.error("Invalid URL Input", exception); } } evt.preventDefault(); @@ -229,16 +218,10 @@ public PreviewViewer( private void highlightSearchPattern() { String callbackForUnmark = ""; if (searchHighlightPattern.isPresent()) { - String javaScriptRegex = createJavaScriptRegex( - searchHighlightPattern.get() - ); - callbackForUnmark = - String.format(JS_MARK_REG_EXP_CALLBACK, javaScriptRegex); + String javaScriptRegex = createJavaScriptRegex(searchHighlightPattern.get()); + callbackForUnmark = String.format(JS_MARK_REG_EXP_CALLBACK, javaScriptRegex); } - String unmarkInstance = String.format( - JS_UNMARK_WITH_CALLBACK, - callbackForUnmark - ); + String unmarkInstance = String.format(JS_UNMARK_WITH_CALLBACK, callbackForUnmark); previewView.getEngine().executeScript(unmarkInstance); } @@ -296,10 +279,7 @@ private void update() { .onRunning(() -> setPreviewText( "" + - Localization.lang( - "Processing %0", - Localization.lang("Citation Style") - ) + + Localization.lang("Processing %0", Localization.lang("Citation Style")) + ": " + layout.getDisplayName() + " ..." + @@ -308,13 +288,8 @@ private void update() { ) .onSuccess(this::setPreviewText) .onFailure(exception -> { - LOGGER.error( - "Error while generating citation style", - exception - ); - setPreviewText( - Localization.lang("Error while generating citation style") - ); + LOGGER.error("Error while generating citation style", exception); + setPreviewText(Localization.lang("Error while generating citation style")); }) .executeWith(taskExecutor); } @@ -349,11 +324,7 @@ public void print() { .wrap(() -> { job .getJobSettings() - .setJobName( - entry - .flatMap(BibEntry::getCitationKey) - .orElse("NO ENTRY") - ); + .setJobName(entry.flatMap(BibEntry::getCitationKey).orElse("NO ENTRY")); previewView.getEngine().print(job); job.endJob(); }) @@ -372,9 +343,7 @@ public void copyPreviewToClipBoard() { ClipboardContent content = new ClipboardContent(); content.putString(document.getElementById("content").getTextContent()); content.putHtml( - (String) previewView - .getEngine() - .executeScript("document.documentElement.outerHTML") + (String) previewView.getEngine().executeScript("document.documentElement.outerHTML") ); clipBoardManager.setContent(content); @@ -394,14 +363,10 @@ public void invalidated(Observable observable) { } public String getSelectionTextContent() { - return (String) previewView - .getEngine() - .executeScript("window.getSelection().toString()"); + return (String) previewView.getEngine().executeScript("window.getSelection().toString()"); } public String getSelectionHtmlContent() { - return (String) previewView - .getEngine() - .executeScript(JS_GET_SELECTION_HTML_SCRIPT); + return (String) previewView.getEngine().executeScript(JS_GET_SELECTION_HTML_SCRIPT); } } diff --git a/src/main/java/org/jabref/gui/push/AbstractPushToApplication.java b/src/main/java/org/jabref/gui/push/AbstractPushToApplication.java index f4b4790d092..5e3e27d2341 100644 --- a/src/main/java/org/jabref/gui/push/AbstractPushToApplication.java +++ b/src/main/java/org/jabref/gui/push/AbstractPushToApplication.java @@ -23,9 +23,7 @@ */ public abstract class AbstractPushToApplication implements PushToApplication { - private static final Logger LOGGER = LoggerFactory.getLogger( - AbstractPushToApplication.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(AbstractPushToApplication.class); private static final String CITE_KEY1 = "key1"; private static final String CITE_KEY2 = "key2"; @@ -56,10 +54,7 @@ private void dissectCiteCommand() { .getExternalApplicationsPreferences() .getCiteCommand(); - if ( - preferencesCiteCommand != null && - preferencesCiteCommand.equals(cachedCiteCommand) - ) { + if (preferencesCiteCommand != null && preferencesCiteCommand.equals(cachedCiteCommand)) { return; } @@ -67,25 +62,19 @@ private void dissectCiteCommand() { int indexKey1 = cachedCiteCommand.indexOf(CITE_KEY1); int indexKey2 = cachedCiteCommand.indexOf(CITE_KEY2); - if ( - indexKey1 < 0 || - indexKey2 < 0 || - indexKey2 < (indexKey1 + CITE_KEY1.length()) - ) { + if (indexKey1 < 0 || indexKey2 < 0 || indexKey2 < (indexKey1 + CITE_KEY1.length())) { return; } cachedCitePrefix = preferencesCiteCommand.substring(0, indexKey1); cachedCiteDelimiter = preferencesCiteCommand.substring( - preferencesCiteCommand.lastIndexOf(CITE_KEY1) + - CITE_KEY1.length(), + preferencesCiteCommand.lastIndexOf(CITE_KEY1) + CITE_KEY1.length(), indexKey2 ); cachedCiteSuffix = preferencesCiteCommand.substring( - preferencesCiteCommand.lastIndexOf(CITE_KEY2) + - CITE_KEY2.length() + preferencesCiteCommand.lastIndexOf(CITE_KEY2) + CITE_KEY2.length() ); } @@ -96,10 +85,7 @@ public JabRefIcon getApplicationIcon() { @Override public String getTooltip() { - return Localization.lang( - "Push entries to external application (%0)", - getDisplayName() - ); + return Localization.lang("Push entries to external application (%0)", getDisplayName()); } @Override @@ -108,11 +94,7 @@ public Action getAction() { } @Override - public void pushEntries( - BibDatabaseContext database, - List entries, - String keyString - ) { + public void pushEntries(BibDatabaseContext database, List entries, String keyString) { couldNotPush = false; couldNotCall = false; notDefined = false; @@ -150,17 +132,11 @@ public void pushEntries( ); processBuilder.start(); } else { - ProcessBuilder processBuilder = new ProcessBuilder( - getCommandLine(keyString) - ); + ProcessBuilder processBuilder = new ProcessBuilder(getCommandLine(keyString)); processBuilder.start(); } } catch (IOException excep) { - LOGGER.warn( - "Error: Could not call executable '{}'", - commandPath, - excep - ); + LOGGER.warn("Error: Could not call executable '{}'", commandPath, excep); couldNotCall = true; } } @@ -170,27 +146,21 @@ public void onOperationCompleted() { if (notDefined) { dialogService.showErrorDialogAndWait( Localization.lang("Error pushing entries"), - Localization.lang("Path to %0 not defined", getDisplayName()) + - "." + Localization.lang("Path to %0 not defined", getDisplayName()) + "." ); } else if (couldNotCall) { dialogService.showErrorDialogAndWait( Localization.lang("Error pushing entries"), - Localization.lang("Could not call executable") + - " '" + - commandPath + - "'." + Localization.lang("Could not call executable") + " '" + commandPath + "'." ); } else if (couldNotPush) { dialogService.showErrorDialogAndWait( Localization.lang("Error pushing entries"), - Localization.lang("Could not connect to %0", getDisplayName()) + - "." + Localization.lang("Could not connect to %0", getDisplayName()) + "." ); } else { dialogService.notify( - Localization.lang("Pushed citations to %0", getDisplayName()) + - "." + Localization.lang("Pushed citations to %0", getDisplayName()) + "." ); } } @@ -252,10 +222,7 @@ protected class PushToApplicationAction implements Action { @Override public String getText() { - return Localization.lang( - "Push entries to external application (%0)", - getDisplayName() - ); + return Localization.lang("Push entries to external application (%0)", getDisplayName()); } @Override diff --git a/src/main/java/org/jabref/gui/push/PushToApplication.java b/src/main/java/org/jabref/gui/push/PushToApplication.java index 5b9754a83db..fa70fea231b 100644 --- a/src/main/java/org/jabref/gui/push/PushToApplication.java +++ b/src/main/java/org/jabref/gui/push/PushToApplication.java @@ -21,11 +21,7 @@ public interface PushToApplication { * The actual operation. This method will not be called on the event dispatch thread, so it should not do GUI * operations without utilizing invokeLater(). */ - void pushEntries( - BibDatabaseContext database, - List entries, - String keyString - ); + void pushEntries(BibDatabaseContext database, List entries, String keyString); /** * Reporting etc., this method is called on the event dispatch thread after pushEntries() returns. diff --git a/src/main/java/org/jabref/gui/push/PushToApplicationCommand.java b/src/main/java/org/jabref/gui/push/PushToApplicationCommand.java index d52a544491d..da6e441c1c4 100644 --- a/src/main/java/org/jabref/gui/push/PushToApplicationCommand.java +++ b/src/main/java/org/jabref/gui/push/PushToApplicationCommand.java @@ -31,9 +31,7 @@ */ public class PushToApplicationCommand extends SimpleCommand { - private static final Logger LOGGER = LoggerFactory.getLogger( - PushToApplicationCommand.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(PushToApplicationCommand.class); private final StateManager stateManager; private final DialogService dialogService; @@ -56,29 +54,20 @@ public PushToApplicationCommand( this.taskExecutor = taskExecutor; setApplication( - preferencesService - .getPushToApplicationPreferences() - .getActiveApplicationName() + preferencesService.getPushToApplicationPreferences().getActiveApplicationName() ); EasyBind.subscribe( - preferencesService - .getPushToApplicationPreferences() - .activeApplicationNameProperty(), + preferencesService.getPushToApplicationPreferences().activeApplicationNameProperty(), this::setApplication ); - this.executable.bind( - needsDatabase(stateManager) - .and(needsEntriesSelected(stateManager)) - ); + this.executable.bind(needsDatabase(stateManager).and(needsEntriesSelected(stateManager))); this.statusMessage.bind( BindingsHelper.ifThenElse( this.executable, "", - Localization.lang( - "This operation requires one or more entries to be selected." - ) + Localization.lang("This operation requires one or more entries to be selected.") ) ); } @@ -97,11 +86,7 @@ private void setApplication(String applicationName) { preferencesService.getKeyBindingRepository() ); PushToApplication application = PushToApplications - .getApplicationByName( - applicationName, - dialogService, - preferencesService - ) + .getApplicationByName(applicationName, dialogService, preferencesService) .orElse(new PushToEmacs(dialogService, preferencesService)); preferencesService @@ -111,17 +96,9 @@ private void setApplication(String applicationName) { reconfigurableControls.forEach(object -> { if (object instanceof MenuItem) { - factory.configureMenuItem( - application.getAction(), - this, - (MenuItem) object - ); + factory.configureMenuItem(application.getAction(), this, (MenuItem) object); } else if (object instanceof ButtonBase) { - factory.configureIconButton( - application.getAction(), - this, - (ButtonBase) object - ); + factory.configureIconButton(application.getAction(), this, (ButtonBase) object); } }); } @@ -130,10 +107,7 @@ public Action getAction() { return application.getAction(); } - private static String getKeyString( - List entries, - String delimiter - ) { + private static String getKeyString(List entries, String delimiter) { StringBuilder result = new StringBuilder(); Optional citeKey; boolean first = true; @@ -185,10 +159,7 @@ private void pushEntries() { application.pushEntries( database, stateManager.getSelectedEntries(), - getKeyString( - stateManager.getSelectedEntries(), - application.getDelimiter() - ) + getKeyString(stateManager.getSelectedEntries(), application.getDelimiter()) ); } } diff --git a/src/main/java/org/jabref/gui/push/PushToApplicationSettings.java b/src/main/java/org/jabref/gui/push/PushToApplicationSettings.java index fb8b088f167..c23b1703859 100644 --- a/src/main/java/org/jabref/gui/push/PushToApplicationSettings.java +++ b/src/main/java/org/jabref/gui/push/PushToApplicationSettings.java @@ -54,23 +54,17 @@ public PushToApplicationSettings( if (this.application.getCommandName() == null) { commandLine.append(':'); } else { - commandLine - .append(" (") - .append(this.application.getCommandName()) - .append("):"); + commandLine.append(" (").append(this.application.getCommandName()).append("):"); } commandLabel.setText(commandLine.toString()); settingsPane.add(commandLabel, 0, 0); - path.setText( - preferences.getCommandPaths().get(this.application.getDisplayName()) - ); + path.setText(preferences.getCommandPaths().get(this.application.getDisplayName())); settingsPane.add(path, 1, 0); - FileDialogConfiguration fileDialogConfiguration = - new FileDialogConfiguration.Builder() - .withInitialDirectory(filePreferences.getWorkingDirectory()) - .build(); + FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() + .withInitialDirectory(filePreferences.getWorkingDirectory()) + .build(); browse.setOnAction(e -> dialogService .showFileOpenDialog(fileDialogConfiguration) @@ -94,9 +88,7 @@ public PushToApplicationSettings( * state of the widgets in the settings panel to Globals.prefs. */ public void storeSettings() { - Map commandPaths = new HashMap<>( - preferences.getCommandPaths() - ); + Map commandPaths = new HashMap<>(preferences.getCommandPaths()); commandPaths.put(application.getDisplayName(), path.getText()); preferences.setCommandPaths(commandPaths); } diff --git a/src/main/java/org/jabref/gui/push/PushToApplications.java b/src/main/java/org/jabref/gui/push/PushToApplications.java index e5e8ad797a6..0377573adc8 100644 --- a/src/main/java/org/jabref/gui/push/PushToApplications.java +++ b/src/main/java/org/jabref/gui/push/PushToApplications.java @@ -17,8 +17,7 @@ public class PushToApplications { public static final String SUBLIME_TEXT = "Sublime Text"; public static final String TEXSHOP = "TeXShop"; - private static final List APPLICATIONS = - new ArrayList<>(); + private static final List APPLICATIONS = new ArrayList<>(); private PushToApplications() {} @@ -53,9 +52,7 @@ public static Optional getApplicationByName( ) { return getAllApplications(dialogService, preferencesService) .stream() - .filter(application -> - application.getDisplayName().equals(applicationName) - ) + .filter(application -> application.getDisplayName().equals(applicationName)) .findAny(); } } diff --git a/src/main/java/org/jabref/gui/push/PushToEmacs.java b/src/main/java/org/jabref/gui/push/PushToEmacs.java index d5136deb81e..df93e7c0e1b 100644 --- a/src/main/java/org/jabref/gui/push/PushToEmacs.java +++ b/src/main/java/org/jabref/gui/push/PushToEmacs.java @@ -21,17 +21,12 @@ public class PushToEmacs extends AbstractPushToApplication { public static final String NAME = PushToApplications.EMACS; - private static final Logger LOGGER = LoggerFactory.getLogger( - PushToEmacs.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(PushToEmacs.class); /** * @param preferencesService getPushToApplicationPreferences(), getExternalApplicationsPreferences(), and getFilePreferences() are used */ - public PushToEmacs( - DialogService dialogService, - PreferencesService preferencesService - ) { + public PushToEmacs(DialogService dialogService, PreferencesService preferencesService) { super(dialogService, preferencesService); } @@ -46,11 +41,7 @@ public JabRefIcon getApplicationIcon() { } @Override - public void pushEntries( - BibDatabaseContext database, - List entries, - String keys - ) { + public void pushEntries(BibDatabaseContext database, List entries, String keys) { couldNotPush = false; couldNotCall = false; notDefined = false; @@ -58,32 +49,23 @@ public void pushEntries( PushToApplicationPreferences pushToApplicationPreferences = preferencesService.getPushToApplicationPreferences(); - commandPath = - pushToApplicationPreferences - .getCommandPaths() - .get(this.getDisplayName()); + commandPath = pushToApplicationPreferences.getCommandPaths().get(this.getDisplayName()); if ((commandPath == null) || commandPath.trim().isEmpty()) { notDefined = true; return; } - commandPath = - pushToApplicationPreferences - .getCommandPaths() - .get(this.getDisplayName()); + commandPath = pushToApplicationPreferences.getCommandPaths().get(this.getDisplayName()); - String[] addParams = pushToApplicationPreferences - .getEmacsArguments() - .split(" "); + String[] addParams = pushToApplicationPreferences.getEmacsArguments().split(" "); try { String[] com = new String[addParams.length + 2]; com[0] = commandPath; System.arraycopy(addParams, 0, com, 1, addParams.length); // Surrounding with is handled below - String prefix = - "(with-current-buffer (window-buffer (selected-window)) (insert "; + String prefix = "(with-current-buffer (window-buffer (selected-window)) (insert "; String suffix = "))"; if (OS.WINDOWS) { diff --git a/src/main/java/org/jabref/gui/push/PushToEmacsSettings.java b/src/main/java/org/jabref/gui/push/PushToEmacsSettings.java index 995d624b947..08cd9145e54 100644 --- a/src/main/java/org/jabref/gui/push/PushToEmacsSettings.java +++ b/src/main/java/org/jabref/gui/push/PushToEmacsSettings.java @@ -18,11 +18,7 @@ public PushToEmacsSettings( PushToApplicationPreferences preferences ) { super(application, dialogService, filePreferences, preferences); - settingsPane.add( - new Label(Localization.lang("Additional parameters") + ":"), - 0, - 1 - ); + settingsPane.add(new Label(Localization.lang("Additional parameters") + ":"), 0, 1); settingsPane.add(additionalParams, 1, 1); additionalParams.setText(preferences.getEmacsArguments()); } diff --git a/src/main/java/org/jabref/gui/push/PushToLyx.java b/src/main/java/org/jabref/gui/push/PushToLyx.java index e855cb88ac8..694a2c9e315 100644 --- a/src/main/java/org/jabref/gui/push/PushToLyx.java +++ b/src/main/java/org/jabref/gui/push/PushToLyx.java @@ -22,14 +22,9 @@ public class PushToLyx extends AbstractPushToApplication { public static final String NAME = PushToApplications.LYX; - private static final Logger LOGGER = LoggerFactory.getLogger( - PushToLyx.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(PushToLyx.class); - public PushToLyx( - DialogService dialogService, - PreferencesService preferencesService - ) { + public PushToLyx(DialogService dialogService, PreferencesService preferencesService) { super(dialogService, preferencesService); } @@ -48,9 +43,7 @@ public void onOperationCompleted() { if (couldNotPush) { dialogService.showErrorDialogAndWait( Localization.lang("Error pushing entries"), - Localization.lang( - "Verify that LyX is running and that the lyxpipe is valid." - ) + + Localization.lang("Verify that LyX is running and that the lyxpipe is valid.") + "[" + commandPath + "]" @@ -118,8 +111,7 @@ public void pushEntries( FileWriter fw = new FileWriter(lyxpipe, StandardCharsets.UTF_8); BufferedWriter lyxOut = new BufferedWriter(fw) ) { - String citeStr = - "LYXCMD:sampleclient:citation-insert:" + keyString; + String citeStr = "LYXCMD:sampleclient:citation-insert:" + keyString; lyxOut.write(citeStr + "\n"); } catch (IOException excep) { couldNotCall = true; diff --git a/src/main/java/org/jabref/gui/push/PushToSublimeText.java b/src/main/java/org/jabref/gui/push/PushToSublimeText.java index c1eda0aba8e..f2bb764cf8a 100644 --- a/src/main/java/org/jabref/gui/push/PushToSublimeText.java +++ b/src/main/java/org/jabref/gui/push/PushToSublimeText.java @@ -21,14 +21,9 @@ public class PushToSublimeText extends AbstractPushToApplication { public static final String NAME = PushToApplications.SUBLIME_TEXT; - private static final Logger LOGGER = LoggerFactory.getLogger( - PushToSublimeText.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(PushToSublimeText.class); - public PushToSublimeText( - DialogService dialogService, - PreferencesService preferencesService - ) { + public PushToSublimeText(DialogService dialogService, PreferencesService preferencesService) { super(dialogService, preferencesService); } @@ -43,11 +38,7 @@ public JabRefIcon getApplicationIcon() { } @Override - public void pushEntries( - BibDatabaseContext database, - List entries, - String keyString - ) { + public void pushEntries(BibDatabaseContext database, List entries, String keyString) { couldNotPush = false; couldNotCall = false; notDefined = false; @@ -64,13 +55,8 @@ public void pushEntries( return; } try { - LOGGER.debug( - "Sublime string: {}", - String.join(" ", getCommandLine(keyString)) - ); - ProcessBuilder processBuilder = new ProcessBuilder( - getCommandLine(keyString) - ); + LOGGER.debug("Sublime string: {}", String.join(" ", getCommandLine(keyString))); + ProcessBuilder processBuilder = new ProcessBuilder(getCommandLine(keyString)); processBuilder.inheritIO(); Map envs = processBuilder.environment(); envs.put("PATH", Path.of(commandPath).getParent().toString()); @@ -88,11 +74,7 @@ public void pushEntries( JabRefExecutorService.INSTANCE.execute(streamGobblerInput); JabRefExecutorService.INSTANCE.execute(streamGobblerError); } catch (IOException excep) { - LOGGER.warn( - "Error: Could not call executable '{}'", - commandPath, - excep - ); + LOGGER.warn("Error: Could not call executable '{}'", commandPath, excep); couldNotCall = true; } } diff --git a/src/main/java/org/jabref/gui/push/PushToTeXstudio.java b/src/main/java/org/jabref/gui/push/PushToTeXstudio.java index 30daf218884..75c6c649e31 100644 --- a/src/main/java/org/jabref/gui/push/PushToTeXstudio.java +++ b/src/main/java/org/jabref/gui/push/PushToTeXstudio.java @@ -9,10 +9,7 @@ public class PushToTeXstudio extends AbstractPushToApplication { public static final String NAME = PushToApplications.TEXSTUDIO; - public PushToTeXstudio( - DialogService dialogService, - PreferencesService preferencesService - ) { + public PushToTeXstudio(DialogService dialogService, PreferencesService preferencesService) { super(dialogService, preferencesService); } @@ -31,12 +28,7 @@ protected String[] getCommandLine(String keyString) { return new String[] { commandPath, "--insert-cite", - String.format( - "%s%s%s", - getCitePrefix(), - keyString, - getCiteSuffix() - ), + String.format("%s%s%s", getCitePrefix(), keyString, getCiteSuffix()), }; } } diff --git a/src/main/java/org/jabref/gui/push/PushToTexShop.java b/src/main/java/org/jabref/gui/push/PushToTexShop.java index b971332b7de..1acdb26ccd0 100644 --- a/src/main/java/org/jabref/gui/push/PushToTexShop.java +++ b/src/main/java/org/jabref/gui/push/PushToTexShop.java @@ -19,14 +19,9 @@ public class PushToTexShop extends AbstractPushToApplication { public static final String NAME = PushToApplications.TEXSHOP; - private static final Logger LOGGER = LoggerFactory.getLogger( - PushToTexShop.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(PushToTexShop.class); - public PushToTexShop( - DialogService dialogService, - PreferencesService preferencesService - ) { + public PushToTexShop(DialogService dialogService, PreferencesService preferencesService) { super(dialogService, preferencesService); } @@ -41,11 +36,7 @@ public JabRefIcon getApplicationIcon() { } @Override - public void pushEntries( - BibDatabaseContext database, - List entries, - String keyString - ) { + public void pushEntries(BibDatabaseContext database, List entries, String keyString) { couldNotPush = false; couldNotCall = false; notDefined = false; @@ -57,13 +48,8 @@ public void pushEntries( .get(this.getDisplayName()); try { - LOGGER.debug( - "TexShop string: {}", - String.join(" ", getCommandLine(keyString)) - ); - ProcessBuilder processBuilder = new ProcessBuilder( - getCommandLine(keyString) - ); + LOGGER.debug("TexShop string: {}", String.join(" ", getCommandLine(keyString))); + ProcessBuilder processBuilder = new ProcessBuilder(getCommandLine(keyString)); processBuilder.inheritIO(); Process process = processBuilder.start(); StreamGobbler streamGobblerInput = new StreamGobbler( @@ -78,11 +64,7 @@ public void pushEntries( JabRefExecutorService.INSTANCE.execute(streamGobblerInput); JabRefExecutorService.INSTANCE.execute(streamGobblerError); } catch (IOException excep) { - LOGGER.warn( - "Error: Could not call executable '{}'", - commandPath, - excep - ); + LOGGER.warn("Error: Could not call executable '{}'", commandPath, excep); couldNotCall = true; } } @@ -111,9 +93,7 @@ protected String[] getCommandLine(String keyString) { } else { dialogService.showInformationDialogAndWait( Localization.lang("Push to application"), - Localization.lang( - "Pushing citations to TeXShop is only possible on macOS!" - ) + Localization.lang("Pushing citations to TeXShop is only possible on macOS!") ); return new String[] {}; } diff --git a/src/main/java/org/jabref/gui/push/PushToTexmaker.java b/src/main/java/org/jabref/gui/push/PushToTexmaker.java index 12351050d68..e846b52debe 100644 --- a/src/main/java/org/jabref/gui/push/PushToTexmaker.java +++ b/src/main/java/org/jabref/gui/push/PushToTexmaker.java @@ -12,10 +12,7 @@ public class PushToTexmaker extends AbstractPushToApplication { public static final String NAME = "Texmaker"; - public PushToTexmaker( - DialogService dialogService, - PreferencesService preferencesService - ) { + public PushToTexmaker(DialogService dialogService, PreferencesService preferencesService) { super(dialogService, preferencesService); } diff --git a/src/main/java/org/jabref/gui/push/PushToVim.java b/src/main/java/org/jabref/gui/push/PushToVim.java index e0e14295924..6c3ddeca6f2 100644 --- a/src/main/java/org/jabref/gui/push/PushToVim.java +++ b/src/main/java/org/jabref/gui/push/PushToVim.java @@ -20,14 +20,9 @@ public class PushToVim extends AbstractPushToApplication { public static final String NAME = PushToApplications.VIM; - private static final Logger LOGGER = LoggerFactory.getLogger( - PushToVim.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(PushToVim.class); - public PushToVim( - DialogService dialogService, - PreferencesService preferencesService - ) { + public PushToVim(DialogService dialogService, PreferencesService preferencesService) { super(dialogService, preferencesService); } @@ -55,11 +50,7 @@ public PushToApplicationSettings getSettings( } @Override - public void pushEntries( - BibDatabaseContext database, - List entries, - String keys - ) { + public void pushEntries(BibDatabaseContext database, List entries, String keys) { couldNotPush = false; couldNotCall = false; notDefined = false; @@ -79,9 +70,7 @@ public void pushEntries( String[] com = new String[] { commandPath, "--servername", - preferencesService - .getPushToApplicationPreferences() - .getVimServer(), + preferencesService.getPushToApplicationPreferences().getVimServer(), "--remote-send", "a" + getCitePrefix() + keys + getCiteSuffix(), }; diff --git a/src/main/java/org/jabref/gui/push/PushToVimSettings.java b/src/main/java/org/jabref/gui/push/PushToVimSettings.java index 58cb9fdcb53..0581c7233d1 100644 --- a/src/main/java/org/jabref/gui/push/PushToVimSettings.java +++ b/src/main/java/org/jabref/gui/push/PushToVimSettings.java @@ -18,11 +18,7 @@ public PushToVimSettings( PushToApplicationPreferences preferences ) { super(application, dialogService, filePreferences, preferences); - settingsPane.add( - new Label(Localization.lang("Vim server name") + ":"), - 0, - 1 - ); + settingsPane.add(new Label(Localization.lang("Vim server name") + ":"), 0, 1); settingsPane.add(vimServer, 1, 1); vimServer.setText(preferences.getVimServer()); } diff --git a/src/main/java/org/jabref/gui/push/PushToWinEdt.java b/src/main/java/org/jabref/gui/push/PushToWinEdt.java index b6728dbd0fa..949965f722d 100644 --- a/src/main/java/org/jabref/gui/push/PushToWinEdt.java +++ b/src/main/java/org/jabref/gui/push/PushToWinEdt.java @@ -9,10 +9,7 @@ public class PushToWinEdt extends AbstractPushToApplication { public static final String NAME = PushToApplications.WIN_EDT; - public PushToWinEdt( - DialogService dialogService, - PreferencesService preferencesService - ) { + public PushToWinEdt(DialogService dialogService, PreferencesService preferencesService) { super(dialogService, preferencesService); } diff --git a/src/main/java/org/jabref/gui/remote/CLIMessageHandler.java b/src/main/java/org/jabref/gui/remote/CLIMessageHandler.java index 016df2a44d9..91f41983220 100644 --- a/src/main/java/org/jabref/gui/remote/CLIMessageHandler.java +++ b/src/main/java/org/jabref/gui/remote/CLIMessageHandler.java @@ -15,9 +15,7 @@ public class CLIMessageHandler implements RemoteMessageHandler { - private static final Logger LOGGER = LoggerFactory.getLogger( - CLIMessageHandler.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(CLIMessageHandler.class); private final PreferencesService preferencesService; private final FileUpdateMonitor fileUpdateMonitor; diff --git a/src/main/java/org/jabref/gui/search/GlobalSearchBar.java b/src/main/java/org/jabref/gui/search/GlobalSearchBar.java index f6782af6905..d70b237a5c1 100644 --- a/src/main/java/org/jabref/gui/search/GlobalSearchBar.java +++ b/src/main/java/org/jabref/gui/search/GlobalSearchBar.java @@ -78,15 +78,13 @@ public class GlobalSearchBar extends HBox { - private static final Logger LOGGER = LoggerFactory.getLogger( - GlobalSearchBar.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(GlobalSearchBar.class); private static final int SEARCH_DELAY = 400; - private static final PseudoClass CLASS_NO_RESULTS = - PseudoClass.getPseudoClass("emptyResult"); - private static final PseudoClass CLASS_RESULTS_FOUND = - PseudoClass.getPseudoClass("emptyResult"); + private static final PseudoClass CLASS_NO_RESULTS = PseudoClass.getPseudoClass("emptyResult"); + private static final PseudoClass CLASS_RESULTS_FOUND = PseudoClass.getPseudoClass( + "emptyResult" + ); private final CustomTextField searchField = SearchTextField.create(); private final ToggleButton caseSensitiveButton; @@ -106,8 +104,7 @@ public class GlobalSearchBar extends HBox { private final SearchPreferences searchPreferences; private final DialogService dialogService; - private final BooleanProperty globalSearchActive = - new SimpleBooleanProperty(false); + private final BooleanProperty globalSearchActive = new SimpleBooleanProperty(false); private GlobalSearchResultDialog globalSearchResultDialog; public GlobalSearchBar( @@ -134,13 +131,11 @@ public GlobalSearchBar( searchFieldTooltip.setMaxHeight(10); updateHintVisibility(); - KeyBindingRepository keyBindingRepository = - preferencesService.getKeyBindingRepository(); + KeyBindingRepository keyBindingRepository = preferencesService.getKeyBindingRepository(); searchField.addEventFilter( KeyEvent.KEY_PRESSED, event -> { - Optional keyBinding = - keyBindingRepository.mapToKeyBinding(event); + Optional keyBinding = keyBindingRepository.mapToKeyBinding(event); if (keyBinding.isPresent()) { if (keyBinding.get() == KeyBinding.CLOSE) { // Clear search and select first entry, if available @@ -157,39 +152,28 @@ public GlobalSearchBar( ); searchField.setContextMenu( - SearchFieldRightClickMenu.create( - keyBindingRepository, - stateManager, - searchField, - frame - ) + SearchFieldRightClickMenu.create(keyBindingRepository, stateManager, searchField, frame) ); ObservableList search = stateManager.getWholeSearchHistory(); - search.addListener((ListChangeListener.Change< - ? extends String - > change) -> { - searchField.setContextMenu( - SearchFieldRightClickMenu.create( - keyBindingRepository, - stateManager, - searchField, - frame - ) - ); - } - ); + search.addListener((ListChangeListener.Change change) -> { + searchField.setContextMenu( + SearchFieldRightClickMenu.create( + keyBindingRepository, + stateManager, + searchField, + frame + ) + ); + }); ClipBoardManager.addX11Support(searchField); regularExpressionButton = IconTheme.JabRefIcons.REG_EX.asToggleButton(); - caseSensitiveButton = - IconTheme.JabRefIcons.CASE_SENSITIVE.asToggleButton(); + caseSensitiveButton = IconTheme.JabRefIcons.CASE_SENSITIVE.asToggleButton(); fulltextButton = IconTheme.JabRefIcons.FULLTEXT.asToggleButton(); - openGlobalSearchButton = - IconTheme.JabRefIcons.OPEN_GLOBAL_SEARCH.asButton(); - keepSearchString = - IconTheme.JabRefIcons.KEEP_SEARCH_STRING.asToggleButton(); + openGlobalSearchButton = IconTheme.JabRefIcons.OPEN_GLOBAL_SEARCH.asButton(); + keepSearchString = IconTheme.JabRefIcons.KEEP_SEARCH_STRING.asToggleButton(); initSearchModifierButtons(); @@ -211,12 +195,7 @@ public GlobalSearchBar( keepSearchString.visibleProperty().bind(focusedOrActive); StackPane modifierButtons = new StackPane( - new HBox( - regularExpressionButton, - caseSensitiveButton, - fulltextButton, - keepSearchString - ) + new HBox(regularExpressionButton, caseSensitiveButton, fulltextButton, keepSearchString) ); modifierButtons.setAlignment(Pos.CENTER); searchField.setRight(new HBox(searchField.getRight(), modifierButtons)); @@ -227,30 +206,20 @@ public GlobalSearchBar( regexValidator = new FunctionBasedValidator<>( searchField.textProperty(), - query -> - !(regularExpressionButton.isSelected() && !validRegex()), - ValidationMessage.error( - Localization.lang("Invalid regular expression") - ) + query -> !(regularExpressionButton.isSelected() && !validRegex()), + ValidationMessage.error(Localization.lang("Invalid regular expression")) ); ControlsFxVisualizer visualizer = new ControlsFxVisualizer(); visualizer.setDecoration(new IconValidationDecorator(Pos.CENTER_LEFT)); Platform.runLater(() -> - visualizer.initVisualization( - regexValidator.getValidationStatus(), - searchField - ) + visualizer.initVisualization(regexValidator.getValidationStatus(), searchField) ); - this.getChildren() - .addAll(searchField, openGlobalSearchButton, currentResults); + this.getChildren().addAll(searchField, openGlobalSearchButton, currentResults); this.setSpacing(4.0); this.setAlignment(Pos.CENTER_LEFT); - Timer searchTask = FxTimer.create( - Duration.ofMillis(SEARCH_DELAY), - this::updateSearchQuery - ); + Timer searchTask = FxTimer.create(Duration.ofMillis(SEARCH_DELAY), this::updateSearchQuery); BindingsHelper.bindBidirectional( stateManager.activeSearchQueryProperty(), searchField.textProperty(), @@ -282,12 +251,8 @@ public GlobalSearchBar( .focusedProperty() .addListener((obs, oldValue, newValue) -> { // Focus lost can be derived by checking that there is no newValue (or the text is empty) - if ( - oldValue && !(newValue || searchField.getText().isBlank()) - ) { - this.stateManager.addSearchHistory( - searchField.textProperty().get() - ); + if (oldValue && !(newValue || searchField.getText().isBlank())) { + this.stateManager.addSearchHistory(searchField.textProperty().get()); } }); } @@ -301,12 +266,8 @@ private void updateSearchResultsForQuery(SearchQuery query) { } private void initSearchModifierButtons() { - regularExpressionButton.setSelected( - searchPreferences.isRegularExpression() - ); - regularExpressionButton.setTooltip( - new Tooltip(Localization.lang("regular expression")) - ); + regularExpressionButton.setSelected(searchPreferences.isRegularExpression()); + regularExpressionButton.setTooltip(new Tooltip(Localization.lang("regular expression"))); initSearchModifierButton(regularExpressionButton); regularExpressionButton.setOnAction(event -> { searchPreferences.setSearchFlag( @@ -317,9 +278,7 @@ private void initSearchModifierButtons() { }); caseSensitiveButton.setSelected(searchPreferences.isCaseSensitive()); - caseSensitiveButton.setTooltip( - new Tooltip(Localization.lang("Case sensitive")) - ); + caseSensitiveButton.setTooltip(new Tooltip(Localization.lang("Case sensitive"))); initSearchModifierButton(caseSensitiveButton); caseSensitiveButton.setOnAction(event -> { searchPreferences.setSearchFlag( @@ -330,9 +289,7 @@ private void initSearchModifierButtons() { }); fulltextButton.setSelected(searchPreferences.isFulltext()); - fulltextButton.setTooltip( - new Tooltip(Localization.lang("Fulltext search")) - ); + fulltextButton.setTooltip(new Tooltip(Localization.lang("Fulltext search"))); initSearchModifierButton(fulltextButton); fulltextButton.setOnAction(event -> { searchPreferences.setSearchFlag( @@ -342,13 +299,9 @@ private void initSearchModifierButtons() { updateSearchQuery(); }); - keepSearchString.setSelected( - searchPreferences.shouldKeepSearchString() - ); + keepSearchString.setSelected(searchPreferences.shouldKeepSearchString()); keepSearchString.setTooltip( - new Tooltip( - Localization.lang("Keep search string across libraries") - ) + new Tooltip(Localization.lang("Keep search string across libraries")) ); initSearchModifierButton(keepSearchString); keepSearchString.setOnAction(evt -> { @@ -359,19 +312,14 @@ private void initSearchModifierButtons() { updateSearchQuery(); }); - openGlobalSearchButton - .disableProperty() - .bindBidirectional(globalSearchActive); + openGlobalSearchButton.disableProperty().bindBidirectional(globalSearchActive); openGlobalSearchButton.setTooltip( - new Tooltip( - Localization.lang("Search across libraries in a new window") - ) + new Tooltip(Localization.lang("Search across libraries in a new window")) ); initSearchModifierButton(openGlobalSearchButton); openGlobalSearchButton.setOnAction(evt -> { globalSearchActive.setValue(true); - globalSearchResultDialog = - new GlobalSearchResultDialog(undoManager); + globalSearchResultDialog = new GlobalSearchResultDialog(undoManager); updateSearchQuery(); dialogService.showCustomDialogAndWait(globalSearchResultDialog); globalSearchActive.setValue(false); @@ -413,9 +361,7 @@ public void updateSearchQuery() { // Invalid regular expression if (!regexValidator.getValidationStatus().isValid()) { - currentResults.setText( - Localization.lang("Invalid regular expression") - ); + currentResults.setText(Localization.lang("Invalid regular expression")); return; } @@ -445,25 +391,17 @@ private void informUserAboutInvalidSearchQuery() { stateManager.clearSearchQuery(); - String illegalSearch = Localization.lang( - "Search failed: illegal search expression" - ); + String illegalSearch = Localization.lang("Search failed: illegal search expression"); currentResults.setText(illegalSearch); } public void setAutoCompleter(SuggestionProvider searchCompleter) { - if ( - preferencesService.getAutoCompletePreferences().shouldAutoComplete() - ) { + if (preferencesService.getAutoCompletePreferences().shouldAutoComplete()) { AutoCompletionTextInputBinding autoComplete = AutoCompletionTextInputBinding.autoComplete( searchField, searchCompleter::provideSuggestions, - new PersonNameStringConverter( - false, - false, - AutoCompleteFirstNameMode.BOTH - ), + new PersonNameStringConverter(false, false, AutoCompleteFirstNameMode.BOTH), new AppendPersonNamesStrategy() ); AutoCompletePopup popup = getPopup(autoComplete); @@ -475,37 +413,25 @@ public void setAutoCompleter(SuggestionProvider searchCompleter) { * The popup has private access in {@link AutoCompletionBinding}, so we use reflection to access it. */ @SuppressWarnings("unchecked") - private AutoCompletePopup getPopup( - AutoCompletionBinding autoCompletionBinding - ) { + private AutoCompletePopup getPopup(AutoCompletionBinding autoCompletionBinding) { try { // TODO: reflective access, should be removed Field privatePopup = - AutoCompletionBinding.class.getDeclaredField( - "autoCompletionPopup" - ); + AutoCompletionBinding.class.getDeclaredField("autoCompletionPopup"); privatePopup.setAccessible(true); - return (AutoCompletePopup) privatePopup.get( - autoCompletionBinding - ); + return (AutoCompletePopup) privatePopup.get(autoCompletionBinding); } catch (IllegalAccessException | NoSuchFieldException e) { LOGGER.error("Could not get access to auto completion popup", e); return new AutoCompletePopup<>(); } } - private void updateResults( - int matched, - TextFlow description, - boolean grammarBasedSearch - ) { + private void updateResults(int matched, TextFlow description, boolean grammarBasedSearch) { if (matched == 0) { currentResults.setText(Localization.lang("No results found.")); searchField.pseudoClassStateChanged(CLASS_NO_RESULTS, true); } else { - currentResults.setText( - Localization.lang("Found %0 results.", String.valueOf(matched)) - ); + currentResults.setText(Localization.lang("Found %0 results.", String.valueOf(matched))); searchField.pseudoClassStateChanged(CLASS_RESULTS_FOUND, true); } if (grammarBasedSearch) { @@ -520,16 +446,13 @@ private void updateResults( } private void setSearchFieldHintTooltip(TextFlow description) { - if ( - preferencesService - .getWorkspacePreferences() - .shouldShowAdvancedHints() - ) { + if (preferencesService.getWorkspacePreferences().shouldShowAdvancedHints()) { String genericDescription = Localization.lang( "Hint:\n\nTo search all fields for Smith, enter:\nsmith\n\nTo search the field author for Smith and the field title for electrical, enter:\nauthor=Smith and title=electrical" ); - List genericDescriptionTexts = - TooltipTextUtil.createTextsFromHtml(genericDescription); + List genericDescriptionTexts = TooltipTextUtil.createTextsFromHtml( + genericDescription + ); if (description == null) { TextFlow emptyHintTooltip = new TextFlow(); @@ -552,13 +475,10 @@ public void setSearchTerm(String searchTerm) { return; } - DefaultTaskExecutor.runInJavaFXThread(() -> - searchField.setText(searchTerm) - ); + DefaultTaskExecutor.runInJavaFXThread(() -> searchField.setText(searchTerm)); } - private static class SearchPopupSkin - implements Skin> { + private static class SearchPopupSkin implements Skin> { private final AutoCompletePopup control; private final ListView suggestionList; @@ -572,9 +492,7 @@ public SearchPopupSkin(AutoCompletePopup control) { .add( Objects .requireNonNull( - AutoCompletionBinding.class.getResource( - "autocompletion.css" - ) + AutoCompletionBinding.class.getResource("autocompletion.css") ) .toExternalForm() ); @@ -591,12 +509,9 @@ public SearchPopupSkin(AutoCompletePopup control) { this.suggestionList.setCellFactory( TextFieldListCell.forListView(control.getConverter()) ); - this.suggestionList.prefWidthProperty() - .bind(control.prefWidthProperty()); - this.suggestionList.maxWidthProperty() - .bind(control.maxWidthProperty()); - this.suggestionList.minWidthProperty() - .bind(control.minWidthProperty()); + this.suggestionList.prefWidthProperty().bind(control.prefWidthProperty()); + this.suggestionList.maxWidthProperty().bind(control.maxWidthProperty()); + this.suggestionList.minWidthProperty().bind(control.minWidthProperty()); this.container = new BorderPane(); this.container.setCenter(suggestionList); @@ -608,8 +523,7 @@ private void registerEventListener() { this.suggestionList.setOnMouseClicked(me -> { if (me.getButton() == MouseButton.PRIMARY) { this.onSuggestionChosen( - this.suggestionList.getSelectionModel() - .getSelectedItem() + this.suggestionList.getSelectionModel().getSelectedItem() ); } }); @@ -618,8 +532,7 @@ private void registerEventListener() { case TAB: case ENTER: this.onSuggestionChosen( - this.suggestionList.getSelectionModel() - .getSelectedItem() + this.suggestionList.getSelectionModel().getSelectedItem() ); break; case ESCAPE: @@ -635,10 +548,7 @@ private void registerEventListener() { private void onSuggestionChosen(T suggestion) { if (suggestion != null) { - Event.fireEvent( - this.control, - new AutoCompletePopup.SuggestionEvent<>(suggestion) - ); + Event.fireEvent(this.control, new AutoCompletePopup.SuggestionEvent<>(suggestion)); } } diff --git a/src/main/java/org/jabref/gui/search/GlobalSearchResultDialog.java b/src/main/java/org/jabref/gui/search/GlobalSearchResultDialog.java index 654e7e8fa76..df63f3c0bbc 100644 --- a/src/main/java/org/jabref/gui/search/GlobalSearchResultDialog.java +++ b/src/main/java/org/jabref/gui/search/GlobalSearchResultDialog.java @@ -69,9 +69,7 @@ private void initialize() { taskExecutor ); previewViewer.setLayout( - preferencesService - .getPreviewPreferences() - .getSelectedPreviewLayout() + preferencesService.getPreviewPreferences().getSelectedPreviewLayout() ); SearchResultsTableDataModel model = new SearchResultsTableDataModel( @@ -89,15 +87,11 @@ private void initialize() { taskExecutor ); - resultsTable - .getColumns() - .removeIf(SpecialFieldColumn.class::isInstance); + resultsTable.getColumns().removeIf(SpecialFieldColumn.class::isInstance); resultsTable.getSelectionModel().selectFirst(); if (resultsTable.getSelectionModel().getSelectedItem() != null) { - previewViewer.setEntry( - resultsTable.getSelectionModel().getSelectedItem().getEntry() - ); + previewViewer.setEntry(resultsTable.getSelectionModel().getSelectedItem().getEntry()); } resultsTable @@ -135,15 +129,11 @@ private void initialize() { event -> { getDialogPane() .setPrefHeight( - preferencesService - .getSearchPreferences() - .getSearchWindowHeight() + preferencesService.getSearchPreferences().getSearchWindowHeight() ); getDialogPane() .setPrefWidth( - preferencesService - .getSearchPreferences() - .getSearchWindowWidth() + preferencesService.getSearchPreferences().getSearchWindowWidth() ); } ); @@ -154,12 +144,8 @@ private void initialize() { .addEventHandler( WindowEvent.WINDOW_HIDDEN, event -> { - preferencesService - .getSearchPreferences() - .setSearchWindowHeight(getHeight()); - preferencesService - .getSearchPreferences() - .setSearchWindowWidth(getWidth()); + preferencesService.getSearchPreferences().setSearchWindowHeight(getHeight()); + preferencesService.getSearchPreferences().setSearchWindowWidth(getWidth()); } ); } diff --git a/src/main/java/org/jabref/gui/search/GlobalSearchResultDialogViewModel.java b/src/main/java/org/jabref/gui/search/GlobalSearchResultDialogViewModel.java index 81162ddafcf..8e9c47af9ab 100644 --- a/src/main/java/org/jabref/gui/search/GlobalSearchResultDialogViewModel.java +++ b/src/main/java/org/jabref/gui/search/GlobalSearchResultDialogViewModel.java @@ -9,22 +9,15 @@ public class GlobalSearchResultDialogViewModel { - private final BibDatabaseContext searchDatabaseContext = - new BibDatabaseContext(); + private final BibDatabaseContext searchDatabaseContext = new BibDatabaseContext(); private final BooleanProperty keepOnTop = new SimpleBooleanProperty(); - public GlobalSearchResultDialogViewModel( - PreferencesService preferencesService - ) { - SearchPreferences searchPreferences = - preferencesService.getSearchPreferences(); + public GlobalSearchResultDialogViewModel(PreferencesService preferencesService) { + SearchPreferences searchPreferences = preferencesService.getSearchPreferences(); keepOnTop.set(searchPreferences.shouldKeepWindowOnTop()); - EasyBind.subscribe( - this.keepOnTop, - searchPreferences::setKeepWindowOnTop - ); + EasyBind.subscribe(this.keepOnTop, searchPreferences::setKeepWindowOnTop); } public BibDatabaseContext getSearchDatabaseContext() { diff --git a/src/main/java/org/jabref/gui/search/RebuildFulltextSearchIndexAction.java b/src/main/java/org/jabref/gui/search/RebuildFulltextSearchIndexAction.java index e50eb69e85a..9b28d4afc5d 100644 --- a/src/main/java/org/jabref/gui/search/RebuildFulltextSearchIndexAction.java +++ b/src/main/java/org/jabref/gui/search/RebuildFulltextSearchIndexAction.java @@ -18,9 +18,7 @@ public class RebuildFulltextSearchIndexAction extends SimpleCommand { - private static final Logger LOGGER = LoggerFactory.getLogger( - LibraryTab.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(LibraryTab.class); private final StateManager stateManager; private final GetCurrentLibraryTab currentLibraryTab; @@ -62,17 +60,13 @@ public void init() { databaseContext = stateManager.getActiveDatabase().get(); boolean confirm = dialogService.showConfirmationDialogAndWait( Localization.lang("Rebuild fulltext search index"), - Localization.lang( - "Rebuild fulltext search index for current library?" - ) + Localization.lang("Rebuild fulltext search index for current library?") ); if (!confirm) { shouldContinue = false; return; } - dialogService.notify( - Localization.lang("Rebuilding fulltext search index...") - ); + dialogService.notify(Localization.lang("Rebuilding fulltext search index...")); } private void rebuildIndex() { @@ -87,14 +81,9 @@ private void rebuildIndex() { currentLibraryTab .get() .getIndexingTaskManager() - .updateIndex( - PdfIndexer.of(databaseContext, filePreferences), - databaseContext - ); + .updateIndex(PdfIndexer.of(databaseContext, filePreferences), databaseContext); } catch (IOException e) { - dialogService.notify( - Localization.lang("Failed to access fulltext search index") - ); + dialogService.notify(Localization.lang("Failed to access fulltext search index")); LOGGER.error("Failed to access fulltext search index", e); } } diff --git a/src/main/java/org/jabref/gui/search/SearchDisplayMode.java b/src/main/java/org/jabref/gui/search/SearchDisplayMode.java index b98dbe6f12d..c023b1b09d2 100644 --- a/src/main/java/org/jabref/gui/search/SearchDisplayMode.java +++ b/src/main/java/org/jabref/gui/search/SearchDisplayMode.java @@ -7,14 +7,8 @@ * Collects the possible search modes */ public enum SearchDisplayMode { - FLOAT( - () -> Localization.lang("Float"), - () -> Localization.lang("Gray out non-hits") - ), - FILTER( - () -> Localization.lang("Filter"), - () -> Localization.lang("Hide non-hits") - ); + FLOAT(() -> Localization.lang("Float"), () -> Localization.lang("Gray out non-hits")), + FILTER(() -> Localization.lang("Filter"), () -> Localization.lang("Hide non-hits")); private final Supplier displayName; private final Supplier toolTipText; @@ -22,10 +16,7 @@ public enum SearchDisplayMode { /** * We have to use supplier for the localized text so that language changes are correctly reflected. */ - SearchDisplayMode( - Supplier displayName, - Supplier toolTipText - ) { + SearchDisplayMode(Supplier displayName, Supplier toolTipText) { this.displayName = displayName; this.toolTipText = toolTipText; } diff --git a/src/main/java/org/jabref/gui/search/SearchFieldRightClickMenu.java b/src/main/java/org/jabref/gui/search/SearchFieldRightClickMenu.java index 9ed8c583f01..fab86321571 100644 --- a/src/main/java/org/jabref/gui/search/SearchFieldRightClickMenu.java +++ b/src/main/java/org/jabref/gui/search/SearchFieldRightClickMenu.java @@ -55,17 +55,9 @@ public static ContextMenu create( new SeparatorMenuItem(), factory.createMenuItem( StandardActions.SELECT_ALL, - new EditAction( - StandardActions.SELECT_ALL, - null, - stateManager - ) + new EditAction(StandardActions.SELECT_ALL, null, stateManager) ), - createSearchFromHistorySubMenu( - factory, - stateManager, - searchField - ) + createSearchFromHistorySubMenu(factory, stateManager, searchField) ); return contextMenu; @@ -82,9 +74,7 @@ private static Menu createSearchFromHistorySubMenu( int num = stateManager.getLastSearchHistory(10).size(); if (num == 0) { - MenuItem item = new MenuItem( - Localization.lang("your search history is empty") - ); + MenuItem item = new MenuItem(Localization.lang("your search history is empty")); searchFromHistorySubMenu.getItems().addAll(item); } else { for (int i = 0; i < num; i++) { @@ -94,11 +84,7 @@ private static Menu createSearchFromHistorySubMenu( new SimpleCommand() { @Override public void execute() { - searchField.setText( - stateManager - .getLastSearchHistory(10) - .get(finalI) - ); + searchField.setText(stateManager.getLastSearchHistory(10).get(finalI)); } } ); @@ -113,9 +99,7 @@ public void execute() { } } ); - searchFromHistorySubMenu - .getItems() - .addAll(new SeparatorMenuItem(), clear); + searchFromHistorySubMenu.getItems().addAll(new SeparatorMenuItem(), clear); } return searchFromHistorySubMenu; } diff --git a/src/main/java/org/jabref/gui/search/SearchResultsTable.java b/src/main/java/org/jabref/gui/search/SearchResultsTable.java index 4ff9ce1e64e..8acf8e3f96e 100644 --- a/src/main/java/org/jabref/gui/search/SearchResultsTable.java +++ b/src/main/java/org/jabref/gui/search/SearchResultsTable.java @@ -31,20 +31,18 @@ public SearchResultsTable( TaskExecutor taskExecutor ) { super(); - MainTablePreferences mainTablePreferences = - preferencesService.getMainTablePreferences(); + MainTablePreferences mainTablePreferences = preferencesService.getMainTablePreferences(); - List> allCols = - new MainTableColumnFactory( - database, - preferencesService, - preferencesService.getSearchDialogColumnPreferences(), - undoManager, - dialogService, - stateManager, - taskExecutor - ) - .createColumns(); + List> allCols = new MainTableColumnFactory( + database, + preferencesService, + preferencesService.getSearchDialogColumnPreferences(), + undoManager, + dialogService, + stateManager, + taskExecutor + ) + .createColumns(); if (allCols.stream().noneMatch(LibraryColumn.class::isInstance)) { allCols.add(0, new LibraryColumn()); @@ -71,19 +69,12 @@ public SearchResultsTable( this.getSelectionModel().setSelectionMode(SelectionMode.SINGLE); this.setItems(model.getEntriesFilteredAndSorted()); // Enable sorting - model - .getEntriesFilteredAndSorted() - .comparatorProperty() - .bind(this.comparatorProperty()); + model.getEntriesFilteredAndSorted().comparatorProperty().bind(this.comparatorProperty()); - this.getStylesheets() - .add(MainTable.class.getResource("MainTable.css").toExternalForm()); + this.getStylesheets().add(MainTable.class.getResource("MainTable.css").toExternalForm()); // Store visual state - new PersistenceVisualStateTable( - this, - preferencesService.getSearchDialogColumnPreferences() - ) + new PersistenceVisualStateTable(this, preferencesService.getSearchDialogColumnPreferences()) .addListeners(); database.getDatabase().registerListener(this); diff --git a/src/main/java/org/jabref/gui/search/SearchResultsTableDataModel.java b/src/main/java/org/jabref/gui/search/SearchResultsTableDataModel.java index 0e9fb6484d6..56d7e1443b9 100644 --- a/src/main/java/org/jabref/gui/search/SearchResultsTableDataModel.java +++ b/src/main/java/org/jabref/gui/search/SearchResultsTableDataModel.java @@ -22,9 +22,7 @@ public class SearchResultsTableDataModel { private final FilteredList entriesFiltered; private final SortedList entriesSorted; - private final ObjectProperty< - MainTableFieldValueFormatter - > fieldValueFormatter; + private final ObjectProperty fieldValueFormatter; private final NameDisplayPreferences nameDisplayPreferences; private final BibDatabaseContext bibDatabaseContext; @@ -33,31 +31,20 @@ public SearchResultsTableDataModel( PreferencesService preferencesService, StateManager stateManager ) { - this.nameDisplayPreferences = - preferencesService.getNameDisplayPreferences(); + this.nameDisplayPreferences = preferencesService.getNameDisplayPreferences(); this.bibDatabaseContext = bibDatabaseContext; this.fieldValueFormatter = new SimpleObjectProperty<>( - new MainTableFieldValueFormatter( - nameDisplayPreferences, - bibDatabaseContext - ) + new MainTableFieldValueFormatter(nameDisplayPreferences, bibDatabaseContext) ); ObservableList entriesViewModel = FXCollections.observableArrayList(); for (BibDatabaseContext context : stateManager.getOpenDatabases()) { - ObservableList entriesForDb = context - .getDatabase() - .getEntries(); + ObservableList entriesForDb = context.getDatabase().getEntries(); List viewModelForDb = EasyBind.mapBacked( entriesForDb, - entry -> - new BibEntryTableViewModel( - entry, - context, - fieldValueFormatter - ) + entry -> new BibEntryTableViewModel(entry, context, fieldValueFormatter) ); entriesViewModel.addAll(viewModelForDb); } @@ -76,13 +63,8 @@ public SearchResultsTableDataModel( entriesSorted = new SortedList<>(entriesFiltered); } - private boolean isMatchedBySearch( - Optional query, - BibEntryTableViewModel entry - ) { - return query - .map(matcher -> matcher.isMatch(entry.getEntry())) - .orElse(true); + private boolean isMatchedBySearch(Optional query, BibEntryTableViewModel entry) { + return query.map(matcher -> matcher.isMatch(entry.getEntry())).orElse(true); } public SortedList getEntriesFilteredAndSorted() { @@ -91,10 +73,7 @@ public SortedList getEntriesFilteredAndSorted() { public void refresh() { this.fieldValueFormatter.setValue( - new MainTableFieldValueFormatter( - nameDisplayPreferences, - bibDatabaseContext - ) + new MainTableFieldValueFormatter(nameDisplayPreferences, bibDatabaseContext) ); } } diff --git a/src/main/java/org/jabref/gui/search/SearchTextField.java b/src/main/java/org/jabref/gui/search/SearchTextField.java index 961add7ff6e..e29610477d6 100644 --- a/src/main/java/org/jabref/gui/search/SearchTextField.java +++ b/src/main/java/org/jabref/gui/search/SearchTextField.java @@ -8,8 +8,7 @@ public class SearchTextField { public static CustomTextField create() { - CustomTextField textField = - (CustomTextField) TextFields.createClearableTextField(); + CustomTextField textField = (CustomTextField) TextFields.createClearableTextField(); textField.setPromptText(Localization.lang("Search") + "..."); textField.setLeft(IconTheme.JabRefIcons.SEARCH.getGraphicNode()); textField.setId("searchField"); diff --git a/src/main/java/org/jabref/gui/search/rules/describer/ContainsAndRegexBasedSearchRuleDescriber.java b/src/main/java/org/jabref/gui/search/rules/describer/ContainsAndRegexBasedSearchRuleDescriber.java index 66579508b17..bf29e13b662 100644 --- a/src/main/java/org/jabref/gui/search/rules/describer/ContainsAndRegexBasedSearchRuleDescriber.java +++ b/src/main/java/org/jabref/gui/search/rules/describer/ContainsAndRegexBasedSearchRuleDescriber.java @@ -10,8 +10,7 @@ import org.jabref.model.search.rules.SearchRules.SearchFlags; import org.jabref.model.search.rules.SentenceAnalyzer; -public class ContainsAndRegexBasedSearchRuleDescriber - implements SearchDescriber { +public class ContainsAndRegexBasedSearchRuleDescriber implements SearchDescriber { private final EnumSet searchFlags; private final String query; @@ -29,9 +28,7 @@ public TextFlow getDescription() { List words = new SentenceAnalyzer(query).getWords(); String firstWord = words.isEmpty() ? "" : words.get(0); - String temp = searchFlags.contains( - SearchRules.SearchFlags.REGULAR_EXPRESSION - ) + String temp = searchFlags.contains(SearchRules.SearchFlags.REGULAR_EXPRESSION) ? Localization.lang( "This search contains entries in which any field contains the regular expression %0" ) @@ -56,12 +53,7 @@ public TextFlow getDescription() { TooltipTextUtil.TextType.NORMAL ) ); - textList.add( - TooltipTextUtil.createText( - word, - TooltipTextUtil.TextType.BOLD - ) - ); + textList.add(TooltipTextUtil.createText(word, TooltipTextUtil.TextType.BOLD)); } } diff --git a/src/main/java/org/jabref/gui/search/rules/describer/GrammarBasedSearchRuleDescriber.java b/src/main/java/org/jabref/gui/search/rules/describer/GrammarBasedSearchRuleDescriber.java index f7eedec2c86..a9875ee0c55 100644 --- a/src/main/java/org/jabref/gui/search/rules/describer/GrammarBasedSearchRuleDescriber.java +++ b/src/main/java/org/jabref/gui/search/rules/describer/GrammarBasedSearchRuleDescriber.java @@ -23,10 +23,7 @@ public class GrammarBasedSearchRuleDescriber implements SearchDescriber { private final EnumSet searchFlags; private final ParseTree parseTree; - public GrammarBasedSearchRuleDescriber( - EnumSet searchFlags, - ParseTree parseTree - ) { + public GrammarBasedSearchRuleDescriber(EnumSet searchFlags, ParseTree parseTree) { this.searchFlags = searchFlags; this.parseTree = Objects.requireNonNull(parseTree); } @@ -44,24 +41,15 @@ public TextFlow getDescription() { TooltipTextUtil.createText( String.format( "%s ", - Localization.lang( - "This search contains entries in which" - ) + Localization.lang("This search contains entries in which") ), TooltipTextUtil.TextType.NORMAL ) ); + textFlow.getChildren().addAll(descriptionSearchBaseVisitor.visit(parseTree)); textFlow .getChildren() - .addAll(descriptionSearchBaseVisitor.visit(parseTree)); - textFlow - .getChildren() - .add( - TooltipTextUtil.createText( - ". ", - TooltipTextUtil.TextType.NORMAL - ) - ); + .add(TooltipTextUtil.createText(". ", TooltipTextUtil.TextType.NORMAL)); textFlow .getChildren() .add( @@ -75,8 +63,7 @@ public TextFlow getDescription() { return textFlow; } - private class DescriptionSearchBaseVisitor - extends SearchBaseVisitor> { + private class DescriptionSearchBaseVisitor extends SearchBaseVisitor> { @Override public List visitStart(SearchParser.StartContext context) { @@ -84,9 +71,7 @@ public List visitStart(SearchParser.StartContext context) { } @Override - public List visitUnaryExpression( - SearchParser.UnaryExpressionContext context - ) { + public List visitUnaryExpression(SearchParser.UnaryExpressionContext context) { List textList = visit(context.expression()); textList.add( 0, @@ -99,9 +84,7 @@ public List visitUnaryExpression( } @Override - public List visitParenExpression( - SearchParser.ParenExpressionContext context - ) { + public List visitParenExpression(SearchParser.ParenExpressionContext context) { ArrayList textList = new ArrayList<>(); textList.add( TooltipTextUtil.createText( @@ -113,9 +96,7 @@ public List visitParenExpression( } @Override - public List visitBinaryExpression( - SearchParser.BinaryExpressionContext context - ) { + public List visitBinaryExpression(SearchParser.BinaryExpressionContext context) { List textList = visit(context.left); if ("AND".equalsIgnoreCase(context.operator.getText())) { textList.add( @@ -137,105 +118,52 @@ public List visitBinaryExpression( } @Override - public List visitComparison( - SearchParser.ComparisonContext context - ) { + public List visitComparison(SearchParser.ComparisonContext context) { final List textList = new ArrayList<>(); - final Optional fieldDescriptor = - Optional.ofNullable(context.left); - final String value = StringUtil.unquote( - context.right.getText(), - '"' + final Optional fieldDescriptor = Optional.ofNullable( + context.left ); + final String value = StringUtil.unquote(context.right.getText(), '"'); if (!fieldDescriptor.isPresent()) { - TextFlow description = - new ContainsAndRegexBasedSearchRuleDescriber( - searchFlags, - value - ) - .getDescription(); - description - .getChildren() - .forEach(it -> textList.add((Text) it)); + TextFlow description = new ContainsAndRegexBasedSearchRuleDescriber( + searchFlags, + value + ) + .getDescription(); + description.getChildren().forEach(it -> textList.add((Text) it)); return textList; } - final String field = StringUtil.unquote( - fieldDescriptor.get().getText(), - '"' - ); + final String field = StringUtil.unquote(fieldDescriptor.get().getText(), '"'); final GrammarBasedSearchRule.ComparisonOperator operator = - GrammarBasedSearchRule.ComparisonOperator.build( - context.operator.getText() - ); + GrammarBasedSearchRule.ComparisonOperator.build(context.operator.getText()); final boolean regExpFieldSpec = !Pattern.matches("\\w+", field); String temp = regExpFieldSpec - ? Localization.lang( - "any field that matches the regular expression %0" - ) + ? Localization.lang("any field that matches the regular expression %0") : Localization.lang("the field %0"); - if ( - operator == GrammarBasedSearchRule.ComparisonOperator.CONTAINS - ) { - if ( - searchFlags.contains( - SearchRules.SearchFlags.REGULAR_EXPRESSION - ) - ) { - temp = - Localization.lang( - "%0 contains the regular expression %1", - temp - ); + if (operator == GrammarBasedSearchRule.ComparisonOperator.CONTAINS) { + if (searchFlags.contains(SearchRules.SearchFlags.REGULAR_EXPRESSION)) { + temp = Localization.lang("%0 contains the regular expression %1", temp); } else { - temp = - Localization.lang( - "%0 contains the term %1", - temp - ); + temp = Localization.lang("%0 contains the term %1", temp); } - } else if ( - operator == GrammarBasedSearchRule.ComparisonOperator.EXACT - ) { - if ( - searchFlags.contains( - SearchRules.SearchFlags.REGULAR_EXPRESSION - ) - ) { - temp = - Localization.lang( - "%0 matches the regular expression %1", - temp - ); + } else if (operator == GrammarBasedSearchRule.ComparisonOperator.EXACT) { + if (searchFlags.contains(SearchRules.SearchFlags.REGULAR_EXPRESSION)) { + temp = Localization.lang("%0 matches the regular expression %1", temp); } else { - temp = - Localization.lang( - "%0 matches the term %1", - temp - ); + temp = Localization.lang("%0 matches the term %1", temp); } - } else if ( - operator == - GrammarBasedSearchRule.ComparisonOperator.DOES_NOT_CONTAIN - ) { - if ( - searchFlags.contains( - SearchRules.SearchFlags.REGULAR_EXPRESSION - ) - ) { + } else if (operator == GrammarBasedSearchRule.ComparisonOperator.DOES_NOT_CONTAIN) { + if (searchFlags.contains(SearchRules.SearchFlags.REGULAR_EXPRESSION)) { temp = Localization.lang( "%0 doesn't contain the regular expression %1", temp ); } else { - temp = - Localization.lang( - "%0 doesn't contain the term %1", - temp - ); + temp = Localization.lang("%0 doesn't contain the term %1", temp); } } else { throw new IllegalStateException("CANNOT HAPPEN!"); diff --git a/src/main/java/org/jabref/gui/search/rules/describer/SearchDescribers.java b/src/main/java/org/jabref/gui/search/rules/describer/SearchDescribers.java index c509786f4f5..f04b0b4553c 100644 --- a/src/main/java/org/jabref/gui/search/rules/describer/SearchDescribers.java +++ b/src/main/java/org/jabref/gui/search/rules/describer/SearchDescribers.java @@ -15,29 +15,20 @@ private SearchDescribers() {} * @param searchQuery the search query * @return the search describer to turn the search into something human understandable */ - public static SearchDescriber getSearchDescriberFor( - SearchQuery searchQuery - ) { - if ( - searchQuery.getRule() instanceof - GrammarBasedSearchRule grammarBasedSearchRule - ) { + public static SearchDescriber getSearchDescriberFor(SearchQuery searchQuery) { + if (searchQuery.getRule() instanceof GrammarBasedSearchRule grammarBasedSearchRule) { return new GrammarBasedSearchRuleDescriber( grammarBasedSearchRule.getSearchFlags(), grammarBasedSearchRule.getTree() ); } else if ( - searchQuery.getRule() instanceof - ContainsBasedSearchRule containBasedSearchRule + searchQuery.getRule() instanceof ContainsBasedSearchRule containBasedSearchRule ) { return new ContainsAndRegexBasedSearchRuleDescriber( containBasedSearchRule.getSearchFlags(), searchQuery.getQuery() ); - } else if ( - searchQuery.getRule() instanceof - RegexBasedSearchRule regexBasedSearchRule - ) { + } else if (searchQuery.getRule() instanceof RegexBasedSearchRule regexBasedSearchRule) { return new ContainsAndRegexBasedSearchRuleDescriber( regexBasedSearchRule.getSearchFlags(), searchQuery.getQuery() diff --git a/src/main/java/org/jabref/gui/shared/ConnectToSharedDatabaseCommand.java b/src/main/java/org/jabref/gui/shared/ConnectToSharedDatabaseCommand.java index 28b90236808..b4fa8f81cd0 100644 --- a/src/main/java/org/jabref/gui/shared/ConnectToSharedDatabaseCommand.java +++ b/src/main/java/org/jabref/gui/shared/ConnectToSharedDatabaseCommand.java @@ -18,11 +18,7 @@ public ConnectToSharedDatabaseCommand(JabRefFrame jabRefFrame) { @Override public void execute() { - DialogService dialogService = Injector.instantiateModelOrService( - DialogService.class - ); - dialogService.showCustomDialogAndWait( - new SharedDatabaseLoginDialogView(jabRefFrame) - ); + DialogService dialogService = Injector.instantiateModelOrService(DialogService.class); + dialogService.showCustomDialogAndWait(new SharedDatabaseLoginDialogView(jabRefFrame)); } } diff --git a/src/main/java/org/jabref/gui/shared/PullChangesFromSharedAction.java b/src/main/java/org/jabref/gui/shared/PullChangesFromSharedAction.java index 849f6f43ee6..65d720ab435 100644 --- a/src/main/java/org/jabref/gui/shared/PullChangesFromSharedAction.java +++ b/src/main/java/org/jabref/gui/shared/PullChangesFromSharedAction.java @@ -23,8 +23,7 @@ public void execute() { stateManager .getActiveDatabase() .ifPresent(databaseContext -> { - DatabaseSynchronizer dbmsSynchronizer = - databaseContext.getDBMSSynchronizer(); + DatabaseSynchronizer dbmsSynchronizer = databaseContext.getDBMSSynchronizer(); dbmsSynchronizer.pullChanges(); }); } diff --git a/src/main/java/org/jabref/gui/shared/SharedDatabaseLoginDialogView.java b/src/main/java/org/jabref/gui/shared/SharedDatabaseLoginDialogView.java index cf8e15be38a..9b83f964405 100644 --- a/src/main/java/org/jabref/gui/shared/SharedDatabaseLoginDialogView.java +++ b/src/main/java/org/jabref/gui/shared/SharedDatabaseLoginDialogView.java @@ -108,26 +108,17 @@ public SharedDatabaseLoginDialogView(JabRefFrame frame) { ViewLoader.view(this).load().setAsDialogPane(this); - ControlHelper.setAction( - connectButton, - this.getDialogPane(), - event -> openDatabase() - ); - Button btnConnect = (Button) this.getDialogPane() - .lookupButton(connectButton); + ControlHelper.setAction(connectButton, this.getDialogPane(), event -> openDatabase()); + Button btnConnect = (Button) this.getDialogPane().lookupButton(connectButton); // must be set here, because in initialize the button is still null - btnConnect - .disableProperty() - .bind(viewModel.formValidation().validProperty().not()); + btnConnect.disableProperty().bind(viewModel.formValidation().validProperty().not()); btnConnect .textProperty() .bind( EasyBind.map( viewModel.loadingProperty(), loading -> - loading - ? Localization.lang("Connecting...") - : Localization.lang("Connect") + loading ? Localization.lang("Connecting...") : Localization.lang("Connect") ) ); } @@ -164,78 +155,39 @@ private void initialize() { user.textProperty().bindBidirectional(viewModel.userProperty()); password.textProperty().bindBidirectional(viewModel.passwordProperty()); port.textProperty().bindBidirectional(viewModel.portProperty()); - serverTimezone - .textProperty() - .bindBidirectional(viewModel.serverTimezoneProperty()); - databaseType - .valueProperty() - .bindBidirectional(viewModel.selectedDbmstypeProperty()); + serverTimezone.textProperty().bindBidirectional(viewModel.serverTimezoneProperty()); + databaseType.valueProperty().bindBidirectional(viewModel.selectedDbmstypeProperty()); folder.textProperty().bindBidirectional(viewModel.folderProperty()); browseButton.disableProperty().bind(viewModel.autosaveProperty().not()); folder.disableProperty().bind(viewModel.autosaveProperty().not()); - autosave - .selectedProperty() - .bindBidirectional(viewModel.autosaveProperty()); + autosave.selectedProperty().bindBidirectional(viewModel.autosaveProperty()); useSSL.selectedProperty().bindBidirectional(viewModel.useSSLProperty()); - fileKeystore - .textProperty() - .bindBidirectional(viewModel.keyStoreProperty()); + fileKeystore.textProperty().bindBidirectional(viewModel.keyStoreProperty()); browseKeystore.disableProperty().bind(viewModel.useSSLProperty().not()); - passwordKeystore - .disableProperty() - .bind(viewModel.useSSLProperty().not()); - passwordKeystore - .textProperty() - .bindBidirectional(viewModel.keyStorePasswordProperty()); - rememberPassword - .selectedProperty() - .bindBidirectional(viewModel.rememberPasswordProperty()); + passwordKeystore.disableProperty().bind(viewModel.useSSLProperty().not()); + passwordKeystore.textProperty().bindBidirectional(viewModel.keyStorePasswordProperty()); + rememberPassword.selectedProperty().bindBidirectional(viewModel.rememberPasswordProperty()); // Must be executed after the initialization of the view, otherwise it doesn't work Platform.runLater(() -> { - visualizer.initVisualization( - viewModel.dbValidation(), - database, - true - ); - visualizer.initVisualization( - viewModel.hostValidation(), - host, - true - ); - visualizer.initVisualization( - viewModel.portValidation(), - port, - true - ); - visualizer.initVisualization( - viewModel.userValidation(), - user, - true - ); + visualizer.initVisualization(viewModel.dbValidation(), database, true); + visualizer.initVisualization(viewModel.hostValidation(), host, true); + visualizer.initVisualization(viewModel.portValidation(), port, true); + visualizer.initVisualization(viewModel.userValidation(), user, true); EasyBind.subscribe( autosave.selectedProperty(), - selected -> - visualizer.initVisualization( - viewModel.folderValidation(), - folder, - true - ) + selected -> visualizer.initVisualization(viewModel.folderValidation(), folder, true) ); EasyBind.subscribe( useSSL.selectedProperty(), selected -> - visualizer.initVisualization( - viewModel.keystoreValidation(), - fileKeystore, - true - ) + visualizer.initVisualization(viewModel.keystoreValidation(), fileKeystore, true) ); }); } diff --git a/src/main/java/org/jabref/gui/shared/SharedDatabaseLoginDialogViewModel.java b/src/main/java/org/jabref/gui/shared/SharedDatabaseLoginDialogViewModel.java index 8ea753c9f6f..2d454161fe4 100644 --- a/src/main/java/org/jabref/gui/shared/SharedDatabaseLoginDialogViewModel.java +++ b/src/main/java/org/jabref/gui/shared/SharedDatabaseLoginDialogViewModel.java @@ -59,8 +59,9 @@ public class SharedDatabaseLoginDialogViewModel extends AbstractViewModel { SharedDatabaseLoginDialogViewModel.class ); - private final ObjectProperty selectedDBMSType = - new SimpleObjectProperty<>(DBMSType.values()[0]); + private final ObjectProperty selectedDBMSType = new SimpleObjectProperty<>( + DBMSType.values()[0] + ); private final StringProperty database = new SimpleStringProperty(""); private final StringProperty host = new SimpleStringProperty(""); @@ -69,13 +70,11 @@ public class SharedDatabaseLoginDialogViewModel extends AbstractViewModel { private final StringProperty password = new SimpleStringProperty(""); private final StringProperty folder = new SimpleStringProperty(""); private final BooleanProperty autosave = new SimpleBooleanProperty(); - private final BooleanProperty rememberPassword = - new SimpleBooleanProperty(); + private final BooleanProperty rememberPassword = new SimpleBooleanProperty(); private final BooleanProperty loading = new SimpleBooleanProperty(); private final StringProperty keystore = new SimpleStringProperty(""); private final BooleanProperty useSSL = new SimpleBooleanProperty(); - private final StringProperty keyStorePasswordProperty = - new SimpleStringProperty(""); + private final StringProperty keyStorePasswordProperty = new SimpleStringProperty(""); private final StringProperty serverTimezone = new SimpleStringProperty(""); private final JabRefFrame frame; @@ -118,12 +117,10 @@ public SharedDatabaseLoginDialogViewModel( EasyBind.subscribe( selectedDBMSType, - selected -> - port.setValue(Integer.toString(selected.getDefaultPort())) + selected -> port.setValue(Integer.toString(selected.getDefaultPort())) ); - Predicate notEmpty = input -> - (input != null) && !input.trim().isEmpty(); + Predicate notEmpty = input -> (input != null) && !input.trim().isEmpty(); Predicate fileExists = input -> Files.exists(Path.of(input)); Predicate notEmptyAndfilesExist = notEmpty.and(fileExists); @@ -143,10 +140,7 @@ public SharedDatabaseLoginDialogViewModel( host, notEmpty, ValidationMessage.error( - Localization.lang( - "Required field \"%0\" is empty.", - Localization.lang("Port") - ) + Localization.lang("Required field \"%0\" is empty.", Localization.lang("Port")) ) ); portValidator = @@ -154,10 +148,7 @@ public SharedDatabaseLoginDialogViewModel( port, notEmpty, ValidationMessage.error( - Localization.lang( - "Required field \"%0\" is empty.", - Localization.lang("Host") - ) + Localization.lang("Required field \"%0\" is empty.", Localization.lang("Host")) ) ); userValidator = @@ -165,55 +156,42 @@ public SharedDatabaseLoginDialogViewModel( user, notEmpty, ValidationMessage.error( - Localization.lang( - "Required field \"%0\" is empty.", - Localization.lang("User") - ) + Localization.lang("Required field \"%0\" is empty.", Localization.lang("User")) ) ); folderValidator = new FunctionBasedValidator<>( folder, notEmptyAndfilesExist, - ValidationMessage.error( - Localization.lang("Please enter a valid file path.") - ) + ValidationMessage.error(Localization.lang("Please enter a valid file path.")) ); keystoreValidator = new FunctionBasedValidator<>( keystore, notEmptyAndfilesExist, - ValidationMessage.error( - Localization.lang("Please enter a valid file path.") - ) + ValidationMessage.error(Localization.lang("Please enter a valid file path.")) ); formValidator = new CompositeValidator(); - formValidator.addValidators( - databaseValidator, - hostValidator, - portValidator, - userValidator - ); + formValidator.addValidators(databaseValidator, hostValidator, portValidator, userValidator); applyPreferences(); } public boolean openDatabase() { - DBMSConnectionProperties connectionProperties = - new DBMSConnectionPropertiesBuilder() - .setType(selectedDBMSType.getValue()) - .setHost(host.getValue()) - .setPort(Integer.parseInt(port.getValue())) - .setDatabase(database.getValue()) - .setUser(user.getValue()) - .setPassword(password.getValue()) - .setUseSSL(useSSL.getValue()) - // Authorize client to retrieve RSA server public key when serverRsaPublicKeyFile is not set (for sha256_password and caching_sha2_password authentication password) - .setAllowPublicKeyRetrieval(true) - .setKeyStore(keystore.getValue()) - .setServerTimezone(serverTimezone.getValue()) - .createDBMSConnectionProperties(); + DBMSConnectionProperties connectionProperties = new DBMSConnectionPropertiesBuilder() + .setType(selectedDBMSType.getValue()) + .setHost(host.getValue()) + .setPort(Integer.parseInt(port.getValue())) + .setDatabase(database.getValue()) + .setUser(user.getValue()) + .setPassword(password.getValue()) + .setUseSSL(useSSL.getValue()) + // Authorize client to retrieve RSA server public key when serverRsaPublicKeyFile is not set (for sha256_password and caching_sha2_password authentication password) + .setAllowPublicKeyRetrieval(true) + .setKeyStore(keystore.getValue()) + .setServerTimezone(serverTimezone.getValue()) + .createDBMSConnectionProperties(); setupKeyStore(); return openSharedDatabase(connectionProperties); @@ -221,16 +199,11 @@ public boolean openDatabase() { private void setupKeyStore() { System.setProperty("javax.net.ssl.trustStore", keystore.getValue()); - System.setProperty( - "javax.net.ssl.trustStorePassword", - keyStorePasswordProperty.getValue() - ); + System.setProperty("javax.net.ssl.trustStorePassword", keyStorePasswordProperty.getValue()); System.setProperty("javax.net.debug", "ssl"); } - private boolean openSharedDatabase( - DBMSConnectionProperties connectionProperties - ) { + private boolean openSharedDatabase(DBMSConnectionProperties connectionProperties) { if (isSharedDatabaseAlreadyPresent(connectionProperties)) { dialogService.showWarningDialogAndWait( Localization.lang("Shared database connection"), @@ -244,19 +217,16 @@ private boolean openSharedDatabase( if (autosave.get()) { Path localFilePath = Path.of(folder.getValue()); - if ( - Files.exists(localFilePath) && !Files.isDirectory(localFilePath) - ) { - boolean overwriteFilePressed = - dialogService.showConfirmationDialogAndWait( - Localization.lang("Existing file"), - Localization.lang( - "'%0' exists. Overwrite file?", - localFilePath.getFileName().toString() - ), - Localization.lang("Overwrite file"), - Localization.lang("Cancel") - ); + if (Files.exists(localFilePath) && !Files.isDirectory(localFilePath)) { + boolean overwriteFilePressed = dialogService.showConfirmationDialogAndWait( + Localization.lang("Existing file"), + Localization.lang( + "'%0' exists. Overwrite file?", + localFilePath.getFileName().toString() + ), + Localization.lang("Overwrite file"), + Localization.lang("Cancel") + ); if (!overwriteFilePressed) { return true; } @@ -276,9 +246,7 @@ private boolean openSharedDatabase( undoManager, taskExecutor ); - LibraryTab libraryTab = manager.openNewSharedDatabaseTab( - connectionProperties - ); + LibraryTab libraryTab = manager.openNewSharedDatabaseTab(connectionProperties); setPreferences(); if (!folder.getValue().isEmpty() && autosave.get()) { @@ -296,34 +264,24 @@ private boolean openSharedDatabase( } return true; - } catch ( - SQLException | InvalidDBMSConnectionPropertiesException exception - ) { - dialogService.showErrorDialogAndWait( - Localization.lang("Connection error"), - exception - ); + } catch (SQLException | InvalidDBMSConnectionPropertiesException exception) { + dialogService.showErrorDialogAndWait(Localization.lang("Connection error"), exception); } catch (DatabaseNotSupportedException exception) { ButtonType openHelp = new ButtonType("Open Help", ButtonData.OTHER); - Optional result = - dialogService.showCustomButtonDialogAndWait( - AlertType.INFORMATION, - Localization.lang("Migration help information"), - Localization.lang( - "Entered database has obsolete structure and is no longer supported." - ) + - "\n" + - Localization.lang( - "Click help to learn about the migration of pre-3.6 databases." - ) + - "\n" + - Localization.lang( - "However, a new database was created alongside the pre-3.6 one." - ), - ButtonType.OK, - openHelp - ); + Optional result = dialogService.showCustomButtonDialogAndWait( + AlertType.INFORMATION, + Localization.lang("Migration help information"), + Localization.lang( + "Entered database has obsolete structure and is no longer supported." + ) + + "\n" + + Localization.lang("Click help to learn about the migration of pre-3.6 databases.") + + "\n" + + Localization.lang("However, a new database was created alongside the pre-3.6 one."), + ButtonType.OK, + openHelp + ); result .filter(btn -> btn.equals(openHelp)) @@ -344,9 +302,7 @@ private boolean openSharedDatabase( } private void setPreferences() { - sharedDatabasePreferences.setType( - selectedDBMSType.getValue().toString() - ); + sharedDatabasePreferences.setType(selectedDBMSType.getValue().toString()); sharedDatabasePreferences.setHost(host.getValue()); sharedDatabasePreferences.setPort(port.getValue()); sharedDatabasePreferences.setName(database.getValue()); @@ -360,13 +316,8 @@ private void setPreferences() { sharedDatabasePreferences.setPassword( new Password(password.getValue(), user.getValue()).encrypt() ); - } catch ( - GeneralSecurityException | UnsupportedEncodingException e - ) { - LOGGER.error( - "Could not store the password due to encryption problems.", - e - ); + } catch (GeneralSecurityException | UnsupportedEncodingException e) { + LOGGER.error("Could not store the password due to encryption problems.", e); } } else { sharedDatabasePreferences.clearPassword(); // for the case that the password is already set @@ -382,31 +333,19 @@ private void setPreferences() { * Fetches possibly saved data and configures the control elements respectively. */ private void applyPreferences() { - Optional sharedDatabaseType = - sharedDatabasePreferences.getType(); - Optional sharedDatabaseHost = - sharedDatabasePreferences.getHost(); - Optional sharedDatabasePort = - sharedDatabasePreferences.getPort(); - Optional sharedDatabaseName = - sharedDatabasePreferences.getName(); - Optional sharedDatabaseUser = - sharedDatabasePreferences.getUser(); - Optional sharedDatabasePassword = - sharedDatabasePreferences.getPassword(); - boolean sharedDatabaseRememberPassword = - sharedDatabasePreferences.getRememberPassword(); - Optional sharedDatabaseFolder = - sharedDatabasePreferences.getFolder(); - boolean sharedDatabaseAutosave = - sharedDatabasePreferences.getAutosave(); - Optional sharedDatabaseKeystoreFile = - sharedDatabasePreferences.getKeyStoreFile(); + Optional sharedDatabaseType = sharedDatabasePreferences.getType(); + Optional sharedDatabaseHost = sharedDatabasePreferences.getHost(); + Optional sharedDatabasePort = sharedDatabasePreferences.getPort(); + Optional sharedDatabaseName = sharedDatabasePreferences.getName(); + Optional sharedDatabaseUser = sharedDatabasePreferences.getUser(); + Optional sharedDatabasePassword = sharedDatabasePreferences.getPassword(); + boolean sharedDatabaseRememberPassword = sharedDatabasePreferences.getRememberPassword(); + Optional sharedDatabaseFolder = sharedDatabasePreferences.getFolder(); + boolean sharedDatabaseAutosave = sharedDatabasePreferences.getAutosave(); + Optional sharedDatabaseKeystoreFile = sharedDatabasePreferences.getKeyStoreFile(); if (sharedDatabaseType.isPresent()) { - Optional dbmsType = DBMSType.fromString( - sharedDatabaseType.get() - ); + Optional dbmsType = DBMSType.fromString(sharedDatabaseType.get()); dbmsType.ifPresent(selectedDBMSType::set); } @@ -417,9 +356,7 @@ private void applyPreferences() { sharedDatabaseKeystoreFile.ifPresent(keystore::set); useSSL.setValue(sharedDatabasePreferences.isUseSSL()); - if ( - sharedDatabasePassword.isPresent() && sharedDatabaseUser.isPresent() - ) { + if (sharedDatabasePassword.isPresent() && sharedDatabaseUser.isPresent()) { try { password.setValue( new Password( @@ -428,13 +365,8 @@ private void applyPreferences() { ) .decrypt() ); - } catch ( - GeneralSecurityException | UnsupportedEncodingException e - ) { - LOGGER.error( - "Could not read the password due to decryption problems.", - e - ); + } catch (GeneralSecurityException | UnsupportedEncodingException e) { + LOGGER.error("Could not read the password due to decryption problems.", e); } } @@ -444,9 +376,7 @@ private void applyPreferences() { autosave.set(sharedDatabaseAutosave); } - private boolean isSharedDatabaseAlreadyPresent( - DBMSConnectionProperties connectionProperties - ) { + private boolean isSharedDatabaseAlreadyPresent(DBMSConnectionProperties connectionProperties) { List libraryTabs = frame.getLibraryTabs(); return libraryTabs .parallelStream() @@ -463,37 +393,23 @@ private boolean isSharedDatabaseAlreadyPresent( } public void showSaveDbToFileDialog() { - FileDialogConfiguration fileDialogConfiguration = - new FileDialogConfiguration.Builder() - .addExtensionFilter(StandardFileType.BIBTEX_DB) - .withDefaultExtension(StandardFileType.BIBTEX_DB) - .withInitialDirectory( - preferencesService - .getFilePreferences() - .getWorkingDirectory() - ) - .build(); - Optional exportPath = dialogService.showFileSaveDialog( - fileDialogConfiguration - ); + FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() + .addExtensionFilter(StandardFileType.BIBTEX_DB) + .withDefaultExtension(StandardFileType.BIBTEX_DB) + .withInitialDirectory(preferencesService.getFilePreferences().getWorkingDirectory()) + .build(); + Optional exportPath = dialogService.showFileSaveDialog(fileDialogConfiguration); exportPath.ifPresent(path -> folder.setValue(path.toString())); } public void showOpenKeystoreFileDialog() { - FileDialogConfiguration fileDialogConfiguration = - new FileDialogConfiguration.Builder() - .addExtensionFilter(FileFilterConverter.ANY_FILE) - .addExtensionFilter(StandardFileType.JAVA_KEYSTORE) - .withDefaultExtension(StandardFileType.JAVA_KEYSTORE) - .withInitialDirectory( - preferencesService - .getFilePreferences() - .getWorkingDirectory() - ) - .build(); - Optional keystorePath = dialogService.showFileOpenDialog( - fileDialogConfiguration - ); + FileDialogConfiguration fileDialogConfiguration = new FileDialogConfiguration.Builder() + .addExtensionFilter(FileFilterConverter.ANY_FILE) + .addExtensionFilter(StandardFileType.JAVA_KEYSTORE) + .withDefaultExtension(StandardFileType.JAVA_KEYSTORE) + .withInitialDirectory(preferencesService.getFilePreferences().getWorkingDirectory()) + .build(); + Optional keystorePath = dialogService.showFileOpenDialog(fileDialogConfiguration); keystorePath.ifPresent(path -> keystore.setValue(path.toString())); } diff --git a/src/main/java/org/jabref/gui/shared/SharedDatabaseUIManager.java b/src/main/java/org/jabref/gui/shared/SharedDatabaseUIManager.java index fac4bd13dde..fb4ec7bd39e 100644 --- a/src/main/java/org/jabref/gui/shared/SharedDatabaseUIManager.java +++ b/src/main/java/org/jabref/gui/shared/SharedDatabaseUIManager.java @@ -72,44 +72,29 @@ public SharedDatabaseUIManager( @Subscribe public void listen(ConnectionLostEvent connectionLostEvent) { - ButtonType reconnect = new ButtonType( - Localization.lang("Reconnect"), - ButtonData.YES - ); - ButtonType workOffline = new ButtonType( - Localization.lang("Work offline"), - ButtonData.NO - ); + ButtonType reconnect = new ButtonType(Localization.lang("Reconnect"), ButtonData.YES); + ButtonType workOffline = new ButtonType(Localization.lang("Work offline"), ButtonData.NO); ButtonType closeLibrary = new ButtonType( Localization.lang("Close library"), ButtonData.CANCEL_CLOSE ); - Optional answer = - dialogService.showCustomButtonDialogAndWait( - AlertType.WARNING, - Localization.lang("Connection lost"), - Localization.lang( - "The connection to the server has been terminated." - ), - reconnect, - workOffline, - closeLibrary - ); + Optional answer = dialogService.showCustomButtonDialogAndWait( + AlertType.WARNING, + Localization.lang("Connection lost"), + Localization.lang("The connection to the server has been terminated."), + reconnect, + workOffline, + closeLibrary + ); if (answer.isPresent()) { if (answer.get().equals(reconnect)) { frame.closeCurrentTab(); - dialogService.showCustomDialogAndWait( - new SharedDatabaseLoginDialogView(frame) - ); + dialogService.showCustomDialogAndWait(new SharedDatabaseLoginDialogView(frame)); } else if (answer.get().equals(workOffline)) { - connectionLostEvent - .getBibDatabaseContext() - .convertToLocalDatabase(); - frame - .getLibraryTabs() - .forEach(tab -> tab.updateTabTitle(tab.isModified())); + connectionLostEvent.getBibDatabaseContext().convertToLocalDatabase(); + frame.getLibraryTabs().forEach(tab -> tab.updateTabTitle(tab.isModified())); dialogService.notify(Localization.lang("Working offline.")); } } else { @@ -125,49 +110,38 @@ public void listen(UpdateRefusedEvent updateRefusedEvent) { BibEntry sharedBibEntry = updateRefusedEvent.getSharedBibEntry(); String message = - Localization.lang( - "Update could not be performed due to existing change conflicts." - ) + + Localization.lang("Update could not be performed due to existing change conflicts.") + "\r\n" + - Localization.lang( - "You are not working on the newest version of BibEntry." - ) + + Localization.lang("You are not working on the newest version of BibEntry.") + "\r\n" + Localization.lang( "Shared version: %0", - String.valueOf( - sharedBibEntry.getSharedBibEntryData().getVersion() - ) + String.valueOf(sharedBibEntry.getSharedBibEntryData().getVersion()) ) + "\r\n" + Localization.lang( "Local version: %0", - String.valueOf( - localBibEntry.getSharedBibEntryData().getVersion() - ) + String.valueOf(localBibEntry.getSharedBibEntryData().getVersion()) ) + "\r\n" + Localization.lang( "Press \"Merge entries\" to merge the changes and resolve this problem." ) + "\r\n" + - Localization.lang( - "Canceling this operation will leave your changes unsynchronized." - ); + Localization.lang("Canceling this operation will leave your changes unsynchronized."); ButtonType merge = new ButtonType( Localization.lang("Merge entries"), ButtonBar.ButtonData.YES ); - Optional response = - dialogService.showCustomButtonDialogAndWait( - AlertType.CONFIRMATION, - Localization.lang("Update refused"), - message, - ButtonType.CANCEL, - merge - ); + Optional response = dialogService.showCustomButtonDialogAndWait( + AlertType.CONFIRMATION, + Localization.lang("Update refused"), + message, + ButtonType.CANCEL, + merge + ); if (response.isPresent() && response.get().equals(merge)) { MergeEntriesDialog dialog = new MergeEntriesDialog( @@ -183,14 +157,10 @@ public void listen(UpdateRefusedEvent updateRefusedEvent) { mergedEntry.ifPresent(mergedBibEntry -> { mergedBibEntry .getSharedBibEntryData() - .setSharedID( - sharedBibEntry.getSharedBibEntryData().getSharedID() - ); + .setSharedID(sharedBibEntry.getSharedBibEntryData().getSharedID()); mergedBibEntry .getSharedBibEntryData() - .setVersion( - sharedBibEntry.getSharedBibEntryData().getVersion() - ); + .setVersion(sharedBibEntry.getSharedBibEntryData().getVersion()); dbmsSynchronizer.synchronizeSharedEntry(mergedBibEntry); dbmsSynchronizer.synchronizeLocalDatabase(); @@ -205,16 +175,10 @@ public void listen(SharedEntriesNotPresentEvent event) { libraryTab .getUndoManager() - .addEdit( - new UndoableRemoveEntries( - libraryTab.getDatabase(), - event.getBibEntries() - ) - ); + .addEdit(new UndoableRemoveEntries(libraryTab.getDatabase(), event.getBibEntries())); if ( - Objects.nonNull(entryEditor) && - (event.getBibEntries().contains(entryEditor.getEntry())) + Objects.nonNull(entryEditor) && (event.getBibEntries().contains(entryEditor.getEntry())) ) { dialogService.showInformationDialogAndWait( Localization.lang("Shared entry is no longer present"), @@ -222,9 +186,7 @@ public void listen(SharedEntriesNotPresentEvent event) { "The entry you currently work on has been deleted on the shared side." ) + "\n" + - Localization.lang( - "You can restore the entry using the \"Undo\" operation." - ) + Localization.lang("You can restore the entry using the \"Undo\" operation.") ); libraryTab.closeBottomPane(); } @@ -236,30 +198,22 @@ public void listen(SharedEntriesNotPresentEvent event) { * @param dbmsConnectionProperties Connection data * @return BasePanel which also used by {@link SaveDatabaseAction} */ - public LibraryTab openNewSharedDatabaseTab( - DBMSConnectionProperties dbmsConnectionProperties - ) + public LibraryTab openNewSharedDatabaseTab(DBMSConnectionProperties dbmsConnectionProperties) throws SQLException, DatabaseNotSupportedException, InvalidDBMSConnectionPropertiesException { BibDatabaseContext bibDatabaseContext = new BibDatabaseContext(); bibDatabaseContext.setMode( - preferencesService - .getLibraryPreferences() - .getDefaultBibDatabaseMode() + preferencesService.getLibraryPreferences().getDefaultBibDatabaseMode() ); DBMSSynchronizer synchronizer = new DBMSSynchronizer( bibDatabaseContext, preferencesService.getBibEntryPreferences().getKeywordSeparator(), - preferencesService - .getCitationKeyPatternPreferences() - .getKeyPattern(), + preferencesService.getCitationKeyPatternPreferences().getKeyPattern(), fileUpdateMonitor ); bibDatabaseContext.convertToSharedDatabase(synchronizer); dbmsSynchronizer = bibDatabaseContext.getDBMSSynchronizer(); - dbmsSynchronizer.openSharedDatabase( - new DBMSConnection(dbmsConnectionProperties) - ); + dbmsSynchronizer.openSharedDatabase(new DBMSConnection(dbmsConnectionProperties)); dbmsSynchronizer.registerListener(this); dialogService.notify( Localization.lang( @@ -294,23 +248,18 @@ public void openSharedDatabaseFromParserResult(ParserResult parserResult) } String sharedDatabaseID = sharedDatabaseIDOptional.get(); - DBMSConnectionProperties dbmsConnectionProperties = - new DBMSConnectionProperties( - new SharedDatabasePreferences(sharedDatabaseID) - ); + DBMSConnectionProperties dbmsConnectionProperties = new DBMSConnectionProperties( + new SharedDatabasePreferences(sharedDatabaseID) + ); BibDatabaseContext bibDatabaseContext = new BibDatabaseContext(); bibDatabaseContext.setMode( - preferencesService - .getLibraryPreferences() - .getDefaultBibDatabaseMode() + preferencesService.getLibraryPreferences().getDefaultBibDatabaseMode() ); DBMSSynchronizer synchronizer = new DBMSSynchronizer( bibDatabaseContext, preferencesService.getBibEntryPreferences().getKeywordSeparator(), - preferencesService - .getCitationKeyPatternPreferences() - .getKeyPattern(), + preferencesService.getCitationKeyPatternPreferences().getKeyPattern(), fileUpdateMonitor ); bibDatabaseContext.convertToSharedDatabase(synchronizer); @@ -321,9 +270,7 @@ public void openSharedDatabaseFromParserResult(ParserResult parserResult) ); dbmsSynchronizer = bibDatabaseContext.getDBMSSynchronizer(); - dbmsSynchronizer.openSharedDatabase( - new DBMSConnection(dbmsConnectionProperties) - ); + dbmsSynchronizer.openSharedDatabase(new DBMSConnection(dbmsConnectionProperties)); dbmsSynchronizer.registerListener(this); parserResult.setDatabaseContext(bibDatabaseContext); dialogService.notify( diff --git a/src/main/java/org/jabref/gui/sidepane/GroupsSidePaneComponent.java b/src/main/java/org/jabref/gui/sidepane/GroupsSidePaneComponent.java index 8447f60d077..89954c0a9a1 100644 --- a/src/main/java/org/jabref/gui/sidepane/GroupsSidePaneComponent.java +++ b/src/main/java/org/jabref/gui/sidepane/GroupsSidePaneComponent.java @@ -25,13 +25,7 @@ public GroupsSidePaneComponent( GroupsPreferences groupsPreferences, DialogService dialogService ) { - super( - SidePaneType.GROUPS, - closeCommand, - moveUpCommand, - moveDownCommand, - contentFactory - ); + super(SidePaneType.GROUPS, closeCommand, moveUpCommand, moveDownCommand, contentFactory); this.groupsPreferences = groupsPreferences; this.dialogService = dialogService; setupIntersectionUnionToggle(); @@ -40,21 +34,15 @@ public GroupsSidePaneComponent( groupsPreferences.groupViewModeProperty(), mode -> { GroupModeViewModel modeViewModel = new GroupModeViewModel(mode); - intersectionUnionToggle.setGraphic( - modeViewModel.getUnionIntersectionGraphic() - ); - intersectionUnionToggle.setTooltip( - modeViewModel.getUnionIntersectionTooltip() - ); + intersectionUnionToggle.setGraphic(modeViewModel.getUnionIntersectionGraphic()); + intersectionUnionToggle.setTooltip(modeViewModel.getUnionIntersectionTooltip()); } ); } private void setupIntersectionUnionToggle() { addExtraButtonToHeader(intersectionUnionToggle, 0); - intersectionUnionToggle.setOnAction(event -> - new ToggleUnionIntersectionAction().execute() - ); + intersectionUnionToggle.setOnAction(event -> new ToggleUnionIntersectionAction().execute()); } private class ToggleUnionIntersectionAction extends SimpleCommand { @@ -65,14 +53,10 @@ public void execute() { if (mode == GroupViewMode.UNION) { groupsPreferences.setGroupViewMode(GroupViewMode.INTERSECTION); - dialogService.notify( - Localization.lang("Group view mode set to intersection") - ); + dialogService.notify(Localization.lang("Group view mode set to intersection")); } else if (mode == GroupViewMode.INTERSECTION) { groupsPreferences.setGroupViewMode(GroupViewMode.UNION); - dialogService.notify( - Localization.lang("Group view mode set to union") - ); + dialogService.notify(Localization.lang("Group view mode set to union")); } } } diff --git a/src/main/java/org/jabref/gui/sidepane/SidePane.java b/src/main/java/org/jabref/gui/sidepane/SidePane.java index 2ea44ba7785..a5a2c08e395 100644 --- a/src/main/java/org/jabref/gui/sidepane/SidePane.java +++ b/src/main/java/org/jabref/gui/sidepane/SidePane.java @@ -25,8 +25,7 @@ public class SidePane extends VBox { // These bindings need to be stored, otherwise they are garbage collected @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") - private final Map visibleBindings = - new HashMap<>(); + private final Map visibleBindings = new HashMap<>(); public SidePane( LibraryTabContainer tabContainer, diff --git a/src/main/java/org/jabref/gui/sidepane/SidePaneComponent.java b/src/main/java/org/jabref/gui/sidepane/SidePaneComponent.java index c4aa87f6c51..74531f48569 100644 --- a/src/main/java/org/jabref/gui/sidepane/SidePaneComponent.java +++ b/src/main/java/org/jabref/gui/sidepane/SidePaneComponent.java @@ -42,12 +42,7 @@ private void initialize() { getStyleClass().add("sidePaneComponent"); setTop(createHeaderView()); setCenter(contentFactory.create(sidePaneType)); - VBox.setVgrow( - this, - sidePaneType == SidePaneType.GROUPS - ? Priority.ALWAYS - : Priority.NEVER - ); + VBox.setVgrow(this, sidePaneType == SidePaneType.GROUPS ? Priority.ALWAYS : Priority.NEVER); } private Node createHeaderView() { @@ -60,9 +55,7 @@ private Node createHeaderView() { upButton.setOnAction(e -> moveUpCommand.execute()); Button downButton = IconTheme.JabRefIcons.DOWN.asButton(); - downButton.setTooltip( - new Tooltip(Localization.lang("Move panel down")) - ); + downButton.setTooltip(new Tooltip(Localization.lang("Move panel down"))); downButton.setOnAction(e -> moveDownCommand.execute()); this.buttonContainer = new HBox(); diff --git a/src/main/java/org/jabref/gui/sidepane/SidePaneContentFactory.java b/src/main/java/org/jabref/gui/sidepane/SidePaneContentFactory.java index f11a28f26c0..1d20498034b 100644 --- a/src/main/java/org/jabref/gui/sidepane/SidePaneContentFactory.java +++ b/src/main/java/org/jabref/gui/sidepane/SidePaneContentFactory.java @@ -69,11 +69,7 @@ public Node create(SidePaneType sidePaneType) { undoManager ) .getContent(); - case WEB_SEARCH -> new WebSearchPaneView( - preferences, - dialogService, - stateManager - ); + case WEB_SEARCH -> new WebSearchPaneView(preferences, dialogService, stateManager); }; } } diff --git a/src/main/java/org/jabref/gui/sidepane/SidePaneViewModel.java b/src/main/java/org/jabref/gui/sidepane/SidePaneViewModel.java index 42e546f5903..bc6053fe004 100644 --- a/src/main/java/org/jabref/gui/sidepane/SidePaneViewModel.java +++ b/src/main/java/org/jabref/gui/sidepane/SidePaneViewModel.java @@ -26,12 +26,9 @@ public class SidePaneViewModel extends AbstractViewModel { - private static final Logger LOGGER = LoggerFactory.getLogger( - SidePaneViewModel.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(SidePaneViewModel.class); - private final Map sidePaneComponentLookup = - new HashMap<>(); + private final Map sidePaneComponentLookup = new HashMap<>(); private final PreferencesService preferencesService; private final StateManager stateManager; @@ -65,10 +62,7 @@ public SidePaneViewModel( undoManager ); - preferencesService - .getSidePanePreferences() - .visiblePanes() - .forEach(this::show); + preferencesService.getSidePanePreferences().visiblePanes().forEach(this::show); getPanes() .addListener( (ListChangeListener) change -> { @@ -126,9 +120,7 @@ private void updatePreferredPositions() { IntStream .range(0, getPanes().size()) .forEach(i -> preferredPositions.put(getPanes().get(i), i)); - preferencesService - .getSidePanePreferences() - .setPreferredPositions(preferredPositions); + preferencesService.getSidePanePreferences().setPreferredPositions(preferredPositions); } public void moveUp(SidePaneType pane) { @@ -154,10 +146,7 @@ public void moveDown(SidePaneType pane) { swap(getPanes(), currentPosition, newPosition); updatePreferredPositions(); } else { - LOGGER.debug( - "SidePaneComponent {} is already at the top", - pane.getTitle() - ); + LOGGER.debug("SidePaneComponent {} is already at the top", pane.getTitle()); } } else { LOGGER.warn("SidePaneComponent {} not visible", pane.getTitle()); @@ -167,12 +156,7 @@ public void moveDown(SidePaneType pane) { private void show(SidePaneType pane) { if (!getPanes().contains(pane)) { getPanes().add(pane); - getPanes() - .sort( - new PreferredIndexSort( - preferencesService.getSidePanePreferences() - ) - ); + getPanes().sort(new PreferredIndexSort(preferencesService.getSidePanePreferences())); } else { LOGGER.warn("SidePaneComponent {} not visible", pane.getTitle()); } @@ -191,14 +175,12 @@ private void swap(ObservableList observableList, int i, int j) { /** * Helper class for sorting visible side panes based on their preferred position. */ - protected static class PreferredIndexSort - implements Comparator { + protected static class PreferredIndexSort implements Comparator { private final Map preferredPositions; public PreferredIndexSort(SidePanePreferences sidePanePreferences) { - this.preferredPositions = - sidePanePreferences.getPreferredPositions(); + this.preferredPositions = sidePanePreferences.getPreferredPositions(); } @Override diff --git a/src/main/java/org/jabref/gui/sidepane/TogglePaneAction.java b/src/main/java/org/jabref/gui/sidepane/TogglePaneAction.java index 399adf0c2c4..334b08c0214 100644 --- a/src/main/java/org/jabref/gui/sidepane/TogglePaneAction.java +++ b/src/main/java/org/jabref/gui/sidepane/TogglePaneAction.java @@ -26,11 +26,7 @@ public void execute() { stateManager.getVisibleSidePaneComponents().add(pane); stateManager .getVisibleSidePaneComponents() - .sort( - new SidePaneViewModel.PreferredIndexSort( - sidePanePreferences - ) - ); + .sort(new SidePaneViewModel.PreferredIndexSort(sidePanePreferences)); } else { stateManager.getVisibleSidePaneComponents().remove(pane); } diff --git a/src/main/java/org/jabref/gui/slr/EditExistingStudyAction.java b/src/main/java/org/jabref/gui/slr/EditExistingStudyAction.java index 141530c272f..74affe4fb4f 100644 --- a/src/main/java/org/jabref/gui/slr/EditExistingStudyAction.java +++ b/src/main/java/org/jabref/gui/slr/EditExistingStudyAction.java @@ -16,17 +16,12 @@ public class EditExistingStudyAction extends SimpleCommand { - private static final Logger LOGGER = LoggerFactory.getLogger( - EditExistingStudyAction.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(EditExistingStudyAction.class); private final DialogService dialogService; private final StateManager stateManager; - public EditExistingStudyAction( - DialogService dialogService, - StateManager stateManager - ) { + public EditExistingStudyAction(DialogService dialogService, StateManager stateManager) { this.dialogService = dialogService; this.stateManager = stateManager; this.executable.bind(ActionHelper.needsStudyDatabase(stateManager)); @@ -42,9 +37,7 @@ public void execute() { ) { return; } - BibDatabaseContext bibDatabaseContext = stateManager - .getActiveDatabase() - .get(); + BibDatabaseContext bibDatabaseContext = stateManager.getActiveDatabase().get(); // The action can only be called on an existing AND saved study library // The saving is ensured at creation of a study library @@ -63,21 +56,14 @@ public void execute() { study = new StudyYamlParser() .parseStudyYamlFile( - studyDirectory.resolve( - StudyRepository.STUDY_DEFINITION_FILE_NAME - ) + studyDirectory.resolve(StudyRepository.STUDY_DEFINITION_FILE_NAME) ); } catch (IOException e) { - dialogService.showErrorDialogAndWait( - Localization.lang("Error opening file"), - e - ); + dialogService.showErrorDialogAndWait(Localization.lang("Error opening file"), e); return; } // When the dialog returns, the study.yml file is updated (or kept unmodified at Cancel) - dialogService.showCustomDialogAndWait( - new ManageStudyDefinitionView(study, studyDirectory) - ); + dialogService.showCustomDialogAndWait(new ManageStudyDefinitionView(study, studyDirectory)); } } diff --git a/src/main/java/org/jabref/gui/slr/ExistingStudySearchAction.java b/src/main/java/org/jabref/gui/slr/ExistingStudySearchAction.java index a08f1ae300a..51c9e2acd8c 100644 --- a/src/main/java/org/jabref/gui/slr/ExistingStudySearchAction.java +++ b/src/main/java/org/jabref/gui/slr/ExistingStudySearchAction.java @@ -24,9 +24,7 @@ public class ExistingStudySearchAction extends SimpleCommand { - private static final Logger LOGGER = LoggerFactory.getLogger( - ExistingStudySearchAction.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(ExistingStudySearchAction.class); protected final DialogService dialogService; @@ -93,16 +91,13 @@ public void execute() { LOGGER.error("Database is not present, even if it should"); return; } - BibDatabaseContext bibDatabaseContext = stateManager - .getActiveDatabase() - .get(); + BibDatabaseContext bibDatabaseContext = stateManager.getActiveDatabase().get(); if (bibDatabaseContext.getDatabasePath().isEmpty()) { LOGGER.error("Database path is not present, even if it should"); return; } - this.studyDirectory = - bibDatabaseContext.getDatabasePath().get().getParent(); + this.studyDirectory = bibDatabaseContext.getDatabasePath().get().getParent(); crawl(); } @@ -131,9 +126,7 @@ protected void crawl() { } catch (IOException | ParseException e) { LOGGER.error("Error during reading of study definition file.", e); dialogService.showErrorDialogAndWait( - Localization.lang( - "Error during reading of study definition file." - ), + Localization.lang("Error during reading of study definition file."), e ); return; @@ -148,19 +141,14 @@ protected void crawl() { .onFailure(e -> { LOGGER.error("Error during persistence of crawling results."); dialogService.showErrorDialogAndWait( - Localization.lang( - "Error during persistence of crawling results." - ), + Localization.lang("Error during persistence of crawling results."), e ); }) .onSuccess(unused -> { dialogService.notify(Localization.lang("Finished Searching")); openDatabaseAction.openFile( - Path.of( - this.studyDirectory.toString(), - Crawler.FILENAME_STUDY_RESULT_BIB - ) + Path.of(this.studyDirectory.toString(), Crawler.FILENAME_STUDY_RESULT_BIB) ); }) .executeWith(taskExecutor); @@ -169,8 +157,7 @@ protected void crawl() { /** * Hook for setting up the crawl phase (e.g., initialization the repository) */ - protected void crawlPreparation(Path studyRepositoryRoot) - throws IOException, GitAPIException { + protected void crawlPreparation(Path studyRepositoryRoot) throws IOException, GitAPIException { // Do nothing with the repository as repository is already setup // The user focused an SLR diff --git a/src/main/java/org/jabref/gui/slr/ManageStudyDefinitionView.java b/src/main/java/org/jabref/gui/slr/ManageStudyDefinitionView.java index d4f9015ac4e..6587ecbeeb6 100644 --- a/src/main/java/org/jabref/gui/slr/ManageStudyDefinitionView.java +++ b/src/main/java/org/jabref/gui/slr/ManageStudyDefinitionView.java @@ -38,12 +38,9 @@ * This class controls the user interface of the study definition management dialog. The UI elements and their layout * are defined in the FXML file. */ -public class ManageStudyDefinitionView - extends BaseDialog { +public class ManageStudyDefinitionView extends BaseDialog { - private static final Logger LOGGER = LoggerFactory.getLogger( - ManageStudyDefinitionView.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(ManageStudyDefinitionView.class); @FXML private TextField studyTitle; @@ -160,8 +157,7 @@ public ManageStudyDefinitionView(Study study, Path studyDirectory) { } private void setupSaveSurveyButton(boolean isEdit) { - Button saveSurveyButton = (Button) this.getDialogPane() - .lookupButton(saveSurveyButtonType); + Button saveSurveyButton = (Button) this.getDialogPane().lookupButton(saveSurveyButtonType); if (!isEdit) { saveSurveyButton.setText(Localization.lang("Start survey")); @@ -220,9 +216,7 @@ private void initialize() { // Listen whether any catalogs are removed from selection -> Add back to the catalog selector studyTitle.textProperty().bindBidirectional(viewModel.titleProperty()); - studyDirectory - .textProperty() - .bindBidirectional(viewModel.getDirectory()); + studyDirectory.textProperty().bindBidirectional(viewModel.getDirectory()); initAuthorTab(); initQuestionsTab(); @@ -237,11 +231,7 @@ private void initAuthorTab() { authorsColumn, authorsActionColumn ); - setupCellFactories( - authorsColumn, - authorsActionColumn, - viewModel::deleteAuthor - ); + setupCellFactories(authorsColumn, authorsActionColumn, viewModel::deleteAuthor); authorTableView.setItems(viewModel.getAuthors()); } @@ -252,11 +242,7 @@ private void initQuestionsTab() { questionsColumn, questionsActionColumn ); - setupCellFactories( - questionsColumn, - questionsActionColumn, - viewModel::deleteQuestion - ); + setupCellFactories(questionsColumn, questionsActionColumn, viewModel::deleteQuestion); questionTableView.setItems(viewModel.getResearchQuestions()); } @@ -267,22 +253,14 @@ private void initQueriesTab() { queriesColumn, queriesActionColumn ); - setupCellFactories( - queriesColumn, - queriesActionColumn, - viewModel::deleteQuery - ); + setupCellFactories(queriesColumn, queriesActionColumn, viewModel::deleteQuery); queryTableView.setItems(viewModel.getQueries()); // TODO: Keep until PR #7279 is merged helpIcon.setTooltip( new Tooltip( new StringJoiner("\n") - .add( - Localization.lang( - "Query terms are separated by spaces." - ) - ) + .add(Localization.lang("Query terms are separated by spaces.")) .add( Localization.lang( "All query terms are joined using the logical AND, and OR operators" @@ -318,17 +296,11 @@ private void initCatalogsTab() { catalogEnabledColumn.setResizable(false); catalogEnabledColumn.setReorderable(false); - catalogEnabledColumn.setCellFactory( - CheckBoxTableCell.forTableColumn(catalogEnabledColumn) - ); - catalogEnabledColumn.setCellValueFactory(param -> - param.getValue().enabledProperty() - ); + catalogEnabledColumn.setCellFactory(CheckBoxTableCell.forTableColumn(catalogEnabledColumn)); + catalogEnabledColumn.setCellValueFactory(param -> param.getValue().enabledProperty()); catalogColumn.setEditable(false); - catalogColumn.setCellValueFactory(param -> - param.getValue().nameProperty() - ); + catalogColumn.setCellValueFactory(param -> param.getValue().nameProperty()); catalogTable.setItems(viewModel.getCatalogs()); } @@ -356,16 +328,10 @@ private void setupCellFactories( TableColumn actionColumn, Consumer removeAction ) { - contentColumn.setCellValueFactory(param -> - new SimpleStringProperty(param.getValue()) - ); - actionColumn.setCellValueFactory(param -> - new SimpleStringProperty(param.getValue()) - ); + contentColumn.setCellValueFactory(param -> new SimpleStringProperty(param.getValue())); + actionColumn.setCellValueFactory(param -> new SimpleStringProperty(param.getValue())); new ValueTableCellFactory() - .withGraphic(item -> - IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode() - ) + .withGraphic(item -> IconTheme.JabRefIcons.DELETE_ENTRY.getGraphicNode()) .withTooltip(name -> Localization.lang("Remove")) .withOnMouseClickedEvent(item -> evt -> removeAction.accept(item)) .install(actionColumn); @@ -397,9 +363,7 @@ public void selectStudyDirectory() { .build(); viewModel.setStudyDirectory( - dialogService.showDirectorySelectionDialog( - directoryDialogConfiguration - ) + dialogService.showDirectorySelectionDialog(directoryDialogConfiguration) ); } } diff --git a/src/main/java/org/jabref/gui/slr/ManageStudyDefinitionViewModel.java b/src/main/java/org/jabref/gui/slr/ManageStudyDefinitionViewModel.java index f0213b13564..2126e027cec 100644 --- a/src/main/java/org/jabref/gui/slr/ManageStudyDefinitionViewModel.java +++ b/src/main/java/org/jabref/gui/slr/ManageStudyDefinitionViewModel.java @@ -51,14 +51,10 @@ public class ManageStudyDefinitionViewModel { ); private final StringProperty title = new SimpleStringProperty(); - private final ObservableList authors = - FXCollections.observableArrayList(); - private final ObservableList researchQuestions = - FXCollections.observableArrayList(); - private final ObservableList queries = - FXCollections.observableArrayList(); - private final ObservableList databases = - FXCollections.observableArrayList(); + private final ObservableList authors = FXCollections.observableArrayList(); + private final ObservableList researchQuestions = FXCollections.observableArrayList(); + private final ObservableList queries = FXCollections.observableArrayList(); + private final ObservableList databases = FXCollections.observableArrayList(); // Hold the complement of databases for the selector private final SimpleStringProperty directory = new SimpleStringProperty(); @@ -75,17 +71,12 @@ public ManageStudyDefinitionViewModel( ) { databases.addAll( WebFetchers - .getSearchBasedFetchers( - importFormatPreferences, - importerPreferences - ) + .getSearchBasedFetchers(importFormatPreferences, importerPreferences) .stream() .map(SearchBasedFetcher::getName) // The user wants to select specific fetchers // The fetcher summarizing ALL fetchers can be emulated by selecting ALL fetchers (which happens rarely when doing an SLR) - .filter(name -> - !name.equals(CompositeSearchBasedFetcher.FETCHER_NAME) - ) + .filter(name -> !name.equals(CompositeSearchBasedFetcher.FETCHER_NAME)) .map(name -> { boolean enabled = DEFAULT_SELECTION.contains(name); return new StudyCatalogItem(name, enabled); @@ -112,27 +103,18 @@ public ManageStudyDefinitionViewModel( authors.addAll(Objects.requireNonNull(study).getAuthors()); title.setValue(study.getTitle()); researchQuestions.addAll(study.getResearchQuestions()); - queries.addAll( - study.getQueries().stream().map(StudyQuery::getQuery).toList() - ); + queries.addAll(study.getQueries().stream().map(StudyQuery::getQuery).toList()); List studyDatabases = study.getDatabases(); databases.addAll( WebFetchers - .getSearchBasedFetchers( - importFormatPreferences, - importerPreferences - ) + .getSearchBasedFetchers(importFormatPreferences, importerPreferences) .stream() .map(SearchBasedFetcher::getName) // The user wants to select specific fetchers // The fetcher summarizing ALL fetchers can be emulated by selecting ALL fetchers (which happens rarely when doing an SLR) - .filter(name -> - !name.equals(CompositeSearchBasedFetcher.FETCHER_NAME) - ) + .filter(name -> !name.equals(CompositeSearchBasedFetcher.FETCHER_NAME)) .map(name -> { - boolean enabled = studyDatabases.contains( - new StudyDatabase(name, true) - ); + boolean enabled = studyDatabases.contains(new StudyDatabase(name, true)); return new StudyCatalogItem(name, enabled); }) .toList() @@ -174,10 +156,7 @@ public void addAuthor(String author) { } public void addResearchQuestion(String researchQuestion) { - if ( - researchQuestion.isBlank() || - researchQuestions.contains(researchQuestion) - ) { + if (researchQuestion.isBlank() || researchQuestions.contains(researchQuestion)) { return; } researchQuestions.add(researchQuestion); @@ -199,10 +178,7 @@ public SlrStudyAndDirectory saveStudy() { databases .stream() .map(studyDatabaseItem -> - new StudyDatabase( - studyDatabaseItem.getName(), - studyDatabaseItem.isEnabled() - ) + new StudyDatabase(studyDatabaseItem.getName(), studyDatabaseItem.isEnabled()) ) .filter(StudyDatabase::isEnabled) .collect(Collectors.toList()) @@ -212,15 +188,9 @@ public SlrStudyAndDirectory saveStudy() { try { studyDirectory = Path.of(studyDirectoryAsString); } catch (InvalidPathException e) { - LOGGER.error( - "Invalid path was provided: {}", - studyDirectoryAsString - ); + LOGGER.error("Invalid path was provided: {}", studyDirectoryAsString); dialogService.notify( - Localization.lang( - "Unable to write to %0.", - studyDirectoryAsString - ) + Localization.lang("Unable to write to %0.", studyDirectoryAsString) ); // We do not assume another path - we return that there is an invalid object. return null; @@ -229,18 +199,11 @@ public SlrStudyAndDirectory saveStudy() { StudyRepository.STUDY_DEFINITION_FILE_NAME ); try { - new StudyYamlParser() - .writeStudyYamlFile(study, studyDefinitionFile); + new StudyYamlParser().writeStudyYamlFile(study, studyDefinitionFile); } catch (IOException e) { - LOGGER.error( - "Could not write study file {}", - studyDefinitionFile, - e - ); + LOGGER.error("Could not write study file {}", studyDefinitionFile, e); dialogService.notify( - Localization.lang("Please enter a valid file path.") + - ": " + - studyDirectoryAsString + Localization.lang("Please enter a valid file path.") + ": " + studyDirectoryAsString ); // We do not assume another path - we return that there is an invalid object. return null; @@ -256,9 +219,7 @@ public SlrStudyAndDirectory saveStudy() { e ); dialogService.notify( - Localization.lang("Please enter a valid file path.") + - ": " + - studyDirectory + Localization.lang("Please enter a valid file path.") + ": " + studyDirectory ); // We continue nevertheless as the directory itself could be valid } diff --git a/src/main/java/org/jabref/gui/slr/StartNewStudyAction.java b/src/main/java/org/jabref/gui/slr/StartNewStudyAction.java index 70cfa629a2d..6b78fc0b1ef 100644 --- a/src/main/java/org/jabref/gui/slr/StartNewStudyAction.java +++ b/src/main/java/org/jabref/gui/slr/StartNewStudyAction.java @@ -30,9 +30,7 @@ */ public class StartNewStudyAction extends ExistingStudySearchAction { - private static final Logger LOGGER = LoggerFactory.getLogger( - StartNewStudyAction.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(StartNewStudyAction.class); Study newStudy; @@ -56,34 +54,27 @@ public StartNewStudyAction( } @Override - protected void crawlPreparation(Path studyRepositoryRoot) - throws IOException, GitAPIException { + protected void crawlPreparation(Path studyRepositoryRoot) throws IOException, GitAPIException { StudyYamlParser studyYAMLParser = new StudyYamlParser(); studyYAMLParser.writeStudyYamlFile( newStudy, - studyRepositoryRoot.resolve( - StudyRepository.STUDY_DEFINITION_FILE_NAME - ) + studyRepositoryRoot.resolve(StudyRepository.STUDY_DEFINITION_FILE_NAME) ); // When execution reaches this point, the user created a new study. // The GitHandler is already called to initialize the repository with one single commit "Initial commit". // The "Initial commit" should also contain the created YAML. // Thus, we append to that commit. - new GitHandler(studyRepositoryRoot) - .createCommitOnCurrentBranch("Initial commit", true); + new GitHandler(studyRepositoryRoot).createCommitOnCurrentBranch("Initial commit", true); } @Override public void execute() { - Optional studyAndDirectory = - dialogService.showCustomDialogAndWait( - new ManageStudyDefinitionView( - preferencesService - .getFilePreferences() - .getWorkingDirectory() - ) - ); + Optional studyAndDirectory = dialogService.showCustomDialogAndWait( + new ManageStudyDefinitionView( + preferencesService.getFilePreferences().getWorkingDirectory() + ) + ); if (studyAndDirectory.isEmpty()) { return; } @@ -92,9 +83,7 @@ public void execute() { LOGGER.error("Study directory is blank"); // This branch probably is never taken // Thus, we re-use existing localization - dialogService.showErrorDialogAndWait( - Localization.lang("Must not be empty!") - ); + dialogService.showErrorDialogAndWait(Localization.lang("Must not be empty!")); return; } studyDirectory = studyAndDirectory.get().getStudyDirectory(); diff --git a/src/main/java/org/jabref/gui/slr/StudyCatalogItem.java b/src/main/java/org/jabref/gui/slr/StudyCatalogItem.java index c2c763ecc0b..6eb9be8bd44 100644 --- a/src/main/java/org/jabref/gui/slr/StudyCatalogItem.java +++ b/src/main/java/org/jabref/gui/slr/StudyCatalogItem.java @@ -46,14 +46,7 @@ public BooleanProperty enabledProperty() { @Override public String toString() { - return ( - "StudyCatalogItem{" + - "name=" + - name.get() + - ", enabled=" + - enabled.get() + - '}' - ); + return ("StudyCatalogItem{" + "name=" + name.get() + ", enabled=" + enabled.get() + '}'); } @Override diff --git a/src/main/java/org/jabref/gui/specialfields/SpecialFieldAction.java b/src/main/java/org/jabref/gui/specialfields/SpecialFieldAction.java index aa5ced02ee1..f5cf1c4767e 100644 --- a/src/main/java/org/jabref/gui/specialfields/SpecialFieldAction.java +++ b/src/main/java/org/jabref/gui/specialfields/SpecialFieldAction.java @@ -23,9 +23,7 @@ public class SpecialFieldAction extends SimpleCommand { - private static final Logger LOGGER = LoggerFactory.getLogger( - SpecialFieldAction.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(SpecialFieldAction.class); private final JabRefFrame frame; private final SpecialField specialField; private final String value; @@ -81,9 +79,7 @@ public void execute() { nullFieldIfValueIsTheSame ); - change.ifPresent(fieldChange -> - ce.addEdit(new UndoableFieldChange(fieldChange)) - ); + change.ifPresent(fieldChange -> ce.addEdit(new UndoableFieldChange(fieldChange))); } ce.end(); if (ce.hasEdits()) { @@ -92,15 +88,9 @@ public void execute() { frame.getCurrentLibraryTab().updateEntryEditorIfShowing(); String outText; if (nullFieldIfValueIsTheSame || value == null) { - outText = - getTextDone(specialField, Integer.toString(bes.size())); + outText = getTextDone(specialField, Integer.toString(bes.size())); } else { - outText = - getTextDone( - specialField, - value, - Integer.toString(bes.size()) - ); + outText = getTextDone(specialField, value, Integer.toString(bes.size())); } dialogService.notify(outText); } @@ -119,11 +109,7 @@ private String getTextDone(SpecialField field, String... params) { undoManager ); - if ( - field.isSingleValueField() && - (params.length == 1) && - (params[0] != null) - ) { + if (field.isSingleValueField() && (params.length == 1) && (params[0] != null)) { // Single value fields can be toggled only return Localization.lang( "Toggled '%0' for %1 entries", @@ -137,20 +123,9 @@ private String getTextDone(SpecialField field, String... params) { (params[1] != null) ) { // setting a multi value special field - the setted value is displayed, too - String[] allParams = { - viewModel.getLocalization(), - params[0], - params[1], - }; - return Localization.lang( - "Set '%0' to '%1' for %2 entries", - allParams - ); - } else if ( - !field.isSingleValueField() && - (params.length == 1) && - (params[0] != null) - ) { + String[] allParams = { viewModel.getLocalization(), params[0], params[1] }; + return Localization.lang("Set '%0' to '%1' for %2 entries", allParams); + } else if (!field.isSingleValueField() && (params.length == 1) && (params[0] != null)) { // clearing a multi value specialfield return Localization.lang( "Cleared '%0' for %1 entries", diff --git a/src/main/java/org/jabref/gui/specialfields/SpecialFieldMenuItemFactory.java b/src/main/java/org/jabref/gui/specialfields/SpecialFieldMenuItemFactory.java index f3b62857e86..b7692792a28 100644 --- a/src/main/java/org/jabref/gui/specialfields/SpecialFieldMenuItemFactory.java +++ b/src/main/java/org/jabref/gui/specialfields/SpecialFieldMenuItemFactory.java @@ -24,25 +24,17 @@ public static MenuItem getSpecialFieldSingleItem( UndoManager undoManager, StateManager stateManager ) { - SpecialFieldValueViewModel specialField = - new SpecialFieldValueViewModel(field.getValues().get(0)); + SpecialFieldValueViewModel specialField = new SpecialFieldValueViewModel( + field.getValues().get(0) + ); MenuItem menuItem = factory.createMenuItem( specialField.getAction(), new SpecialFieldViewModel(field, preferencesService, undoManager) - .getSpecialFieldAction( - field.getValues().get(0), - frame, - dialogService, - stateManager - ) + .getSpecialFieldAction(field.getValues().get(0), frame, dialogService, stateManager) ); menuItem .visibleProperty() - .bind( - preferencesService - .getSpecialFieldsPreferences() - .specialFieldsEnabledProperty() - ); + .bind(preferencesService.getSpecialFieldsPreferences().specialFieldsEnabledProperty()); return menuItem; } @@ -61,11 +53,7 @@ public static Menu createSpecialFieldMenu( preferencesService, undoManager, specialField -> - new SpecialFieldViewModel( - field, - preferencesService, - undoManager - ) + new SpecialFieldViewModel(field, preferencesService, undoManager) .getSpecialFieldAction( specialField.getValue(), frame, @@ -90,8 +78,7 @@ public static Menu createSpecialFieldMenu( Menu menu = factory.createMenu(viewModel.getAction()); for (SpecialFieldValue Value : field.getValues()) { - SpecialFieldValueViewModel valueViewModel = - new SpecialFieldValueViewModel(Value); + SpecialFieldValueViewModel valueViewModel = new SpecialFieldValueViewModel(Value); menu .getItems() .add( @@ -104,11 +91,7 @@ public static Menu createSpecialFieldMenu( menu .visibleProperty() - .bind( - preferencesService - .getSpecialFieldsPreferences() - .specialFieldsEnabledProperty() - ); + .bind(preferencesService.getSpecialFieldsPreferences().specialFieldsEnabledProperty()); return menu; } } diff --git a/src/main/java/org/jabref/gui/specialfields/SpecialFieldValueViewModel.java b/src/main/java/org/jabref/gui/specialfields/SpecialFieldValueViewModel.java index 6df1ae372bd..0ea1434ace0 100644 --- a/src/main/java/org/jabref/gui/specialfields/SpecialFieldValueViewModel.java +++ b/src/main/java/org/jabref/gui/specialfields/SpecialFieldValueViewModel.java @@ -43,9 +43,7 @@ public String getToolTipText() { case RANK_3 -> Localization.lang("Three stars"); case RANK_4 -> Localization.lang("Four stars"); case RANK_5 -> Localization.lang("Five stars"); - case CLEAR_READ_STATUS -> Localization.lang( - "No read status information" - ); + case CLEAR_READ_STATUS -> Localization.lang("No read status information"); case READ -> Localization.lang("Read status read"); case SKIMMED -> Localization.lang("Read status skimmed"); case RELEVANT -> Localization.lang("Toggle relevance"); diff --git a/src/main/java/org/jabref/gui/specialfields/SpecialFieldViewModel.java b/src/main/java/org/jabref/gui/specialfields/SpecialFieldViewModel.java index 6b3a8210dd9..0dba82cb7bd 100644 --- a/src/main/java/org/jabref/gui/specialfields/SpecialFieldViewModel.java +++ b/src/main/java/org/jabref/gui/specialfields/SpecialFieldViewModel.java @@ -90,10 +90,7 @@ public List getValues() { .collect(Collectors.toList()); } - public void setSpecialFieldValue( - BibEntry bibEntry, - SpecialFieldValue value - ) { + public void setSpecialFieldValue(BibEntry bibEntry, SpecialFieldValue value) { Optional change = UpdateField.updateField( bibEntry, getField(), @@ -101,9 +98,7 @@ public void setSpecialFieldValue( getField().isSingleValueField() ); - change.ifPresent(fieldChange -> - undoManager.addEdit(new UndoableFieldChange(fieldChange)) - ); + change.ifPresent(fieldChange -> undoManager.addEdit(new UndoableFieldChange(fieldChange))); } public void toggle(BibEntry entry) { diff --git a/src/main/java/org/jabref/gui/specialfields/SpecialFieldsPreferences.java b/src/main/java/org/jabref/gui/specialfields/SpecialFieldsPreferences.java index a59bef6bfd1..ee015786a0d 100644 --- a/src/main/java/org/jabref/gui/specialfields/SpecialFieldsPreferences.java +++ b/src/main/java/org/jabref/gui/specialfields/SpecialFieldsPreferences.java @@ -10,8 +10,7 @@ public class SpecialFieldsPreferences { private final BooleanProperty specialFieldsEnabled; public SpecialFieldsPreferences(boolean specialFieldsEnabled) { - this.specialFieldsEnabled = - new SimpleBooleanProperty(specialFieldsEnabled); + this.specialFieldsEnabled = new SimpleBooleanProperty(specialFieldsEnabled); } public boolean isSpecialFieldsEnabled() { diff --git a/src/main/java/org/jabref/gui/texparser/CitationsDisplay.java b/src/main/java/org/jabref/gui/texparser/CitationsDisplay.java index 5b3e2d9477d..546f1ba798d 100644 --- a/src/main/java/org/jabref/gui/texparser/CitationsDisplay.java +++ b/src/main/java/org/jabref/gui/texparser/CitationsDisplay.java @@ -42,34 +42,20 @@ private Node getDisplayGraphic(Citation item) { basePath.set(item.getPath().getRoot()); } - Node citationIcon = - IconTheme.JabRefIcons.LATEX_COMMENT.getGraphicNode(); - Text contextText = new Text( - LatexToUnicodeAdapter.format(item.getContext()) - ); - contextText - .wrappingWidthProperty() - .bind(this.widthProperty().subtract(85)); + Node citationIcon = IconTheme.JabRefIcons.LATEX_COMMENT.getGraphicNode(); + Text contextText = new Text(LatexToUnicodeAdapter.format(item.getContext())); + contextText.wrappingWidthProperty().bind(this.widthProperty().subtract(85)); HBox contextBox = new HBox(8, citationIcon, contextText); contextBox.getStyleClass().add("contextBox"); Label fileNameLabel = new Label( String.format("%s", basePath.get().relativize(item.getPath())) ); - fileNameLabel.setGraphic( - IconTheme.JabRefIcons.LATEX_FILE.getGraphicNode() - ); + fileNameLabel.setGraphic(IconTheme.JabRefIcons.LATEX_FILE.getGraphicNode()); Label positionLabel = new Label( - String.format( - "(%s:%s-%s)", - item.getLine(), - item.getColStart(), - item.getColEnd() - ) - ); - positionLabel.setGraphic( - IconTheme.JabRefIcons.LATEX_LINE.getGraphicNode() + String.format("(%s:%s-%s)", item.getLine(), item.getColStart(), item.getColEnd()) ); + positionLabel.setGraphic(IconTheme.JabRefIcons.LATEX_LINE.getGraphicNode()); HBox dataBox = new HBox(5, fileNameLabel, positionLabel); return new VBox(contextBox, dataBox); diff --git a/src/main/java/org/jabref/gui/texparser/ParseLatexAction.java b/src/main/java/org/jabref/gui/texparser/ParseLatexAction.java index d8af43dbaaa..a511623f966 100644 --- a/src/main/java/org/jabref/gui/texparser/ParseLatexAction.java +++ b/src/main/java/org/jabref/gui/texparser/ParseLatexAction.java @@ -18,14 +18,10 @@ public ParseLatexAction(StateManager stateManager) { @Override public void execute() { - DialogService dialogService = Injector.instantiateModelOrService( - DialogService.class - ); + DialogService dialogService = Injector.instantiateModelOrService(DialogService.class); BibDatabaseContext database = stateManager .getActiveDatabase() .orElseThrow(NullPointerException::new); - dialogService.showCustomDialogAndWait( - new ParseLatexDialogView(database) - ); + dialogService.showCustomDialogAndWait(new ParseLatexDialogView(database)); } } diff --git a/src/main/java/org/jabref/gui/texparser/ParseLatexDialogView.java b/src/main/java/org/jabref/gui/texparser/ParseLatexDialogView.java index 48ff82026c0..a73fc0957d2 100644 --- a/src/main/java/org/jabref/gui/texparser/ParseLatexDialogView.java +++ b/src/main/java/org/jabref/gui/texparser/ParseLatexDialogView.java @@ -86,8 +86,7 @@ public ParseLatexDialogView(BibDatabaseContext databaseContext) { getDialogPane(), event -> viewModel.parseButtonClicked() ); - Button parseButton = (Button) getDialogPane() - .lookupButton(parseButtonType); + Button parseButton = (Button) getDialogPane().lookupButton(parseButtonType); parseButton .disableProperty() .bind( @@ -110,22 +109,14 @@ private void initialize() { fileMonitor ); - fileTreeView - .getSelectionModel() - .setSelectionMode(SelectionMode.MULTIPLE); - fileTreeView - .showRootProperty() - .bindBidirectional(viewModel.successfulSearchProperty()); + fileTreeView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); + fileTreeView.showRootProperty().bindBidirectional(viewModel.successfulSearchProperty()); fileTreeView .rootProperty() .bind( EasyBind.map( viewModel.rootProperty(), - fileNode -> - new RecursiveTreeItem<>( - fileNode, - FileNodeViewModel::getChildren - ) + fileNode -> new RecursiveTreeItem<>(fileNode, FileNodeViewModel::getChildren) ) ); @@ -153,21 +144,13 @@ private void initialize() { viewModel.latexDirectoryValidation(), latexDirectoryField ); - browseButton - .disableProperty() - .bindBidirectional(viewModel.searchInProgressProperty()); + browseButton.disableProperty().bindBidirectional(viewModel.searchInProgressProperty()); searchButton .disableProperty() .bind(viewModel.latexDirectoryValidation().validProperty().not()); - selectAllButton - .disableProperty() - .bindBidirectional(viewModel.noFilesFoundProperty()); - unselectAllButton - .disableProperty() - .bindBidirectional(viewModel.noFilesFoundProperty()); - progressIndicator - .visibleProperty() - .bindBidirectional(viewModel.searchInProgressProperty()); + selectAllButton.disableProperty().bindBidirectional(viewModel.noFilesFoundProperty()); + unselectAllButton.disableProperty().bindBidirectional(viewModel.noFilesFoundProperty()); + progressIndicator.visibleProperty().bindBidirectional(viewModel.searchInProgressProperty()); } @FXML diff --git a/src/main/java/org/jabref/gui/texparser/ParseLatexDialogViewModel.java b/src/main/java/org/jabref/gui/texparser/ParseLatexDialogViewModel.java index 34f83e2582d..cfe064c92d0 100644 --- a/src/main/java/org/jabref/gui/texparser/ParseLatexDialogViewModel.java +++ b/src/main/java/org/jabref/gui/texparser/ParseLatexDialogViewModel.java @@ -41,9 +41,7 @@ public class ParseLatexDialogViewModel extends AbstractViewModel { - private static final Logger LOGGER = LoggerFactory.getLogger( - ParseLatexDialogViewModel.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(ParseLatexDialogViewModel.class); private static final String TEX_EXT = ".tex"; private final BibDatabaseContext databaseContext; private final DialogService dialogService; @@ -74,15 +72,11 @@ public ParseLatexDialogViewModel( new SimpleStringProperty( databaseContext .getMetaData() - .getLatexFileDirectory( - preferencesService.getFilePreferences().getUserAndHost() - ) + .getLatexFileDirectory(preferencesService.getFilePreferences().getUserAndHost()) .orElse( FileUtil.getInitialDirectory( databaseContext, - preferencesService - .getFilePreferences() - .getWorkingDirectory() + preferencesService.getFilePreferences().getWorkingDirectory() ) ) .toAbsolutePath() @@ -94,15 +88,12 @@ public ParseLatexDialogViewModel( this.searchInProgress = new SimpleBooleanProperty(false); this.successfulSearch = new SimpleBooleanProperty(false); - Predicate isDirectory = path -> - Path.of(path).toFile().isDirectory(); + Predicate isDirectory = path -> Path.of(path).toFile().isDirectory(); latexDirectoryValidator = new FunctionBasedValidator<>( latexFileDirectory, isDirectory, - ValidationMessage.error( - Localization.lang("Please enter a valid file path.") - ) + ValidationMessage.error(Localization.lang("Please enter a valid file path.")) ); } @@ -143,9 +134,7 @@ public void browseButtonClicked() { dialogService .showDirectorySelectionDialog(directoryDialogConfiguration) .ifPresent(selectedDirectory -> { - latexFileDirectory.set( - selectedDirectory.toAbsolutePath().toString() - ); + latexFileDirectory.set(selectedDirectory.toAbsolutePath().toString()); preferencesService .getFilePreferences() .setWorkingDirectory(selectedDirectory.toAbsolutePath()); @@ -178,16 +167,11 @@ private void handleFailure(Exception exception) { final boolean permissionProblem = (exception instanceof IOException) && (exception.getCause() instanceof FileSystemException) && - exception - .getCause() - .getMessage() - .endsWith("Operation not permitted"); + exception.getCause().getMessage().endsWith("Operation not permitted"); if (permissionProblem) { dialogService.showErrorDialogAndWait( String.format( - Localization.lang( - "JabRef does not have permission to access %s" - ), + Localization.lang("JabRef does not have permission to access %s"), exception.getCause().getMessage() ) ); @@ -196,12 +180,9 @@ private void handleFailure(Exception exception) { } } - private FileNodeViewModel searchDirectory(Path directory) - throws IOException { + private FileNodeViewModel searchDirectory(Path directory) throws IOException { if ((directory == null) || !directory.toFile().isDirectory()) { - throw new IOException( - String.format("Invalid directory for searching: %s", directory) - ); + throw new IOException(String.format("Invalid directory for searching: %s", directory)); } FileNodeViewModel parent = new FileNodeViewModel(directory); @@ -209,11 +190,7 @@ private FileNodeViewModel searchDirectory(Path directory) try (Stream filesStream = Files.list(directory)) { fileListPartition = - filesStream.collect( - Collectors.partitioningBy(path -> - path.toFile().isDirectory() - ) - ); + filesStream.collect(Collectors.partitioningBy(path -> path.toFile().isDirectory())); } catch (IOException e) { LOGGER.error( String.format( @@ -245,12 +222,7 @@ private FileNodeViewModel searchDirectory(Path directory) parent.setFileCount(files.size() + fileCount); parent .getChildren() - .addAll( - files - .stream() - .map(FileNodeViewModel::new) - .collect(Collectors.toList()) - ); + .addAll(files.stream().map(FileNodeViewModel::new).collect(Collectors.toList())); return parent; } @@ -276,11 +248,7 @@ public void parseButtonClicked() { ); BackgroundTask - .wrap(() -> - entriesResolver.resolve( - new DefaultLatexParser().parse(fileList) - ) - ) + .wrap(() -> entriesResolver.resolve(new DefaultLatexParser().parse(fileList))) .onRunning(() -> searchInProgress.set(true)) .onFinished(() -> searchInProgress.set(false)) .onSuccess(result -> diff --git a/src/main/java/org/jabref/gui/texparser/ParseLatexResultView.java b/src/main/java/org/jabref/gui/texparser/ParseLatexResultView.java index d209e16c030..a438f7845e6 100644 --- a/src/main/java/org/jabref/gui/texparser/ParseLatexResultView.java +++ b/src/main/java/org/jabref/gui/texparser/ParseLatexResultView.java @@ -58,19 +58,15 @@ public ParseLatexResultView( close(); } ); - Button importButton = (Button) getDialogPane() - .lookupButton(importButtonType); - importButton - .disableProperty() - .bind(viewModel.importButtonDisabledProperty()); + Button importButton = (Button) getDialogPane().lookupButton(importButtonType); + importButton.disableProperty().bind(viewModel.importButtonDisabledProperty()); themeManager.updateFontStyle(getDialogPane().getScene()); } @FXML private void initialize() { - viewModel = - new ParseLatexResultViewModel(resolverResult, databaseContext); + viewModel = new ParseLatexResultViewModel(resolverResult, databaseContext); referenceListView.setItems(viewModel.getReferenceList()); referenceListView.getSelectionModel().selectFirst(); diff --git a/src/main/java/org/jabref/gui/texparser/ParseLatexResultViewModel.java b/src/main/java/org/jabref/gui/texparser/ParseLatexResultViewModel.java index 48826f3f7bc..c3225e20703 100644 --- a/src/main/java/org/jabref/gui/texparser/ParseLatexResultViewModel.java +++ b/src/main/java/org/jabref/gui/texparser/ParseLatexResultViewModel.java @@ -48,19 +48,13 @@ public ParseLatexResultViewModel( .entrySet()) { String key = entry.getKey(); referenceList.add( - new ReferenceViewModel( - key, - newEntryKeys.contains(key), - entry.getValue() - ) + new ReferenceViewModel(key, newEntryKeys.contains(key), entry.getValue()) ); } this.importButtonDisabled = new SimpleBooleanProperty( - referenceList - .stream() - .noneMatch(ReferenceViewModel::isHighlighted) + referenceList.stream().noneMatch(ReferenceViewModel::isHighlighted) ); } @@ -91,14 +85,10 @@ public void activeReferenceChanged(ReferenceViewModel reference) { * Search and import unknown references from associated BIB files. */ public void importButtonClicked() { - DialogService dialogService = Injector.instantiateModelOrService( - DialogService.class - ); + DialogService dialogService = Injector.instantiateModelOrService(DialogService.class); ImportEntriesDialog dialog = new ImportEntriesDialog( databaseContext, - BackgroundTask.wrap(() -> - new ParserResult(resolverResult.getNewEntries()) - ) + BackgroundTask.wrap(() -> new ParserResult(resolverResult.getNewEntries())) ); dialog.setTitle(Localization.lang("Import entries from LaTeX files")); dialogService.showCustomDialogAndWait(dialog); diff --git a/src/main/java/org/jabref/gui/theme/StyleSheet.java b/src/main/java/org/jabref/gui/theme/StyleSheet.java index 7ada5f1903a..cffd23adc5b 100644 --- a/src/main/java/org/jabref/gui/theme/StyleSheet.java +++ b/src/main/java/org/jabref/gui/theme/StyleSheet.java @@ -15,9 +15,7 @@ abstract class StyleSheet { static final String DATA_URL_PREFIX = "data:text/css;charset=utf-8;base64,"; static final String EMPTY_WEBENGINE_CSS = DATA_URL_PREFIX; - private static final Logger LOGGER = LoggerFactory.getLogger( - StyleSheet.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(StyleSheet.class); abstract URL getSceneStylesheet(); @@ -30,9 +28,7 @@ Path getWatchPath() { abstract void reload(); static Optional create(String name) { - Optional styleSheetUrl = Optional.ofNullable( - JabRefFrame.class.getResource(name) - ); + Optional styleSheetUrl = Optional.ofNullable(JabRefFrame.class.getResource(name)); if (styleSheetUrl.isEmpty()) { try { @@ -54,9 +50,7 @@ static Optional create(String name) { if (styleSheetUrl.isEmpty()) { try { - return Optional.of( - new StyleSheetDataUrl(new URL(EMPTY_WEBENGINE_CSS)) - ); + return Optional.of(new StyleSheetDataUrl(new URL(EMPTY_WEBENGINE_CSS))); } catch (MalformedURLException e) { return Optional.empty(); } diff --git a/src/main/java/org/jabref/gui/theme/StyleSheetFile.java b/src/main/java/org/jabref/gui/theme/StyleSheetFile.java index ee1f0227bee..add71923b84 100644 --- a/src/main/java/org/jabref/gui/theme/StyleSheetFile.java +++ b/src/main/java/org/jabref/gui/theme/StyleSheetFile.java @@ -44,9 +44,7 @@ final class StyleSheetFile extends StyleSheet { */ static final int MAX_IN_MEMORY_CSS_LENGTH = 48000; - private static final Logger LOGGER = LoggerFactory.getLogger( - StyleSheetFile.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(StyleSheetFile.class); private final URL url; private final Path path; @@ -72,10 +70,7 @@ void reload() { @Override public URL getSceneStylesheet() { if (!Files.exists(path)) { - LOGGER.warn( - "Cannot load additional css {} because the file does not exist.", - path - ); + LOGGER.warn("Cannot load additional css {} because the file does not exist.", path); return null; } @@ -120,12 +115,8 @@ static Optional getDataUrl(URL url) { byte[] data = inputStream.readNBytes(MAX_IN_MEMORY_CSS_LENGTH); if (data.length < MAX_IN_MEMORY_CSS_LENGTH) { String embeddedDataUrl = - DATA_URL_PREFIX + - Base64.getEncoder().encodeToString(data); - LOGGER.debug( - "Embedded css in data URL of length {}", - embeddedDataUrl.length() - ); + DATA_URL_PREFIX + Base64.getEncoder().encodeToString(data); + LOGGER.debug("Embedded css in data URL of length {}", embeddedDataUrl.length()); return Optional.of(embeddedDataUrl); } else { LOGGER.debug( diff --git a/src/main/java/org/jabref/gui/theme/ThemeManager.java b/src/main/java/org/jabref/gui/theme/ThemeManager.java index 703dc9a9f50..f512e75a764 100644 --- a/src/main/java/org/jabref/gui/theme/ThemeManager.java +++ b/src/main/java/org/jabref/gui/theme/ThemeManager.java @@ -36,9 +36,7 @@ */ public class ThemeManager { - private static final Logger LOGGER = LoggerFactory.getLogger( - ThemeManager.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(ThemeManager.class); private final WorkspacePreferences workspacePreferences; private final FileUpdateMonitor fileUpdateMonitor; @@ -48,9 +46,7 @@ public class ThemeManager { private Theme theme; private Scene mainWindowScene; - private final Set webEngines = Collections.newSetFromMap( - new WeakHashMap<>() - ); + private final Set webEngines = Collections.newSetFromMap(new WeakHashMap<>()); private final OsThemeDetector detector = OsThemeDetector.getDetector(); public ThemeManager( @@ -58,8 +54,7 @@ public ThemeManager( FileUpdateMonitor fileUpdateMonitor, Consumer updateRunner ) { - this.workspacePreferences = - Objects.requireNonNull(workspacePreferences); + this.workspacePreferences = Objects.requireNonNull(workspacePreferences); this.fileUpdateMonitor = Objects.requireNonNull(fileUpdateMonitor); this.updateRunner = Objects.requireNonNull(updateRunner); @@ -71,10 +66,7 @@ public ThemeManager( addStylesheetToWatchlist(this.baseStyleSheet, this::baseCssLiveUpdate); baseCssLiveUpdate(); - EasyBind.subscribe( - workspacePreferences.themeProperty(), - theme -> updateThemeSettings() - ); + EasyBind.subscribe(workspacePreferences.themeProperty(), theme -> updateThemeSettings()); EasyBind.subscribe( workspacePreferences.themeSyncOsProperty(), theme -> updateThemeSettings() @@ -91,9 +83,7 @@ public ThemeManager( } private void updateThemeSettings() { - Theme newTheme = Objects.requireNonNull( - workspacePreferences.getTheme() - ); + Theme newTheme = Objects.requireNonNull(workspacePreferences.getTheme()); if (workspacePreferences.themeSyncOsProperty().getValue()) { if (detector.isDark()) { @@ -106,24 +96,15 @@ private void updateThemeSettings() { if (newTheme.equals(theme)) { LOGGER.info("Not updating theme because it hasn't changed"); } else { - theme - .getAdditionalStylesheet() - .ifPresent(this::removeStylesheetFromWatchList); + theme.getAdditionalStylesheet().ifPresent(this::removeStylesheetFromWatchList); } this.theme = newTheme; - LOGGER.info( - "Theme set to {} with base css {}", - newTheme, - baseStyleSheet - ); + LOGGER.info("Theme set to {} with base css {}", newTheme, baseStyleSheet); this.theme.getAdditionalStylesheet() .ifPresent(styleSheet -> - addStylesheetToWatchlist( - styleSheet, - this::additionalCssLiveUpdate - ) + addStylesheetToWatchlist(styleSheet, this::additionalCssLiveUpdate) ); additionalCssLiveUpdate(); @@ -131,38 +112,26 @@ private void updateThemeSettings() { private void updateFontSettings() { DefaultTaskExecutor.runInJavaFXThread(() -> - updateRunner.accept(() -> - getMainWindowScene().ifPresent(this::updateFontStyle) - ) + updateRunner.accept(() -> getMainWindowScene().ifPresent(this::updateFontStyle)) ); } private void removeStylesheetFromWatchList(StyleSheet styleSheet) { Path oldPath = styleSheet.getWatchPath(); if (oldPath != null) { - fileUpdateMonitor.removeListener( - oldPath, - this::additionalCssLiveUpdate - ); + fileUpdateMonitor.removeListener(oldPath, this::additionalCssLiveUpdate); LOGGER.info("No longer watch css {} for live updates", oldPath); } } - private void addStylesheetToWatchlist( - StyleSheet styleSheet, - FileUpdateListener updateMethod - ) { + private void addStylesheetToWatchlist(StyleSheet styleSheet, FileUpdateListener updateMethod) { Path watchPath = styleSheet.getWatchPath(); if (watchPath != null) { try { fileUpdateMonitor.addListenerForFile(watchPath, updateMethod); LOGGER.info("Watching css {} for live updates", watchPath); } catch (IOException e) { - LOGGER.warn( - "Cannot watch css path {} for live updates", - watchPath, - e - ); + LOGGER.warn("Cannot watch css path {} for live updates", watchPath, e); } } } @@ -175,9 +144,7 @@ private void baseCssLiveUpdate() { LOGGER.debug("Updating base CSS for main window scene"); } - DefaultTaskExecutor.runInJavaFXThread(() -> - updateRunner.accept(this::updateBaseCss) - ); + DefaultTaskExecutor.runInJavaFXThread(() -> updateRunner.accept(this::updateBaseCss)); } private void additionalCssLiveUpdate() { @@ -200,11 +167,7 @@ private void additionalCssLiveUpdate() { webEngines.forEach(webEngine -> { // force refresh by unloading style sheet, if the location hasn't changed - if ( - newStyleSheetLocation.equals( - webEngine.getUserStyleSheetLocation() - ) - ) { + if (newStyleSheetLocation.equals(webEngine.getUserStyleSheetLocation())) { webEngine.setUserStyleSheetLocation(null); } webEngine.setUserStyleSheetLocation(newStyleSheetLocation); @@ -221,10 +184,7 @@ private void updateBaseCss() { stylesheets.remove(0); } - stylesheets.add( - 0, - baseStyleSheet.getSceneStylesheet().toExternalForm() - ); + stylesheets.add(0, baseStyleSheet.getSceneStylesheet().toExternalForm()); }); } @@ -235,14 +195,11 @@ private void updateAdditionalCss() { .getStylesheets() .setAll( List.of( - baseStyleSheet - .getSceneStylesheet() - .toExternalForm(), + baseStyleSheet.getSceneStylesheet().toExternalForm(), theme .getAdditionalStylesheet() .map(styleSheet -> { - URL stylesheetUrl = - styleSheet.getSceneStylesheet(); + URL stylesheetUrl = styleSheet.getSceneStylesheet(); if (stylesheetUrl != null) { return stylesheetUrl.toExternalForm(); } else { @@ -281,9 +238,7 @@ public void installCss(WebEngine webEngine) { if (this.webEngines.add(webEngine)) { webEngine.setUserStyleSheetLocation( this.theme.getAdditionalStylesheet().isPresent() - ? this.theme.getAdditionalStylesheet() - .get() - .getWebEngineStylesheet() + ? this.theme.getAdditionalStylesheet().get().getWebEngineStylesheet() : "" ); } @@ -300,19 +255,11 @@ public void updateFontStyle(Scene scene) { if (workspacePreferences.shouldOverrideDefaultFontSize()) { scene .getRoot() - .setStyle( - "-fx-font-size: " + - workspacePreferences.getMainFontSize() + - "pt;" - ); + .setStyle("-fx-font-size: " + workspacePreferences.getMainFontSize() + "pt;"); } else { scene .getRoot() - .setStyle( - "-fx-font-size: " + - workspacePreferences.getDefaultFontSize() + - "pt;" - ); + .setStyle("-fx-font-size: " + workspacePreferences.getDefaultFontSize() + "pt;"); } } diff --git a/src/main/java/org/jabref/gui/undo/AbstractUndoableJabRefEdit.java b/src/main/java/org/jabref/gui/undo/AbstractUndoableJabRefEdit.java index 3c9b6c2cee3..b93ec0b4501 100644 --- a/src/main/java/org/jabref/gui/undo/AbstractUndoableJabRefEdit.java +++ b/src/main/java/org/jabref/gui/undo/AbstractUndoableJabRefEdit.java @@ -7,23 +7,11 @@ public class AbstractUndoableJabRefEdit extends AbstractUndoableEdit { @Override public String getUndoPresentationName() { - return ( - "" + - Localization.lang("Undo") + - ": " + - getPresentationName() + - "" - ); + return ("" + Localization.lang("Undo") + ": " + getPresentationName() + ""); } @Override public String getRedoPresentationName() { - return ( - "" + - Localization.lang("Redo") + - ": " + - getPresentationName() + - "" - ); + return ("" + Localization.lang("Redo") + ": " + getPresentationName() + ""); } } diff --git a/src/main/java/org/jabref/gui/undo/UndoRedoAction.java b/src/main/java/org/jabref/gui/undo/UndoRedoAction.java index 5bfad338bb1..7a703ec5be6 100644 --- a/src/main/java/org/jabref/gui/undo/UndoRedoAction.java +++ b/src/main/java/org/jabref/gui/undo/UndoRedoAction.java @@ -15,9 +15,7 @@ public class UndoRedoAction extends SimpleCommand { - private static final Logger LOGGER = LoggerFactory.getLogger( - UndoRedoAction.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(UndoRedoAction.class); private final StandardActions action; private final JabRefFrame frame; @@ -47,9 +45,7 @@ public void execute() { libraryTab.markBaseChanged(); dialogService.notify(Localization.lang("Undo")); } catch (CannotUndoException ex) { - dialogService.notify( - Localization.lang("Nothing to undo") + '.' - ); + dialogService.notify(Localization.lang("Nothing to undo") + '.'); } frame.getCurrentLibraryTab().markChangedOrUnChanged(); } else if (action == StandardActions.REDO) { @@ -58,9 +54,7 @@ public void execute() { libraryTab.markBaseChanged(); dialogService.notify(Localization.lang("Redo")); } catch (CannotRedoException ex) { - dialogService.notify( - Localization.lang("Nothing to redo") + '.' - ); + dialogService.notify(Localization.lang("Nothing to redo") + '.'); } libraryTab.markChangedOrUnChanged(); diff --git a/src/main/java/org/jabref/gui/undo/UndoableChangeType.java b/src/main/java/org/jabref/gui/undo/UndoableChangeType.java index 19edc2b6dce..eae5733bbc1 100644 --- a/src/main/java/org/jabref/gui/undo/UndoableChangeType.java +++ b/src/main/java/org/jabref/gui/undo/UndoableChangeType.java @@ -24,11 +24,7 @@ public UndoableChangeType(FieldChange change) { ); } - public UndoableChangeType( - BibEntry entry, - EntryType oldType, - EntryType newType - ) { + public UndoableChangeType(BibEntry entry, EntryType oldType, EntryType newType) { this.oldType = oldType; this.newType = newType; this.entry = entry; @@ -38,13 +34,8 @@ public UndoableChangeType( public String getPresentationName() { return Localization.lang( "change type of entry %0 from %1 to %2", - StringUtil.boldHTML( - entry.getCitationKey().orElse(Localization.lang("undefined")) - ), - StringUtil.boldHTML( - oldType.getDisplayName(), - Localization.lang("undefined") - ), + StringUtil.boldHTML(entry.getCitationKey().orElse(Localization.lang("undefined"))), + StringUtil.boldHTML(oldType.getDisplayName(), Localization.lang("undefined")), StringUtil.boldHTML(newType.getDisplayName()) ); } diff --git a/src/main/java/org/jabref/gui/undo/UndoableFieldChange.java b/src/main/java/org/jabref/gui/undo/UndoableFieldChange.java index 2d5b172d3bc..85932f42407 100644 --- a/src/main/java/org/jabref/gui/undo/UndoableFieldChange.java +++ b/src/main/java/org/jabref/gui/undo/UndoableFieldChange.java @@ -15,21 +15,14 @@ */ public class UndoableFieldChange extends AbstractUndoableJabRefEdit { - private static final Logger LOGGER = LoggerFactory.getLogger( - UndoableFieldChange.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(UndoableFieldChange.class); private final BibEntry entry; private final Field field; private final String oldValue; private final String newValue; - public UndoableFieldChange( - BibEntry entry, - Field field, - String oldValue, - String newValue - ) { + public UndoableFieldChange(BibEntry entry, Field field, String oldValue, String newValue) { this.entry = entry; this.field = field; this.oldValue = oldValue; @@ -37,12 +30,7 @@ public UndoableFieldChange( } public UndoableFieldChange(FieldChange change) { - this( - change.getEntry(), - change.getField(), - change.getOldValue(), - change.getNewValue() - ); + this(change.getEntry(), change.getField(), change.getOldValue(), change.getNewValue()); } @Override @@ -50,9 +38,7 @@ public String getPresentationName() { return Localization.lang( "change field %0 of entry %1 from %2 to %3", StringUtil.boldHTML(field.getDisplayName()), - StringUtil.boldHTML( - entry.getCitationKey().orElse(Localization.lang("undefined")) - ), + StringUtil.boldHTML(entry.getCitationKey().orElse(Localization.lang("undefined"))), StringUtil.boldHTML(oldValue, Localization.lang("undefined")), StringUtil.boldHTML(newValue, Localization.lang("undefined")) ); diff --git a/src/main/java/org/jabref/gui/undo/UndoableInsertEntries.java b/src/main/java/org/jabref/gui/undo/UndoableInsertEntries.java index 9c1264c5143..c11be8c3976 100644 --- a/src/main/java/org/jabref/gui/undo/UndoableInsertEntries.java +++ b/src/main/java/org/jabref/gui/undo/UndoableInsertEntries.java @@ -16,9 +16,7 @@ */ public class UndoableInsertEntries extends AbstractUndoableJabRefEdit { - private static final Logger LOGGER = LoggerFactory.getLogger( - UndoableInsertEntries.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(UndoableInsertEntries.class); private final BibDatabase database; private final List entries; private final boolean paste; @@ -31,11 +29,7 @@ public UndoableInsertEntries(BibDatabase database, List entries) { this(database, entries, false); } - public UndoableInsertEntries( - BibDatabase database, - List entries, - boolean paste - ) { + public UndoableInsertEntries(BibDatabase database, List entries, boolean paste) { this.database = database; this.entries = entries; this.paste = paste; @@ -50,10 +44,7 @@ public String getPresentationName() { return Localization.lang( "paste entry %0", StringUtil.boldHTML( - entries - .get(0) - .getCitationKey() - .orElse(Localization.lang("undefined")) + entries.get(0).getCitationKey().orElse(Localization.lang("undefined")) ) ); } else { @@ -66,10 +57,7 @@ public String getPresentationName() { return Localization.lang( "insert entry %0", StringUtil.boldHTML( - entries - .get(0) - .getCitationKey() - .orElse(Localization.lang("undefined")) + entries.get(0).getCitationKey().orElse(Localization.lang("undefined")) ) ); } else { diff --git a/src/main/java/org/jabref/gui/undo/UndoableInsertString.java b/src/main/java/org/jabref/gui/undo/UndoableInsertString.java index aee395f42ea..0f0ef17a108 100644 --- a/src/main/java/org/jabref/gui/undo/UndoableInsertString.java +++ b/src/main/java/org/jabref/gui/undo/UndoableInsertString.java @@ -10,9 +10,7 @@ public class UndoableInsertString extends AbstractUndoableJabRefEdit { - private static final Logger LOGGER = LoggerFactory.getLogger( - UndoableInsertString.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(UndoableInsertString.class); private final BibDatabase base; private final BibtexString string; @@ -24,10 +22,7 @@ public UndoableInsertString(BibDatabase base, BibtexString string) { @Override public String getPresentationName() { - return Localization.lang( - "insert string %0", - StringUtil.boldHTML(string.toString()) - ); + return Localization.lang("insert string %0", StringUtil.boldHTML(string.toString())); } @Override diff --git a/src/main/java/org/jabref/gui/undo/UndoablePreambleChange.java b/src/main/java/org/jabref/gui/undo/UndoablePreambleChange.java index 67e05b211d3..af90af87ebd 100644 --- a/src/main/java/org/jabref/gui/undo/UndoablePreambleChange.java +++ b/src/main/java/org/jabref/gui/undo/UndoablePreambleChange.java @@ -12,11 +12,7 @@ public class UndoablePreambleChange extends AbstractUndoableJabRefEdit { private final String oldValue; private final String newValue; - public UndoablePreambleChange( - BibDatabase base, - String oldValue, - String newValue - ) { + public UndoablePreambleChange(BibDatabase base, String oldValue, String newValue) { this.base = base; this.oldValue = oldValue; this.newValue = newValue; diff --git a/src/main/java/org/jabref/gui/undo/UndoableRemoveEntries.java b/src/main/java/org/jabref/gui/undo/UndoableRemoveEntries.java index 7351a9d4338..6c0395b76f4 100644 --- a/src/main/java/org/jabref/gui/undo/UndoableRemoveEntries.java +++ b/src/main/java/org/jabref/gui/undo/UndoableRemoveEntries.java @@ -19,9 +19,7 @@ */ public class UndoableRemoveEntries extends AbstractUndoableJabRefEdit { - private static final Logger LOGGER = LoggerFactory.getLogger( - UndoableRemoveEntries.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(UndoableRemoveEntries.class); private final BibDatabase base; private final List entries; private final boolean cut; @@ -34,11 +32,7 @@ public UndoableRemoveEntries(BibDatabase base, List entries) { this(base, entries, false); } - public UndoableRemoveEntries( - BibDatabase base, - List entries, - boolean cut - ) { + public UndoableRemoveEntries(BibDatabase base, List entries, boolean cut) { this.base = base; this.entries = entries; this.cut = cut; @@ -53,10 +47,7 @@ public String getPresentationName() { return Localization.lang( "cut entry %0", StringUtil.boldHTML( - entries - .get(0) - .getCitationKey() - .orElse(Localization.lang("undefined")) + entries.get(0).getCitationKey().orElse(Localization.lang("undefined")) ) ); } else { @@ -69,10 +60,7 @@ public String getPresentationName() { return Localization.lang( "remove entry %0", StringUtil.boldHTML( - entries - .get(0) - .getCitationKey() - .orElse(Localization.lang("undefined")) + entries.get(0).getCitationKey().orElse(Localization.lang("undefined")) ) ); } else { diff --git a/src/main/java/org/jabref/gui/undo/UndoableRemoveString.java b/src/main/java/org/jabref/gui/undo/UndoableRemoveString.java index 9babbdf2f97..cca522be9c3 100644 --- a/src/main/java/org/jabref/gui/undo/UndoableRemoveString.java +++ b/src/main/java/org/jabref/gui/undo/UndoableRemoveString.java @@ -10,9 +10,7 @@ public class UndoableRemoveString extends AbstractUndoableJabRefEdit { - private static final Logger LOGGER = LoggerFactory.getLogger( - UndoableRemoveString.class - ); + private static final Logger LOGGER = LoggerFactory.getLogger(UndoableRemoveString.class); private final BibDatabase base; private final BibtexString string; @@ -23,10 +21,7 @@ public UndoableRemoveString(BibDatabase base, BibtexString string) { @Override public String getPresentationName() { - return Localization.lang( - "remove string %0", - StringUtil.boldHTML(string.toString()) - ); + return Localization.lang("remove string %0", StringUtil.boldHTML(string.toString())); } @Override diff --git a/src/main/java/org/jabref/gui/util/BackgroundTask.java b/src/main/java/org/jabref/gui/util/BackgroundTask.java index 824eaa9474d..823e842f4b2 100644 --- a/src/main/java/org/jabref/gui/util/BackgroundTask.java +++ b/src/main/java/org/jabref/gui/util/BackgroundTask.java @@ -40,25 +40,18 @@ public abstract class BackgroundTask { private Consumer onException; private Runnable onFinished; private final BooleanProperty isCanceled = new SimpleBooleanProperty(false); - private final ObjectProperty progress = - new SimpleObjectProperty<>(new BackgroundProgress(0, 0)); - private final StringProperty message = new SimpleStringProperty(""); - private final StringProperty title = new SimpleStringProperty( - this.getClass().getSimpleName() - ); - private final DoubleProperty workDonePercentage = new SimpleDoubleProperty( - 0 + private final ObjectProperty progress = new SimpleObjectProperty<>( + new BackgroundProgress(0, 0) ); + private final StringProperty message = new SimpleStringProperty(""); + private final StringProperty title = new SimpleStringProperty(this.getClass().getSimpleName()); + private final DoubleProperty workDonePercentage = new SimpleDoubleProperty(0); private final BooleanProperty showToUser = new SimpleBooleanProperty(false); - private final BooleanProperty willBeRecoveredAutomatically = - new SimpleBooleanProperty(false); + private final BooleanProperty willBeRecoveredAutomatically = new SimpleBooleanProperty(false); public BackgroundTask() { workDonePercentage.bind( - EasyBind.map( - progress, - BackgroundTask.BackgroundProgress::getWorkDonePercentage - ) + EasyBind.map(progress, BackgroundTask.BackgroundProgress::getWorkDonePercentage) ); } @@ -144,9 +137,7 @@ public boolean willBeRecoveredAutomatically() { return willBeRecoveredAutomatically.get(); } - public void willBeRecoveredAutomatically( - boolean willBeRecoveredAutomatically - ) { + public void willBeRecoveredAutomatically(boolean willBeRecoveredAutomatically) { this.willBeRecoveredAutomatically.set(willBeRecoveredAutomatically); } @@ -194,11 +185,7 @@ public Future executeWith(TaskExecutor taskExecutor) { return taskExecutor.execute(this); } - public Future scheduleWith( - TaskExecutor taskExecutor, - long delay, - TimeUnit unit - ) { + public Future scheduleWith(TaskExecutor taskExecutor, long delay, TimeUnit unit) { return taskExecutor.schedule(this, delay, unit); } @@ -217,18 +204,13 @@ public BackgroundTask onFinished(Runnable onFinished) { * @param nextTaskFactory the function that creates the new task * @param type of the return value of the second task */ - public BackgroundTask then( - Function> nextTaskFactory - ) { + public BackgroundTask then(Function> nextTaskFactory) { return new BackgroundTask<>() { @Override protected T call() throws Exception { V result = BackgroundTask.this.call(); BackgroundTask nextTask = nextTaskFactory.apply(result); - EasyBind.subscribe( - nextTask.progressProperty(), - this::updateProgress - ); + EasyBind.subscribe(nextTask.progressProperty(), this::updateProgress); return nextTask.call(); } }; @@ -245,13 +227,8 @@ public BackgroundTask thenRun(Function nextOperation) { @Override protected T call() throws Exception { V result = BackgroundTask.this.call(); - BackgroundTask nextTask = BackgroundTask.wrap(() -> - nextOperation.apply(result) - ); - EasyBind.subscribe( - nextTask.progressProperty(), - this::updateProgress - ); + BackgroundTask nextTask = BackgroundTask.wrap(() -> nextOperation.apply(result)); + EasyBind.subscribe(nextTask.progressProperty(), this::updateProgress); return nextTask.call(); } }; @@ -270,10 +247,7 @@ protected Void call() throws Exception { BackgroundTask nextTask = BackgroundTask.wrap(() -> nextOperation.accept(result) ); - EasyBind.subscribe( - nextTask.progressProperty(), - this::updateProgress - ); + EasyBind.subscribe(nextTask.progressProperty(), this::updateProgress); return nextTask.call(); } }; diff --git a/src/main/java/org/jabref/gui/util/BaseDialog.java b/src/main/java/org/jabref/gui/util/BaseDialog.java index 2b49e9762b8..91edc09b1cc 100644 --- a/src/main/java/org/jabref/gui/util/BaseDialog.java +++ b/src/main/java/org/jabref/gui/util/BaseDialog.java @@ -12,22 +12,14 @@ import org.jabref.gui.keyboard.KeyBinding; import org.jabref.gui.keyboard.KeyBindingRepository; -public class BaseDialog - extends Dialog - implements org.jabref.gui.Dialog { +public class BaseDialog extends Dialog implements org.jabref.gui.Dialog { protected BaseDialog() { getDialogPane() .getScene() .setOnKeyPressed(event -> { - KeyBindingRepository keyBindingRepository = - Globals.getKeyPrefs(); - if ( - keyBindingRepository.checkKeyCombinationEquality( - KeyBinding.CLOSE, - event - ) - ) { + KeyBindingRepository keyBindingRepository = Globals.getKeyPrefs(); + if (keyBindingRepository.checkKeyCombinationEquality(KeyBinding.CLOSE, event)) { close(); } else if ( keyBindingRepository.checkKeyCombinationEquality( @@ -52,9 +44,7 @@ protected BaseDialog() { } private Optional