From c11f8fc6d867c1c05a0fcbaf3f612ee870eec876 Mon Sep 17 00:00:00 2001 From: Loay Ghreeb Date: Fri, 10 Jan 2025 00:54:25 +0200 Subject: [PATCH] Fix main table sorting (#12371) * Fix main table sorting * Add changelog entries --------- Co-authored-by: Carl Christian Snethlage <50491877+calixtus@users.noreply.github.com> --- CHANGELOG.md | 2 ++ .../org/jabref/gui/maintable/MainTable.java | 23 ++++++++++++++++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c89c2daf5f6..78969b0b554 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,8 @@ Note that this project **does not** adhere to [Semantic Versioning](https://semv ### Fixed - We fixed an issue where a bib file with UFF-8 charset was wrongly loaded with a different charset [forum#5369](https://discourse.jabref.org/t/jabref-5-15-opens-bib-files-with-shift-jis-encoding-instead-of-utf-8/5369/) +- We fixed an issue where new entries were inserted in the middle of the table instead of at the end. [#12371](https://github.com/JabRef/jabref/pull/12371) +- We fixed an issue where removing the sort from the table did not restore the original order. [#12371](https://github.com/JabRef/jabref/pull/12371) ### Removed diff --git a/src/main/java/org/jabref/gui/maintable/MainTable.java b/src/main/java/org/jabref/gui/maintable/MainTable.java index accc3879fd3..c24019ea46b 100644 --- a/src/main/java/org/jabref/gui/maintable/MainTable.java +++ b/src/main/java/org/jabref/gui/maintable/MainTable.java @@ -185,7 +185,28 @@ public MainTable(MainTableDataModel model, this.setItems(model.getEntriesFilteredAndSorted()); // Enable sorting - model.getEntriesFilteredAndSorted().comparatorProperty().bind(this.comparatorProperty()); + // Workaround for a JavaFX bug: https://bugs.openjdk.org/browse/JDK-8301761 (The sorting of the SortedList can become invalid) + // The default comparator of the SortedList does not consider the insertion index of entries that are equal according to the comparator. + // When two entries are equal based on the comparator, the entry that was inserted first should be considered smaller. + this.setSortPolicy(_ -> true); + model.getEntriesFilteredAndSorted().comparatorProperty().bind( + this.comparatorProperty().map(comparator -> { + if (comparator == null) { + return null; + } + + return (entry1, entry2) -> { + int result = comparator.compare(entry1, entry2); + if (result != 0) { + return result; + } + // If the entries are equal according to the comparator, compare them by their index in the database. + // The comparison should ideally be based on the database index, but retrieving the index takes log(n). See {@link BibDatabase#indexOf}. + // Using the entry ID is also valid since IDs are monotonically increasing. + return entry1.getEntry().getId().compareTo(entry2.getEntry().getId()); + }; + }) + ); // Store visual state new PersistenceVisualStateTable(this, mainTablePreferences.getColumnPreferences()).addListeners();