Skip to content

Add toggle functionality for journal abbreviation lists #12912

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 49 commits into
base: main
Choose a base branch
from

Conversation

zikunz
Copy link

@zikunz zikunz commented Apr 8, 2025

Toggle Functionality for Journal Abbreviation Lists

Closes #12468.

Documentation repo's issue is JabRef/user-documentation#560

What

This feature is comprehensive and solves more than what is asked in #12468.

Specifially, this PR adds the ability to enable/disable any journal abbreviation lists in JabRef, including both the built-in list and external CSV files. Users can now toggle all types of journal abbreviation lists on/off to make them enabled/disabled.

We can disable and re-enable the built-in list:
Screen Shot 2025-04-24 at 4 03 14 AM

If the built-in list is disabled, journal names found in the built-in list will not be abbreviated or unabbreviated:
Screen Shot 2025-04-24 at 4 03 55 AM
Screen Shot 2025-04-24 at 4 04 27 AM

In addition, external CSV files can be disabled or enabled. Likewise, if an external CSV file is disabled, journal names found in the external CSV file will not be abbreviated or unabbreviated too.

Why

In the original codebase, all journal abbreviation lists were always active once loaded. Users had no way to temporarily disable specific abbreviation sources without completely removing them. This was particularly problematic with the built-in list, which could not be removed at all. Detailed reasons about why we want to disable built-in list sometimes can be found in #12468.

This feature improves workflow flexibility by allowing users to:

  • Temporarily enable/disable specific sources during editing sessions
  • Control which lists are active without removing them

How

The implementation follows JabRef's existing architecture patterns

Key Features

Filtering Logic

  • Only enabled abbreviation sources will apply changes during operations
  • Disabled abbreviation sources have no effect on journal name processing
  • The repository dynamically filters abbreviations based on source enabled state

Persistence

  • Toggle states are stored in preferences only upon clicking "Save"
  • If the user clicks "Cancel" or closes the dialog (X), previous states are restored
  • States persist between application restarts

UI Feedback

  • Visual indicators show enabled/disabled state for each list
  • Toggle button provides easy access to state change
  • Dropdown shows current state with clear visual indicators

Design Considerations

Performance Considerations

The implementation reloads the journal repository before each abbreviation operation to ensure it uses the latest toggle states. This approach has minimal performance impact because:

  1. Repository loading is very efficient as it only builds active abbreviation sets
  2. Abbreviation operations are typically infrequent user actions
  3. The benefits of having accurate, up-to-date toggle states outweigh the small overhead of reloading

I have also tested with fairly large abbreviation lists and observed no noticeable performance degradation.

Design Alternatives Considered

  1. Event-based updates: I considered using an event system to update the repository when toggle states change. While potentially more efficient, this approach would be more complex and error-prone, requiring careful synchronization between preference changes and repository state.

  2. Runtime filtering: Another approach was to keep all abbreviations loaded and filter at runtime during abbreviation operations. This would be slightly faster but would require more memory and complicate the core lookup methods.

  3. Separate repositories: I also considered maintaining separate repositories for each source, but this would diverge significantly from JabRef's existing architecture and complicate cross-source operations.

The chosen approach of reloading the repository provides the best balance of reliability, maintainability, and adherence to existing architecture patterns.

Proposed Code Changes

Frontend Changes (GUI)

  1. JournalAbbreviationsTab.java

    • Purpose: User interface tab for managing journal abbreviations
    • Changes:
      • Added toggle button next to journal list dropdown
      • Created custom ListCell displaying checkmarks (✓) or circles (○) to indicate enabled state
      • Implemented real-time UI refresh when toggling lists
    • Why: Provides the visual interface for users to see and change enabled states
  2. AbbreviationsFileViewModel.java

    • Purpose: View model for a single abbreviation file
    • Changes:
      • Added enabledProperty to track and bind state
      • Implemented getter/setter methods for state access
      • Added path handling for consistent preference storage
    • Why: Provides the model binding for UI components to reflect enabled state changes
  3. JournalAbbreviationsTabViewModel.java

    • Purpose: Manages the journal abbreviation tab's business logic
    • Changes:
      • Implemented state tracking with proper model update notification
      • Added event handling for toggle button click
      • Added methods to build file list with correct initial states
      • Connected UI state to persistence layer
    • Why: Connects the UI actions to the model and ensures proper state synchronization
  4. MainMenu.java

    • Purpose: Builds the application's main menu
    • Changes:
      • Updated constructor calls to accommodate new repository loading mechanism
    • Why: Required to accommodate the new repository loading approach in AbbreviateAction

Backend Changes (Logic)

  1. JournalAbbreviationRepository.java

    • Purpose: Central repository that stores and retrieves abbreviations
    • Changes:
      • Added source tracking with sourceToAbbreviations map to associate abbreviations with their sources
      • Added enabledSources map to track enabled/disabled state of each source
      • Modified core lookup methods to filter based on enabled state
      • Implemented proper updating of active abbreviations when toggling
    • Why: This is the core component where abbreviation filtering happens. When a source is disabled, its abbreviations shouldn't be used in operations
  2. JournalAbbreviationLoader.java

    • Purpose: Loads abbreviations from various sources into the repository
    • Changes:
      • Modified to respect enabled states from preferences
      • Implemented consistent key naming for external list identification
      • Added robust error handling for missing files
    • Why: The loader needed to initialize the repository with the correct enabled states and ensure proper source identification
  3. AbbreviateAction.java

    • Purpose: Handles abbreviation/unabbreviation commands from menu
    • Changes:
      • Implemented repository reload before abbreviation operations
      • Ensured operations use the latest toggle states
    • Why: Without reloading the repository, toggle state changes wouldn't affect already-running abbreviation operations
  4. JournalAbbreviationPreferences.java

    • Purpose: Stores user preferences for journal abbreviations
    • Changes:
      • Added enabledExternalLists map to store enabled/disabled states
      • Added methods to check if a specific source has an explicit enabled setting
      • Enhanced preference retrieval with multiple lookup strategies
    • Why: Provides the persistence mechanism for toggle states between application sessions
  5. JabRefCliPreferences.java

    • Purpose: Handles preference loading/saving at application level
    • Changes:
      • Added settings for journal abbreviation toggle states
      • Integrated with the overall preference system
    • Why: Ensures toggle states are properly saved/loaded at application level

Testing Strategy

Test Files and Coverage

  1. JournalAbbreviationRepositoryTest.java

    • Purpose: Tests the core backend functionality for source tracking and toggle behavior
    • Test Cases:
      • multipleSourcesCanBeToggled: Verifies that multiple sources can be independently enabled/disabled
      • disabledSourcesAreFilteredFromLookup: Ensures abbreviations from disabled sources aren't returned in lookups
      • builtInListCanBeToggled: Confirms the built-in list can be toggled like external sources
      • toggleStateAffectsAbbreviationSets: Tests that abbreviation sets are properly filtered by source state
  2. JournalAbbreviationsViewModelTabTest.java

    • Purpose: Tests the UI view model for toggle functionality
    • Test Cases:
      • addBuiltInListInitializesWithCorrectEnabledState: Verifies built-in list loaded with correct enabled state
      • enabledExternalListFiltersAbbreviationsWhenDisabled: Tests that UI reflects filtered abbreviations
      • storeSettingsPersistsEnabledStateToPreferences: Ensures toggle states are saved to preferences

Implementation Additions for Testing

The following methods and properties were added specifically to support testing:

  1. AbbreviationsFileViewModel.java

    • Added refreshAbbreviations() method to simulate UI updates when toggle state changes
    • Added thorough isEnabled(), setEnabled(), and enabledProperty() methods for test validation
  2. JournalAbbreviationsTabViewModel.java

    • Added markAsDirty() method to allow tests to mark files as needing to be saved
    • Enhanced storeSettings() to provide verification points for proper state persistence
  3. JournalAbbreviationRepository.java

    • Implemented addCustomAbbreviation(abbreviation, sourcePath, enabled) with source tracking for test scenarios
    • Added test-friendly mapping between abbreviations and their sources for verification
  4. JournalAbbreviationPreferences.java

    • Added hasExplicitEnabledSetting() method to improve testability of preference storage
    • Implemented clean getters/setters for toggle states to simplify test verification

These additions ensure the toggle functionality can be thoroughly tested while maintaining clean separation between the application code and test code.

Mandatory checks

  • I own the copyright of the code submitted and I license it under the MIT license
  • Change in CHANGELOG.md described in a way that is understandable for the average user (if change is visible to the user)
  • Tests created for changes (if applicable)
  • Manually tested changed features in running JabRef (always required)
  • Screenshots added in PR description (if change is visible to the user)
  • Checked developer's documentation: Is the information available and up to date? If not, I outlined it in this pull request.
  • Checked documentation: Is the information available and up to date? If not, I created an issue at https://github.com/JabRef/user-documentation/issues or, even better, I submitted a pull request to the documentation repository.

This feature allows users to enable/disable specific journal abbreviation lists, including both the built-in list and external CSV files, without removing them from configuration.

- Added toggle controls in UI with visual indicators for enabled/disabled states

- Implemented filtering of abbreviations based on source enabled state

- Ensured toggle states persist between application sessions

- Optimized performance with efficient repository loading

- Added comprehensive test coverage for new functionality

Closes JabRef#12468
@zikunz zikunz force-pushed the feature/journal-abbreviation-toggle branch from dd85326 to 37c8d2c Compare April 8, 2025 15:02
@subhramit subhramit marked this pull request as draft April 8, 2025 15:21
@subhramit
Copy link
Member

Please update your screenshots here as well.

@zikunz
Copy link
Author

zikunz commented Apr 8, 2025

@subhramit Got it, I will make sure all the screenshots will be updated in the PR content above :)

@zikunz
Copy link
Author

zikunz commented Apr 8, 2025

I tried to fix the two screenshots in the PR content, may I ask whether you are able to see them? @subhramit

@subhramit
Copy link
Member

I tried to fix the two screenshots in the PR content, may I ask whether you are able to see them? @subhramit

yes, they are fine now

@zikunz
Copy link
Author

zikunz commented Apr 8, 2025

Thank you! @subhramit

Journal abbreviations coming from sources that the user has disabled should neither be generated nor reversed.\n\nThis patch:\n
1. Makes UndoableUnabbreviator skip entries whose source is disabled\n2. Introduces AbbreviationWithSource to persist source metadata\n3. Filters candidates early in AbbreviateAction\n4. Refreshes repository state when a source is toggled in the UI
@zikunz
Copy link
Author

zikunz commented Apr 13, 2025

Update: the bug is now fixed and I proceed to refactor the code now. Afterwards, this PR will be ready for review :)

zikunz added 8 commits April 13, 2025 18:17
This commit fixes test failures that occurred after implementing the
journal abbreviation toggle feature. The changes include:

1. Ensuring the built-in list is always enabled by default in the
   JournalAbbreviationLoader for backward compatibility

2. Updating journal abbreviation tests to use controlled test data
   rather than depending on the built-in repository contents

3. Adding a more comprehensive test case for the abbreviation cycle
@jabref-machine
Copy link
Collaborator

Your pull request conflicts with the target branch.

Please merge upstream/main with your code. For a step-by-step guide to resolve merge conflicts, see https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/addressing-merge-conflicts/resolving-a-merge-conflict-using-the-command-line.

@jabref-machine
Copy link
Collaborator

Your pull request conflicts with the target branch.

Please merge upstream/main with your code. For a step-by-step guide to resolve merge conflicts, see https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/addressing-merge-conflicts/resolving-a-merge-conflict-using-the-command-line.

Integrate journal abbreviation toggle functionality (JabRef#12880) with the LTWA repository support from main branch. Resolve conflicts in JournalAbbreviationRepository, JournalAbbreviationLoader, and MainMenu to ensure both features work correctly together. The combined functionality allows users to enable/disable specific journal abbreviation sources while maintaining LTWA abbreviation support.
@zikunz
Copy link
Author

zikunz commented Apr 18, 2025

@koppor @Siedlerchr @subhramit

I have completed resolving the 6 merge conflicts between my PR and PR #12880 (which closed #12273). The resolved changes are reflected in my recent commit with the commit message of "feat: resolve merge conflicts with journal abbreviation toggle feature".

To properly test the combined functionality, I first proceeded to git checkout 1a4e1f38864e9bb1fc336a366ec24c3c0d48a94f in main branch to understand the behavior after merging #12880 to main (without my code changes).

During my local testing of the merged functionality, I observed some behavior that I would like to confirm is working as intended:

  1. When testing with the LTWA abbreviation mode, I noticed that the word "graph" does not get abbreviated to "gr." despite the csv file found in Add support for LTWA #12273 containing the entry -graph-;"-gr.";"eng".
Screen Shot 2025-04-19 at 2 39 11 AM Screen Shot 2025-04-19 at 2 39 21 AM
  1. I can successfully abbreviate "Journal of Polymer Science Part A" to "J. Polym. Sci. A" using LTWA mode (matching a test case in Add support for LTWA #12273), but when I try to unabbreviate it, it does not revert to the original text. In addition, "Journal of Polymer Science Part A" does not seem to be found in the the csv file found in Add support for LTWA #12273.
Screen Shot 2025-04-19 at 2 38 22 AM Screen Shot 2025-04-19 at 2 38 34 AM Screen Shot 2025-04-19 at 2 38 48 AM Screen Shot 2025-04-19 at 2 38 57 AM
  1. When attempting to abbreviate "Dem" (this is achieved by first abbreviating "Demonstration" using the shortest unique mode) using LTWA mode, the result is an empty string.
Screen Shot 2025-04-19 at 2 36 27 AM Screen Shot 2025-04-19 at 2 36 32 AM

I want to ensure that my merge conflict resolution is correct and that I am understanding the expected behavior of the LTWA abbreviation functionality properly. Could you please advise if these observations align with the intended functionality of the LTWA implementation, or if further adjustments are needed?

Thank you for your guidance.

@koppor
Copy link
Member

koppor commented Apr 19, 2025

@Yubo-Cao Can you look into #12912 (comment) maybe? I currently don't have the resources to properly answer.

@zikunz
Copy link
Author

zikunz commented Apr 19, 2025

@Yubo-Cao Can you look into #12912 (comment) maybe? I currently don't have the resources to properly answer.

@koppor Thank you!

@Yubo-Cao I look forward to your guidance. Thank you in advance!

@Test
void checkBasicAbbreviate() {
BibEntry entry = new BibEntry();
entry.setField(StandardField.JOURNAL, "TJ");
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When creating a new BibEntry object, 'withers' should be used instead of 'setField'. This improves code readability and follows modern Java practices.

@zikunz zikunz force-pushed the feature/journal-abbreviation-toggle branch from b51c301 to d9437e2 Compare April 26, 2025 20:49
…pository caching

  - Add singleton repository manager with proper thread safety to cache repo
  - Fix issue where abbreviation operations would ignore disabled journal lists
  - Fix issue where toggling journal lists would update preferences when dialog is canceled
  - Update both abbreviation and unabbreviation to respect disabled sources
  - Apply double-checked locking pattern to ensure thread safety while preserving performance
@zikunz
Copy link
Author

zikunz commented Apr 26, 2025

Could you also answer #12912 (comment)

Yes sure, please give me some time, I will quote the comment and answer it :)

Thank you for raising this important design question which I did not consider. The current approach is suboptimal. Creating a new repository for every unabbreviate operation is inefficient and could potentially impact performance, especially with multiple external abbreviation lists.

On repository creation

I initially implemented it this way to ensure the operation always uses the latest toggle states, but there is definitely a better approach. I now propose implementing a caching mechanism through a JournalAbbreviationRepositoryManager that would:

  • Cache the repository instance
  • Only rebuild when preferences actually change
  • Provide thread-safe access to the repository

This would maintain the same functionality while eliminating unnecessary repository recreation.

On preferences dependency

Regarding whether unabbreviate should depend on preferences at all, I think the answer is yes, it should, but indirectly. The unabbreviate operation needs to know which abbreviation lists are active, which is determined by user preferences.

However, I agree the current direct dependency is not ideal architecturally. A better approach would be:

  1. Have the repository depend on preferences (it needs to know which sources are enabled)
  2. Have the unabbreviate operation depend only on the repository
  3. Use dependency injection to connect these components

This maintains the same functionality (enabling / disabling abbreviation sources) while better separating concerns.

I just implemented this repository manager approach in this PR. I also addressed all the previous comments you left. Could you please advise me what to do now? Thank you so much! @subhramit

Copy link

trag-bot bot commented Apr 27, 2025

@trag-bot didn't find any issues in the code! ✅✨

@InAnYan
Copy link
Member

InAnYan commented Apr 27, 2025

Hi, @zikunz! I think I can hop in and help Subhramit et al. with this PR.

As JabRef is primarily done in free time by volunteers, we typically write small issues and expected small/medium PRs. But sometimes we have PRs that escalate in a lot of work.

Can you tell me:

  1. Do you have any blockers?
  2. Do you have any questions for design choices that should be discussed with maintainers?
  3. What specifically this PR solves/done/improves? So that I know what to test for.
  4. What is currently in progress and (if there is) planned in future?

For 4th point -- I think it's better to postpone this

@calixtus
Copy link
Member

Please not another Manager. Especially not a repository manager. This is silly, almost funny.
The repository provides everything the application needs. If it needs to be refreshed because preferences have changed and the loading mechanics are dependent on the preferences (which they shouldn't!) the repository needs to handle this internally.

And please do not use AI to communicate with us. Speak real, use your own words.
Remember our two golden rules for use of ai: never let an ai think for you, never let an ai speak for you.

@zikunz
Copy link
Author

zikunz commented Apr 27, 2025

Hi, @zikunz! I think I can hop in and help Subhramit et al. with this PR.

As JabRef is primarily done in free time by volunteers, we typically write small issues and expected small/medium PRs. But sometimes we have PRs that escalate in a lot of work.

Can you tell me:

  1. Do you have any blockers?
  2. Do you have any questions for design choices that should be discussed with maintainers?
  3. What specifically this PR solves/done/improves? So that I know what to test for.
  4. What is currently in progress and (if there is) planned in future?

For 4th point -- I think it's better to postpone this

Hi @InAnYan, thank you so much for helping to review this PR, please find below the answers for your 3 questions:

Q: Do you have any blockers?
A: I do not have any blockers at this point of time. This feature is fully implemented and all checks have passed :)

Q: Do you have any questions for design choices that should be discussed with maintainers?
A: I currently do not have any questions for design choices, but there could be design choices made which are suboptimal in this PR. I can also take another look and try to see if there are better design(s) that I did not consider and does/do not cause a big, costly change in the existing codebase.

Q: What specifically this PR solves/done/improves? So that I know what to test for.
A: As seen from the PR content, from the user point of view, this PR adds a toggle functionality for all journal abbreviation lists which include both built-in lists as well as external CSV files.

image

After pressing toggle, a list will change from enabled to disabled or change from disabled to enabled. This will be saved only if the user clicks Save, if the user clicks x or Cancel, the state change will not be saved.

After the users save enabled / disabled states for the lists, when they try to abbreviate and unabbreviate one or more journal names, only journal names found in the enabled lists will be abbreviated or unabbreviated. If a list is disabled, journal name(s) found in the disabled list cannot be abbreviated or unabbreviated.

Please let me know if anything written above is not clear. Thank you again for your help!

Copy link
Member

@InAnYan InAnYan left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's very good that you wrote tests

@@ -98,6 +108,10 @@ public void execute() {
}

private String abbreviate(BibDatabaseContext databaseContext, List<BibEntry> entries) {
// Use the repository manager to get a cached repository or build a new one if needed
abbreviationRepository = JournalAbbreviationRepositoryManager.getInstance()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

JournalAbbreviationRepositoryManager -- I don't like this approach.

Typically, in JabRef for dependencies, we do this:

  1. Get the dependency from the constructor (as it was before).
  2. Use Dependency Injection -- but we are migrating away from it.
  3. And only in rare cases (like for WebViews) we use static classes.

So what I meant to say that we don't use static/singleton classes in a raw form like this. I'm not sure, why this approach was taken, what was the problem with previous approach where a repository was taken from constructor?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for your feedback @InAnYan, this approach was wrongly taken by me yesterday night as I was rushing to get it done (I will take note to have a calm mind when pushing for code changes). Now I understand that this approach is wrong. I cc-ed you in a comment above for details regarding what was the problem to solve, what was the initial approach taken and why this approach was subsequently used by me.

In short, the original problem I was trying to solve was the inefficient creation of new repositories on every operation:

JournalAbbreviationRepository freshRepository = JournalAbbreviationLoader.loadRepository(journalAbbreviationPreferences);

Then, I implemented the separate manager class that works functionally, but I now see now it adds unnecessary abstraction.

I will make the following changes:

  1. Move the caching logic directly into JournalAbbreviationRepository
  2. Add a static getInstance(preferences) method there
  3. Remove JournalAbbreviationRepository

This way, the repository itself will handle when to reload based on preference changes, without needing extra layers.

May I ask whether this approach sound right? I appreciate the guidance and am eager to improve the implementation. :)

*
* @return true if at least one source is enabled, false if all sources are disabled
*/
private boolean areAnyJournalSourcesEnabled() {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this should be moved to JournalAbbreviationPreferences. This is not related to logic in AbbreviateAction, and it's quite general

JournalAbbreviationRepository freshRepository = JournalAbbreviationRepositoryManager.getInstance()
.getRepository(journalAbbreviationPreferences);

Map<String, Boolean> sourceEnabledStates = new HashMap<>();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do you collect a Map instead of just using freshRepository.isSourceEnabled()?

}

var allAbbreviationsWithSources = freshRepository.getAllAbbreviationsWithSources();
Map<String, List<JournalAbbreviationRepository.AbbreviationWithSource>> textToSourceMap = new HashMap<>();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't abbreviation repository is already kinda a Map? Isn't there a method for getting abbreviations/unabbreviations from there


String text = entry.getFieldLatexFree(journalField).orElse("");
List<JournalAbbreviationRepository.AbbreviationWithSource> possibleSources =
textToSourceMap.getOrDefault(text, List.of());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is what I talked about in the previous comment. Doesn't abbreviation repository doesn't have some kind of get method?

* @return true if the source is enabled or has no explicit state (default is enabled)
*/
public boolean isSourceEnabled(String sourcePath) {
if (sourcePath == null) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's better to remove these null checks.

Currently, in JabRef, we don't use nulls, and if a parameter is not marked as @Nullable, then we assume it's always non-null.

Otherwise, if some code passes null there, then there is a flaw. As nulls shouldn't be used

private final ObservableList<String> externalJournalLists;
private final BooleanProperty useFJournalField;

private final Map<String, Boolean> enabledExternalLists = new HashMap<>();
private final BooleanProperty enabledListsChanged = new SimpleBooleanProperty();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For which reasons this is used? Adding listener to ObservableMap doesn't work?

I remember I had problems with ObservableMaps. But if you can add listener there, and it works, you should use this functionality of JavaFX, not a separate property.

Otherwise, add a comment explaining this

return;
}
enabledExternalLists.put(sourcePath, enabled);
enabledListsChanged.set(!enabledListsChanged.get());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What does this line do?

From the name of enabledListsChanged it should be true when lists are changed. setting mutates data, so any call to setters should set enabledListsChanged to true, shouldn't it?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, maybe you toggle states not to indicate whether something change, but to rather trigger listeners of this property on any change?

Then this explains why X <= !X.

I would propose to:

  1. Add a comment explaining this technique.
  2. Move out enabledListsChanged.set(!enabledListsChanged.get()) into a method.

public JournalAbbreviationRepository getRepository(JournalAbbreviationPreferences preferences) {
Objects.requireNonNull(preferences);

LOCK.readLock().lock();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typically, we don't use raw locks in JabRef. My experience in parallel/asynchronous programming in Java is not big, but are there any other synchronization methods? I would prefer something like a synchronized method or Atomic... classes. At least Mutex.

And also why this method should be atomic?

* @param preferences The current preferences to check
* @return true if preferences have changed, false otherwise
*/
private boolean preferencesChanged(JournalAbbreviationPreferences preferences) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a reason that the repository should be rebuilt so lazily?

Would it be problematic to rebuild repositories on clicking "Save" in preferences?

@zikunz
Copy link
Author

zikunz commented Apr 27, 2025

Please not another Manager. Especially not a repository manager. This is silly, almost funny. The repository provides everything the application needs. If it needs to be refreshed because preferences have changed and the loading mechanics are dependent on the preferences (which they shouldn't!) the repository needs to handle this internally.

And please do not use AI to communicate with us. Speak real, use your own words. Remember our two golden rules for use of ai: never let an ai think for you, never let an ai speak for you.

@calixtus Thank you for your constructive feedback. I understand your concerns.

I think I complicated things unnecessarily by creating a separate manager. When you said "the repository provides everything the application needs," it then clicked that I should have simply enhanced the repository class itself.

(cc @InAnYan) The original problem I was trying to solve was the inefficient creation of new repositories on every operation:

JournalAbbreviationRepository freshRepository = JournalAbbreviationLoader.loadRepository(journalAbbreviationPreferences);

This is suboptimal because of expensive I/O (i.e., repeatedly loading data from files), memory churn (i.e., create new objects for every operation) and no caching of previously loaded repositories.

Afterwards, I created JournalAbbreviationRepositoryManager which checks if preferences are changed before rebuilding and caches the repository instance.

This is still suboptimal because:

  1. now there is unnecessary and not meaningful abstraction, creating an extra layer when the repository should handle this internally
  2. (A Question to Clarify) I do not understand why loading mechanics are not dependent on the preferences. I still think the repository should use preferences because it needs to know which sources are enabled. There is a high chance that I misinterpreted what you and @subhramit were hinting to me, are you saying the repository should use preferences, but the caller should not need to manage the repository's lifecycle, instead, the repository should handle that internally?

If my understanding is fully correct now, can you please advise if I should quickly do the following?

  1. Take the caching logic I wrote in JournalAbbreviationRepositoryManager
  2. Move it directly into the JournalAbbreviationRepository class
  3. Remove JournalAbbreviationRepositoryManager

In short,

Instead of:
repository = JournalAbbreviationRepositoryManager.getInstance().getRepository(preferences);

The repository should offer:
repository = JournalAbbreviationRepository.getInstance(preferences);

This way, the repository itself will handle when to reload based on preference changes, without needing extra layers. Does this approach sound right? I appreciate the guidance and am eager to improve the implementation.

@calixtus
Copy link
Member

I think I complicated things unnecessarily by creating a separate manager. When you said "the repository provides everything the application needs," it then clicked that I should have simply enhanced the repository class itself.

This is the state it should be, maybe not it is in now.

@zikunz
Copy link
Author

zikunz commented Apr 27, 2025

I think I complicated things unnecessarily by creating a separate manager. When you said "the repository provides everything the application needs," it then clicked that I should have simply enhanced the repository class itself.

This is the state it should be, maybe not it is in now.

Thank you so much for your guidance, @calixtus. I understand the issue (i.e., the manager class adds complexity without adding value) now completely and will work on letting the repository handle it internally, following the principle of "the simplest solution that works." :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Ability to disable the built-in JabRef journal abbreviation list
7 participants