repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
jabref-main/src/main/java/org/jabref/model/openoffice/style/CitationGroupId.java
package org.jabref.model.openoffice.style; /** * Identifies a citation group in a document. */ public class CitationGroupId { String groupId; public CitationGroupId(String groupId) { this.groupId = groupId; } /** * CitationEntry needs some string identifying the group that it can pass back later. */ public String citationGroupIdAsString() { return groupId; } }
418
19.95
89
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/style/CitationGroups.java
package org.jabref.model.openoffice.style; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.function.Consumer; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.openoffice.util.OOListUtil; import org.jabref.model.openoffice.util.OOPair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * CitationGroups : the set of citation groups in the document. * <p> * This is the main input (as well as output) for creating citation markers and bibliography. */ public class CitationGroups { private static final Logger LOGGER = LoggerFactory.getLogger(CitationGroups.class); private final Map<CitationGroupId, CitationGroup> citationGroupsUnordered; /** * Provides order of appearance for the citation groups. */ private Optional<List<CitationGroupId>> globalOrder; /** * This is going to be the bibliography */ private Optional<CitedKeys> bibliography; /** * Constructor */ public CitationGroups(Map<CitationGroupId, CitationGroup> citationGroups) { this.citationGroupsUnordered = citationGroups; this.globalOrder = Optional.empty(); this.bibliography = Optional.empty(); } public int numberOfCitationGroups() { return citationGroupsUnordered.size(); } /** * For each citation in {@code where} call {@code fun.accept(new Pair(citation, value));} */ public <T> void distributeToCitations(List<CitationPath> where, Consumer<OOPair<Citation, T>> fun, T value) { for (CitationPath p : where) { CitationGroup group = citationGroupsUnordered.get(p.group); if (group == null) { LOGGER.warn("CitationGroups.distributeToCitations: group missing"); continue; } Citation cit = group.citationsInStorageOrder.get(p.storageIndexInGroup); fun.accept(new OOPair<>(cit, value)); } } /* * Look up each Citation in databases. */ public void lookupCitations(List<BibDatabase> databases) { /* * It is not clear which of the two solutions below is better. */ // (1) collect-lookup-distribute // // CitationDatabaseLookupResult for the same citation key is the same object. Until we // insert a new citation from the GUI. CitedKeys cks = getCitedKeysUnordered(); cks.lookupInDatabases(databases); cks.distributeLookupResults(this); // (2) lookup each citation directly // // CitationDatabaseLookupResult for the same citation key may be a different object: // CitedKey.addPath has to use equals, so CitationDatabaseLookupResult has to override // Object.equals, which depends on BibEntry.equals and BibDatabase.equals doing the // right thing. Seems to work. But what we gained from avoiding collect-and-distribute // may be lost in more complicated consistency checking in addPath. // /// for (CitationGroup group : getCitationGroupsUnordered()) { /// for (Citation cit : group.citationsInStorageOrder) { /// cit.lookupInDatabases(databases); /// } /// } } public List<CitationGroup> getCitationGroupsUnordered() { return new ArrayList<>(citationGroupsUnordered.values()); } /** * Citation groups in {@code globalOrder} */ public List<CitationGroup> getCitationGroupsInGlobalOrder() { if (globalOrder.isEmpty()) { throw new IllegalStateException("getCitationGroupsInGlobalOrder: not ordered yet"); } return OOListUtil.map(globalOrder.get(), citationGroupsUnordered::get); } /** * Impose an order of citation groups by providing the order of their citation group idendifiers. * <p> * Also set indexInGlobalOrder for each citation group. */ public void setGlobalOrder(List<CitationGroupId> globalOrder) { Objects.requireNonNull(globalOrder); if (globalOrder.size() != numberOfCitationGroups()) { throw new IllegalStateException("setGlobalOrder: globalOrder.size() != numberOfCitationGroups()"); } this.globalOrder = Optional.of(globalOrder); // Propagate to each CitationGroup for (int i = 0; i < globalOrder.size(); i++) { CitationGroupId groupId = globalOrder.get(i); citationGroupsUnordered.get(groupId).setIndexInGlobalOrder(Optional.of(i)); } } public boolean hasGlobalOrder() { return globalOrder.isPresent(); } /** * Impose an order for citations within each group. */ public void imposeLocalOrder(Comparator<BibEntry> entryComparator) { for (CitationGroup group : citationGroupsUnordered.values()) { group.imposeLocalOrder(entryComparator); } } /** * Collect citations into a list of cited sources using neither CitationGroup.globalOrder or Citation.localOrder */ public CitedKeys getCitedKeysUnordered() { LinkedHashMap<String, CitedKey> res = new LinkedHashMap<>(); for (CitationGroup group : citationGroupsUnordered.values()) { int storageIndexInGroup = 0; for (Citation cit : group.citationsInStorageOrder) { String key = cit.citationKey; CitationPath path = new CitationPath(group.groupId, storageIndexInGroup); if (res.containsKey(key)) { res.get(key).addPath(path, cit); } else { res.put(key, new CitedKey(key, path, cit)); } storageIndexInGroup++; } } return new CitedKeys(res); } /** * CitedKeys created iterating citations in (globalOrder,localOrder) */ public CitedKeys getCitedKeysSortedInOrderOfAppearance() { if (!hasGlobalOrder()) { throw new IllegalStateException("getSortedCitedKeys: no globalOrder"); } LinkedHashMap<String, CitedKey> res = new LinkedHashMap<>(); for (CitationGroup group : getCitationGroupsInGlobalOrder()) { for (int i : group.getLocalOrder()) { Citation cit = group.citationsInStorageOrder.get(i); String citationKey = cit.citationKey; CitationPath path = new CitationPath(group.groupId, i); if (res.containsKey(citationKey)) { res.get(citationKey).addPath(path, cit); } else { res.put(citationKey, new CitedKey(citationKey, path, cit)); } } } return new CitedKeys(res); } public Optional<CitedKeys> getBibliography() { return bibliography; } /** * @return Citation keys where lookupCitations() failed. */ public List<String> getUnresolvedKeys() { CitedKeys bib = getBibliography().orElse(getCitedKeysUnordered()); List<String> unresolvedKeys = new ArrayList<>(); for (CitedKey ck : bib.values()) { if (ck.getLookupResult().isEmpty()) { unresolvedKeys.add(ck.citationKey); } } return unresolvedKeys; } public void createNumberedBibliographySortedInOrderOfAppearance() { if (bibliography.isPresent()) { throw new IllegalStateException("createNumberedBibliographySortedInOrderOfAppearance:" + " already have a bibliography"); } CitedKeys citedKeys = getCitedKeysSortedInOrderOfAppearance(); citedKeys.numberCitedKeysInCurrentOrder(); citedKeys.distributeNumbers(this); bibliography = Optional.of(citedKeys); } /** * precondition: database lookup already performed (otherwise we just sort citation keys) */ public void createPlainBibliographySortedByComparator(Comparator<BibEntry> entryComparator) { if (bibliography.isPresent()) { throw new IllegalStateException("createPlainBibliographySortedByComparator: already have a bibliography"); } CitedKeys citedKeys = getCitedKeysUnordered(); citedKeys.sortByComparator(entryComparator); bibliography = Optional.of(citedKeys); } /** * precondition: database lookup already performed (otherwise we just sort citation keys) */ public void createNumberedBibliographySortedByComparator(Comparator<BibEntry> entryComparator) { if (bibliography.isPresent()) { throw new IllegalStateException("createNumberedBibliographySortedByComparator: already have a bibliography"); } CitedKeys citedKeys = getCitedKeysUnordered(); citedKeys.sortByComparator(entryComparator); citedKeys.numberCitedKeysInCurrentOrder(); citedKeys.distributeNumbers(this); bibliography = Optional.of(citedKeys); } /* * Query by CitationGroupId */ public Optional<CitationGroup> getCitationGroup(CitationGroupId groupId) { CitationGroup group = citationGroupsUnordered.get(groupId); return Optional.ofNullable(group); } /** * @return true if all citation groups have referenceMarkNameForLinking */ public boolean citationGroupsProvideReferenceMarkNameForLinking() { for (CitationGroup group : citationGroupsUnordered.values()) { if (group.getReferenceMarkNameForLinking().isEmpty()) { return false; } } return true; } /* * Callbacks. */ public void afterCreateCitationGroup(CitationGroup group) { citationGroupsUnordered.put(group.groupId, group); globalOrder = Optional.empty(); bibliography = Optional.empty(); } public void afterRemoveCitationGroup(CitationGroup group) { citationGroupsUnordered.remove(group.groupId); globalOrder.map(l -> l.remove(group.groupId)); bibliography = Optional.empty(); } }
10,396
34.975779
121
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/style/CitationLookupResult.java
package org.jabref.model.openoffice.style; import java.util.Objects; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; public class CitationLookupResult { public final BibEntry entry; public final BibDatabase database; public CitationLookupResult(BibEntry entry, BibDatabase database) { Objects.requireNonNull(entry); Objects.requireNonNull(database); this.entry = entry; this.database = database; } /** * Note: BibEntry overrides Object.equals, but BibDatabase does not. * <p> * Consequently, {@code this.database.equals(that.database)} below is equivalent to {@code this.database == that.database}. * <p> * Since within each GUI call we use a fixed list of databases, it is OK. * <p> * CitationLookupResult.equals is used in CitedKey.addPath to check the added Citation refers to the same source as the others. As long as we look up each citation key only once (in CitationGroups.lookupCitations), the default implementation for equals would be sufficient (and could also omit hashCode below). */ @Override public boolean equals(Object otherObject) { if (otherObject == this) { return true; } if (!(otherObject instanceof CitationLookupResult)) { return false; } CitationLookupResult that = (CitationLookupResult) otherObject; return Objects.equals(this.entry, that.entry) && Objects.equals(this.database, that.database); } @Override public int hashCode() { return Objects.hash(entry, database); } }
1,641
34.695652
314
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/style/CitationMarkerEntry.java
package org.jabref.model.openoffice.style; import java.util.Optional; import org.jabref.model.openoffice.ootext.OOText; /** * This is what we need for createCitationMarker to produce author-year citation markers. */ public interface CitationMarkerEntry extends CitationMarkerNormEntry { /** * uniqueLetter or Optional.empty() if not needed. */ Optional<String> getUniqueLetter(); /** * pageInfo for this citation, provided by the user. May be empty, for none. */ Optional<OOText> getPageInfo(); /** * @return true if this citation is the first appearance of the source cited. Some styles use different limit on the number of authors shown in this case. */ boolean getIsFirstAppearanceOfSource(); }
760
27.185185
158
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/style/CitationMarkerNormEntry.java
package org.jabref.model.openoffice.style; import java.util.Optional; /** * This is what we need to produce normalized author-year citation markers. */ public interface CitationMarkerNormEntry { /** * Citation key. This is what we usually get from the document. * <p> * Used if getLookupResult() returns empty, which indicates failure to lookup in the databases. */ String getCitationKey(); /** * Result of looking up citation key in databases. * <p> * Optional.empty() indicates unresolved citation. */ Optional<CitationLookupResult> getLookupResult(); }
618
24.791667
99
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/style/CitationMarkerNumericBibEntry.java
package org.jabref.model.openoffice.style; import java.util.Optional; /** * This is for the numeric bibliography labels. */ public interface CitationMarkerNumericBibEntry { /** * For unresolved citation we show the citation key. */ String getCitationKey(); /** * @return Optional.empty() for unresolved */ Optional<Integer> getNumber(); }
381
18.1
56
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/style/CitationMarkerNumericEntry.java
package org.jabref.model.openoffice.style; import java.util.Optional; import org.jabref.model.openoffice.ootext.OOText; /** * This is what we need for numeric citation markers. */ public interface CitationMarkerNumericEntry { String getCitationKey(); /** * @return Optional.empty() for unresolved */ Optional<Integer> getNumber(); Optional<OOText> getPageInfo(); }
399
18.047619
53
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/style/CitationPath.java
package org.jabref.model.openoffice.style; /** * Identifies a citation with the identifier of the citation group containing it and its storage index within. */ public class CitationPath { public final CitationGroupId group; public final int storageIndexInGroup; CitationPath(CitationGroupId group, int storageIndexInGroup) { this.group = group; this.storageIndexInGroup = storageIndexInGroup; } }
435
24.647059
110
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/style/CitationType.java
package org.jabref.model.openoffice.style; /* * Presentation types of citation groups. */ public enum CitationType { AUTHORYEAR_PAR, AUTHORYEAR_INTEXT, INVISIBLE_CIT; public boolean inParenthesis() { return switch (this) { case AUTHORYEAR_PAR, INVISIBLE_CIT -> true; case AUTHORYEAR_INTEXT -> false; }; } public boolean withText() { return this != INVISIBLE_CIT; } }
451
17.08
55
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/style/CitedKey.java
package org.jabref.model.openoffice.style; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.openoffice.ootext.OOText; /** * Cited keys are collected from the citations in citation groups. * <p> * They contain backreferences to the corresponding citations in {@code where}. This allows the extra information generated using CitedKeys to be distributed back to the in-text citations. */ public class CitedKey implements ComparableCitedKey, CitationMarkerNormEntry, CitationMarkerNumericBibEntry { public final String citationKey; private final List<CitationPath> where; private Optional<CitationLookupResult> db; private Optional<Integer> number; // For Numbered citation styles. private Optional<String> uniqueLetter; // For AuthorYear citation styles. private Optional<OOText> normCitMarker; // For AuthorYear citation styles. CitedKey(String citationKey, CitationPath path, Citation citation) { this.citationKey = citationKey; this.where = new ArrayList<>(); // remember order this.where.add(path); // synchronized with Citation this.db = citation.getLookupResult(); this.number = citation.getNumber(); this.uniqueLetter = citation.getUniqueLetter(); // CitedKey only this.normCitMarker = Optional.empty(); } /* * Implement ComparableCitedKey */ @Override public String getCitationKey() { return citationKey; } @Override public Optional<BibEntry> getBibEntry() { return db.map(e -> e.entry); } /* * Implement CitationMarkerNormEntry */ @Override public Optional<CitationLookupResult> getLookupResult() { return db; } /* * Implement CitationMarkerNumericBibEntry */ @Override public Optional<Integer> getNumber() { return number; } public void setNumber(Optional<Integer> number) { this.number = number; } public List<CitationPath> getCitationPaths() { return new ArrayList<>(where); } public Optional<String> getUniqueLetter() { return uniqueLetter; } public void setUniqueLetter(Optional<String> uniqueLetter) { this.uniqueLetter = uniqueLetter; } public Optional<OOText> getNormalizedCitationMarker() { return normCitMarker; } public void setNormalizedCitationMarker(Optional<OOText> normCitMarker) { this.normCitMarker = normCitMarker; } /** * Appends to end of {@code where} */ void addPath(CitationPath path, Citation cit) { this.where.add(path); // Check consistency if (!cit.getLookupResult().equals(this.db)) { throw new IllegalStateException("CitedKey.addPath: mismatch on cit.db"); } if (!cit.getNumber().equals(this.number)) { throw new IllegalStateException("CitedKey.addPath: mismatch on cit.number"); } if (!cit.getUniqueLetter().equals(this.uniqueLetter)) { throw new IllegalStateException("CitedKey.addPath: mismatch on cit.uniqueLetter"); } } /* * Lookup */ void lookupInDatabases(List<BibDatabase> databases) { this.db = Citation.lookup(databases, this.citationKey); } void distributeLookupResult(CitationGroups citationGroups) { citationGroups.distributeToCitations(where, Citation::setLookupResult, db); } /* * Make unique using a letter or by numbering */ void distributeNumber(CitationGroups citationGroups) { citationGroups.distributeToCitations(where, Citation::setNumber, number); } void distributeUniqueLetter(CitationGroups citationGroups) { citationGroups.distributeToCitations(where, Citation::setUniqueLetter, uniqueLetter); } }
3,989
28.124088
188
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/style/CitedKeys.java
package org.jabref.model.openoffice.style; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Optional; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; public class CitedKeys { /** * Order-preserving map from citation keys to associated data. */ private LinkedHashMap<String, CitedKey> data; CitedKeys(LinkedHashMap<String, CitedKey> data) { this.data = data; } /** * The cited keys in their current order. */ public List<CitedKey> values() { return new ArrayList<>(data.values()); } public CitedKey get(String citationKey) { return data.get(citationKey); } /** * Sort entries for the bibliography. */ void sortByComparator(Comparator<BibEntry> entryComparator) { List<CitedKey> cks = new ArrayList<>(data.values()); cks.sort(new CompareCitedKey(entryComparator, true)); LinkedHashMap<String, CitedKey> newData = new LinkedHashMap<>(); for (CitedKey ck : cks) { newData.put(ck.citationKey, ck); } data = newData; } void numberCitedKeysInCurrentOrder() { int index = 1; for (CitedKey ck : data.values()) { if (ck.getLookupResult().isPresent()) { ck.setNumber(Optional.of(index)); index++; } else { // Unresolved citations do not get a number. ck.setNumber(Optional.empty()); } } } public void lookupInDatabases(List<BibDatabase> databases) { for (CitedKey ck : this.data.values()) { ck.lookupInDatabases(databases); } } void distributeLookupResults(CitationGroups citationGroups) { for (CitedKey ck : this.data.values()) { ck.distributeLookupResult(citationGroups); } } void distributeNumbers(CitationGroups citationGroups) { for (CitedKey ck : this.data.values()) { ck.distributeNumber(citationGroups); } } public void distributeUniqueLetters(CitationGroups citationGroups) { for (CitedKey ck : this.data.values()) { ck.distributeUniqueLetter(citationGroups); } } }
2,334
26.797619
72
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/style/ComparableCitation.java
package org.jabref.model.openoffice.style; import java.util.Optional; import org.jabref.model.openoffice.ootext.OOText; /** * When sorting citations (in a group), we also consider pageInfo. Otherwise we sort citations as cited keys. */ public interface ComparableCitation extends ComparableCitedKey { Optional<OOText> getPageInfo(); }
344
25.538462
109
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/style/ComparableCitedKey.java
package org.jabref.model.openoffice.style; import java.util.Optional; import org.jabref.model.entry.BibEntry; /** * This is what we need to sort bibliography entries. */ public interface ComparableCitedKey { String getCitationKey(); Optional<BibEntry> getBibEntry(); }
285
15.823529
53
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/style/CompareCitation.java
package org.jabref.model.openoffice.style; import java.util.Comparator; import org.jabref.model.entry.BibEntry; /* * Given a Comparator<BibEntry> provide a Comparator<ComparableCitation> that can handle unresolved * citation keys and takes pageInfo into account. */ public class CompareCitation implements Comparator<ComparableCitation> { private final CompareCitedKey citedKeyComparator; CompareCitation(Comparator<BibEntry> entryComparator, boolean unresolvedComesFirst) { this.citedKeyComparator = new CompareCitedKey(entryComparator, unresolvedComesFirst); } public int compare(ComparableCitation a, ComparableCitation b) { int res = citedKeyComparator.compare(a, b); // Also consider pageInfo if (res == 0) { res = PageInfo.comparePageInfo(a.getPageInfo(), b.getPageInfo()); } return res; } }
890
27.741935
99
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/style/CompareCitedKey.java
package org.jabref.model.openoffice.style; import java.util.Comparator; import java.util.Optional; import org.jabref.model.entry.BibEntry; /* * Given a Comparator<BibEntry> provide a Comparator<ComparableCitedKey> that also handles * unresolved citation keys. */ public class CompareCitedKey implements Comparator<ComparableCitedKey> { Comparator<BibEntry> entryComparator; boolean unresolvedComesFirst; CompareCitedKey(Comparator<BibEntry> entryComparator, boolean unresolvedComesFirst) { this.entryComparator = entryComparator; this.unresolvedComesFirst = unresolvedComesFirst; } public int compare(ComparableCitedKey a, ComparableCitedKey b) { Optional<BibEntry> aBibEntry = a.getBibEntry(); Optional<BibEntry> bBibEntry = b.getBibEntry(); final int mul = unresolvedComesFirst ? (+1) : -1; if (aBibEntry.isEmpty() && bBibEntry.isEmpty()) { // Both are unresolved: compare them by citation key. return a.getCitationKey().compareTo(b.getCitationKey()); } else if (aBibEntry.isEmpty()) { return -mul; } else if (bBibEntry.isEmpty()) { return mul; } else { // Proper comparison of entries return entryComparator.compare(aBibEntry.get(), bBibEntry.get()); } } }
1,346
32.675
90
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/style/NonUniqueCitationMarker.java
package org.jabref.model.openoffice.style; /** * What should createCitationMarker do if it discovers that uniqueLetters provided are not sufficient for unique presentation? */ public enum NonUniqueCitationMarker { /** * Give an insufficient representation anyway. */ FORGIVEN, /** * Throw an exception */ THROWS }
356
17.789474
126
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/style/OODataModel.java
package org.jabref.model.openoffice.style; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.jabref.model.openoffice.ootext.OOText; /** * What is the data stored? */ public enum OODataModel { /** * JabRef52: pageInfo belongs to CitationGroup, not Citation. */ JabRef52, /** * JabRef60: pageInfo belongs to Citation. */ JabRef60; /** * @param pageInfo Nullable. * @return JabRef60 style pageInfo list with pageInfo in the last slot. */ public static List<Optional<OOText>> fakePageInfos(String pageInfo, int nCitations) { List<Optional<OOText>> pageInfos = new ArrayList<>(nCitations); for (int i = 0; i < nCitations; i++) { pageInfos.add(Optional.empty()); } if (pageInfo != null) { final int last = nCitations - 1; Optional<OOText> optionalPageInfo = Optional.ofNullable(OOText.fromString(pageInfo)); pageInfos.set(last, PageInfo.normalizePageInfo(optionalPageInfo)); } return pageInfos; } }
1,099
25.829268
97
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/style/PageInfo.java
package org.jabref.model.openoffice.style; import java.util.Optional; import org.jabref.model.openoffice.ootext.OOText; public class PageInfo { private PageInfo() { } /* * pageInfo normalization */ public static Optional<OOText> normalizePageInfo(Optional<OOText> optionalText) { if (optionalText == null || optionalText.isEmpty() || "".equals(OOText.toString(optionalText.get()))) { return Optional.empty(); } String str = OOText.toString(optionalText.get()); String trimmed = str.trim(); if ("".equals(trimmed)) { return Optional.empty(); } return Optional.of(OOText.fromString(trimmed)); } /** * Defines sort order for pageInfo strings. * <p> * Optional.empty comes before non-empty. */ public static int comparePageInfo(Optional<OOText> a, Optional<OOText> b) { Optional<OOText> aa = PageInfo.normalizePageInfo(a); Optional<OOText> bb = PageInfo.normalizePageInfo(b); if (aa.isEmpty() && bb.isEmpty()) { return 0; } if (aa.isEmpty()) { return -1; } if (bb.isEmpty()) { return +1; } return aa.get().toString().compareTo(bb.get().toString()); } }
1,305
26.787234
111
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/uno/CreationException.java
package org.jabref.model.openoffice.uno; /** * Exception used to indicate failure in either * <p> * XMultiServiceFactory.createInstance() XMultiComponentFactory.createInstanceWithContext() */ public class CreationException extends Exception { public CreationException(String message) { super(message); } }
328
22.5
91
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/uno/NoDocumentException.java
package org.jabref.model.openoffice.uno; public class NoDocumentException extends Exception { public NoDocumentException(String message) { super(message); } public NoDocumentException() { super("Not connected to a document"); } }
265
19.461538
52
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/uno/UnoBookmark.java
package org.jabref.model.openoffice.uno; import java.util.Optional; import com.sun.star.container.NoSuchElementException; import com.sun.star.container.XNameAccess; import com.sun.star.container.XNamed; import com.sun.star.lang.DisposedException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XBookmarksSupplier; import com.sun.star.text.XTextContent; import com.sun.star.text.XTextDocument; import com.sun.star.text.XTextRange; public class UnoBookmark { private UnoBookmark() { } /** * Provides access to bookmarks by name. */ public static XNameAccess getNameAccess(XTextDocument doc) throws NoDocumentException { XBookmarksSupplier supplier = UnoCast.cast(XBookmarksSupplier.class, doc).get(); try { return supplier.getBookmarks(); } catch (DisposedException ex) { throw new NoDocumentException("UnoBookmark.getNameAccess failed with" + ex); } } /** * Get the XTextRange corresponding to the named bookmark. * * @param name The name of the bookmark to find. * @return The XTextRange for the bookmark, or Optional.empty(). */ public static Optional<XTextRange> getAnchor(XTextDocument doc, String name) throws WrappedTargetException, NoDocumentException { XNameAccess nameAccess = getNameAccess(doc); return UnoNameAccess.getTextContentByName(nameAccess, name).map(XTextContent::getAnchor); } /** * Insert a bookmark with the given name at the cursor provided, or with another name if the one we asked for is already in use. * <p> * In LibreOffice the another name is in "{name}{number}" format. * * @param name For the bookmark. * @param range Cursor marking the location or range for the bookmark. * @param absorb Shall we incorporate range? * @return The XNamed interface of the bookmark. * result.getName() should be checked by the caller, because its name may differ from the one requested. */ public static XNamed create(XTextDocument doc, String name, XTextRange range, boolean absorb) throws CreationException { return UnoNamed.insertNamedTextContent(doc, "com.sun.star.text.Bookmark", name, range, absorb); } /** * Remove the named bookmark if it exists. */ public static void removeIfExists(XTextDocument doc, String name) throws NoDocumentException, WrappedTargetException { XNameAccess marks = UnoBookmark.getNameAccess(doc); if (marks.hasByName(name)) { Optional<XTextContent> mark = UnoNameAccess.getTextContentByName(marks, name); if (mark.isEmpty()) { return; } try { doc.getText().removeTextContent(mark.get()); } catch (NoSuchElementException ex) { // The caller gets what it expects. } } } }
3,052
32.922222
132
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/uno/UnoCast.java
package org.jabref.model.openoffice.uno; import java.util.Optional; import com.sun.star.uno.UnoRuntime; public class UnoCast { private UnoCast() { } /** * cast : short for Optional.ofNullable(UnoRuntime.queryInterface(...)) * * @return A reference to the requested UNO interface type if available, otherwise Optional.empty() */ public static <T> Optional<T> cast(Class<T> zInterface, Object object) { return Optional.ofNullable(UnoRuntime.queryInterface(zInterface, object)); } }
533
24.428571
103
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/uno/UnoCrossRef.java
package org.jabref.model.openoffice.uno; import com.sun.star.beans.PropertyVetoException; import com.sun.star.beans.UnknownPropertyException; import com.sun.star.beans.XPropertySet; import com.sun.star.lang.WrappedTargetException; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.text.ReferenceFieldPart; import com.sun.star.text.ReferenceFieldSource; import com.sun.star.text.XTextContent; import com.sun.star.text.XTextDocument; import com.sun.star.text.XTextRange; import com.sun.star.util.XRefreshable; public class UnoCrossRef { private UnoCrossRef() { } /** * Update TextFields, etc. We use it to refresh cross-references in the document. */ public static void refresh(XTextDocument doc) { // Refresh the document XRefreshable xRefresh = UnoCast.cast(XRefreshable.class, doc).get(); xRefresh.refresh(); } /** * Insert a clickable cross-reference to a reference mark, with a label containing the target's page number. * <p> * May need a documentConnection.refresh() after, to update the text shown. */ public static void insertReferenceToPageNumberOfReferenceMark(XTextDocument doc, String referenceMarkName, XTextRange cursor) throws CreationException, WrappedTargetException { // based on: https://wiki.openoffice.org/wiki/Documentation/DevGuide/Text/Reference_Marks XMultiServiceFactory msf = UnoCast.cast(XMultiServiceFactory.class, doc).get(); // Create a 'GetReference' text field to refer to the reference mark we just inserted, // and get it's XPropertySet interface XPropertySet xFieldProps; try { String name = "com.sun.star.text.textfield.GetReference"; xFieldProps = UnoCast.cast(XPropertySet.class, msf.createInstance(name)).get(); } catch (com.sun.star.uno.Exception e) { throw new CreationException(e.getMessage()); } try { // Set the SourceName of the GetReference text field to the referenceMarkName xFieldProps.setPropertyValue("SourceName", referenceMarkName); } catch (UnknownPropertyException ex) { throw new java.lang.IllegalStateException("The created GetReference does not have property 'SourceName'"); } catch (PropertyVetoException ex) { throw new java.lang.IllegalStateException("Caught PropertyVetoException on 'SourceName'"); } try { // specify that the source is a reference mark (could also be a footnote, // bookmark or sequence field) xFieldProps.setPropertyValue("ReferenceFieldSource", ReferenceFieldSource.REFERENCE_MARK); } catch (UnknownPropertyException ex) { throw new java.lang.IllegalStateException("The created GetReference does not have property" + " 'ReferenceFieldSource'"); } catch (PropertyVetoException ex) { throw new java.lang.IllegalStateException("Caught PropertyVetoException on 'ReferenceFieldSource'"); } try { // We want the reference displayed as page number xFieldProps.setPropertyValue("ReferenceFieldPart", ReferenceFieldPart.PAGE); } catch (UnknownPropertyException ex) { throw new java.lang.IllegalStateException("The created GetReference does not have property" + " 'ReferenceFieldPart'"); } catch (PropertyVetoException ex) { throw new java.lang.IllegalStateException("Caught PropertyVetoException on 'ReferenceFieldPart'"); } // Get the XTextContent interface of the GetReference text field XTextContent xRefContent = UnoCast.cast(XTextContent.class, xFieldProps).get(); // Insert the text field cursor.getText().insertTextContent(cursor.getEnd(), xRefContent, false); } }
4,051
44.022222
118
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/uno/UnoCursor.java
package org.jabref.model.openoffice.uno; import java.util.Optional; import com.sun.star.text.XTextContent; import com.sun.star.text.XTextCursor; import com.sun.star.text.XTextDocument; import com.sun.star.text.XTextRange; import com.sun.star.text.XTextViewCursor; import com.sun.star.text.XTextViewCursorSupplier; public class UnoCursor { private UnoCursor() { } /** * Get the cursor positioned by the user. */ public static Optional<XTextViewCursor> getViewCursor(XTextDocument doc) { return UnoTextDocument.getCurrentController(doc) .flatMap(e -> UnoCast.cast(XTextViewCursorSupplier.class, e)) .map(XTextViewCursorSupplier::getViewCursor); } /** * Create a text cursor for a textContent. * * @return Optional.empty if mark is null, otherwise cursor. */ public static Optional<XTextCursor> getTextCursorOfTextContentAnchor(XTextContent mark) { if (mark == null) { return Optional.empty(); } XTextRange markAnchor = mark.getAnchor(); if (markAnchor == null) { return Optional.empty(); } return Optional.of(markAnchor.getText().createTextCursorByRange(markAnchor)); } public static XTextCursor createTextCursorByRange(XTextRange range) { return range.getText().createTextCursorByRange(range); } }
1,424
29.978261
93
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/uno/UnoNameAccess.java
package org.jabref.model.openoffice.uno; import java.util.Optional; import com.sun.star.container.NoSuchElementException; import com.sun.star.container.XNameAccess; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextContent; public class UnoNameAccess { private UnoNameAccess() { } /** * @return null if name not found, or if the result does not support the XTextContent interface. */ public static Optional<XTextContent> getTextContentByName(XNameAccess nameAccess, String name) throws WrappedTargetException { try { return UnoCast.cast(XTextContent.class, nameAccess.getByName(name)); } catch (NoSuchElementException ex) { return Optional.empty(); } } }
791
27.285714
100
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/uno/UnoNamed.java
package org.jabref.model.openoffice.uno; import com.sun.star.container.XNamed; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.text.XTextContent; import com.sun.star.text.XTextDocument; import com.sun.star.text.XTextRange; public class UnoNamed { private UnoNamed() { } /** * Insert a new instance of a service at the provided cursor position. * * @param service For example "com.sun.star.text.ReferenceMark", "com.sun.star.text.Bookmark" or "com.sun.star.text.TextSection". * <p> * Passed to this.asXMultiServiceFactory().createInstance(service) The result is expected to support the XNamed and XTextContent interfaces. * @param name For the ReferenceMark, Bookmark, TextSection. If the name is already in use, LibreOffice may change the name. * @param range Marks the location or range for the thing to be inserted. * @param absorb ReferenceMark, Bookmark and TextSection can incorporate a text range. If absorb is true, the text in the range becomes part of the thing. If absorb is false, the thing is inserted at the end of the range. * @return The XNamed interface, in case we need to check the actual name. */ static XNamed insertNamedTextContent(XTextDocument doc, String service, String name, XTextRange range, boolean absorb) throws CreationException { XMultiServiceFactory msf = UnoCast.cast(XMultiServiceFactory.class, doc).get(); Object xObject; try { xObject = msf.createInstance(service); } catch (com.sun.star.uno.Exception e) { throw new CreationException(e.getMessage()); } XNamed xNamed = UnoCast.cast(XNamed.class, xObject) .orElseThrow(() -> new IllegalArgumentException("Service is not an XNamed")); xNamed.setName(name); // get XTextContent interface XTextContent xTextContent = UnoCast.cast(XTextContent.class, xObject) .orElseThrow(() -> new IllegalArgumentException("Service is not an XTextContent")); range.getText().insertTextContent(range, xTextContent, absorb); return xNamed; } }
2,419
44.660377
226
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/uno/UnoProperties.java
package org.jabref.model.openoffice.uno; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import com.sun.star.beans.Property; import com.sun.star.beans.UnknownPropertyException; import com.sun.star.beans.XPropertyContainer; import com.sun.star.beans.XPropertySet; import com.sun.star.beans.XPropertySetInfo; import com.sun.star.lang.WrappedTargetException; /** * Utilities for properties. */ public class UnoProperties { private UnoProperties() { } public static Optional<XPropertySet> asPropertySet(XPropertyContainer propertyContainer) { return UnoCast.cast(XPropertySet.class, propertyContainer); } public static Optional<XPropertySetInfo> getPropertySetInfo(XPropertySet propertySet) { return Optional.ofNullable(propertySet) .flatMap(e -> Optional.ofNullable(e.getPropertySetInfo())); } public static Optional<XPropertySetInfo> getPropertySetInfo(XPropertyContainer propertyContainer) { return Optional.ofNullable(propertyContainer).flatMap(UnoProperties::getPropertySetInfo); } public static List<String> getPropertyNames(Property[] properties) { Objects.requireNonNull(properties); return Arrays.stream(properties) .map(p -> p.Name) .collect(Collectors.toList()); } public static List<String> getPropertyNames(XPropertySetInfo propertySetInfo) { return getPropertyNames(propertySetInfo.getProperties()); } public static List<String> getPropertyNames(XPropertySet propertySet) { return getPropertyNames(propertySet.getPropertySetInfo()); } public static List<String> getPropertyNames(XPropertyContainer propertyContainer) { return asPropertySet(propertyContainer) .map(UnoProperties::getPropertyNames) .orElse(new ArrayList<>()); } public static Optional<Object> getValueAsObject(XPropertySet propertySet, String property) throws WrappedTargetException { Objects.requireNonNull(propertySet); Objects.requireNonNull(property); try { return Optional.ofNullable(propertySet.getPropertyValue(property)); } catch (UnknownPropertyException e) { return Optional.empty(); } } public static Optional<Object> getValueAsObject(XPropertyContainer propertyContainer, String property) throws WrappedTargetException { Optional<XPropertySet> propertySet = asPropertySet(propertyContainer); if (propertySet.isEmpty()) { return Optional.empty(); } return UnoProperties.getValueAsObject(propertySet.get(), property); } }
2,839
34.061728
106
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/uno/UnoRedlines.java
package org.jabref.model.openoffice.uno; import java.util.Optional; import com.sun.star.beans.UnknownPropertyException; import com.sun.star.beans.XPropertySet; import com.sun.star.container.NoSuchElementException; import com.sun.star.container.XEnumeration; import com.sun.star.container.XEnumerationAccess; import com.sun.star.document.XRedlinesSupplier; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextDocument; /** * Change tracking and Redlines */ public class UnoRedlines { public static boolean getRecordChanges(XTextDocument doc) throws WrappedTargetException { // https://wiki.openoffice.org/wiki/Documentation/DevGuide/Text/Settings // "Properties of com.sun.star.text.TextDocument" XPropertySet propertySet = UnoCast.cast(XPropertySet.class, doc).get(); try { return (boolean) propertySet.getPropertyValue("RecordChanges"); } catch (UnknownPropertyException ex) { throw new java.lang.IllegalStateException("Caught UnknownPropertyException on 'RecordChanges'"); } } private static Optional<XRedlinesSupplier> getRedlinesSupplier(XTextDocument doc) { return UnoCast.cast(XRedlinesSupplier.class, doc); } public static int countRedlines(XTextDocument doc) { Optional<XRedlinesSupplier> supplier = getRedlinesSupplier(doc); if (supplier.isEmpty()) { return 0; } XEnumerationAccess enumerationAccess = supplier.get().getRedlines(); XEnumeration enumeration = enumerationAccess.createEnumeration(); if (enumeration == null) { return 0; } else { int count = 0; while (enumeration.hasMoreElements()) { try { enumeration.nextElement(); count++; } catch (NoSuchElementException | WrappedTargetException ex) { break; } } return count; } } }
2,054
32.145161
108
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/uno/UnoReferenceMark.java
package org.jabref.model.openoffice.uno; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import com.sun.star.container.NoSuchElementException; import com.sun.star.container.XNameAccess; import com.sun.star.container.XNamed; import com.sun.star.lang.DisposedException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XReferenceMarksSupplier; import com.sun.star.text.XTextContent; import com.sun.star.text.XTextDocument; import com.sun.star.text.XTextRange; public class UnoReferenceMark { private UnoReferenceMark() { } /** * @throws NoDocumentException If cannot get reference marks * <p> * Note: also used by `isDocumentConnectionMissing` to test if we have a working connection. */ public static XNameAccess getNameAccess(XTextDocument doc) throws NoDocumentException { XReferenceMarksSupplier supplier = UnoCast.cast(XReferenceMarksSupplier.class, doc).get(); try { return supplier.getReferenceMarks(); } catch (DisposedException ex) { throw new NoDocumentException("UnoReferenceMarks.getNameAccess failed with" + ex); } } /** * Names of all reference marks. * <p> * Empty list for nothing. */ public static List<String> getListOfNames(XTextDocument doc) throws NoDocumentException { XNameAccess nameAccess = UnoReferenceMark.getNameAccess(doc); String[] names = nameAccess.getElementNames(); if (names == null) { return new ArrayList<>(); } return Arrays.asList(names); } /** * Remove the named reference mark. * <p> * Removes both the text and the mark itself. */ public static void removeIfExists(XTextDocument doc, String name) throws WrappedTargetException, NoDocumentException { XNameAccess xReferenceMarks = UnoReferenceMark.getNameAccess(doc); if (xReferenceMarks.hasByName(name)) { Optional<XTextContent> mark = UnoNameAccess.getTextContentByName(xReferenceMarks, name); if (mark.isEmpty()) { return; } try { doc.getText().removeTextContent(mark.get()); } catch (NoSuchElementException ex) { // The caller gets what it expects. } } } /** * @return reference mark as XTextContent, Optional.empty if not found. */ public static Optional<XTextContent> getAsTextContent(XTextDocument doc, String name) throws NoDocumentException, WrappedTargetException { XNameAccess nameAccess = UnoReferenceMark.getNameAccess(doc); return UnoNameAccess.getTextContentByName(nameAccess, name); } /** * XTextRange for the named reference mark, Optional.empty if not found. */ public static Optional<XTextRange> getAnchor(XTextDocument doc, String name) throws NoDocumentException, WrappedTargetException { return UnoReferenceMark.getAsTextContent(doc, name) .map(XTextContent::getAnchor); } /** * Insert a new reference mark at the provided cursor position. * <p> * If {@code absorb} is true, the text in the cursor range will become the text with gray background. * <p> * Note: LibreOffice 6.4.6.2 will create multiple reference marks with the same name without error or renaming. Its GUI does not allow this, but we can create them programmatically. In the GUI, clicking on any of those identical names will move the cursor to the same mark. * * @param name For the reference mark. * @param range Cursor marking the location or range for the reference mark. */ public static XNamed create(XTextDocument doc, String name, XTextRange range, boolean absorb) throws CreationException { return UnoNamed.insertNamedTextContent(doc, "com.sun.star.text.ReferenceMark", name, range, absorb); } }
4,224
33.917355
277
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/uno/UnoScreenRefresh.java
package org.jabref.model.openoffice.uno; import com.sun.star.text.XTextDocument; /** * Disable/enable screen refresh. */ public class UnoScreenRefresh { private UnoScreenRefresh() { } /** * Disable screen refresh. * <p> * Must be paired with unlockControllers() * <p> * https://www.openoffice.org/api/docs/common/ref/com/sun/star/frame/XModel.html * <p> * While there is at least one lock remaining, some notifications for display updates are not broadcasted. */ public static void lockControllers(XTextDocument doc) { doc.lockControllers(); } public static void unlockControllers(XTextDocument doc) { doc.unlockControllers(); } public static boolean hasControllersLocked(XTextDocument doc) { return doc.hasControllersLocked(); } }
840
23.735294
110
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/uno/UnoSelection.java
package org.jabref.model.openoffice.uno; import java.util.Objects; import java.util.Optional; import com.sun.star.frame.XController; import com.sun.star.lang.XServiceInfo; import com.sun.star.text.XTextDocument; import com.sun.star.view.XSelectionSupplier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Selection in the document. */ public class UnoSelection { private static final Logger LOGGER = LoggerFactory.getLogger(UnoSelection.class); private UnoSelection() { } private static Optional<XSelectionSupplier> getSelectionSupplier(XTextDocument doc) { if (doc == null) { LOGGER.warn("UnoSelection.getSelectionSupplier: doc is null"); return Optional.empty(); } Optional<XController> controller = UnoTextDocument.getCurrentController(doc); if (controller.isEmpty()) { LOGGER.warn("UnoSelection.getSelectionSupplier: getCurrentController(doc) returned empty"); return Optional.empty(); } Optional<XSelectionSupplier> supplier = UnoCast.cast(XSelectionSupplier.class, controller.get()); if (supplier.isEmpty()) { LOGGER.warn("UnoSelection.getSelectionSupplier: cast to XSelectionSupplier returned empty"); return Optional.empty(); } return supplier; } /** * @return may be Optional.empty(), or some type supporting XServiceInfo * So far it seems the first thing we have to do with a selection is to decide what do we have. * <p> * One way to do that is accessing its XServiceInfo interface. * <p> * Experiments using printServiceInfo with cursor in various positions in the document: * <p> * With cursor within the frame, in text: *** xserviceinfo.getImplementationName: "SwXTextRanges" "com.sun.star.text.TextRanges" * <p> * With cursor somewhere else in text: *** xserviceinfo.getImplementationName: "SwXTextRanges" "com.sun.star.text.TextRanges" * <p> * With cursor in comment (also known as "annotation"): *** XSelectionSupplier is OK *** Object initialSelection is null *** xserviceinfo is null * <p> * With frame selected: *** xserviceinfo.getImplementationName: "SwXTextFrame" "com.sun.star.text.BaseFrame" "com.sun.star.text.TextContent" "com.sun.star.document.LinkTarget" "com.sun.star.text.TextFrame" "com.sun.star.text.Text" * <p> * With cursor selecting an inserted image: *** XSelectionSupplier is OK *** Object initialSelection is OK *** xserviceinfo is OK *** xserviceinfo.getImplementationName: "SwXTextGraphicObject" "com.sun.star.text.BaseFrame" "com.sun.star.text.TextContent" "com.sun.star.document.LinkTarget" "com.sun.star.text.TextGraphicObject" */ public static Optional<XServiceInfo> getSelectionAsXServiceInfo(XTextDocument doc) { Objects.requireNonNull(doc); Optional<XSelectionSupplier> supplier = getSelectionSupplier(doc); if (supplier.isEmpty()) { LOGGER.warn("getSelectionSupplier returned empty"); return Optional.empty(); } Object selection = supplier.get().getSelection(); if (selection == null) { return Optional.empty(); } Optional<XServiceInfo> result = UnoCast.cast(XServiceInfo.class, selection); if (result.isEmpty()) { LOGGER.warn("cast to XServiceInfo returned empty"); return Optional.empty(); } return result; } /** * Select the object represented by {@code newSelection} if it is known and selectable in this {@code XSelectionSupplier} object. * <p> * Presumably result from {@code XSelectionSupplier.getSelection()} is usually OK. It also accepted {@code XTextRange newSelection = doc.getText().getStart();} */ public static void select(XTextDocument doc, Object newSelection) { Objects.requireNonNull(doc); getSelectionSupplier(doc).ifPresent(e -> e.select(newSelection)); } }
4,010
44.579545
331
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/uno/UnoStyle.java
package org.jabref.model.openoffice.uno; import java.util.Optional; import com.sun.star.container.NoSuchElementException; import com.sun.star.container.XNameAccess; import com.sun.star.container.XNameContainer; import com.sun.star.lang.WrappedTargetException; import com.sun.star.style.XStyle; import com.sun.star.style.XStyleFamiliesSupplier; import com.sun.star.text.XTextDocument; /** * Styles in the document. */ public class UnoStyle { public static final String CHARACTER_STYLES = "CharacterStyles"; public static final String PARAGRAPH_STYLES = "ParagraphStyles"; private UnoStyle() { } private static Optional<XStyle> getStyleFromFamily(XTextDocument doc, String familyName, String styleName) throws WrappedTargetException { XStyleFamiliesSupplier fss = UnoCast.cast(XStyleFamiliesSupplier.class, doc).get(); XNameAccess families = UnoCast.cast(XNameAccess.class, fss.getStyleFamilies()).get(); XNameContainer xFamily; try { xFamily = UnoCast.cast(XNameContainer.class, families.getByName(familyName)).get(); } catch (NoSuchElementException ex) { String msg = String.format("Style family name '%s' is not recognized", familyName); throw new java.lang.IllegalArgumentException(msg, ex); } try { Object style = xFamily.getByName(styleName); return UnoCast.cast(XStyle.class, style); } catch (NoSuchElementException ex) { return Optional.empty(); } } public static Optional<XStyle> getParagraphStyle(XTextDocument doc, String styleName) throws WrappedTargetException { return getStyleFromFamily(doc, PARAGRAPH_STYLES, styleName); } public static Optional<XStyle> getCharacterStyle(XTextDocument doc, String styleName) throws WrappedTargetException { return getStyleFromFamily(doc, CHARACTER_STYLES, styleName); } public static Optional<String> getInternalNameOfStyle(XTextDocument doc, String familyName, String name) throws WrappedTargetException { return getStyleFromFamily(doc, familyName, name) .map(XStyle::getName); } public static Optional<String> getInternalNameOfParagraphStyle(XTextDocument doc, String name) throws WrappedTargetException { return getInternalNameOfStyle(doc, PARAGRAPH_STYLES, name); } public static Optional<String> getInternalNameOfCharacterStyle(XTextDocument doc, String name) throws WrappedTargetException { return getInternalNameOfStyle(doc, CHARACTER_STYLES, name); } }
2,790
34.782051
110
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/uno/UnoTextDocument.java
package org.jabref.model.openoffice.uno; import java.util.Optional; import com.sun.star.beans.XPropertySet; import com.sun.star.document.XDocumentProperties; import com.sun.star.document.XDocumentPropertiesSupplier; import com.sun.star.frame.XController; import com.sun.star.frame.XFrame; import com.sun.star.lang.DisposedException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextDocument; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class UnoTextDocument { private static final Logger LOGGER = LoggerFactory.getLogger(UnoTextDocument.class); private UnoTextDocument() { } /** * @return True if we cannot reach the current document. */ public static boolean isDocumentConnectionMissing(XTextDocument doc) { boolean missing = doc == null; // Attempt to check document is really available if (!missing) { try { UnoReferenceMark.getNameAccess(doc); } catch (NoDocumentException | DisposedException ex) { missing = true; } } return missing; } public static Optional<XController> getCurrentController(XTextDocument doc) { if (doc == null) { return Optional.empty(); } XController controller = doc.getCurrentController(); if (controller == null) { LOGGER.warn("doc.getCurrentController() returned null"); return Optional.empty(); } return Optional.of(controller); } /** * @param doc The XTextDocument we want the frame title for. Null allowed. * @return The title or Optional.empty() */ public static Optional<String> getFrameTitle(XTextDocument doc) { Optional<XFrame> frame = getCurrentController(doc).map(XController::getFrame); if (frame.isEmpty()) { return Optional.empty(); } Optional<XPropertySet> propertySet = UnoCast.cast(XPropertySet.class, frame.get()); if (propertySet.isEmpty()) { return Optional.empty(); } try { Optional<Object> frameTitleObj = UnoProperties.getValueAsObject(propertySet.get(), "Title"); if (frameTitleObj.isEmpty()) { return Optional.empty(); } String frameTitleString = String.valueOf(frameTitleObj.get()); return Optional.ofNullable(frameTitleString); } catch (WrappedTargetException e) { LOGGER.warn("Could not get document title", e); return Optional.empty(); } } static Optional<XDocumentProperties> getDocumentProperties(XTextDocument doc) { return Optional.ofNullable(doc) .flatMap(e -> UnoCast.cast(XDocumentPropertiesSupplier.class, e)) .map(XDocumentPropertiesSupplier::getDocumentProperties); } }
2,922
32.597701
104
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/uno/UnoTextRange.java
package org.jabref.model.openoffice.uno; import java.util.Optional; import com.sun.star.text.XFootnote; import com.sun.star.text.XTextContent; import com.sun.star.text.XTextRange; import com.sun.star.text.XTextRangeCompare; public class UnoTextRange { private UnoTextRange() { } /** * If original is in a footnote, return a range containing the corresponding footnote marker. * <p> * Returns Optional.empty if not in a footnote. */ public static Optional<XTextRange> getFootnoteMarkRange(XTextRange original) { Optional<XFootnote> footer = UnoCast.cast(XFootnote.class, original.getText()); // If we are inside a footnote, // find the linking footnote marker: // The footnote's anchor gives the correct position in the text: return footer.map(XTextContent::getAnchor); } /** * Test if two XTextRange values are comparable (i.e. they share the same getText()). */ public static boolean comparables(XTextRange a, XTextRange b) { return a.getText() == b.getText(); } /** * @return follows java conventions * 1 if (a &gt; b); (-1) if (a &lt; b) */ public static int compareStartsUnsafe(XTextRangeCompare compare, XTextRange a, XTextRange b) { return -1 * compare.compareRegionStarts(a, b); } public static int compareStarts(XTextRange a, XTextRange b) { if (!comparables(a, b)) { throw new java.lang.IllegalArgumentException("compareStarts: got incomparable regions"); } final XTextRangeCompare compare = UnoCast.cast(XTextRangeCompare.class, a.getText()).get(); return compareStartsUnsafe(compare, a, b); } /** * @return follows java conventions * 1 if (a &gt; b); (-1) if (a &lt; b) */ public static int compareEnds(XTextRange a, XTextRange b) { if (!comparables(a, b)) { throw new java.lang.IllegalArgumentException("compareEnds: got incomparable regions"); } final XTextRangeCompare compare = UnoCast.cast(XTextRangeCompare.class, a.getText()).get(); return -1 * compare.compareRegionEnds(a, b); } /* * Assumes a and b belong to the same XText as compare. */ public static int compareStartsThenEndsUnsafe(XTextRangeCompare compare, XTextRange a, XTextRange b) { int res = compare.compareRegionStarts(a, b); if (res != 0) { return -1 * res; } return -1 * compare.compareRegionEnds(a, b); } public static int compareStartsThenEnds(XTextRange a, XTextRange b) { if (!comparables(a, b)) { throw new java.lang.IllegalArgumentException("compareStartsThenEnds: got incomparable regions"); } final XTextRangeCompare compare = UnoCast.cast(XTextRangeCompare.class, a.getText()).get(); return compareStartsThenEndsUnsafe(compare, a, b); } }
2,930
34.743902
108
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/uno/UnoTextSection.java
package org.jabref.model.openoffice.uno; import java.util.Optional; import com.sun.star.container.NoSuchElementException; import com.sun.star.container.XNameAccess; import com.sun.star.container.XNamed; import com.sun.star.lang.DisposedException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextContent; import com.sun.star.text.XTextDocument; import com.sun.star.text.XTextRange; import com.sun.star.text.XTextSection; import com.sun.star.text.XTextSectionsSupplier; import com.sun.star.uno.Any; public class UnoTextSection { /** * @return An XNameAccess to find sections by name. */ public static XNameAccess getNameAccess(XTextDocument doc) throws NoDocumentException { XTextSectionsSupplier supplier = UnoCast.cast(XTextSectionsSupplier.class, doc).get(); try { return supplier.getTextSections(); } catch (DisposedException ex) { throw new NoDocumentException("UnoTextSection.getNameAccess failed with" + ex); } } /** * Get an XTextSection by name. */ public static Optional<XTextSection> getByName(XTextDocument doc, String name) throws WrappedTargetException, NoDocumentException { XNameAccess nameAccess = getNameAccess(doc); try { return Optional.ofNullable((XTextSection) ((Any) nameAccess.getByName(name)).getObject()); } catch (NoSuchElementException ex) { return Optional.empty(); } } /** * Get the XTextRange covering to the named section. * * @param name The name of the section to find. * @return The XTextRange for the section, or Optional.empty(). */ public static Optional<XTextRange> getAnchor(XTextDocument doc, String name) throws WrappedTargetException, NoDocumentException { XNameAccess nameAccess = getNameAccess(doc); return UnoNameAccess.getTextContentByName(nameAccess, name).map(XTextContent::getAnchor); } /** * Create a text section with the provided name and insert it at the provided cursor. * * @param name The desired name for the section. * @param range The location to insert at. * <p> * If an XTextSection by that name already exists, LibreOffice (6.4.6.2) creates a section with a name different from what we requested, in "Section {number}" format. */ public static XNamed create(XTextDocument doc, String name, XTextRange range, boolean absorb) throws CreationException { return UnoNamed.insertNamedTextContent(doc, "com.sun.star.text.TextSection", name, range, absorb); } }
2,768
33.6125
183
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/uno/UnoUndo.java
package org.jabref.model.openoffice.uno; import java.util.Optional; import com.sun.star.document.XUndoManager; import com.sun.star.document.XUndoManagerSupplier; import com.sun.star.text.XTextDocument; import com.sun.star.util.InvalidStateException; /** * Undo : group document changes into larger Undo actions. */ public class UnoUndo { private UnoUndo() { } public static Optional<XUndoManager> getXUndoManager(XTextDocument doc) { // https://www.openoffice.org/api/docs/common/ref/com/sun/star/document/XUndoManager.html return UnoCast.cast(XUndoManagerSupplier.class, doc) .map(XUndoManagerSupplier::getUndoManager); } /** * Each call to enterUndoContext must be paired by a call to leaveUndoContext, otherwise, the document's undo stack is left in an inconsistent state. */ public static void enterUndoContext(XTextDocument doc, String title) { getXUndoManager(doc).ifPresent(undoManager -> undoManager.enterUndoContext(title)); } public static void leaveUndoContext(XTextDocument doc) { Optional<XUndoManager> undoManager = getXUndoManager(doc); if (undoManager.isPresent()) { try { undoManager.get().leaveUndoContext(); } catch (InvalidStateException ex) { throw new IllegalStateException("leaveUndoContext reported InvalidStateException"); } } } }
1,450
33.547619
153
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/uno/UnoUserDefinedProperty.java
package org.jabref.model.openoffice.uno; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; import com.sun.star.beans.IllegalTypeException; import com.sun.star.beans.NotRemoveableException; import com.sun.star.beans.PropertyAttribute; import com.sun.star.beans.PropertyExistException; import com.sun.star.beans.PropertyVetoException; import com.sun.star.beans.UnknownPropertyException; import com.sun.star.beans.XPropertyContainer; import com.sun.star.beans.XPropertySet; import com.sun.star.beans.XPropertySetInfo; import com.sun.star.document.XDocumentProperties; import com.sun.star.lang.WrappedTargetException; import com.sun.star.text.XTextDocument; import com.sun.star.uno.Any; import com.sun.star.uno.Type; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Document level user-defined properties. * <p> * LibreOffice GUI: [File]/[Properties]/[Custom Properties] */ public class UnoUserDefinedProperty { private static final Logger LOGGER = LoggerFactory.getLogger(UnoUserDefinedProperty.class); private UnoUserDefinedProperty() { } public static Optional<XPropertyContainer> getPropertyContainer(XTextDocument doc) { return UnoTextDocument.getDocumentProperties(doc).map(XDocumentProperties::getUserDefinedProperties); } public static List<String> getListOfNames(XTextDocument doc) { return UnoUserDefinedProperty.getPropertyContainer(doc) .map(UnoProperties::getPropertyNames) .orElse(new ArrayList<>()); } /** * @param property Name of a custom document property in the current document. * @return The value of the property or Optional.empty() * These properties are used to store extra data about individual citation. In particular, the `pageInfo` part. */ public static Optional<String> getStringValue(XTextDocument doc, String property) throws WrappedTargetException { Optional<XPropertySet> propertySet = UnoUserDefinedProperty.getPropertyContainer(doc) .flatMap(UnoProperties::asPropertySet); if (propertySet.isEmpty()) { throw new java.lang.IllegalArgumentException("getting UserDefinedProperties as XPropertySet failed"); } try { String value = propertySet.get().getPropertyValue(property).toString(); return Optional.ofNullable(value); } catch (UnknownPropertyException ex) { return Optional.empty(); } } /** * @param property Name of a custom document property in the current document. Created if does not exist yet. * @param value The value to be stored. */ public static void setStringProperty(XTextDocument doc, String property, String value) throws IllegalTypeException, PropertyVetoException, WrappedTargetException { Objects.requireNonNull(property); Objects.requireNonNull(value); Optional<XPropertyContainer> container = UnoUserDefinedProperty.getPropertyContainer(doc); if (container.isEmpty()) { throw new java.lang.IllegalArgumentException("UnoUserDefinedProperty.getPropertyContainer failed"); } Optional<XPropertySet> propertySet = container.flatMap(UnoProperties::asPropertySet); if (propertySet.isEmpty()) { throw new java.lang.IllegalArgumentException("asPropertySet failed"); } XPropertySetInfo propertySetInfo = propertySet.get().getPropertySetInfo(); if (propertySetInfo.hasPropertyByName(property)) { try { propertySet.get().setPropertyValue(property, value); return; } catch (UnknownPropertyException ex) { // fall through to addProperty } } try { container.get().addProperty(property, PropertyAttribute.REMOVEABLE, new Any(Type.STRING, value)); } catch (PropertyExistException ex) { throw new java.lang.IllegalStateException("Caught PropertyExistException for property assumed not to exist"); } } /** * @param property Name of a custom document property in the current document. * <p> * Logs warning if does not exist. */ public static void remove(XTextDocument doc, String property) throws NotRemoveableException { Objects.requireNonNull(property); Optional<XPropertyContainer> container = UnoUserDefinedProperty.getPropertyContainer(doc); if (container.isEmpty()) { throw new java.lang.IllegalArgumentException("getUserDefinedPropertiesAsXPropertyContainer failed"); } try { container.get().removeProperty(property); } catch (UnknownPropertyException ex) { LOGGER.warn(String.format("UnoUserDefinedProperty.remove(%s) This property was not there to remove", property)); } } /** * @param property Name of a custom document property in the current document. * <p> * Keep silent if property did not exist. */ public static void removeIfExists(XTextDocument doc, String property) throws NotRemoveableException { Objects.requireNonNull(property); Optional<XPropertyContainer> container = UnoUserDefinedProperty.getPropertyContainer(doc); if (container.isEmpty()) { throw new java.lang.IllegalArgumentException("getUserDefinedPropertiesAsXPropertyContainer failed"); } try { container.get().removeProperty(property); } catch (UnknownPropertyException ex) { // did not exist } } }
5,954
36.45283
121
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/util/OOListUtil.java
package org.jabref.model.openoffice.util; import java.util.Comparator; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; public class OOListUtil { public static <T, U> List<U> map(List<T> list, Function<T, U> fun) { return list.stream().map(fun).collect(Collectors.toList()); } /** * Integers 0..(len-1) */ public static List<Integer> makeIndices(int len) { return Stream.iterate(0, i -> i + 1).limit(len).collect(Collectors.toList()); } /** * Return indices so that list.get(indices.get(i)) is sorted. */ public static <T extends U, U> List<Integer> order(List<T> list, Comparator<U> comparator) { List<Integer> indices = makeIndices(list.size()); indices.sort((a, b) -> comparator.compare(list.get(a), list.get(b))); return indices; } }
913
28.483871
96
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/util/OOPair.java
package org.jabref.model.openoffice.util; public class OOPair<A, B> { public final A a; public final B b; public OOPair(A a, B b) { this.a = a; this.b = b; } }
195
14.076923
41
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/util/OOResult.java
package org.jabref.model.openoffice.util; import java.util.NoSuchElementException; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Function; /* * An instance of this class represents either the result of a computation, or an error * value. Neither of these is allowed to be null. * * Void is not allowed for R, use OOVoidResult instead. * * Out of `isPresent()` and `isError()` exactly one is true. */ public class OOResult<R, E> { private final Optional<R> result; private final Optional<E> error; /** * Exactly one of the arguments should be Optional.empty() */ private OOResult(Optional<R> result, Optional<E> error) { this.result = result; this.error = error; } public static <R, E> OOResult<R, E> ok(R result) { return new OOResult<>(Optional.of(result), Optional.empty()); } public static <R, E> OOResult<R, E> error(E error) { return new OOResult<>(Optional.empty(), Optional.of(error)); } public boolean isPresent() { return result.isPresent(); } public boolean isEmpty() { return !isPresent(); } public boolean isError() { return error.isPresent(); } public boolean isOK() { return !isError(); } public R get() { if (isError()) { throw new NoSuchElementException("Cannot get from error"); } return result.get(); } public E getError() { return error.get(); } public OOResult<R, E> ifPresent(Consumer<R> fun) { if (isPresent()) { fun.accept(get()); } return this; } public OOResult<R, E> ifError(Consumer<E> fun) { if (isError()) { fun.accept(getError()); } return this; } public <S> OOResult<S, E> map(Function<R, S> fun) { if (isError()) { return error(getError()); } else { return ok(fun.apply(get())); } } public <F> OOResult<R, F> mapError(Function<E, F> fun) { if (isError()) { return error(fun.apply(getError())); } else { return ok(get()); } } /** * Throw away the error part. */ public Optional<R> getOptional() { return result; } /** * Throw away the result part. */ public OOVoidResult<E> asVoidResult() { if (isError()) { return OOVoidResult.error(getError()); } else { return OOVoidResult.ok(); } } }
2,590
21.929204
87
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/util/OOTuple3.java
package org.jabref.model.openoffice.util; /** * This class allows three objects to be packed together, and later accessed as fields `a`, `b` and `c`. * <p> * Can be used to avoid creating a new class for just this purpose. * <p> * Can be useful if you do not have `Trifunction` at hand but need to pass three objects at a time. */ public class OOTuple3<A, B, C> { public final A a; public final B b; public final C c; public OOTuple3(A a, B b, C c) { this.a = a; this.b = b; this.c = c; } }
545
22.73913
104
java
null
jabref-main/src/main/java/org/jabref/model/openoffice/util/OOVoidResult.java
package org.jabref.model.openoffice.util; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Function; /* * error cannot be null */ public class OOVoidResult<E> { private final Optional<E> error; private OOVoidResult(Optional<E> error) { this.error = error; } public static <E> OOVoidResult<E> ok() { return new OOVoidResult<>(Optional.empty()); } public static <E> OOVoidResult<E> error(E error) { return new OOVoidResult<>(Optional.of(error)); } public boolean isError() { return error.isPresent(); } public boolean isOK() { return !isError(); } public E getError() { return error.get(); } public OOVoidResult<E> ifError(Consumer<E> fun) { if (isError()) { fun.accept(getError()); } return this; } public <F> OOVoidResult<F> mapError(Function<E, F> fun) { if (isError()) { return error(fun.apply(getError())); } else { return ok(); } } }
1,091
19.603774
61
java
null
jabref-main/src/main/java/org/jabref/model/paging/Page.java
package org.jabref.model.paging; import java.util.Collection; import java.util.Collections; public class Page<T> { private int pageNumber; private String query; private Collection<T> content; public Page(String query, int pageNumber, Collection<T> content) { this.query = query; this.pageNumber = pageNumber; this.content = Collections.unmodifiableCollection(content); } public Page(String query, int pageNumber) { this(query, pageNumber, Collections.emptyList()); } public Collection<T> getContent() { return content; } public int getPageNumber() { return pageNumber; } public String getQuery() { return query; } public int getSize() { return content.size(); } }
797
20
70
java
null
jabref-main/src/main/java/org/jabref/model/pdf/FileAnnotation.java
package org.jabref.model.pdf; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.Objects; import java.util.Optional; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FileAnnotation { private static final Logger LOGGER = LoggerFactory.getLogger(FileAnnotation.class); private final static int ABBREVIATED_ANNOTATION_NAME_LENGTH = 45; private static final String DATE_TIME_STRING = "^D:\\d{14}$"; private static final String DATE_TIME_STRING_WITH_TIME_ZONE = "^D:\\d{14}.+"; private static final String ANNOTATION_DATE_FORMAT = "yyyyMMddHHmmss"; private final String author; private final LocalDateTime timeModified; private final int page; private final String content; private final FileAnnotationType annotationType; private final Optional<FileAnnotation> linkedFileAnnotation; /** * A flexible constructor, mainly used as dummy if there is actually no annotation. * * @param author The authors of the annotation * @param timeModified The last time this annotation was modified * @param pageNumber The page of the pdf where the annotation occurs * @param content the actual content of the annotation * @param annotationType the type of the annotation */ public FileAnnotation(final String author, final LocalDateTime timeModified, final int pageNumber, final String content, final FileAnnotationType annotationType, final Optional<FileAnnotation> linkedFileAnnotation) { this.author = author; this.timeModified = timeModified; this.page = pageNumber; this.content = parseContent(content); this.annotationType = annotationType; this.linkedFileAnnotation = linkedFileAnnotation; } /** * Creating a normal FileAnnotation from a PDAnnotation. * * @param annotation The actual annotation that holds the information * @param pageNumber The page of the pdf where the annotation occurs */ public FileAnnotation(final PDAnnotation annotation, final int pageNumber) { this(annotation.getCOSObject().getString(COSName.T), extractModifiedTime(annotation.getModifiedDate()), pageNumber, annotation.getContents(), FileAnnotationType.parse(annotation), Optional.empty()); } /** * For creating a FileAnnotation that has a connection to another FileAnnotation. Needed when creating a text * highlighted or underlined annotation with a sticky note. * * @param annotation The actual annotation that holds the information * @param pageNumber The page of the pdf where the annotation occurs * @param linkedFileAnnotation The corresponding note of a marked text area. */ public FileAnnotation(final PDAnnotation annotation, final int pageNumber, FileAnnotation linkedFileAnnotation) { this(annotation.getCOSObject().getString(COSName.T), extractModifiedTime(annotation.getModifiedDate()), pageNumber, annotation.getContents(), FileAnnotationType.parse(annotation), Optional.of(linkedFileAnnotation)); } /** * Parses a String into a LocalDateTime. * * @param dateTimeString In this case of format yyyyMMddHHmmss. * @return a LocalDateTime parsed from the dateTimeString */ public static LocalDateTime extractModifiedTime(String dateTimeString) { if (dateTimeString == null) { return LocalDateTime.now(); } if (dateTimeString.matches(DATE_TIME_STRING_WITH_TIME_ZONE)) { dateTimeString = dateTimeString.substring(2, 16); } else if (dateTimeString.matches(DATE_TIME_STRING)) { dateTimeString = dateTimeString.substring(2); } try { return LocalDateTime.parse(dateTimeString, DateTimeFormatter.ofPattern(ANNOTATION_DATE_FORMAT)); } catch (DateTimeParseException e) { LOGGER.info(String.format("Expected a parseable date string! However, this text could not be parsed: '%s'", dateTimeString)); return LocalDateTime.now(); } } private String parseContent(final String content) { if (content == null) { return ""; } final String unreadableContent = "þÿ"; if (content.trim().equals(unreadableContent)) { return ""; } return content.trim(); } /** * Abbreviate annotation names when they are longer than {@code ABBREVIATED_ANNOTATION_NAME_LENGTH} chars * * @param annotationName annotation to be shortened * @return the abbreviated name */ private String abbreviateAnnotationName(final String annotationName) { if (annotationName.length() > ABBREVIATED_ANNOTATION_NAME_LENGTH) { return annotationName.subSequence(0, ABBREVIATED_ANNOTATION_NAME_LENGTH).toString() + "..."; } return annotationName; } @Override public String toString() { return abbreviateAnnotationName(content); } @Override public boolean equals(Object other) { if (this == other) { return true; } if ((other == null) || (getClass() != other.getClass())) { return false; } FileAnnotation that = (FileAnnotation) other; return Objects.equals(this.annotationType, that.annotationType) && Objects.equals(this.author, that.author) && Objects.equals(this.content, that.content) && Objects.equals(this.page, that.page) && Objects.equals(this.linkedFileAnnotation, that.linkedFileAnnotation) && Objects.equals(this.timeModified, that.timeModified); } @Override public int hashCode() { return Objects.hash(annotationType, author, content, page, linkedFileAnnotation, timeModified); } public String getAuthor() { return author; } public LocalDateTime getTimeModified() { return timeModified; } public int getPage() { return page; } public String getContent() { return content; } public FileAnnotationType getAnnotationType() { return annotationType; } public boolean hasLinkedAnnotation() { return this.linkedFileAnnotation.isPresent(); } /** * Before this getter is called the presence of the linked annotation must be checked via hasLinkedAnnotation()! * * @return the note attached to the annotation */ public FileAnnotation getLinkedFileAnnotation() { return linkedFileAnnotation.get(); } }
6,888
36.237838
143
java
null
jabref-main/src/main/java/org/jabref/model/pdf/FileAnnotationType.java
package org.jabref.model.pdf; import java.util.Locale; import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Our representation of the type of the FileAnnotation. This is needed as some FileAnnotationTypes require special * handling (e.g., Highlight or Underline), because of the linked FileAnnotations. */ public enum FileAnnotationType { TEXT("Text", false), HIGHLIGHT("Highlight", true), SQUIGGLY("Squiggly", true), UNDERLINE("Underline", true), STRIKEOUT("StrikeOut", true), POLYGON("Polygon", false), POPUP("Popup", false), LINE("Line", false), CIRCLE("Circle", false), FREETEXT("FreeText", false), INK("Ink", false), UNKNOWN("Unknown", false), NONE("None", false); private static final Logger LOGGER = LoggerFactory.getLogger(FileAnnotationType.class); private final String name; private final boolean linkedFileAnnotationType; FileAnnotationType(String name, boolean linkedFileAnnotationType) { this.name = name; this.linkedFileAnnotationType = linkedFileAnnotationType; } /** * Determines the FileAnnotationType of a raw PDAnnotation. Returns 'UNKNOWN' if the type is currently not in our * list of FileAnnotationTypes. * * @param annotation the raw PDAnnotation * @return The determined FileAnnotationType */ public static FileAnnotationType parse(PDAnnotation annotation) { try { return FileAnnotationType.valueOf(annotation.getSubtype().toUpperCase(Locale.ROOT)); } catch (IllegalArgumentException e) { LOGGER.info(String.format("FileAnnotationType %s is not supported and was converted into 'Unknown'!", annotation.getSubtype())); return UNKNOWN; } } /** * Determines if a String is a supported marked FileAnnotation type. * * @param annotationType a type descriptor * @return true if annotationType is a supported marked FileAnnotation type */ public static boolean isMarkedFileAnnotationType(String annotationType) { try { return FileAnnotationType.valueOf(annotationType.toUpperCase(Locale.ROOT)).linkedFileAnnotationType; } catch (IllegalArgumentException e) { return false; } } public boolean isLinkedFileAnnotationType() { return linkedFileAnnotationType; } public String toString() { return this.name; } }
2,525
31.805195
140
java
null
jabref-main/src/main/java/org/jabref/model/pdf/search/EnglishStemAnalyzer.java
package org.jabref.model.pdf.search; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.LowerCaseFilter; import org.apache.lucene.analysis.StopFilter; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.Tokenizer; import org.apache.lucene.analysis.core.DecimalDigitFilter; import org.apache.lucene.analysis.en.EnglishAnalyzer; import org.apache.lucene.analysis.en.PorterStemFilter; import org.apache.lucene.analysis.standard.StandardTokenizer; public class EnglishStemAnalyzer extends Analyzer { @Override protected TokenStreamComponents createComponents(String fieldName) { Tokenizer source = new StandardTokenizer(); TokenStream filter = new LowerCaseFilter(source); filter = new StopFilter(filter, EnglishAnalyzer.ENGLISH_STOP_WORDS_SET); filter = new DecimalDigitFilter(filter); filter = new PorterStemFilter(filter); return new TokenStreamComponents(source, filter); } }
996
37.346154
80
java
null
jabref-main/src/main/java/org/jabref/model/pdf/search/PdfSearchResults.java
package org.jabref.model.pdf.search; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; public final class PdfSearchResults { private final List<SearchResult> searchResults; public PdfSearchResults(List<SearchResult> search) { this.searchResults = Collections.unmodifiableList(search); } public PdfSearchResults() { this.searchResults = Collections.emptyList(); } public List<SearchResult> getSortedByScore() { List<SearchResult> sortedList = new ArrayList<>(searchResults); sortedList.sort((searchResult, t1) -> Float.compare(searchResult.getLuceneScore(), t1.getLuceneScore())); return Collections.unmodifiableList(sortedList); } public List<SearchResult> getSearchResults() { return this.searchResults; } public HashMap<String, List<SearchResult>> getSearchResultsByPath() { HashMap<String, List<SearchResult>> resultsByPath = new HashMap<>(); for (SearchResult result : searchResults) { if (resultsByPath.containsKey(result.getPath())) { resultsByPath.get(result.getPath()).add(result); } else { List<SearchResult> resultsForPath = new ArrayList<>(); resultsForPath.add(result); resultsByPath.put(result.getPath(), resultsForPath); } } return resultsByPath; } public int numSearchResults() { return this.searchResults.size(); } }
1,539
31.083333
113
java
null
jabref-main/src/main/java/org/jabref/model/pdf/search/SearchFieldConstants.java
package org.jabref.model.pdf.search; public class SearchFieldConstants { public static final String PATH = "path"; public static final String CONTENT = "content"; public static final String PAGE_NUMBER = "pageNumber"; public static final String ANNOTATIONS = "annotations"; public static final String MODIFIED = "modified"; public static final String[] PDF_FIELDS = new String[]{PATH, CONTENT, PAGE_NUMBER, MODIFIED, ANNOTATIONS}; public static final String VERSION = "95"; }
508
32.933333
110
java
null
jabref-main/src/main/java/org/jabref/model/pdf/search/SearchResult.java
package org.jabref.model.pdf.search; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.jabref.model.entry.BibEntry; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.index.IndexableField; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.highlight.Highlighter; import org.apache.lucene.search.highlight.InvalidTokenOffsetsException; import org.apache.lucene.search.highlight.QueryScorer; import org.apache.lucene.search.highlight.SimpleHTMLFormatter; import org.apache.lucene.search.highlight.TextFragment; import static org.jabref.model.pdf.search.SearchFieldConstants.ANNOTATIONS; import static org.jabref.model.pdf.search.SearchFieldConstants.CONTENT; import static org.jabref.model.pdf.search.SearchFieldConstants.MODIFIED; import static org.jabref.model.pdf.search.SearchFieldConstants.PAGE_NUMBER; import static org.jabref.model.pdf.search.SearchFieldConstants.PATH; public final class SearchResult { private final String path; private final int pageNumber; private final long modified; private final float luceneScore; private List<String> contentResultStringsHtml; private List<String> annotationsResultStringsHtml; public SearchResult(IndexSearcher searcher, Query query, ScoreDoc scoreDoc) throws IOException { this.path = getFieldContents(searcher, scoreDoc, PATH); this.pageNumber = Integer.parseInt(getFieldContents(searcher, scoreDoc, PAGE_NUMBER)); this.modified = Long.parseLong(getFieldContents(searcher, scoreDoc, MODIFIED)); this.luceneScore = scoreDoc.score; String content = getFieldContents(searcher, scoreDoc, CONTENT); String annotations = getFieldContents(searcher, scoreDoc, ANNOTATIONS); Highlighter highlighter = new Highlighter(new SimpleHTMLFormatter("<b>", "</b>"), new QueryScorer(query)); try (TokenStream contentStream = new EnglishStemAnalyzer().tokenStream(CONTENT, content)) { TextFragment[] frags = highlighter.getBestTextFragments(contentStream, content, true, 10); this.contentResultStringsHtml = Arrays.stream(frags).map(TextFragment::toString).collect(Collectors.toList()); } catch (InvalidTokenOffsetsException e) { this.contentResultStringsHtml = List.of(); } try (TokenStream annotationStream = new EnglishStemAnalyzer().tokenStream(ANNOTATIONS, annotations)) { TextFragment[] frags = highlighter.getBestTextFragments(annotationStream, annotations, true, 10); this.annotationsResultStringsHtml = Arrays.stream(frags).map(TextFragment::toString).collect(Collectors.toList()); } catch (InvalidTokenOffsetsException e) { this.annotationsResultStringsHtml = List.of(); } } private String getFieldContents(IndexSearcher searcher, ScoreDoc scoreDoc, String field) throws IOException { IndexableField indexableField = searcher.doc(scoreDoc.doc).getField(field); if (indexableField == null) { return ""; } return indexableField.stringValue(); } public boolean isResultFor(BibEntry entry) { return entry.getFiles().stream().anyMatch(linkedFile -> path.equals(linkedFile.getLink())); } public String getPath() { return path; } public long getModified() { return modified; } public float getLuceneScore() { return luceneScore; } public List<String> getContentResultStringsHtml() { return contentResultStringsHtml; } public List<String> getAnnotationsResultStringsHtml() { return annotationsResultStringsHtml; } public int getPageNumber() { return pageNumber; } }
3,895
37.96
126
java
null
jabref-main/src/main/java/org/jabref/model/schema/DublinCoreSchemaCustom.java
package org.jabref.model.schema; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import org.apache.commons.lang3.reflect.FieldUtils; import org.apache.xmpbox.XMPMetadata; import org.apache.xmpbox.schema.DublinCoreSchema; import org.apache.xmpbox.type.AbstractField; import org.apache.xmpbox.type.ArrayProperty; import org.apache.xmpbox.type.DateType; import org.apache.xmpbox.type.StructuredType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A DublinCoreSchema extension Class. * In case anyone intends to alter standard behaviour. */ @StructuredType(preferedPrefix = "dc", namespace = "http://purl.org/dc/elements/1.1/") public class DublinCoreSchemaCustom extends DublinCoreSchema { private static final Logger LOGGER = LoggerFactory.getLogger(DublinCoreSchemaCustom.class); public DublinCoreSchemaCustom(XMPMetadata metadata) { super(metadata); } public static DublinCoreSchema copyDublinCoreSchema(DublinCoreSchema dcSchema) { if (Objects.isNull(dcSchema)) { return null; } try { DublinCoreSchemaCustom dublinCoreSchemaCustom = new DublinCoreSchemaCustom(dcSchema.getMetadata()); FieldUtils.writeField(dublinCoreSchemaCustom, "container", dcSchema.getContainer(), true); FieldUtils.writeField(dublinCoreSchemaCustom, "attributes", FieldUtils.readField(dcSchema, "attributes", true), true); return dublinCoreSchemaCustom; } catch (Exception e) { LOGGER.error("Error making custom DC Schema. Using the default", e); return dcSchema; } } /** * Overloaded XMP Schema method * Behaviour is same except when seqName is "Date". Will return raw value instead */ @Override public List<String> getUnqualifiedSequenceValueList(String seqName) { AbstractField abstractProperty = getAbstractProperty(seqName); if (abstractProperty instanceof ArrayProperty) { if ("date".equals(seqName)) { return ((ArrayProperty) abstractProperty).getContainer() .getAllProperties() .stream() .map(field -> (String) ((DateType) field).getRawValue()) .collect(Collectors.toList()); } return ((ArrayProperty) abstractProperty).getElementsAsString(); } return null; } }
2,494
36.238806
111
java
null
jabref-main/src/main/java/org/jabref/model/search/GroupSearchQuery.java
package org.jabref.model.search; import java.util.EnumSet; import java.util.Objects; import org.jabref.model.entry.BibEntry; import org.jabref.model.search.rules.SearchRule; import org.jabref.model.search.rules.SearchRules; import org.jabref.model.search.rules.SearchRules.SearchFlags; public class GroupSearchQuery implements SearchMatcher { private final String query; private final EnumSet<SearchFlags> searchFlags; private final SearchRule rule; public GroupSearchQuery(String query, EnumSet<SearchFlags> searchFlags) { this.query = Objects.requireNonNull(query); this.searchFlags = searchFlags; this.rule = Objects.requireNonNull(getSearchRule()); } @Override public String toString() { return String.format("\"%s\" (%s, %s)", query, getCaseSensitiveDescription(), getRegularExpressionDescription()); } @Override public boolean isMatch(BibEntry entry) { return this.getRule().applyRule(query, entry); } private SearchRule getSearchRule() { return SearchRules.getSearchRuleByQuery(query, searchFlags); } private String getCaseSensitiveDescription() { if (searchFlags.contains(SearchRules.SearchFlags.CASE_SENSITIVE)) { return "case sensitive"; } else { return "case insensitive"; } } private String getRegularExpressionDescription() { if (searchFlags.contains(SearchRules.SearchFlags.REGULAR_EXPRESSION)) { return "regular expression"; } else { return "plain text"; } } public SearchRule getRule() { return rule; } public String getSearchExpression() { return query; } public EnumSet<SearchFlags> getSearchFlags() { return searchFlags; } }
1,833
26.787879
85
java
null
jabref-main/src/main/java/org/jabref/model/search/SearchMatcher.java
package org.jabref.model.search; import org.jabref.model.entry.BibEntry; @FunctionalInterface public interface SearchMatcher { boolean isMatch(BibEntry entry); }
168
17.777778
39
java
null
jabref-main/src/main/java/org/jabref/model/search/matchers/AndMatcher.java
package org.jabref.model.search.matchers; import org.jabref.model.entry.BibEntry; /** * A set of matchers that returns true if all matcher match the given entry. */ public class AndMatcher extends MatcherSet { @Override public boolean isMatch(BibEntry entry) { return matchers.stream() .allMatch(rule -> rule.isMatch(entry)); } }
378
22.6875
76
java
null
jabref-main/src/main/java/org/jabref/model/search/matchers/MatcherSet.java
package org.jabref.model.search.matchers; import java.util.ArrayList; import java.util.List; import java.util.Objects; import org.jabref.model.search.SearchMatcher; public abstract class MatcherSet implements SearchMatcher { protected final List<SearchMatcher> matchers = new ArrayList<>(); @Override public boolean equals(Object o) { if (this == o) { return true; } if ((o == null) || (getClass() != o.getClass())) { return false; } MatcherSet that = (MatcherSet) o; return Objects.equals(matchers, that.matchers); } @Override public int hashCode() { return Objects.hash(matchers); } public void addRule(SearchMatcher newRule) { matchers.add(Objects.requireNonNull(newRule)); } @Override public String toString() { final StringBuilder sb = new StringBuilder("MatcherSet{"); sb.append("matchers=").append(matchers); sb.append('}'); return sb.toString(); } }
1,036
22.568182
69
java
null
jabref-main/src/main/java/org/jabref/model/search/matchers/MatcherSets.java
package org.jabref.model.search.matchers; public class MatcherSets { public enum MatcherType { AND, OR } public static MatcherSet build(MatcherType ruleSet) { if (ruleSet == MatcherType.AND) { return new AndMatcher(); } else { return new OrMatcher(); } } }
340
17.944444
57
java
null
jabref-main/src/main/java/org/jabref/model/search/matchers/NotMatcher.java
package org.jabref.model.search.matchers; import java.util.Objects; import org.jabref.model.entry.BibEntry; import org.jabref.model.search.SearchMatcher; /** * Inverts the search result. * <p> * Example: * false --> true * true --> false */ public class NotMatcher implements SearchMatcher { private final SearchMatcher otherMatcher; public NotMatcher(SearchMatcher otherMatcher) { this.otherMatcher = Objects.requireNonNull(otherMatcher); } @Override public boolean isMatch(BibEntry entry) { return !otherMatcher.isMatch(entry); } }
586
19.964286
65
java
null
jabref-main/src/main/java/org/jabref/model/search/matchers/OrMatcher.java
package org.jabref.model.search.matchers; import org.jabref.model.entry.BibEntry; import org.jabref.model.util.ListUtil; /** * A set of matchers that returns true if any matcher matches the given entry. */ public class OrMatcher extends MatcherSet { @Override public boolean isMatch(BibEntry entry) { return ListUtil.anyMatch(matchers, rule -> rule.isMatch(entry)); } }
395
23.75
78
java
null
jabref-main/src/main/java/org/jabref/model/search/rules/ContainsBasedSearchRule.java
package org.jabref.model.search.rules; import java.util.EnumSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import org.jabref.architecture.AllowedToUseLogic; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.search.rules.SearchRules.SearchFlags; import org.jabref.model.strings.StringUtil; /** * Search rule for a search based on String.contains() */ @AllowedToUseLogic("Because access to the lucene index is needed") public class ContainsBasedSearchRule extends FullTextSearchRule { public ContainsBasedSearchRule(EnumSet<SearchFlags> searchFlags) { super(searchFlags); } @Override public boolean validateSearchStrings(String query) { return true; } @Override public boolean applyRule(String query, BibEntry bibEntry) { String searchString = query; if (!searchFlags.contains(SearchRules.SearchFlags.CASE_SENSITIVE)) { searchString = searchString.toLowerCase(Locale.ROOT); } List<String> unmatchedWords = new SentenceAnalyzer(searchString).getWords(); for (Field fieldKey : bibEntry.getFields()) { String formattedFieldContent = StringUtil.stripAccents(bibEntry.getLatexFreeField(fieldKey).get()); if (!searchFlags.contains(SearchRules.SearchFlags.CASE_SENSITIVE)) { formattedFieldContent = formattedFieldContent.toLowerCase(Locale.ROOT); } Iterator<String> unmatchedWordsIterator = unmatchedWords.iterator(); while (unmatchedWordsIterator.hasNext()) { String word = StringUtil.stripAccents(unmatchedWordsIterator.next()); if (formattedFieldContent.contains(word)) { unmatchedWordsIterator.remove(); } } if (unmatchedWords.isEmpty()) { return true; } } return getFulltextResults(query, bibEntry).numSearchResults() > 0; // Didn't match all words. } }
2,065
33.433333
111
java
null
jabref-main/src/main/java/org/jabref/model/search/rules/FullTextSearchRule.java
package org.jabref.model.search.rules; import java.io.IOException; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.stream.Collectors; import org.jabref.architecture.AllowedToUseLogic; import org.jabref.gui.Globals; import org.jabref.logic.pdf.search.retrieval.PdfSearcher; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.pdf.search.PdfSearchResults; import org.jabref.model.pdf.search.SearchResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * All classes providing full text search results inherit from this class. * <p> * Some kind of caching of the full text search results is implemented. */ @AllowedToUseLogic("Because access to the lucene index is needed") public abstract class FullTextSearchRule implements SearchRule { private static final Logger LOGGER = LoggerFactory.getLogger(FullTextSearchRule.class); protected final EnumSet<SearchRules.SearchFlags> searchFlags; protected String lastQuery; protected List<SearchResult> lastSearchResults; private final BibDatabaseContext databaseContext; public FullTextSearchRule(EnumSet<SearchRules.SearchFlags> searchFlags) { this.searchFlags = searchFlags; this.lastQuery = ""; lastSearchResults = Collections.emptyList(); databaseContext = Globals.stateManager.getActiveDatabase().orElse(null); } public EnumSet<SearchRules.SearchFlags> getSearchFlags() { return searchFlags; } @Override public PdfSearchResults getFulltextResults(String query, BibEntry bibEntry) { if (!searchFlags.contains(SearchRules.SearchFlags.FULLTEXT) || databaseContext == null) { return new PdfSearchResults(); } if (!query.equals(this.lastQuery)) { this.lastQuery = query; lastSearchResults = Collections.emptyList(); try { PdfSearcher searcher = PdfSearcher.of(databaseContext); PdfSearchResults results = searcher.search(query, 5); lastSearchResults = results.getSortedByScore(); } catch (IOException e) { LOGGER.error("Could not retrieve search results!", e); } } return new PdfSearchResults(lastSearchResults.stream() .filter(searchResult -> searchResult.isResultFor(bibEntry)) .collect(Collectors.toList())); } }
2,572
34.736111
112
java
null
jabref-main/src/main/java/org/jabref/model/search/rules/GrammarBasedSearchRule.java
package org.jabref.model.search.rules; import java.io.IOException; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Predicate; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.jabref.architecture.AllowedToUseLogic; import org.jabref.gui.Globals; import org.jabref.logic.pdf.search.retrieval.PdfSearcher; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.Keyword; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.InternalField; import org.jabref.model.pdf.search.PdfSearchResults; import org.jabref.model.pdf.search.SearchResult; import org.jabref.model.search.rules.SearchRules.SearchFlags; import org.jabref.model.strings.StringUtil; import org.jabref.search.SearchBaseVisitor; import org.jabref.search.SearchLexer; import org.jabref.search.SearchParser; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.BailErrorStrategy; import org.antlr.v4.runtime.BaseErrorListener; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.RecognitionException; import org.antlr.v4.runtime.Recognizer; import org.antlr.v4.runtime.misc.ParseCancellationException; import org.antlr.v4.runtime.tree.ParseTree; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The search query must be specified in an expression that is acceptable by the Search.g4 grammar. * <p> * This class implements the "Advanced Search Mode" described in the help */ @AllowedToUseLogic("Because access to the lucene index is needed") public class GrammarBasedSearchRule implements SearchRule { private static final Logger LOGGER = LoggerFactory.getLogger(GrammarBasedSearchRule.class); private final EnumSet<SearchFlags> searchFlags; private ParseTree tree; private String query; private List<SearchResult> searchResults = new ArrayList<>(); private final BibDatabaseContext databaseContext; public static class ThrowingErrorListener extends BaseErrorListener { public static final ThrowingErrorListener INSTANCE = new ThrowingErrorListener(); @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) throws ParseCancellationException { throw new ParseCancellationException("line " + line + ":" + charPositionInLine + " " + msg); } } public GrammarBasedSearchRule(EnumSet<SearchFlags> searchFlags) throws RecognitionException { this.searchFlags = searchFlags; databaseContext = Globals.stateManager.getActiveDatabase().orElse(null); } public static boolean isValid(EnumSet<SearchFlags> searchFlags, String query) { return new GrammarBasedSearchRule(searchFlags).validateSearchStrings(query); } public ParseTree getTree() { return this.tree; } public String getQuery() { return this.query; } private void init(String query) throws ParseCancellationException { if (Objects.equals(this.query, query)) { return; } SearchLexer lexer = new SearchLexer(new ANTLRInputStream(query)); lexer.removeErrorListeners(); // no infos on file system lexer.addErrorListener(ThrowingErrorListener.INSTANCE); SearchParser parser = new SearchParser(new CommonTokenStream(lexer)); parser.removeErrorListeners(); // no infos on file system parser.addErrorListener(ThrowingErrorListener.INSTANCE); parser.setErrorHandler(new BailErrorStrategy()); // ParseCancelationException on parse errors tree = parser.start(); this.query = query; if (!searchFlags.contains(SearchRules.SearchFlags.FULLTEXT) || (databaseContext == null)) { return; } try { PdfSearcher searcher = PdfSearcher.of(databaseContext); PdfSearchResults results = searcher.search(query, 5); searchResults = results.getSortedByScore(); } catch (IOException e) { LOGGER.error("Could not retrieve search results!", e); } } @Override public boolean applyRule(String query, BibEntry bibEntry) { try { return new BibtexSearchVisitor(searchFlags, bibEntry).visit(tree); } catch (Exception e) { LOGGER.debug("Search failed", e); return getFulltextResults(query, bibEntry).numSearchResults() > 0; } } @Override public PdfSearchResults getFulltextResults(String query, BibEntry bibEntry) { return new PdfSearchResults(searchResults.stream().filter(searchResult -> searchResult.isResultFor(bibEntry)).collect(Collectors.toList())); } @Override public boolean validateSearchStrings(String query) { try { init(query); return true; } catch (ParseCancellationException e) { LOGGER.debug("Search query invalid", e); return false; } } public EnumSet<SearchFlags> getSearchFlags() { return searchFlags; } public enum ComparisonOperator { EXACT, CONTAINS, DOES_NOT_CONTAIN; public static ComparisonOperator build(String value) { if ("CONTAINS".equalsIgnoreCase(value) || "=".equals(value)) { return CONTAINS; } else if ("MATCHES".equalsIgnoreCase(value) || "==".equals(value)) { return EXACT; } else { return DOES_NOT_CONTAIN; } } } public static class Comparator { private final ComparisonOperator operator; private final Pattern fieldPattern; private final Pattern valuePattern; public Comparator(String field, String value, ComparisonOperator operator, EnumSet<SearchFlags> searchFlags) { this.operator = operator; int option = searchFlags.contains(SearchRules.SearchFlags.CASE_SENSITIVE) ? 0 : Pattern.CASE_INSENSITIVE; this.fieldPattern = Pattern.compile(searchFlags.contains(SearchRules.SearchFlags.REGULAR_EXPRESSION) ? StringUtil.stripAccents(field) : "\\Q" + StringUtil.stripAccents(field) + "\\E", option); this.valuePattern = Pattern.compile(searchFlags.contains(SearchRules.SearchFlags.REGULAR_EXPRESSION) ? StringUtil.stripAccents(value) : "\\Q" + StringUtil.stripAccents(value) + "\\E", option); } public boolean compare(BibEntry entry) { // special case for searching for entrytype=phdthesis if (fieldPattern.matcher(InternalField.TYPE_HEADER.getName()).matches()) { return matchFieldValue(entry.getType().getName()); } // special case for searching a single keyword if (fieldPattern.matcher("anykeyword").matches()) { return entry.getKeywords(',').stream().map(Keyword::toString).anyMatch(this::matchFieldValue); } // specification of fieldsKeys to search is done in the search expression itself Set<Field> fieldsKeys = entry.getFields(); // special case for searching allfields=cat and title=dog if (!fieldPattern.matcher("anyfield").matches()) { // Filter out the requested fields fieldsKeys = fieldsKeys.stream().filter(matchFieldKey()).collect(Collectors.toSet()); } for (Field field : fieldsKeys) { Optional<String> fieldValue = entry.getLatexFreeField(field); if (fieldValue.isPresent()) { if (matchFieldValue(StringUtil.stripAccents(fieldValue.get()))) { return true; } } } // special case of asdf!=whatever and entry does not contain asdf return fieldsKeys.isEmpty() && (operator == ComparisonOperator.DOES_NOT_CONTAIN); } private Predicate<Field> matchFieldKey() { return field -> fieldPattern.matcher(field.getName()).matches(); } public boolean matchFieldValue(String content) { Matcher matcher = valuePattern.matcher(content); if (operator == ComparisonOperator.CONTAINS) { return matcher.find(); } else if (operator == ComparisonOperator.EXACT) { return matcher.matches(); } else if (operator == ComparisonOperator.DOES_NOT_CONTAIN) { return !matcher.find(); } else { throw new IllegalStateException("MUST NOT HAPPEN"); } } } /** * Search results in boolean. It may be later on converted to an int. */ static class BibtexSearchVisitor extends SearchBaseVisitor<Boolean> { private final EnumSet<SearchFlags> searchFlags; private final BibEntry entry; public BibtexSearchVisitor(EnumSet<SearchFlags> searchFlags, BibEntry bibEntry) { this.searchFlags = searchFlags; this.entry = bibEntry; } public boolean comparison(String field, ComparisonOperator operator, String value) { return new Comparator(field, value, operator, searchFlags).compare(entry); } @Override public Boolean visitStart(SearchParser.StartContext ctx) { return visit(ctx.expression()); } @Override public Boolean visitComparison(SearchParser.ComparisonContext context) { // remove possible enclosing " symbols String right = context.right.getText(); if (right.startsWith("\"") && right.endsWith("\"")) { right = right.substring(1, right.length() - 1); } Optional<SearchParser.NameContext> fieldDescriptor = Optional.ofNullable(context.left); if (fieldDescriptor.isPresent()) { return comparison(fieldDescriptor.get().getText(), ComparisonOperator.build(context.operator.getText()), right); } else { return SearchRules.getSearchRule(searchFlags).applyRule(right, entry); } } @Override public Boolean visitUnaryExpression(SearchParser.UnaryExpressionContext ctx) { return !visit(ctx.expression()); // negate } @Override public Boolean visitParenExpression(SearchParser.ParenExpressionContext ctx) { return visit(ctx.expression()); // ignore parenthesis } @Override public Boolean visitBinaryExpression(SearchParser.BinaryExpressionContext ctx) { if ("AND".equalsIgnoreCase(ctx.operator.getText())) { return visit(ctx.left) && visit(ctx.right); // and } else { return visit(ctx.left) || visit(ctx.right); // or } } } }
11,134
38.207746
204
java
null
jabref-main/src/main/java/org/jabref/model/search/rules/RegexBasedSearchRule.java
package org.jabref.model.search.rules; import java.util.EnumSet; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import org.jabref.architecture.AllowedToUseLogic; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.Field; import org.jabref.model.search.rules.SearchRules.SearchFlags; import org.jabref.model.strings.StringUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Search rule for regex-based search. */ @AllowedToUseLogic("Because access to the lucene index is needed") public class RegexBasedSearchRule extends FullTextSearchRule { private static final Logger LOGGER = LoggerFactory.getLogger(RegexBasedSearchRule.class); public RegexBasedSearchRule(EnumSet<SearchFlags> searchFlags) { super(searchFlags); } @Override public boolean validateSearchStrings(String query) { try { Pattern.compile(query, searchFlags.contains(SearchRules.SearchFlags.CASE_SENSITIVE) ? 0 : Pattern.CASE_INSENSITIVE); } catch (PatternSyntaxException ex) { return false; } return true; } @Override public boolean applyRule(String query, BibEntry bibEntry) { Pattern pattern; try { pattern = Pattern.compile(StringUtil.stripAccents(query), searchFlags.contains(SearchRules.SearchFlags.CASE_SENSITIVE) ? 0 : Pattern.CASE_INSENSITIVE); } catch (PatternSyntaxException ex) { LOGGER.debug("Could not compile regex {}", query, ex); return false; } for (Field field : bibEntry.getFields()) { Optional<String> fieldOptional = bibEntry.getField(field); if (fieldOptional.isPresent()) { String fieldContentNoBrackets = StringUtil.stripAccents(bibEntry.getLatexFreeField(field).get()); Matcher m = pattern.matcher(fieldContentNoBrackets); if (m.find()) { return true; } } } return getFulltextResults(query, bibEntry).numSearchResults() > 0; } }
2,174
33.52381
163
java
null
jabref-main/src/main/java/org/jabref/model/search/rules/SearchRule.java
package org.jabref.model.search.rules; import org.jabref.model.entry.BibEntry; import org.jabref.model.pdf.search.PdfSearchResults; public interface SearchRule { boolean applyRule(String query, BibEntry bibEntry); PdfSearchResults getFulltextResults(String query, BibEntry bibEntry); boolean validateSearchStrings(String query); }
348
23.928571
73
java
null
jabref-main/src/main/java/org/jabref/model/search/rules/SearchRules.java
package org.jabref.model.search.rules; import java.util.EnumSet; import java.util.regex.Pattern; /** * This is a factory to instantiate the matching SearchRule implementation matching a given query */ public class SearchRules { private static final Pattern SIMPLE_EXPRESSION = Pattern.compile("[^\\p{Punct}]*"); private SearchRules() { } /** * Returns the appropriate search rule that fits best to the given parameter. */ public static SearchRule getSearchRuleByQuery(String query, EnumSet<SearchFlags> searchFlags) { if (isSimpleQuery(query)) { return new ContainsBasedSearchRule(searchFlags); } // this searches specified fields if specified, // and all fields otherwise SearchRule searchExpression = new GrammarBasedSearchRule(searchFlags); if (searchExpression.validateSearchStrings(query)) { return searchExpression; } else { return getSearchRule(searchFlags); } } private static boolean isSimpleQuery(String query) { return SIMPLE_EXPRESSION.matcher(query).matches(); } static SearchRule getSearchRule(EnumSet<SearchFlags> searchFlags) { if (searchFlags.contains(SearchFlags.REGULAR_EXPRESSION)) { return new RegexBasedSearchRule(searchFlags); } else { return new ContainsBasedSearchRule(searchFlags); } } public enum SearchFlags { CASE_SENSITIVE, REGULAR_EXPRESSION, FULLTEXT, KEEP_SEARCH_STRING } }
1,540
29.82
99
java
null
jabref-main/src/main/java/org/jabref/model/search/rules/SentenceAnalyzer.java
package org.jabref.model.search.rules; import java.util.ArrayList; import java.util.List; public class SentenceAnalyzer { public static final char ESCAPE_CHAR = '\\'; public static final char QUOTE_CHAR = '"'; private final String query; public SentenceAnalyzer(String query) { this.query = query; } public List<String> getWords() { List<String> result = new ArrayList<>(); StringBuilder stringBuilder = new StringBuilder(); boolean escaped = false; boolean quoted = false; for (char c : query.toCharArray()) { // Check if we are entering an escape sequence: if (!escaped && c == ESCAPE_CHAR) { escaped = true; } else { // See if we have reached the end of a word: if (!escaped && !quoted && Character.isWhitespace(c)) { if (stringBuilder.length() > 0) { result.add(stringBuilder.toString()); stringBuilder = new StringBuilder(); } } else if (c == QUOTE_CHAR) { // Whether it is a start or end quote, store the current // word if any: if (stringBuilder.length() > 0) { result.add(stringBuilder.toString()); stringBuilder = new StringBuilder(); } quoted = !quoted; } else { // All other possibilities exhausted, we add the char to // the current word: stringBuilder.append(c); } escaped = false; } } // Finished with the loop. If we have a current word, add it: if (stringBuilder.length() > 0) { result.add(stringBuilder.toString()); } return result; } }
1,946
32.568966
76
java
null
jabref-main/src/main/java/org/jabref/model/strings/LatexToUnicodeAdapter.java
package org.jabref.model.strings; import java.text.Normalizer; import java.util.Objects; import java.util.Optional; import java.util.regex.Pattern; import com.github.tomtung.latex2unicode.LaTeX2Unicode; import fastparse.Parsed; /** * Adapter class for the latex2unicode lib. This is an alternative to our LatexToUnicode class */ public class LatexToUnicodeAdapter { private static final Pattern UNDERSCORE_MATCHER = Pattern.compile("_(?!\\{)"); private static final String REPLACEMENT_CHAR = "\uFFFD"; private static final Pattern UNDERSCORE_PLACEHOLDER_MATCHER = Pattern.compile(REPLACEMENT_CHAR); /** * Attempts to resolve all LaTeX in the String. * * @param inField a String containing LaTeX * @return a String with LaTeX resolved into Unicode, or the original String if the LaTeX could not be parsed */ public static String format(String inField) { Objects.requireNonNull(inField); return parse(inField).orElse(Normalizer.normalize(inField, Normalizer.Form.NFC)); } /** * Attempts to resolve all LaTeX in the String. * * @param inField a String containing LaTeX * @return an {@code Optional<String>} with LaTeX resolved into Unicode or {@code empty} on failure. */ public static Optional<String> parse(String inField) { Objects.requireNonNull(inField); String toFormat = UNDERSCORE_MATCHER.matcher(inField).replaceAll(REPLACEMENT_CHAR); var parsingResult = LaTeX2Unicode.parse(toFormat); if (parsingResult instanceof Parsed.Success) { String text = parsingResult.get().value(); toFormat = Normalizer.normalize(text, Normalizer.Form.NFC); return Optional.of(UNDERSCORE_PLACEHOLDER_MATCHER.matcher(toFormat).replaceAll("_")); } return Optional.empty(); } }
1,855
35.392157
113
java
null
jabref-main/src/main/java/org/jabref/model/strings/StringUtil.java
package org.jabref.model.strings; import java.text.Normalizer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jabref.architecture.ApacheCommonsLang3Allowed; import org.jabref.logic.bibtex.FieldWriter; import com.google.common.base.CharMatcher; import org.apache.commons.lang3.StringUtils; @ApacheCommonsLang3Allowed("There is no equivalent in Google's Guava") public class StringUtil { // Non-letters which are used to denote accents in LaTeX-commands, e.g., in {\"{a}} public static final String SPECIAL_COMMAND_CHARS = "\"`^~'=.|"; // contains all possible line breaks, not omitting any break such as "\\n" private static final Pattern LINE_BREAKS = Pattern.compile("\\r\\n|\\r|\\n"); private static final Pattern BRACED_TITLE_CAPITAL_PATTERN = Pattern.compile("\\{[A-Z]+\\}"); private static final UnicodeToReadableCharMap UNICODE_CHAR_MAP = new UnicodeToReadableCharMap(); public static String booleanToBinaryString(boolean expression) { return expression ? "1" : "0"; } /** * Quote special characters. * * @param toQuote The String which may contain special characters. * @param specials A String containing all special characters except the quoting character itself, which is automatically quoted. * @param quoteChar The quoting character. * @return A String with every special character (including the quoting character itself) quoted. */ public static String quote(String toQuote, String specials, char quoteChar) { if (toQuote == null) { return ""; } StringBuilder result = new StringBuilder(); char c; boolean isSpecial; for (int i = 0; i < toQuote.length(); ++i) { c = toQuote.charAt(i); isSpecial = c == quoteChar; // If non-null specials performs logic-or with specials.indexOf(c) >= 0 isSpecial |= (specials != null) && (specials.indexOf(c) >= 0); if (isSpecial) { result.append(quoteChar); } result.append(c); } return result.toString(); } /** * Creates a substring from a text */ public static String getPart(String text, int startIndex, boolean terminateOnEndBraceOnly) { char c; int count = 0; StringBuilder part = new StringBuilder(); // advance to first char and skip whitespace int index = startIndex + 1; while ((index < text.length()) && Character.isWhitespace(text.charAt(index))) { index++; } // then grab whatever is the first token (counting braces) while (index < text.length()) { c = text.charAt(index); if (!terminateOnEndBraceOnly && (count == 0) && Character.isWhitespace(c)) { // end argument and leave whitespace for further processing break; } if ((c == '}') && (--count < 0)) { break; } else if (c == '{') { count++; } part.append(c); index++; } return part.toString(); } /** * Returns the string, after shaving off whitespace at the beginning and end, * and removing (at most) one pair of braces or " surrounding it. */ public static String shaveString(String toShave) { if ((toShave == null) || (toShave.isEmpty())) { return ""; } String shaved = toShave.trim(); if (isInCurlyBrackets(shaved) || isInCitationMarks(shaved)) { return shaved.substring(1, shaved.length() - 1); } return shaved; } /** * Concatenate all strings in the array from index 'from' to 'to' (excluding * to) with the given separator. * <p> * Example: * <p> * String[] s = "ab/cd/ed".split("/"); join(s, "\\", 0, s.length) -> * "ab\\cd\\ed" * * @param to Excluding strings[to] */ public static String join(String[] strings, String separator, int from, int to) { if ((strings.length == 0) || (from >= to)) { return ""; } int updatedFrom = Math.max(0, from); int updatedTo = Math.min(strings.length, to); StringBuilder stringBuilder = new StringBuilder(); for (int i = updatedFrom; i < (updatedTo - 1); i++) { stringBuilder.append(strings[i]).append(separator); } return stringBuilder.append(strings[updatedTo - 1]).toString(); } /** * Removes optional square brackets from the string s */ public static String stripBrackets(String toStrip) { if (isInSquareBrackets(toStrip)) { return toStrip.substring(1, toStrip.length() - 1); } return toStrip; } /** * extends the filename with a default Extension, if no Extension '.x' could * be found */ public static String getCorrectFileName(String orgName, String defaultExtension) { if (orgName == null) { return ""; } if (orgName.toLowerCase(Locale.ROOT).endsWith("." + defaultExtension.toLowerCase(Locale.ROOT))) { return orgName; } int hiddenChar = orgName.indexOf('.', 1); // hidden files Linux/Unix (?) if (hiddenChar < 1) { return orgName + "." + defaultExtension; } return orgName; } /** * Formats field contents for output. Must be "symmetric" with the parse method above, so stored and reloaded fields * are not mangled. * * @param in the string to wrap * @param wrapAmount the number of characters belonging to a line of text * @param newline the newline character(s) * @return the wrapped string */ public static String wrap(String in, int wrapAmount, String newline) { String[] lines = in.split("\n"); StringBuilder result = new StringBuilder(); // remove all whitespace at the end of the string, this especially includes \r created when the field content has \r\n as line separator addWrappedLine(result, CharMatcher.whitespace().trimTrailingFrom(lines[0]), wrapAmount, newline); for (int i = 1; i < lines.length; i++) { if (lines[i].trim().isEmpty()) { result.append(newline); result.append('\t'); } else { result.append(newline); result.append('\t'); result.append(newline); result.append('\t'); // remove all whitespace at the end of the string, this especially includes \r created when the field content has \r\n as line separator String line = CharMatcher.whitespace().trimTrailingFrom(lines[i]); addWrappedLine(result, line, wrapAmount, newline); } } return result.toString(); } /** * Appends a text to a string builder. Wraps the text so that each line is approx wrapAmount characters long. * Wrapping is done using newline and tab character. * * @param line the line of text to be wrapped and appended * @param wrapAmount the number of characters belonging to a line of text * @param newlineString a string containing the newline character(s) */ private static void addWrappedLine(StringBuilder result, String line, int wrapAmount, String newlineString) { // Set our pointer to the beginning of the new line in the StringBuffer: int length = result.length(); // Add the line, unmodified: result.append(line); // insert newlines and one tab character at each position, where wrapping is necessary while (length < result.length()) { int current = result.indexOf(" ", length + wrapAmount); if ((current < 0) || (current >= result.length())) { break; } result.deleteCharAt(current); result.insert(current, newlineString + "\t"); length = current + newlineString.length(); } } /** * Quotes each and every character, e.g. '!' as &#33;. Used for verbatim * display of arbitrary strings that may contain HTML entities. */ public static String quoteForHTML(String toQuote) { StringBuilder result = new StringBuilder(); for (int i = 0; i < toQuote.length(); ++i) { result.append("&#").append((int) toQuote.charAt(i)).append(';'); } return result.toString(); } /** * Decodes an encoded double String array back into array form. The array * is assumed to be square, and delimited by the characters ';' (first dim) and * ':' (second dim). * * @param value The encoded String to be decoded. * @return The decoded String array. */ public static String[][] decodeStringDoubleArray(String value) { List<List<String>> newList = new ArrayList<>(); StringBuilder sb = new StringBuilder(); List<String> thisEntry = new ArrayList<>(); boolean escaped = false; for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); if (!escaped && (c == '\\')) { escaped = true; continue; } else if (!escaped && (c == ':')) { thisEntry.add(sb.toString()); sb = new StringBuilder(); } else if (!escaped && (c == ';')) { thisEntry.add(sb.toString()); sb = new StringBuilder(); newList.add(thisEntry); thisEntry = new ArrayList<>(); } else { sb.append(c); } escaped = false; } if (sb.length() > 0) { thisEntry.add(sb.toString()); } if (!thisEntry.isEmpty()) { newList.add(thisEntry); } // Convert to String[][]: String[][] res = new String[newList.size()][]; for (int i = 0; i < res.length; i++) { res[i] = new String[newList.get(i).size()]; for (int j = 0; j < res[i].length; j++) { res[i][j] = newList.get(i).get(j); } } return res; } /** * Wrap all uppercase letters, or sequences of uppercase letters, in curly * braces. Ignore letters within a pair of # character, as these are part of * a string label that should not be modified. * * @param s The string to modify. * @return The resulting string after wrapping capitals. */ public static String putBracesAroundCapitals(String s) { boolean inString = false; boolean isBracing = false; boolean escaped = false; int inBrace = 0; StringBuilder buf = new StringBuilder(); for (int i = 0; i < s.length(); i++) { // Update variables based on special characters: int c = s.charAt(i); if (c == '{') { inBrace++; } else if (c == '}') { inBrace--; } else if (!escaped && (c == FieldWriter.BIBTEX_STRING_START_END_SYMBOL)) { inString = !inString; } // See if we should start bracing: if ((inBrace == 0) && !isBracing && !inString && Character.isLetter((char) c) && Character.isUpperCase((char) c)) { buf.append('{'); isBracing = true; } // See if we should close a brace set: if (isBracing && !(Character.isLetter((char) c) && Character.isUpperCase((char) c))) { buf.append('}'); isBracing = false; } // Add the current character: buf.append((char) c); // Check if we are entering an escape sequence: escaped = (c == '\\') && !escaped; } // Check if we have an unclosed brace: if (isBracing) { buf.append('}'); } return buf.toString(); } /** * This method looks for occurrences of capital letters enclosed in an * arbitrary number of pairs of braces, e.g. "{AB}" or "{{T}}". All of these * pairs of braces are removed. * * @param s The String to analyze. * @return A new String with braces removed. */ public static String removeBracesAroundCapitals(String s) { String current = s; String previous = s; while ((current = removeSingleBracesAroundCapitals(current)).length() < previous.length()) { previous = current; } return current; } /** * This method looks for occurrences of capital letters enclosed in one pair * of braces, e.g. "{AB}". All these are replaced by only the capitals in * between the braces. * * @param s The String to analyze. * @return A new String with braces removed. */ private static String removeSingleBracesAroundCapitals(String s) { Matcher mcr = BRACED_TITLE_CAPITAL_PATTERN.matcher(s); StringBuilder buf = new StringBuilder(); while (mcr.find()) { String replaceStr = mcr.group(); mcr.appendReplacement(buf, replaceStr.substring(1, replaceStr.length() - 1)); } mcr.appendTail(buf); return buf.toString(); } /** * Replaces all platform-dependent line breaks by OS.NEWLINE line breaks. * AKA normalize newlines * <p> * We do NOT use UNIX line breaks as the user explicitly configures its linebreaks and this method is used in bibtex field writing * * <example> * Legacy Macintosh \r -> OS.NEWLINE * Windows \r\n -> OS.NEWLINE * </example> * * @return a String with only OS.NEWLINE as line breaks */ public static String unifyLineBreaks(String s, String newline) { return LINE_BREAKS.matcher(s).replaceAll(newline); } /** * Checks if the given String has exactly one pair of surrounding curly braces <br> * Strings with escaped characters in curly braces at the beginning and end are respected, too * * @param toCheck The string to check * @return True, if the check was succesful. False otherwise. */ public static boolean isInCurlyBrackets(String toCheck) { int count = 0; int brackets = 0; if ((toCheck == null) || toCheck.isEmpty()) { return false; } else { if ((toCheck.charAt(0) == '{') && (toCheck.charAt(toCheck.length() - 1) == '}')) { for (char c : toCheck.toCharArray()) { if (c == '{') { if (brackets == 0) { count++; } brackets++; } else if (c == '}') { brackets--; } } return count == 1; } return false; } } public static boolean isInSquareBrackets(String toCheck) { if ((toCheck == null) || toCheck.isEmpty()) { return false; // In case of null or empty string } else { return (toCheck.charAt(0) == '[') && (toCheck.charAt(toCheck.length() - 1) == ']'); } } public static boolean isInCitationMarks(String toCheck) { if ((toCheck == null) || (toCheck.length() <= 1)) { return false; // In case of null, empty string, or a single citation mark } else { return (toCheck.charAt(0) == '"') && (toCheck.charAt(toCheck.length() - 1) == '"'); } } /** * Optimized method for converting a String into an Integer * <p> * From http://stackoverflow.com/questions/1030479/most-efficient-way-of-converting-string-to-integer-in-java * * @param str the String holding an Integer value * @return the int value of str * @throws NumberFormatException if str cannot be parsed to an int */ public static int intValueOf(String str) { int idx = 0; int end; boolean sign = false; char ch; if ((str == null) || ((end = str.length()) == 0) || ((((ch = str.charAt(0)) < '0') || (ch > '9')) && (!(sign = ch == '-') || (++idx == end) || ((ch = str.charAt(idx)) < '0') || (ch > '9')))) { throw new NumberFormatException(str); } int ival = 0; for (; ; ival *= 10) { ival += '0' - ch; if (++idx == end) { return sign ? ival : -ival; } if (((ch = str.charAt(idx)) < '0') || (ch > '9')) { throw new NumberFormatException(str); } } } /** * Optimized method for converting a String into an Integer * <p> * From http://stackoverflow.com/questions/1030479/most-efficient-way-of-converting-string-to-integer-in-java * * @param str the String holding an Integer value * @return the int value of str or Optional.empty() if not possible */ public static Optional<Integer> intValueOfOptional(String str) { int idx = 0; int end; boolean sign = false; char ch; if ((str == null) || ((end = str.length()) == 0) || ((((ch = str.charAt(0)) < '0') || (ch > '9')) && (!(sign = ch == '-') || (++idx == end) || ((ch = str.charAt(idx)) < '0') || (ch > '9')))) { return Optional.empty(); } int ival = 0; for (; ; ival *= 10) { ival += '0' - ch; if (++idx == end) { return Optional.of(sign ? ival : -ival); } if (((ch = str.charAt(idx)) < '0') || (ch > '9')) { return Optional.empty(); } } } /** * This method ensures that the output String has only * valid XML unicode characters as specified by the * XML 1.0 standard. For reference, please see * <a href="http://www.w3.org/TR/2000/REC-xml-20001006#NT-Char">the * standard</a>. This method will return an empty * String if the input is null or empty. * <p> * URL: http://cse-mjmcl.cse.bris.ac.uk/blog/2007/02/14/1171465494443.html * * @param in The String whose non-valid characters we want to remove. * @return The in String, stripped of non-valid characters. */ public static String stripNonValidXMLCharacters(String in) { if ((in == null) || in.isEmpty()) { return ""; // vacancy test. } StringBuilder out = new StringBuilder(); // Used to hold the output. char current; // Used to reference the current character. for (int i = 0; i < in.length(); i++) { current = in.charAt(i); // NOTE: No IndexOutOfBoundsException caught here; it should not happen. if ((current == 0x9) || (current == 0xA) || (current == 0xD) || ((current >= 0x20) && (current <= 0xD7FF)) || ((current >= 0xE000) && (current <= 0xFFFD))) { out.append(current); } } return out.toString(); } /* * @param buf String to be tokenized * @param delimstr Delimiter string * @return list {@link java.util.List} of <tt>String</tt> */ public static List<String> tokenizeToList(String buf, String delimstr) { List<String> list = new ArrayList<>(); String buffer = buf + '\n'; StringTokenizer st = new StringTokenizer(buffer, delimstr); while (st.hasMoreTokens()) { list.add(st.nextToken()); } return list; } public static String limitStringLength(String s, int maxLength) { if (s == null) { return ""; } if (s.length() <= maxLength) { return s; } return s.substring(0, maxLength - 3) + "..."; } /** * Replace non-English characters like umlauts etc. with a sensible letter or letter combination that bibtex can * accept. The basis for replacement is the HashMap UnicodeToReadableCharMap. */ public static String replaceSpecialCharacters(String s) { /* Some unicode characters can be encoded in multiple ways. This uses <a href="https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/text/Normalizer.Form.html#NFC">NFC</a> * to re-encode the characters so that these characters can be found. * Most people expect Unicode to work similar to NFC, i.e., if characters looks the same, it is likely that they are equivalent. * Hence, if someone debugs issues in the `UNICODE_CHAR_MAP`, they will expect NFC. * A more holistic approach should likely start with the <a href="http://unicode.org/reports/tr15/#Compatibility_Equivalence_Figure">compatibility equivalence</a>. */ String result = Normalizer.normalize(s, Normalizer.Form.NFC); for (Map.Entry<String, String> chrAndReplace : UNICODE_CHAR_MAP.entrySet()) { result = result.replace(chrAndReplace.getKey(), chrAndReplace.getValue()); } return result; } /** * Return a String with n spaces * * @param n Number of spaces * @return String with n spaces */ public static String repeatSpaces(int n) { return repeat(Math.max(0, n), ' '); } /** * Return a String with n copies of the char c * * @param n Number of copies * @param c char to copy * @return String with n copies of c */ public static String repeat(int n, char c) { StringBuilder resultSB = new StringBuilder(n); for (int i = 0; i < n; i++) { resultSB.append(c); } return resultSB.toString(); } public static boolean isNullOrEmpty(String toTest) { return (toTest == null) || toTest.isEmpty(); } public static boolean isBlank(String string) { return !isNotBlank(string); } public static boolean isBlank(Optional<String> string) { return !isNotBlank(string); } /** * Checks if a CharSequence is not empty (""), not null and not whitespace only. */ public static boolean isNotBlank(String string) { // No Guava equivalent existing return StringUtils.isNotBlank(string); } public static boolean isNotBlank(Optional<String> string) { return string.isPresent() && isNotBlank(string.get()); } /** * Return string enclosed in HTML bold tags */ public static String boldHTML(String input) { return "<b>" + input + "</b>"; } /** * Return string enclosed in HTML bold tags if not null, otherwise return alternative text in HTML bold tags */ public static String boldHTML(String input, String alternative) { if (input == null) { return "<b>" + alternative + "</b>"; } return "<b>" + input + "</b>"; } /** * Unquote special characters. * * @param toUnquote The String which may contain quoted special characters. * @param quoteChar The quoting character. * @return A String with all quoted characters unquoted. */ public static String unquote(String toUnquote, char quoteChar) { StringBuilder result = new StringBuilder(); char c; boolean quoted = false; for (int i = 0; i < toUnquote.length(); ++i) { c = toUnquote.charAt(i); if (quoted) { // append literally... if (c != '\n') { result.append(c); } quoted = false; } else if (c == quoteChar) { // quote char quoted = true; } else { result.append(c); } } return result.toString(); } @ApacheCommonsLang3Allowed("No Guava equivalent existing - see https://stackoverflow.com/q/3322152/873282 for a list of other implementations") public static String stripAccents(String searchQuery) { return StringUtils.stripAccents(searchQuery); } /** * Make first character of String uppercase, and the rest lowercase. */ public static String capitalizeFirst(String toCapitalize) { if (toCapitalize.length() > 1) { return toCapitalize.substring(0, 1).toUpperCase(Locale.ROOT) + toCapitalize.substring(1).toLowerCase(Locale.ROOT); } else { return toCapitalize.toUpperCase(Locale.ROOT); } } /** * Returns a list of words contained in the given text. * Whitespace, comma and semicolon are considered as separator between words. * * @param text the input * @return a list of words */ public static List<String> getStringAsWords(String text) { return Arrays.asList(text.split("[\\s,;]+")); } /** * Returns a list of sentences contained in the given text. */ public static List<String> getStringAsSentences(String text) { // A sentence ends with a .?!;, but not in the case of "Mr.", "Ms.", "Mrs.", "Dr.", "st.", "jr.", "co.", "inc.", and "ltd." Pattern splitTextPattern = Pattern.compile("(?<=[\\.!;\\?])(?<![Mm](([Rr]|[Rr][Ss])|[Ss])\\.|[Dd][Rr]\\.|[Ss][Tt]\\.|[Jj][Rr]\\.|[Cc][Oo]\\.|[Ii][Nn][Cc]\\.|[Ll][Tt][Dd]\\.)\\s+"); return Arrays.asList(splitTextPattern.split(text)); } @ApacheCommonsLang3Allowed("No direct Guava equivalent existing - see https://stackoverflow.com/q/16560635/873282") public static boolean containsIgnoreCase(String text, String searchString) { return StringUtils.containsIgnoreCase(text, searchString); } public static String substringBetween(String str, String open, String close) { return StringUtils.substringBetween(str, open, close); } public static String ignoreCurlyBracket(String title) { return isNotBlank(title) ? title.replace("{", "").replace("}", "") : title; } /** * Encloses the given string with " if there is a space contained * * @return Returns a string */ public static String quoteStringIfSpaceIsContained(String string) { if (string.contains(" ")) { return "\"" + string + "\""; } else { return string; } } /** * Checks if the given string contains any whitespace characters. The supported whitespace characters * are the set of characters matched by {@code \s} in regular expressions, which are {@code [ \t\n\x0B\f\r]}. * * @param s The string to check * @return {@code True} if the given string does contain at least one whitespace character, {@code False} otherwise * */ public static boolean containsWhitespace(String s) { return s.chars().anyMatch(Character::isWhitespace); } @ApacheCommonsLang3Allowed("No Guava equivalent existing - see https://stackoverflow.com/a/23825984") public static String removeStringAtTheEnd(String string, String stringToBeRemoved) { return StringUtils.removeEndIgnoreCase(string, stringToBeRemoved); } @ApacheCommonsLang3Allowed("No Guava equivalent existing") public static boolean endsWithIgnoreCase(String string, String suffix) { return StringUtils.endsWithIgnoreCase(string, suffix); } }
27,740
35.549407
200
java
null
jabref-main/src/main/java/org/jabref/model/strings/UnicodeToReadableCharMap.java
package org.jabref.model.strings; import java.util.HashMap; public class UnicodeToReadableCharMap extends HashMap<String, String> { public UnicodeToReadableCharMap() { put("\u00C0", "A"); put("\u00C1", "A"); put("\u00C2", "A"); put("\u00C3", "A"); put("\u00C4", "Ae"); put("\u00C5", "Aa"); put("\u00C6", "Ae"); put("\u00C7", "C"); put("\u00C8", "E"); put("\u00C9", "E"); put("\u00CA", "E"); put("\u00CB", "E"); put("\u00CC", "I"); put("\u00CD", "I"); put("\u00CE", "I"); put("\u00CF", "I"); put("\u00D0", "D"); put("\u00D1", "N"); put("\u00D2", "O"); put("\u00D3", "O"); put("\u00D4", "O"); put("\u00D5", "O"); put("\u00D6", "Oe"); put("\u00D8", "Oe"); put("\u00D9", "U"); put("\u00DA", "U"); put("\u00DB", "U"); put("\u00DC", "Ue"); // U umlaut .. put("\u00DD", "Y"); put("\u00DF", "ss"); put("\u00E0", "a"); put("\u00E1", "a"); put("\u00E2", "a"); put("\u00E3", "a"); put("\u00E4", "ae"); put("\u00E5", "aa"); put("\u00E6", "ae"); put("\u00E7", "c"); put("\u00E8", "e"); put("\u00E9", "e"); put("\u00EA", "e"); put("\u00EB", "e"); put("\u00EC", "i"); put("\u00ED", "i"); put("\u00EE", "i"); put("\u00EF", "i"); put("\u00F0", "o"); put("\u00F1", "n"); put("\u00F2", "o"); put("\u00F3", "o"); put("\u00F4", "o"); put("\u00F5", "o"); put("\u00F6", "oe"); put("\u00F8", "oe"); put("\u00F9", "u"); put("\u00FA", "u"); put("\u00FB", "u"); put("\u00FC", "ue"); // u umlaut... put("\u00FD", "y"); put("\u00FF", "y"); put("\u0100", "A"); put("\u0101", "a"); put("\u0102", "A"); put("\u0103", "a"); put("\u0104", "A"); put("\u0105", "a"); put("\u0106", "C"); put("\u0107", "c"); put("\u0108", "C"); put("\u0109", "c"); put("\u010A", "C"); put("\u010B", "c"); put("\u010C", "C"); put("\u010D", "c"); put("\u010E", "D"); put("\u010F", "d"); put("\u0110", "D"); put("\u0111", "d"); put("\u0112", "E"); put("\u0113", "e"); put("\u0114", "E"); put("\u0115", "e"); put("\u0116", "E"); put("\u0117", "e"); put("\u0118", "E"); put("\u0119", "e"); put("\u011A", "E"); put("\u011B", "e"); put("\u011C", "G"); put("\u011D", "g"); put("\u011E", "G"); put("\u011F", "g"); put("\u0120", "G"); put("\u0121", "g"); put("\u0122", "G"); put("\u0123", "g"); put("\u0124", "H"); put("\u0125", "h"); put("\u0127", "h"); put("\u0128", "I"); put("\u0129", "i"); put("\u012A", "I"); put("\u012B", "i"); put("\u012C", "I"); put("\u012D", "i"); put("\u012E", "I"); put("\u012F", "i"); put("\u0130", "I"); put("\u0131", "i"); put("\u0132", "IJ"); put("\u0133", "ij"); put("\u0134", "J"); put("\u0135", "j"); put("\u0136", "K"); put("\u0137", "k"); put("\u0138", "k"); put("\u0139", "L"); put("\u013A", "l"); put("\u013B", "L"); put("\u013C", "l"); put("\u013D", "L"); put("\u013E", "l"); put("\u013F", "L"); put("\u0140", "l"); put("\u0141", "L"); put("\u0142", "l"); put("\u0143", "N"); put("\u0144", "n"); put("\u0145", "N"); put("\u0146", "n"); put("\u0147", "N"); put("\u0148", "n"); put("\u0149", "n"); put("\u014A", "N"); put("\u014B", "n"); put("\u014C", "O"); put("\u014D", "o"); put("\u014E", "O"); put("\u014F", "o"); put("\u0150", "Oe"); put("\u0151", "oe"); put("\u0152", "OE"); put("\u0153", "oe"); put("\u0154", "R"); put("\u0155", "r"); put("\u0156", "R"); put("\u0157", "r"); put("\u0158", "R"); put("\u0159", "r"); put("\u015A", "S"); put("\u015B", "s"); put("\u015C", "S"); put("\u015D", "s"); put("\u015E", "S"); put("\u015F", "s"); put("\u0160", "S"); put("\u0161", "s"); put("\u0162", "T"); put("\u0163", "t"); put("\u0164", "T"); put("\u0165", "t"); put("\u0166", "T"); put("\u0167", "t"); put("\u0168", "U"); put("\u0169", "u"); put("\u016A", "U"); put("\u016B", "u"); put("\u016C", "U"); put("\u016D", "u"); put("\u016E", "UU"); put("\u016F", "uu"); put("\u0170", "Ue"); put("\u0171", "ue"); put("\u0172", "U"); put("\u0173", "u"); put("\u0174", "W"); put("\u0175", "w"); put("\u0176", "Y"); put("\u0177", "y"); put("\u0178", "Y"); put("\u0179", "Z"); put("\u017A", "z"); put("\u017B", "Z"); put("\u017C", "z"); put("\u017D", "Z"); put("\u017E", "z"); put("\u1EBC", "E"); put("\u1EBD", "e"); put("\u1EF8", "Y"); put("\u1EF9", "y"); put("\u01CD", "A"); put("\u01CE", "a"); put("\u01CF", "I"); put("\u01D0", "i"); put("\u01D1", "O"); put("\u01D2", "o"); put("\u01D3", "U"); put("\u01D4", "u"); put("\u0232", "Y"); put("\u0233", "y"); put("\u01EA", "O"); put("\u01EB", "o"); put("\u1E0C", "D"); put("\u1E0D", "d"); put("\u1E1A", "E"); // "~" subscript put("\u1E1B", "e"); put("\u1E2C", "I"); put("\u1E2D", "i"); put("\u1E24", "H"); put("\u1E25", "h"); put("\u1E36", "L"); put("\u1E37", "l"); put("\u1E38", "L"); put("\u1E39", "l"); put("\u1E42", "M"); put("\u1E43", "m"); put("\u1E46", "N"); put("\u1E47", "n"); put("\u1E5A", "R"); put("\u1E5B", "r"); put("\u1E5C", "R"); put("\u1E5D", "r"); put("\u1E62", "S"); put("\u1E63", "s"); put("\u1E6C", "T"); put("\u1E6D", "t"); put("\u1E74", "U"); put("\u1E75", "u"); put("\u1EA2", "A"); // hook put("\u1EA3", "a"); put("\u1EBA", "E"); put("\u1EBB", "e"); put("\u1EC8", "I"); put("\u1EC9", "i"); put("\u1ECE", "O"); put("\u1ECF", "o"); put("\u1EE6", "U"); put("\u1EE7", "u"); put("\u1EF6", "Y"); put("\u1EF7", "y"); put("\u00CF", "I"); put("\u008C", "AE"); // doesn't work? put("\u016E", "U"); put("\u016F", "u"); put("\u0178", "Y"); put("\u00FE", ""); // thorn character // UNICODE_CHARS.put("\u0100", ""); } }
7,232
26.819231
71
java
null
jabref-main/src/main/java/org/jabref/model/study/FetchResult.java
package org.jabref.model.study; import org.jabref.model.database.BibDatabase; /** * Represents the result of fetching the results for a query for a specific library */ public class FetchResult { private final String fetcherName; private final BibDatabase fetchResult; public FetchResult(String fetcherName, BibDatabase fetcherResult) { this.fetcherName = fetcherName; this.fetchResult = fetcherResult; } public String getFetcherName() { return fetcherName; } public BibDatabase getFetchResult() { return fetchResult; } }
592
22.72
83
java
null
jabref-main/src/main/java/org/jabref/model/study/QueryResult.java
package org.jabref.model.study; import java.util.List; /** * Represents the result of fetching the results from all active fetchers for a specific query. */ public class QueryResult { private final String query; private final List<FetchResult> resultsPerLibrary; public QueryResult(String query, List<FetchResult> resultsPerLibrary) { this.query = query; this.resultsPerLibrary = resultsPerLibrary; } public String getQuery() { return query; } public List<FetchResult> getResultsPerFetcher() { return resultsPerLibrary; } }
595
22.84
95
java
null
jabref-main/src/main/java/org/jabref/model/study/Study.java
package org.jabref.model.study; import java.util.List; import java.util.Objects; import org.jabref.logic.crawler.StudyYamlParser; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; /** * This class represents a scientific study. * * This class defines all aspects of a scientific study relevant to the application. It is a proxy for the file based study definition. * * The file is parsed using by {@link StudyYamlParser} */ @JsonPropertyOrder({"authors", "title", "research-questions", "queries", "databases"}) // The user might add arbitrary content to the YAML @JsonIgnoreProperties(ignoreUnknown = true) public class Study { private List<String> authors; private String title; @JsonProperty("research-questions") private List<String> researchQuestions; private List<StudyQuery> queries; private List<StudyDatabase> databases; public Study(List<String> authors, String title, List<String> researchQuestions, List<StudyQuery> queryEntries, List<StudyDatabase> databases) { this.authors = authors; this.title = title; this.researchQuestions = researchQuestions; this.queries = queryEntries; this.databases = databases; } /** * Used for Jackson deserialization */ private Study() { } public List<String> getAuthors() { return authors; } public void setAuthors(List<String> authors) { this.authors = authors; } public List<StudyQuery> getQueries() { return queries; } public void setQueries(List<StudyQuery> queries) { this.queries = queries; } public List<StudyDatabase> getDatabases() { return databases; } public void setDatabases(List<StudyDatabase> databases) { this.databases = databases; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public List<String> getResearchQuestions() { return researchQuestions; } public void setResearchQuestions(List<String> researchQuestions) { this.researchQuestions = researchQuestions; } @Override public String toString() { return "Study{" + "authors=" + authors + ", studyName='" + title + '\'' + ", researchQuestions=" + researchQuestions + ", queries=" + queries + ", libraries=" + databases + '}'; } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || getClass() != other.getClass()) { return false; } Study otherStudy = (Study) other; return Objects.equals(authors, otherStudy.authors) && Objects.equals(title, otherStudy.title) && Objects.equals(researchQuestions, otherStudy.researchQuestions) && Objects.equals(queries, otherStudy.queries) && Objects.equals(databases, otherStudy.databases); } @Override public int hashCode() { return Objects.hashCode(this); } }
3,315
25.95935
148
java
null
jabref-main/src/main/java/org/jabref/model/study/StudyDatabase.java
package org.jabref.model.study; /** * data model for the view {@link org.jabref.gui.slr.StudyCatalogItem} */ public class StudyDatabase { private String name; private boolean enabled; public StudyDatabase(String name, boolean enabled) { this.name = name; this.enabled = enabled; } /** * Used for Jackson deserialization */ public StudyDatabase() { // Per default fetcher is activated this.enabled = true; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } StudyDatabase that = (StudyDatabase) o; if (isEnabled() != that.isEnabled()) { return false; } return getName() != null ? getName().equals(that.getName()) : that.getName() == null; } @Override public int hashCode() { int result = getName() != null ? getName().hashCode() : 0; result = 31 * result + (isEnabled() ? 1 : 0); return result; } @Override public String toString() { return "LibraryEntry{" + "name='" + name + '\'' + ", enabled=" + enabled + '}'; } }
1,581
21.28169
93
java
null
jabref-main/src/main/java/org/jabref/model/study/StudyQuery.java
package org.jabref.model.study; public class StudyQuery { private String query; public StudyQuery(String query) { this.query = query; } /** * Used for Jackson deserialization */ public StudyQuery() { } public String getQuery() { return query; } public void setQuery(String query) { this.query = query; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } StudyQuery that = (StudyQuery) o; return getQuery() != null ? getQuery().equals(that.getQuery()) : that.getQuery() == null; } @Override public int hashCode() { return getQuery() != null ? getQuery().hashCode() : 0; } @Override public String toString() { return "QueryEntry{" + "query='" + query + '\'' + '}'; } }
996
18.94
97
java
null
jabref-main/src/main/java/org/jabref/model/texparser/Citation.java
package org.jabref.model.texparser; import java.nio.file.Path; import java.util.Objects; public class Citation { /** * The total number of characters that are shown around a cite (cite width included). */ private static final int CONTEXT_WIDTH = 300; private final Path path; private final int line; private final int colStart; private final int colEnd; private final String lineText; public Citation(Path path, int line, int colStart, int colEnd, String lineText) { if (line <= 0) { throw new IllegalArgumentException("Line has to be greater than 0."); } if (colStart < 0 || colEnd > lineText.length()) { throw new IllegalArgumentException("Citation has to be between 0 and line length."); } this.path = Objects.requireNonNull(path); this.line = line; this.colStart = colStart; this.colEnd = colEnd; this.lineText = lineText; } public Path getPath() { return path; } public int getLine() { return line; } public int getColStart() { return colStart; } public int getColEnd() { return colEnd; } public String getLineText() { return lineText; } /** * Get a fixed-width string that contains a cite and the text that surrounds it along the same line. */ public String getContext() { int center = (colStart + colEnd) / 2; int lineLength = lineText.length(); int start = Math.max(0, (center + CONTEXT_WIDTH / 2 < lineLength) ? center - CONTEXT_WIDTH / 2 : lineLength - CONTEXT_WIDTH); int end = Math.min(lineLength, start + CONTEXT_WIDTH); // Add three dots when the string does not contain all the line. return String.format("%s%s%s", (start > 0) ? "..." : "", lineText.substring(start, end).trim(), (end < lineLength) ? "..." : ""); } @Override public String toString() { return String.format("Citation{path=%s, line=%s, colStart=%s, colEnd=%s, lineText='%s'}", this.path, this.line, this.colStart, this.colEnd, this.lineText); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } Citation that = (Citation) obj; return Objects.equals(path, that.path) && Objects.equals(line, that.line) && Objects.equals(colStart, that.colStart) && Objects.equals(colEnd, that.colEnd) && Objects.equals(lineText, that.lineText); } @Override public int hashCode() { return Objects.hash(path, line, colStart, colEnd, lineText); } }
2,967
26.481481
104
java
null
jabref-main/src/main/java/org/jabref/model/texparser/LatexBibEntriesResolverResult.java
package org.jabref.model.texparser; import java.nio.file.Path; import java.util.HashSet; import java.util.Objects; import java.util.Set; import org.jabref.model.entry.BibEntry; import com.google.common.collect.Multimap; public class LatexBibEntriesResolverResult { private final LatexParserResult latexParserResult; private final Set<BibEntry> newEntries; public LatexBibEntriesResolverResult(LatexParserResult latexParserResult) { this.latexParserResult = latexParserResult; this.newEntries = new HashSet<>(); } public LatexParserResult getLatexParserResult() { return latexParserResult; } public Set<BibEntry> getNewEntries() { return newEntries; } public void addEntry(BibEntry entry) { newEntries.add(entry); } /** * @return the BIB files multimap from the LatexParserResult object. */ public Multimap<Path, Path> getBibFiles() { return latexParserResult.getBibFiles(); } /** * @return the citations multimap from the LatexParserResult object. */ public Multimap<String, Citation> getCitations() { return latexParserResult.getCitations(); } @Override public String toString() { return String.format("TexBibEntriesResolverResult{texParserResult=%s, newEntries=%s}", this.latexParserResult, this.newEntries); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } LatexBibEntriesResolverResult that = (LatexBibEntriesResolverResult) obj; return Objects.equals(latexParserResult, that.latexParserResult) && Objects.equals(newEntries, that.newEntries); } @Override public int hashCode() { return Objects.hash(latexParserResult, newEntries); } }
1,968
24.907895
94
java
null
jabref-main/src/main/java/org/jabref/model/texparser/LatexParserResult.java
package org.jabref.model.texparser; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Set; import org.jabref.model.entry.BibEntry; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; public class LatexParserResult { private final List<Path> fileList; private final List<Path> nestedFiles; private final Multimap<Path, Path> bibFiles; // BibTeXKey --> set of citations private final Multimap<String, Citation> citations; public LatexParserResult() { this.fileList = new ArrayList<>(); this.nestedFiles = new ArrayList<>(); this.bibFiles = HashMultimap.create(); this.citations = HashMultimap.create(); } public List<Path> getFileList() { return fileList; } public List<Path> getNestedFiles() { return nestedFiles; } public Multimap<Path, Path> getBibFiles() { return bibFiles; } public Multimap<String, Citation> getCitations() { return citations; } /** * Return a set of strings with the keys of the citations multimap. */ public Set<String> getCitationsKeySet() { return citations.keySet(); } /** * Return a collection of citations using a string as key reference. */ public Collection<Citation> getCitationsByKey(String key) { return citations.get(key); } /** * Return a collection of citations using a BibEntry as reference. */ public Collection<Citation> getCitationsByKey(BibEntry entry) { return entry.getCitationKey().map(this::getCitationsByKey).orElse(Collections.emptyList()); } /** * Add a list of files to fileList or nestedFiles, depending on whether this is the first list. */ public void addFiles(List<Path> texFiles) { if (fileList.isEmpty()) { fileList.addAll(texFiles); } else { nestedFiles.addAll(texFiles); } } /** * Add a bibliography file to the BIB files set. */ public void addBibFile(Path file, Path bibFile) { bibFiles.put(file, bibFile); } /** * Add a citation to the citations multimap. */ public void addKey(String key, Path file, int lineNumber, int start, int end, String line) { Citation citation = new Citation(file, lineNumber, start, end, line); citations.put(key, citation); } @Override public String toString() { return String.format("TexParserResult{fileList=%s, nestedFiles=%s, bibFiles=%s, citations=%s}", this.fileList, this.nestedFiles, this.bibFiles, this.citations); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } LatexParserResult that = (LatexParserResult) obj; return Objects.equals(fileList, that.fileList) && Objects.equals(nestedFiles, that.nestedFiles) && Objects.equals(bibFiles, that.bibFiles) && Objects.equals(citations, that.citations); } @Override public int hashCode() { return Objects.hash(fileList, nestedFiles, bibFiles, citations); } }
3,479
26.401575
103
java
null
jabref-main/src/main/java/org/jabref/model/util/DummyFileUpdateMonitor.java
package org.jabref.model.util; import java.nio.file.Path; /** * This {@link FileUpdateMonitor} does nothing. * Normally, you want to use {@link org.jabref.gui.util.DefaultFileUpdateMonitor} except if you don't care about updates. */ public class DummyFileUpdateMonitor implements FileUpdateMonitor { @Override public void addListenerForFile(Path file, FileUpdateListener listener) { // empty } @Override public void removeListener(Path path, FileUpdateListener listener) { // empty } @Override public boolean isActive() { return false; } @Override public void shutdown() { // empty } }
675
20.806452
121
java
null
jabref-main/src/main/java/org/jabref/model/util/FileUpdateListener.java
package org.jabref.model.util; public interface FileUpdateListener { /** * The file has been updated. A new call will not result until the file has been modified again. */ void fileUpdated(); }
214
20.5
100
java
null
jabref-main/src/main/java/org/jabref/model/util/FileUpdateMonitor.java
package org.jabref.model.util; import java.io.IOException; import java.nio.file.Path; public interface FileUpdateMonitor { /** * Add a new file to monitor. * * @param file The file to monitor. * @throws IOException if the file does not exist. */ void addListenerForFile(Path file, FileUpdateListener listener) throws IOException; /** * Removes a listener from the monitor. * * @param path The path to remove. */ void removeListener(Path path, FileUpdateListener listener); /** * Indicates whether the native system's file monitor has successfully started. * * @return true is process is running; false otherwise. */ boolean isActive(); /** * stops watching for changes */ void shutdown(); }
804
22.676471
87
java
null
jabref-main/src/main/java/org/jabref/model/util/ListUtil.java
package org.jabref.model.util; import java.util.function.Predicate; /** * Provides a few helper methods for lists. */ public class ListUtil { /** * Equivalent to list.stream().anyMatch but with slightly better performance (especially for small lists). */ public static <T> boolean anyMatch(Iterable<T> list, Predicate<T> predicate) { for (T element : list) { if (predicate.test(element)) { return true; } } return false; } /** * Equivalent to list.stream().allMatch but with slightly better performance (especially for small lists). */ public static <T> boolean allMatch(Iterable<T> list, Predicate<T> predicate) { for (T element : list) { if (!predicate.test(element)) { return false; } } return true; } }
885
25.058824
110
java
null
jabref-main/src/main/java/org/jabref/model/util/MultiKeyMap.java
package org.jabref.model.util; import java.util.EnumMap; import java.util.HashMap; import java.util.Map; import java.util.Optional; public class MultiKeyMap<K1 extends Enum<K1>, K2, V> { private final EnumMap<K1, Map<K2, V>> map; public MultiKeyMap(Class<K1> keyType) { map = new EnumMap<>(keyType); } public Optional<V> get(K1 key1, K2 key2) { Map<K2, V> metaValue = map.get(key1); if (metaValue == null) { return Optional.empty(); } else { return Optional.ofNullable(metaValue.get(key2)); } } public void put(K1 key1, K2 key2, V value) { Map<K2, V> metaValue = map.get(key1); if (metaValue == null) { Map<K2, V> newMetaValue = new HashMap<>(); newMetaValue.put(key2, value); map.put(key1, newMetaValue); } else { metaValue.put(key2, value); } } public void remove(K1 key1) { map.remove(key1); } }
993
24.487179
60
java
null
jabref-main/src/main/java/org/jabref/model/util/OptionalUtil.java
package org.jabref.model.util; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; public class OptionalUtil { public static <T> List<T> toList(Optional<T> value) { if (value.isPresent()) { return Collections.singletonList(value.get()); } else { return Collections.emptyList(); } } public static <T, U> boolean equals(Optional<T> left, Optional<U> right, BiPredicate<T, U> equality) { if (!left.isPresent()) { return !right.isPresent(); } else { if (right.isPresent()) { return equality.test(left.get(), right.get()); } else { return false; } } } /** * No longer needed in Java 9 where {@code Optional<T>.stream()} is added. */ public static <T> Stream<T> toStream(Optional<T> value) { if (value.isPresent()) { return Stream.of(value.get()); } else { return Stream.empty(); } } @SafeVarargs public static <T> List<T> toList(Optional<T>... values) { return Stream.of(values).flatMap(optional -> toList(optional).stream()).collect(Collectors.toList()); } public static <T, R> Stream<R> flatMapFromStream(Optional<T> value, Function<? super T, ? extends Stream<? extends R>> mapper) { return toStream(value).flatMap(mapper); } public static <T, R> Stream<R> flatMap(Optional<T> value, Function<? super T, ? extends Collection<? extends R>> mapper) { return toStream(value).flatMap(element -> mapper.apply(element).stream()); } public static <T> Boolean isPresentAnd(Optional<T> value, Predicate<T> check) { return value.isPresent() && check.test(value.get()); } public static <T> Boolean isPresentAndTrue(Optional<Boolean> value) { return value.isPresent() && value.get(); } public static <T, S, R> Optional<R> combine(Optional<T> valueOne, Optional<S> valueTwo, BiFunction<T, S, R> combine) { if (valueOne.isPresent() && valueTwo.isPresent()) { return Optional.ofNullable(combine.apply(valueOne.get(), valueTwo.get())); } else { return Optional.empty(); } } public static <T> Optional<T> orElse(Optional<? extends T> valueOne, Optional<? extends T> valueTwo) { if (valueOne.isPresent()) { return valueOne.map(f -> f); } else { return valueTwo.map(f -> f); } } public static <T extends S, S> S orElse(Optional<T> optional, S otherwise) { if (optional.isPresent()) { return optional.get(); } else { return otherwise; } } }
2,997
31.586957
132
java
null
jabref-main/src/main/java/org/jabref/model/util/ResultingStringState.java
package org.jabref.model.util; public class ResultingStringState { public final int caretPosition; public final String text; public ResultingStringState(int caretPosition, String text) { this.caretPosition = caretPosition; this.text = text; } }
279
22.333333
65
java
null
jabref-main/src/main/java/org/jabref/model/util/TreeCollector.java
package org.jabref.model.util; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.BiPredicate; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collector; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import org.jabref.model.TreeNode; /** * Merges a list of nodes into a tree. * Nodes with a common parent are added as direct children. * For example, the list { A > A1, A > A2, B } is transformed into the forest { A > A1, A2, B}. */ public class TreeCollector<T> implements Collector<T, ObservableList<T>, ObservableList<T>> { private Function<T, List<T>> getChildren; private BiConsumer<T, T> addChild; private BiPredicate<T, T> equivalence; /** * @param getChildren a function that returns a list of children of the specified node * @param addChild a function that adds the second argument as a child to the first-specified node * @param equivalence a function that tells us whether two nodes are equivalent */ private TreeCollector(Function<T, List<T>> getChildren, BiConsumer<T, T> addChild, BiPredicate<T, T> equivalence) { this.getChildren = getChildren; this.addChild = addChild; this.equivalence = equivalence; } public static <T extends TreeNode<T>> TreeCollector<T> mergeIntoTree(BiPredicate<T, T> equivalence) { return new TreeCollector<>( TreeNode::getChildren, (parent, child) -> child.moveTo(parent), equivalence); } @Override public Supplier<ObservableList<T>> supplier() { return FXCollections::observableArrayList; } @Override public BiConsumer<ObservableList<T>, T> accumulator() { return (alreadyProcessed, newItem) -> { // Check if the node is already in the tree Optional<T> sameItemInTree = alreadyProcessed .stream() .filter(item -> equivalence.test(item, newItem)) .findFirst(); if (sameItemInTree.isPresent()) { for (T child : new ArrayList<>(getChildren.apply(newItem))) { merge(sameItemInTree.get(), child); } } else { alreadyProcessed.add(newItem); } }; } private void merge(T target, T node) { Optional<T> sameItemInTree = getChildren .apply(target).stream() .filter(item -> equivalence.test(item, node)) .findFirst(); if (sameItemInTree.isPresent()) { // We need to copy the list because the #addChild method might remove the child from its own parent for (T child : new ArrayList<>(getChildren.apply(node))) { merge(sameItemInTree.get(), child); } } else { addChild.accept(target, node); } } @Override public BinaryOperator<ObservableList<T>> combiner() { return (list1, list2) -> { for (T item : list2) { accumulator().accept(list1, item); } return list1; }; } @Override public Function<ObservableList<T>, ObservableList<T>> finisher() { return i -> i; } @Override public Set<Characteristics> characteristics() { return EnumSet.of(Characteristics.UNORDERED, Characteristics.IDENTITY_FINISH); } }
3,654
33.158879
119
java
null
jabref-main/src/main/java/org/jabref/preferences/BibEntryPreferences.java
package org.jabref.preferences; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; public class BibEntryPreferences { private final ObjectProperty<Character> keywordSeparator; public BibEntryPreferences(Character keywordSeparator) { this.keywordSeparator = new SimpleObjectProperty<>(keywordSeparator); } public Character getKeywordSeparator() { return keywordSeparator.get(); } public ObjectProperty<Character> keywordSeparatorProperty() { return keywordSeparator; } public void setKeywordSeparator(Character keywordSeparator) { this.keywordSeparator.set(keywordSeparator); } }
698
26.96
77
java
null
jabref-main/src/main/java/org/jabref/preferences/CleanupPreferences.java
package org.jabref.preferences; import java.util.ArrayList; import java.util.EnumSet; import java.util.Set; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableSet; import org.jabref.logic.cleanup.FieldFormatterCleanups; public class CleanupPreferences { private final ObservableSet<CleanupStep> activeJobs; private final ObjectProperty<FieldFormatterCleanups> fieldFormatterCleanups; public CleanupPreferences(EnumSet<CleanupStep> activeJobs) { this(activeJobs, new FieldFormatterCleanups(false, new ArrayList<>())); } public CleanupPreferences(CleanupStep activeJob) { this(EnumSet.of(activeJob)); } public CleanupPreferences(FieldFormatterCleanups formatterCleanups) { this(EnumSet.noneOf(CleanupStep.class), formatterCleanups); } public CleanupPreferences(EnumSet<CleanupStep> activeJobs, FieldFormatterCleanups formatterCleanups) { this.activeJobs = FXCollections.observableSet(activeJobs); this.fieldFormatterCleanups = new SimpleObjectProperty<>(formatterCleanups); } public EnumSet<CleanupStep> getActiveJobs() { if (activeJobs.isEmpty()) { return EnumSet.noneOf(CleanupStep.class); } return EnumSet.copyOf(activeJobs); } public void setActive(CleanupStep job, boolean value) { if (activeJobs.contains(job) && !value) { activeJobs.remove(job); } else if (!activeJobs.contains(job) && value) { activeJobs.add(job); } } protected ObservableSet<CleanupStep> getObservableActiveJobs() { return activeJobs; } public void setActiveJobs(Set<CleanupStep> jobs) { activeJobs.clear(); activeJobs.addAll(jobs); } public Boolean isActive(CleanupStep step) { return activeJobs.contains(step); } public FieldFormatterCleanups getFieldFormatterCleanups() { return fieldFormatterCleanups.get(); } protected ObjectProperty<FieldFormatterCleanups> fieldFormatterCleanupsProperty() { return fieldFormatterCleanups; } public void setFieldFormatterCleanups(FieldFormatterCleanups fieldFormatters) { fieldFormatterCleanups.setValue(fieldFormatters); } public enum CleanupStep { /** * Removes the http://... for each DOI. Moves DOIs from URL and NOTE filed to DOI field. */ CLEAN_UP_DOI, CLEANUP_EPRINT, CLEAN_UP_URL, MAKE_PATHS_RELATIVE, RENAME_PDF, RENAME_PDF_ONLY_RELATIVE_PATHS, /** * Collects file links from the pdf or ps field, and adds them to the list contained in the file field. */ CLEAN_UP_UPGRADE_EXTERNAL_LINKS, /** * Converts to biblatex format */ CONVERT_TO_BIBLATEX, /** * Converts to bibtex format */ CONVERT_TO_BIBTEX, CONVERT_TIMESTAMP_TO_CREATIONDATE, CONVERT_TIMESTAMP_TO_MODIFICATIONDATE, DO_NOT_CONVERT_TIMESTAMP, MOVE_PDF, FIX_FILE_LINKS, CLEAN_UP_ISSN } }
3,223
29.130841
111
java
null
jabref-main/src/main/java/org/jabref/preferences/ExportPreferences.java
package org.jabref.preferences; import java.nio.file.Path; import java.util.List; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import org.jabref.logic.exporter.TemplateExporter; import org.jabref.model.metadata.SaveOrder; public class ExportPreferences { private final StringProperty lastExportExtension; private final ObjectProperty<Path> exportWorkingDirectory; private final ObjectProperty<SaveOrder> exportSaveOrder; private final ObservableList<TemplateExporter> customExporters; public ExportPreferences(String lastExportExtension, Path exportWorkingDirectory, SaveOrder exportSaveOrder, List<TemplateExporter> customExporters) { this.lastExportExtension = new SimpleStringProperty(lastExportExtension); this.exportWorkingDirectory = new SimpleObjectProperty<>(exportWorkingDirectory); this.exportSaveOrder = new SimpleObjectProperty<>(exportSaveOrder); this.customExporters = FXCollections.observableList(customExporters); } public String getLastExportExtension() { return lastExportExtension.get(); } public StringProperty lastExportExtensionProperty() { return lastExportExtension; } public void setLastExportExtension(String lastExportExtension) { this.lastExportExtension.set(lastExportExtension); } public Path getExportWorkingDirectory() { return exportWorkingDirectory.get(); } public ObjectProperty<Path> exportWorkingDirectoryProperty() { return exportWorkingDirectory; } public void setExportWorkingDirectory(Path exportWorkingDirectory) { this.exportWorkingDirectory.set(exportWorkingDirectory); } public SaveOrder getExportSaveOrder() { return exportSaveOrder.get(); } public ObjectProperty<SaveOrder> exportSaveOrderProperty() { return exportSaveOrder; } public void setExportSaveOrder(SaveOrder exportSaveOrder) { this.exportSaveOrder.set(exportSaveOrder); } public ObservableList<TemplateExporter> getCustomExporters() { return customExporters; } public void setCustomExporters(List<TemplateExporter> exporters) { customExporters.clear(); customExporters.addAll(exporters); } }
2,575
31.607595
89
java
null
jabref-main/src/main/java/org/jabref/preferences/ExternalApplicationsPreferences.java
package org.jabref.preferences; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; public class ExternalApplicationsPreferences { private final StringProperty eMailSubject; private final BooleanProperty shouldAutoOpenEmailAttachmentsFolder; private final StringProperty citeCommand; private final BooleanProperty useCustomTerminal; private final StringProperty customTerminalCommand; private final BooleanProperty useCustomFileBrowser; private final StringProperty customFileBrowserCommand; private final StringProperty kindleEmail; public ExternalApplicationsPreferences(String eMailSubject, boolean shouldAutoOpenEmailAttachmentsFolder, String citeCommand, boolean useCustomTerminal, String customTerminalCommand, boolean useCustomFileBrowser, String customFileBrowserCommand, String kindleEmail) { this.eMailSubject = new SimpleStringProperty(eMailSubject); this.shouldAutoOpenEmailAttachmentsFolder = new SimpleBooleanProperty(shouldAutoOpenEmailAttachmentsFolder); this.citeCommand = new SimpleStringProperty(citeCommand); this.useCustomTerminal = new SimpleBooleanProperty(useCustomTerminal); this.customTerminalCommand = new SimpleStringProperty(customTerminalCommand); this.useCustomFileBrowser = new SimpleBooleanProperty(useCustomFileBrowser); this.customFileBrowserCommand = new SimpleStringProperty(customFileBrowserCommand); this.kindleEmail = new SimpleStringProperty(kindleEmail); } public String getEmailSubject() { return eMailSubject.get(); } public StringProperty eMailSubjectProperty() { return eMailSubject; } public void setEMailSubject(String eMailSubject) { this.eMailSubject.set(eMailSubject); } public boolean shouldAutoOpenEmailAttachmentsFolder() { return shouldAutoOpenEmailAttachmentsFolder.get(); } public BooleanProperty autoOpenEmailAttachmentsFolderProperty() { return shouldAutoOpenEmailAttachmentsFolder; } public void setAutoOpenEmailAttachmentsFolder(boolean shouldAutoOpenEmailAttachmentsFolder) { this.shouldAutoOpenEmailAttachmentsFolder.set(shouldAutoOpenEmailAttachmentsFolder); } public String getCiteCommand() { return citeCommand.get(); } public StringProperty citeCommandProperty() { return citeCommand; } public void setCiteCommand(String citeCommand) { this.citeCommand.set(citeCommand); } public boolean useCustomTerminal() { return useCustomTerminal.get(); } public BooleanProperty useCustomTerminalProperty() { return useCustomTerminal; } public void setUseCustomTerminal(boolean useCustomTerminal) { this.useCustomTerminal.set(useCustomTerminal); } public String getCustomTerminalCommand() { return customTerminalCommand.get(); } public StringProperty customTerminalCommandProperty() { return customTerminalCommand; } public void setCustomTerminalCommand(String customTerminalCommand) { this.customTerminalCommand.set(customTerminalCommand); } public boolean useCustomFileBrowser() { return useCustomFileBrowser.get(); } public BooleanProperty useCustomFileBrowserProperty() { return useCustomFileBrowser; } public void setUseCustomFileBrowser(boolean useCustomFileBrowser) { this.useCustomFileBrowser.set(useCustomFileBrowser); } public String getCustomFileBrowserCommand() { return customFileBrowserCommand.get(); } public StringProperty customFileBrowserCommandProperty() { return customFileBrowserCommand; } public void setCustomFileBrowserCommand(String customFileBrowserCommand) { this.customFileBrowserCommand.set(customFileBrowserCommand); } public String getKindleEmail() { return kindleEmail.get(); } public StringProperty kindleEmailProperty() { return kindleEmail; } public void setKindleEmail(String kindleEmail) { this.kindleEmail.set(kindleEmail); } }
4,581
33.19403
116
java
null
jabref-main/src/main/java/org/jabref/preferences/FilePreferences.java
package org.jabref.preferences; import java.nio.file.Path; import java.util.Comparator; import java.util.Optional; import java.util.Set; import java.util.TreeSet; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableSet; import org.jabref.gui.externalfiletype.ExternalFileType; import org.jabref.model.strings.StringUtil; /** * Preferences for the linked files */ public class FilePreferences { public static final String[] DEFAULT_FILENAME_PATTERNS = new String[] {"[bibtexkey]", "[bibtexkey] - [title]"}; private final StringProperty userAndHost = new SimpleStringProperty(); private final SimpleStringProperty mainFileDirectory = new SimpleStringProperty(); private final BooleanProperty storeFilesRelativeToBibFile = new SimpleBooleanProperty(); private final StringProperty fileNamePattern = new SimpleStringProperty(); private final StringProperty fileDirectoryPattern = new SimpleStringProperty(); private final BooleanProperty downloadLinkedFiles = new SimpleBooleanProperty(); private final BooleanProperty fulltextIndexLinkedFiles = new SimpleBooleanProperty(); private final ObjectProperty<Path> workingDirectory = new SimpleObjectProperty<>(); private final ObservableSet<ExternalFileType> externalFileTypes = FXCollections.observableSet(new TreeSet<>(Comparator.comparing(ExternalFileType::getName))); private final BooleanProperty createBackup = new SimpleBooleanProperty(); private final ObjectProperty<Path> backupDirectory = new SimpleObjectProperty<>(); public FilePreferences(String userAndHost, String mainFileDirectory, boolean storeFilesRelativeToBibFile, String fileNamePattern, String fileDirectoryPattern, boolean downloadLinkedFiles, boolean fulltextIndexLinkedFiles, Path workingDirectory, Set<ExternalFileType> externalFileTypes, boolean createBackup, Path backupDirectory) { this.userAndHost.setValue(userAndHost); this.mainFileDirectory.setValue(mainFileDirectory); this.storeFilesRelativeToBibFile.setValue(storeFilesRelativeToBibFile); this.fileNamePattern.setValue(fileNamePattern); this.fileDirectoryPattern.setValue(fileDirectoryPattern); this.downloadLinkedFiles.setValue(downloadLinkedFiles); this.fulltextIndexLinkedFiles.setValue(fulltextIndexLinkedFiles); this.workingDirectory.setValue(workingDirectory); this.externalFileTypes.addAll(externalFileTypes); this.createBackup.setValue(createBackup); this.backupDirectory.setValue(backupDirectory); } public String getUserAndHost() { return userAndHost.getValue(); } public Optional<Path> getMainFileDirectory() { if (StringUtil.isBlank(mainFileDirectory.getValue())) { return Optional.empty(); } else { return Optional.of(Path.of(mainFileDirectory.getValue())); } } public StringProperty mainFileDirectoryProperty() { return mainFileDirectory; } public void setMainFileDirectory(String mainFileDirectory) { this.mainFileDirectory.set(mainFileDirectory); } public boolean shouldStoreFilesRelativeToBibFile() { return storeFilesRelativeToBibFile.get(); } public BooleanProperty storeFilesRelativeToBibFileProperty() { return storeFilesRelativeToBibFile; } public void setStoreFilesRelativeToBibFile(boolean shouldStoreFilesRelativeToBibFile) { this.storeFilesRelativeToBibFile.set(shouldStoreFilesRelativeToBibFile); } public String getFileNamePattern() { return fileNamePattern.get(); } public StringProperty fileNamePatternProperty() { return fileNamePattern; } public void setFileNamePattern(String fileNamePattern) { this.fileNamePattern.set(fileNamePattern); } public String getFileDirectoryPattern() { return fileDirectoryPattern.get(); } public StringProperty fileDirectoryPatternProperty() { return fileDirectoryPattern; } public void setFileDirectoryPattern(String fileDirectoryPattern) { this.fileDirectoryPattern.set(fileDirectoryPattern); } public boolean shouldDownloadLinkedFiles() { return downloadLinkedFiles.get(); } public BooleanProperty downloadLinkedFilesProperty() { return downloadLinkedFiles; } public void setDownloadLinkedFiles(boolean shouldDownloadLinkedFiles) { this.downloadLinkedFiles.set(shouldDownloadLinkedFiles); } public boolean shouldFulltextIndexLinkedFiles() { return fulltextIndexLinkedFiles.get(); } public BooleanProperty fulltextIndexLinkedFilesProperty() { return fulltextIndexLinkedFiles; } public void setFulltextIndexLinkedFiles(boolean shouldFulltextIndexLinkedFiles) { this.fulltextIndexLinkedFiles.set(shouldFulltextIndexLinkedFiles); } public Path getWorkingDirectory() { return workingDirectory.get(); } public ObjectProperty<Path> workingDirectoryProperty() { return workingDirectory; } public void setWorkingDirectory(Path workingDirectory) { this.workingDirectory.set(workingDirectory); } public ObservableSet<ExternalFileType> getExternalFileTypes() { return this.externalFileTypes; } public void setCreateBackup(boolean createBackup) { this.createBackup.set(createBackup); } public boolean shouldCreateBackup() { return this.createBackup.getValue(); } public BooleanProperty createBackupProperty() { return this.createBackup; } public ObjectProperty<Path> backupDirectoryProperty() { return this.backupDirectory; } public void setBackupDirectory(Path backupPath) { this.backupDirectory.set(backupPath); } public Path getBackupDirectory() { return this.backupDirectory.getValue(); } }
6,498
34.320652
162
java
null
jabref-main/src/main/java/org/jabref/preferences/GuiPreferences.java
package org.jabref.preferences; import java.nio.file.Path; import java.util.List; import javafx.beans.property.BooleanProperty; import javafx.beans.property.DoubleProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import org.jabref.gui.mergeentries.DiffMode; import org.jabref.logic.util.io.FileHistory; public class GuiPreferences { private final DoubleProperty positionX; private final DoubleProperty positionY; private final DoubleProperty sizeX; private final DoubleProperty sizeY; private final BooleanProperty windowMaximised; // the last libraries that were open when jabref closes and should be reopened on startup private final ObservableList<String> lastFilesOpened; private final ObjectProperty<Path> lastFocusedFile; // observable list last files opened in the file menu private final FileHistory fileHistory; private final StringProperty lastSelectedIdBasedFetcher; private final ObjectProperty<DiffMode> mergeDiffMode; private final BooleanProperty mergeShouldShowDiff; private final BooleanProperty mergeShouldShowUnifiedDiff; private final BooleanProperty mergeHighlightWords; private final BooleanProperty mergeShowChangedFieldsOnly; private final DoubleProperty sidePaneWidth; public GuiPreferences(double positionX, double positionY, double sizeX, double sizeY, boolean windowMaximised, List<String> lastFilesOpened, Path lastFocusedFile, FileHistory fileHistory, String lastSelectedIdBasedFetcher, DiffMode mergeDiffMode, boolean mergeShouldShowDiff, boolean mergeShouldShowUnifiedDiff, boolean mergeHighlightWords, double sidePaneWidth, boolean mergeShowChangedFieldsOnly) { this.positionX = new SimpleDoubleProperty(positionX); this.positionY = new SimpleDoubleProperty(positionY); this.sizeX = new SimpleDoubleProperty(sizeX); this.sizeY = new SimpleDoubleProperty(sizeY); this.windowMaximised = new SimpleBooleanProperty(windowMaximised); this.lastFilesOpened = FXCollections.observableArrayList(lastFilesOpened); this.lastFocusedFile = new SimpleObjectProperty<>(lastFocusedFile); this.lastSelectedIdBasedFetcher = new SimpleStringProperty(lastSelectedIdBasedFetcher); this.mergeDiffMode = new SimpleObjectProperty<>(mergeDiffMode); this.mergeShouldShowDiff = new SimpleBooleanProperty(mergeShouldShowDiff); this.mergeShouldShowUnifiedDiff = new SimpleBooleanProperty(mergeShouldShowUnifiedDiff); this.mergeHighlightWords = new SimpleBooleanProperty(mergeHighlightWords); this.sidePaneWidth = new SimpleDoubleProperty(sidePaneWidth); this.fileHistory = fileHistory; this.mergeShowChangedFieldsOnly = new SimpleBooleanProperty(mergeShowChangedFieldsOnly); } public double getPositionX() { return positionX.get(); } public DoubleProperty positionXProperty() { return positionX; } public void setPositionX(double positionX) { this.positionX.set(positionX); } public double getPositionY() { return positionY.get(); } public DoubleProperty positionYProperty() { return positionY; } public void setPositionY(double positionY) { this.positionY.set(positionY); } public double getSizeX() { return sizeX.get(); } public DoubleProperty sizeXProperty() { return sizeX; } public void setSizeX(double sizeX) { this.sizeX.set(sizeX); } public double getSizeY() { return sizeY.get(); } public DoubleProperty sizeYProperty() { return sizeY; } public void setSizeY(double sizeY) { this.sizeY.set(sizeY); } public boolean isWindowMaximised() { return windowMaximised.get(); } public BooleanProperty windowMaximisedProperty() { return windowMaximised; } public void setWindowMaximised(boolean windowMaximised) { this.windowMaximised.set(windowMaximised); } public ObservableList<String> getLastFilesOpened() { return lastFilesOpened; } public void setLastFilesOpened(List<String> files) { lastFilesOpened.setAll(files); } public Path getLastFocusedFile() { return lastFocusedFile.get(); } public ObjectProperty<Path> lastFocusedFileProperty() { return lastFocusedFile; } public void setLastFocusedFile(Path lastFocusedFile) { this.lastFocusedFile.set(lastFocusedFile); } public FileHistory getFileHistory() { return fileHistory; } public String getLastSelectedIdBasedFetcher() { return lastSelectedIdBasedFetcher.get(); } public StringProperty lastSelectedIdBasedFetcherProperty() { return lastSelectedIdBasedFetcher; } public void setLastSelectedIdBasedFetcher(String lastSelectedIdBasedFetcher) { this.lastSelectedIdBasedFetcher.set(lastSelectedIdBasedFetcher); } public DiffMode getMergeDiffMode() { return mergeDiffMode.get(); } public ObjectProperty<DiffMode> mergeDiffModeProperty() { return mergeDiffMode; } public void setMergeDiffMode(DiffMode mergeDiffMode) { this.mergeDiffMode.set(mergeDiffMode); } public boolean getMergeShouldShowDiff() { return mergeShouldShowDiff.get(); } public BooleanProperty mergeShouldShowDiffProperty() { return mergeShouldShowDiff; } public void setMergeShouldShowDiff(boolean mergeShouldShowDiff) { this.mergeShouldShowDiff.set(mergeShouldShowDiff); } public boolean getMergeShouldShowUnifiedDiff() { return mergeShouldShowUnifiedDiff.get(); } public BooleanProperty mergeShouldShowUnifiedDiffProperty() { return mergeShouldShowUnifiedDiff; } public void setMergeShouldShowUnifiedDiff(boolean mergeShouldShowUnifiedDiff) { this.mergeShouldShowUnifiedDiff.set(mergeShouldShowUnifiedDiff); } public boolean getMergeHighlightWords() { return mergeHighlightWords.get(); } public BooleanProperty mergeHighlightWordsProperty() { return mergeHighlightWords; } public void setMergeHighlightWords(boolean mergeHighlightsWords) { this.mergeHighlightWords.set(mergeHighlightsWords); } public double getSidePaneWidth() { return sidePaneWidth.get(); } public DoubleProperty sidePaneWidthProperty() { return sidePaneWidth; } public void setSidePaneWidth(double sidePaneWidth) { this.sidePaneWidth.set(sidePaneWidth); } public BooleanProperty mergeShowChangedFieldOnlyProperty() { return mergeShowChangedFieldsOnly; } public boolean isMergeShowChangedFieldsOnly() { return mergeShowChangedFieldsOnly.getValue(); } public void setIsMergedShowChangedFielsOnly(boolean showChangedFieldsOnly) { mergeShowChangedFieldsOnly.setValue(showChangedFieldsOnly); } }
7,707
30.720165
96
java
null
jabref-main/src/main/java/org/jabref/preferences/InternalPreferences.java
package org.jabref.preferences; import java.nio.file.Path; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import org.jabref.logic.util.Version; public class InternalPreferences { private final ObjectProperty<Version> ignoredVersion; private final ObjectProperty<Path> lastPreferencesExportPath; private final StringProperty userAndHost; private final BooleanProperty memoryStickMode; public InternalPreferences(Version ignoredVersion, Path exportPath, String userAndHost, boolean memoryStickMode) { this.ignoredVersion = new SimpleObjectProperty<>(ignoredVersion); this.lastPreferencesExportPath = new SimpleObjectProperty<>(exportPath); this.userAndHost = new SimpleStringProperty(userAndHost); this.memoryStickMode = new SimpleBooleanProperty(memoryStickMode); } public Version getIgnoredVersion() { return ignoredVersion.getValue(); } public ObjectProperty<Version> ignoredVersionProperty() { return ignoredVersion; } public void setIgnoredVersion(Version ignoredVersion) { this.ignoredVersion.set(ignoredVersion); } public Path getLastPreferencesExportPath() { return lastPreferencesExportPath.get(); } public ObjectProperty<Path> lastPreferencesExportPathProperty() { return lastPreferencesExportPath; } public void setLastPreferencesExportPath(Path lastPreferencesExportPath) { this.lastPreferencesExportPath.set(lastPreferencesExportPath); } public String getUserAndHost() { return userAndHost.get(); } public boolean isMemoryStickMode() { return memoryStickMode.get(); } public BooleanProperty memoryStickModeProperty() { return memoryStickMode; } public void setMemoryStickMode(boolean memoryStickMode) { this.memoryStickMode.set(memoryStickMode); } }
2,229
30.408451
80
java
null
jabref-main/src/main/java/org/jabref/preferences/JabRefPreferences.java
package org.jabref.preferences; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.StringReader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.TreeSet; import java.util.UUID; import java.util.prefs.BackingStoreException; import java.util.prefs.InvalidPreferencesFormatException; import java.util.prefs.Preferences; import java.util.stream.Collectors; import java.util.stream.Stream; import javafx.beans.InvalidationListener; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.collections.SetChangeListener; import javafx.scene.control.TableColumn.SortType; import org.jabref.gui.Globals; import org.jabref.gui.autocompleter.AutoCompleteFirstNameMode; import org.jabref.gui.autocompleter.AutoCompletePreferences; import org.jabref.gui.entryeditor.EntryEditorPreferences; import org.jabref.gui.externalfiletype.ExternalFileType; import org.jabref.gui.externalfiletype.ExternalFileTypes; import org.jabref.gui.groups.GroupViewMode; import org.jabref.gui.groups.GroupsPreferences; import org.jabref.gui.keyboard.KeyBindingRepository; import org.jabref.gui.maintable.ColumnPreferences; import org.jabref.gui.maintable.MainTableColumnModel; import org.jabref.gui.maintable.MainTablePreferences; import org.jabref.gui.maintable.NameDisplayPreferences; import org.jabref.gui.maintable.NameDisplayPreferences.AbbreviationStyle; import org.jabref.gui.maintable.NameDisplayPreferences.DisplayStyle; import org.jabref.gui.mergeentries.DiffMode; import org.jabref.gui.push.PushToApplications; import org.jabref.gui.search.SearchDisplayMode; import org.jabref.gui.sidepane.SidePaneType; import org.jabref.gui.specialfields.SpecialFieldsPreferences; import org.jabref.gui.theme.Theme; import org.jabref.logic.JabRefException; import org.jabref.logic.bibtex.FieldPreferences; import org.jabref.logic.citationkeypattern.CitationKeyPatternPreferences; import org.jabref.logic.citationkeypattern.GlobalCitationKeyPattern; import org.jabref.logic.citationstyle.CitationStyle; import org.jabref.logic.citationstyle.CitationStylePreviewLayout; import org.jabref.logic.cleanup.FieldFormatterCleanups; import org.jabref.logic.exporter.MetaDataSerializer; import org.jabref.logic.exporter.SaveConfiguration; import org.jabref.logic.exporter.TemplateExporter; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.ImporterPreferences; import org.jabref.logic.importer.fetcher.DoiFetcher; import org.jabref.logic.importer.fetcher.GrobidPreferences; import org.jabref.logic.importer.fileformat.CustomImporter; import org.jabref.logic.importer.util.MetaDataParser; import org.jabref.logic.journals.JournalAbbreviationPreferences; import org.jabref.logic.l10n.Language; import org.jabref.logic.l10n.Localization; import org.jabref.logic.layout.LayoutFormatterPreferences; import org.jabref.logic.layout.TextBasedPreviewLayout; import org.jabref.logic.layout.format.NameFormatterPreferences; import org.jabref.logic.net.ProxyPreferences; import org.jabref.logic.net.ssl.SSLPreferences; import org.jabref.logic.net.ssl.TrustStoreManager; import org.jabref.logic.openoffice.OpenOfficePreferences; import org.jabref.logic.openoffice.style.StyleLoader; import org.jabref.logic.preferences.DOIPreferences; import org.jabref.logic.preferences.FetcherApiKey; import org.jabref.logic.preferences.OwnerPreferences; import org.jabref.logic.preferences.TimestampPreferences; import org.jabref.logic.preview.PreviewLayout; import org.jabref.logic.protectedterms.ProtectedTermsLoader; import org.jabref.logic.protectedterms.ProtectedTermsPreferences; import org.jabref.logic.remote.RemotePreferences; import org.jabref.logic.shared.prefs.SharedDatabasePreferences; import org.jabref.logic.shared.security.Password; import org.jabref.logic.util.OS; import org.jabref.logic.util.Version; import org.jabref.logic.util.io.AutoLinkPreferences; import org.jabref.logic.util.io.FileHistory; import org.jabref.logic.xmp.XmpPreferences; import org.jabref.model.database.BibDatabaseMode; import org.jabref.model.entry.BibEntryType; import org.jabref.model.entry.BibEntryTypesManager; import org.jabref.model.entry.field.Field; import org.jabref.model.entry.field.FieldFactory; import org.jabref.model.entry.field.InternalField; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.types.EntryType; import org.jabref.model.entry.types.EntryTypeFactory; import org.jabref.model.groups.GroupHierarchyType; import org.jabref.model.metadata.SaveOrder; import org.jabref.model.search.rules.SearchRules; import org.jabref.model.strings.StringUtil; import com.github.javakeyring.Keyring; import com.github.javakeyring.PasswordAccessException; import com.tobiasdiez.easybind.EasyBind; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The {@code JabRefPreferences} class provides the preferences and their defaults using the JDK {@code java.util.prefs} * class. * <p> * Internally it defines symbols used to pick a value from the {@code java.util.prefs} interface and keeps a hashmap * with all the default values. * <p> * There are still some similar preferences classes ({@link org.jabref.logic.openoffice.OpenOfficePreferences} and {@link org.jabref.logic.shared.prefs.SharedDatabasePreferences}) which also use * the {@code java.util.prefs} API. */ public class JabRefPreferences implements PreferencesService { // Push to application preferences public static final String PUSH_EMACS_PATH = "emacsPath"; public static final String PUSH_EMACS_ADDITIONAL_PARAMETERS = "emacsParameters"; public static final String PUSH_LYXPIPE = "lyxpipe"; public static final String PUSH_TEXSTUDIO_PATH = "TeXstudioPath"; public static final String PUSH_WINEDT_PATH = "winEdtPath"; public static final String PUSH_TEXMAKER_PATH = "texmakerPath"; public static final String PUSH_VIM_SERVER = "vimServer"; public static final String PUSH_VIM = "vim"; /* contents of the defaults HashMap that are defined in this class. * There are more default parameters in this map which belong to separate preference classes. */ public static final String EXTERNAL_FILE_TYPES = "externalFileTypes"; public static final String FX_THEME = "fxTheme"; public static final String LANGUAGE = "language"; public static final String NAMES_LAST_ONLY = "namesLastOnly"; public static final String ABBR_AUTHOR_NAMES = "abbrAuthorNames"; public static final String NAMES_NATBIB = "namesNatbib"; public static final String NAMES_FIRST_LAST = "namesFf"; public static final String BIBLATEX_DEFAULT_MODE = "biblatexMode"; public static final String NAMES_AS_IS = "namesAsIs"; public static final String ENTRY_EDITOR_HEIGHT = "entryEditorHeightFX"; public static final String AUTO_RESIZE_MODE = "autoResizeMode"; public static final String WINDOW_MAXIMISED = "windowMaximised"; public static final String REFORMAT_FILE_ON_SAVE_AND_EXPORT = "reformatFileOnSaveAndExport"; public static final String EXPORT_IN_ORIGINAL_ORDER = "exportInOriginalOrder"; public static final String EXPORT_IN_SPECIFIED_ORDER = "exportInSpecifiedOrder"; public static final String EXPORT_PRIMARY_SORT_FIELD = "exportPriSort"; public static final String EXPORT_PRIMARY_SORT_DESCENDING = "exportPriDescending"; public static final String EXPORT_SECONDARY_SORT_FIELD = "exportSecSort"; public static final String EXPORT_SECONDARY_SORT_DESCENDING = "exportSecDescending"; public static final String EXPORT_TERTIARY_SORT_FIELD = "exportTerSort"; public static final String EXPORT_TERTIARY_SORT_DESCENDING = "exportTerDescending"; public static final String NEWLINE = "newline"; // Variable names have changed to ensure backward compatibility with pre 5.0 releases of JabRef // Pre 5.1: columnNames, columnWidths, columnSortTypes, columnSortOrder public static final String COLUMN_NAMES = "mainTableColumnNames"; public static final String COLUMN_WIDTHS = "mainTableColumnWidths"; public static final String COLUMN_SORT_TYPES = "mainTableColumnSortTypes"; public static final String COLUMN_SORT_ORDER = "mainTableColumnSortOrder"; public static final String SEARCH_DIALOG_COLUMN_WIDTHS = "searchTableColumnWidths"; public static final String SEARCH_DIALOG_COLUMN_SORT_TYPES = "searchDialogColumnSortTypes"; public static final String SEARCH_DIALOG_COLUMN_SORT_ORDER = "searchDalogColumnSortOrder"; public static final String SIDE_PANE_COMPONENT_PREFERRED_POSITIONS = "sidePaneComponentPreferredPositions"; public static final String SIDE_PANE_COMPONENT_NAMES = "sidePaneComponentNames"; public static final String XMP_PRIVACY_FILTERS = "xmpPrivacyFilters"; public static final String USE_XMP_PRIVACY_FILTER = "useXmpPrivacyFilter"; public static final String DEFAULT_SHOW_SOURCE = "defaultShowSource"; // Window sizes public static final String SIZE_Y = "mainWindowSizeY"; public static final String SIZE_X = "mainWindowSizeX"; public static final String POS_Y = "mainWindowPosY"; public static final String POS_X = "mainWindowPosX"; public static final String LAST_EDITED = "lastEdited"; public static final String OPEN_LAST_EDITED = "openLastEdited"; public static final String LAST_FOCUSED = "lastFocused"; public static final String AUTO_OPEN_FORM = "autoOpenForm"; public static final String IMPORT_WORKING_DIRECTORY = "importWorkingDirectory"; public static final String LAST_USED_EXPORT = "lastUsedExport"; public static final String EXPORT_WORKING_DIRECTORY = "exportWorkingDirectory"; public static final String WORKING_DIRECTORY = "workingDirectory"; public static final String BACKUP_DIRECTORY = "backupDirectory"; public static final String CREATE_BACKUP = "createBackup"; public static final String KEYWORD_SEPARATOR = "groupKeywordSeparator"; public static final String AUTO_ASSIGN_GROUP = "autoAssignGroup"; public static final String DISPLAY_GROUP_COUNT = "displayGroupCount"; public static final String EXTRA_FILE_COLUMNS = "extraFileColumns"; public static final String OVERRIDE_DEFAULT_FONT_SIZE = "overrideDefaultFontSize"; public static final String MAIN_FONT_SIZE = "mainFontSize"; public static final String RECENT_DATABASES = "recentDatabases"; public static final String MEMORY_STICK_MODE = "memoryStickMode"; public static final String SHOW_ADVANCED_HINTS = "showAdvancedHints"; public static final String DEFAULT_ENCODING = "defaultEncoding"; public static final String BASE_DOI_URI = "baseDOIURI"; public static final String USE_CUSTOM_DOI_URI = "useCustomDOIURI"; public static final String USE_OWNER = "useOwner"; public static final String DEFAULT_OWNER = "defaultOwner"; public static final String OVERWRITE_OWNER = "overwriteOwner"; // Required for migration from pre-v5.3 only public static final String UPDATE_TIMESTAMP = "updateTimestamp"; public static final String TIME_STAMP_FIELD = "timeStampField"; public static final String TIME_STAMP_FORMAT = "timeStampFormat"; public static final String ADD_CREATION_DATE = "addCreationDate"; public static final String ADD_MODIFICATION_DATE = "addModificationDate"; public static final String WARN_ABOUT_DUPLICATES_IN_INSPECTION = "warnAboutDuplicatesInInspection"; public static final String NON_WRAPPABLE_FIELDS = "nonWrappableFields"; public static final String RESOLVE_STRINGS_FOR_FIELDS = "resolveStringsForFields"; public static final String DO_NOT_RESOLVE_STRINGS = "doNotResolveStrings"; // merge related public static final String MERGE_ENTRIES_DIFF_MODE = "mergeEntriesDiffMode"; public static final String MERGE_ENTRIES_SHOULD_SHOW_DIFF = "mergeEntriesShouldShowDiff"; public static final String MERGE_ENTRIES_SHOULD_SHOW_UNIFIED_DIFF = "mergeEntriesShouldShowUnifiedDiff"; public static final String MERGE_ENTRIES_HIGHLIGHT_WORDS = "mergeEntriesHighlightWords"; public static final String MERGE_SHOW_ONLY_CHANGED_FIELDS = "mergeShowOnlyChangedFields"; public static final String CUSTOM_EXPORT_FORMAT = "customExportFormat"; public static final String CUSTOM_IMPORT_FORMAT = "customImportFormat"; public static final String KEY_PATTERN_REGEX = "KeyPatternRegex"; public static final String KEY_PATTERN_REPLACEMENT = "KeyPatternReplacement"; public static final String CONSOLE_COMMAND = "consoleCommand"; public static final String USE_DEFAULT_CONSOLE_APPLICATION = "useDefaultConsoleApplication"; public static final String USE_DEFAULT_FILE_BROWSER_APPLICATION = "userDefaultFileBrowserApplication"; public static final String FILE_BROWSER_COMMAND = "fileBrowserCommand"; public static final String MAIN_FILE_DIRECTORY = "fileDirectory"; public static final String SEARCH_DISPLAY_MODE = "searchDisplayMode"; public static final String SEARCH_CASE_SENSITIVE = "caseSensitiveSearch"; public static final String SEARCH_REG_EXP = "regExpSearch"; public static final String SEARCH_FULLTEXT = "fulltextSearch"; public static final String SEARCH_KEEP_SEARCH_STRING = "keepSearchString"; public static final String SEARCH_KEEP_GLOBAL_WINDOW_ON_TOP = "keepOnTop"; public static final String SEARCH_WINDOW_HEIGHT = "searchWindowHeight"; public static final String SEARCH_WINDOW_WIDTH = "searchWindowWidth"; public static final String GENERATE_KEY_ON_IMPORT = "generateKeyOnImport"; public static final String GROBID_ENABLED = "grobidEnabled"; public static final String GROBID_OPT_OUT = "grobidOptOut"; public static final String GROBID_URL = "grobidURL"; public static final String DEFAULT_CITATION_KEY_PATTERN = "defaultBibtexKeyPattern"; public static final String UNWANTED_CITATION_KEY_CHARACTERS = "defaultUnwantedBibtexKeyCharacters"; public static final String CONFIRM_DELETE = "confirmDelete"; public static final String WARN_BEFORE_OVERWRITING_KEY = "warnBeforeOverwritingKey"; public static final String AVOID_OVERWRITING_KEY = "avoidOverwritingKey"; public static final String AUTOLINK_EXACT_KEY_ONLY = "autolinkExactKeyOnly"; public static final String AUTOLINK_FILES_ENABLED = "autoLinkFilesEnabled"; public static final String SIDE_PANE_WIDTH = "sidePaneWidthFX"; public static final String CITE_COMMAND = "citeCommand"; public static final String GENERATE_KEYS_BEFORE_SAVING = "generateKeysBeforeSaving"; public static final String EMAIL_SUBJECT = "emailSubject"; public static final String KINDLE_EMAIL = "kindleEmail"; public static final String OPEN_FOLDERS_OF_ATTACHED_FILES = "openFoldersOfAttachedFiles"; public static final String KEY_GEN_ALWAYS_ADD_LETTER = "keyGenAlwaysAddLetter"; public static final String KEY_GEN_FIRST_LETTER_A = "keyGenFirstLetterA"; public static final String ALLOW_INTEGER_EDITION_BIBTEX = "allowIntegerEditionBibtex"; public static final String LOCAL_AUTO_SAVE = "localAutoSave"; public static final String AUTOLINK_REG_EXP_SEARCH_EXPRESSION_KEY = "regExpSearchExpression"; public static final String AUTOLINK_USE_REG_EXP_SEARCH_KEY = "useRegExpSearch"; // bibLocAsPrimaryDir is a misleading antique variable name, we keep it for reason of compatibility public static final String STORE_RELATIVE_TO_BIB = "bibLocAsPrimaryDir"; public static final String SELECTED_FETCHER_INDEX = "selectedFetcherIndex"; public static final String WEB_SEARCH_VISIBLE = "webSearchVisible"; public static final String GROUP_SIDEPANE_VISIBLE = "groupSidepaneVisible"; public static final String CUSTOM_TAB_NAME = "customTabName_"; public static final String CUSTOM_TAB_FIELDS = "customTabFields_"; public static final String ASK_AUTO_NAMING_PDFS_AGAIN = "AskAutoNamingPDFsAgain"; public static final String CLEANUP_JOBS = "CleanUpJobs"; public static final String CLEANUP_FIELD_FORMATTERS_ENABLED = "CleanUpFormattersEnabled"; public static final String CLEANUP_FIELD_FORMATTERS = "CleanUpFormatters"; public static final String IMPORT_FILENAMEPATTERN = "importFileNamePattern"; public static final String IMPORT_FILEDIRPATTERN = "importFileDirPattern"; public static final String NAME_FORMATTER_VALUE = "nameFormatterFormats"; public static final String NAME_FORMATER_KEY = "nameFormatterNames"; public static final String PUSH_TO_APPLICATION = "pushToApplication"; public static final String SHOW_RECOMMENDATIONS = "showRecommendations"; public static final String ACCEPT_RECOMMENDATIONS = "acceptRecommendations"; public static final String SHOW_LATEX_CITATIONS = "showLatexCitations"; public static final String SEND_LANGUAGE_DATA = "sendLanguageData"; public static final String SEND_OS_DATA = "sendOSData"; public static final String SEND_TIMEZONE_DATA = "sendTimezoneData"; public static final String VALIDATE_IN_ENTRY_EDITOR = "validateInEntryEditor"; /** * The OpenOffice/LibreOffice connection preferences are: OO_PATH main directory for OO/LO installation, used to detect location on Win/macOS when using manual connect OO_EXECUTABLE_PATH path to soffice-file OO_JARS_PATH directory that contains juh.jar, jurt.jar, ridl.jar, unoil.jar OO_SYNC_WHEN_CITING true if the reference list is updated when adding a new citation OO_SHOW_PANEL true if the OO panel is shown on startup OO_USE_ALL_OPEN_DATABASES true if all databases should be used when citing OO_BIBLIOGRAPHY_STYLE_FILE path to the used style file OO_EXTERNAL_STYLE_FILES list with paths to external style files STYLES_*_* size and position of "Select style" dialog */ public static final String OO_EXECUTABLE_PATH = "ooExecutablePath"; public static final String OO_SHOW_PANEL = "showOOPanel"; public static final String OO_SYNC_WHEN_CITING = "syncOOWhenCiting"; public static final String OO_USE_ALL_OPEN_BASES = "useAllOpenBases"; public static final String OO_BIBLIOGRAPHY_STYLE_FILE = "ooBibliographyStyleFile"; public static final String OO_EXTERNAL_STYLE_FILES = "ooExternalStyleFiles"; // Special field preferences public static final String SPECIALFIELDSENABLED = "specialFieldsEnabled"; // Prefs node for CitationKeyPatterns public static final String CITATION_KEY_PATTERNS_NODE = "bibtexkeypatterns"; // Prefs node for customized entry types public static final String CUSTOMIZED_BIBTEX_TYPES = "customizedBibtexTypes"; public static final String CUSTOMIZED_BIBLATEX_TYPES = "customizedBiblatexTypes"; // Version public static final String VERSION_IGNORED_UPDATE = "versionIgnoreUpdate"; // KeyBindings - keys - public because needed for pref migration public static final String BINDINGS = "bindings"; // AutcompleteFields - public because needed for pref migration public static final String AUTOCOMPLETER_COMPLETE_FIELDS = "autoCompleteFields"; // Id Entry Generator Preferences public static final String ID_ENTRY_GENERATOR = "idEntryGenerator"; // String delimiter public static final Character STRINGLIST_DELIMITER = ';'; // Preview - public for pref migrations public static final String PREVIEW_STYLE = "previewStyle"; public static final String CYCLE_PREVIEW_POS = "cyclePreviewPos"; public static final String CYCLE_PREVIEW = "cyclePreview"; public static final String PREVIEW_AS_TAB = "previewAsTab"; // UI private static final String FONT_FAMILY = "fontFamily"; // Proxy private static final String PROXY_PORT = "proxyPort"; private static final String PROXY_HOSTNAME = "proxyHostname"; private static final String PROXY_USE = "useProxy"; private static final String PROXY_USE_AUTHENTICATION = "useProxyAuthentication"; private static final String PROXY_USERNAME = "proxyUsername"; private static final String PROXY_PASSWORD = "proxyPassword"; private static final String PROXY_PERSIST_PASSWORD = "persistPassword"; // Web search private static final String FETCHER_CUSTOM_KEY_NAMES = "fetcherCustomKeyNames"; private static final String FETCHER_CUSTOM_KEY_USES = "fetcherCustomKeyUses"; // SSL private static final String TRUSTSTORE_PATH = "truststorePath"; // Auto completion private static final String AUTO_COMPLETE = "autoComplete"; private static final String AUTOCOMPLETER_FIRSTNAME_MODE = "autoCompFirstNameMode"; private static final String AUTOCOMPLETER_LAST_FIRST = "autoCompLF"; private static final String AUTOCOMPLETER_FIRST_LAST = "autoCompFF"; private static final String BIND_NAMES = "bindNames"; // User private static final String USER_ID = "userId"; // Journal private static final String EXTERNAL_JOURNAL_LISTS = "externalJournalLists"; private static final String USE_AMS_FJOURNAL = "useAMSFJournal"; // Telemetry collection private static final String COLLECT_TELEMETRY = "collectTelemetry"; private static final String ALREADY_ASKED_TO_COLLECT_TELEMETRY = "askedCollectTelemetry"; private static final String PROTECTED_TERMS_ENABLED_EXTERNAL = "protectedTermsEnabledExternal"; private static final String PROTECTED_TERMS_DISABLED_EXTERNAL = "protectedTermsDisabledExternal"; private static final String PROTECTED_TERMS_ENABLED_INTERNAL = "protectedTermsEnabledInternal"; private static final String PROTECTED_TERMS_DISABLED_INTERNAL = "protectedTermsDisabledInternal"; // GroupViewMode private static final String GROUP_INTERSECT_UNION_VIEW_MODE = "groupIntersectUnionViewModes"; private static final String DEFAULT_HIERARCHICAL_CONTEXT = "defaultHierarchicalContext"; // Dialog states private static final String PREFS_EXPORT_PATH = "prefsExportPath"; private static final String DOWNLOAD_LINKED_FILES = "downloadLinkedFiles"; private static final String FULLTEXT_INDEX_LINKED_FILES = "fulltextIndexLinkedFiles"; // Helper string private static final String USER_HOME = System.getProperty("user.home"); // Indexes for Strings within stored custom export entries private static final int EXPORTER_NAME_INDEX = 0; private static final int EXPORTER_FILENAME_INDEX = 1; private static final int EXPORTER_EXTENSION_INDEX = 2; // Remote private static final String USE_REMOTE_SERVER = "useRemoteServer"; private static final String REMOTE_SERVER_PORT = "remoteServerPort"; private static final Logger LOGGER = LoggerFactory.getLogger(JabRefPreferences.class); private static final Preferences PREFS_NODE = Preferences.userRoot().node("/org/jabref"); // The only instance of this class: private static JabRefPreferences singleton; /** * HashMap that contains all preferences which are set by default */ public final Map<String, Object> defaults = new HashMap<>(); private final Preferences prefs; /** * Cache variables */ private String userAndHost; private LibraryPreferences libraryPreferences; private TelemetryPreferences telemetryPreferences; private DOIPreferences doiPreferences; private OwnerPreferences ownerPreferences; private TimestampPreferences timestampPreferences; private PreviewPreferences previewPreferences; private OpenOfficePreferences openOfficePreferences; private SidePanePreferences sidePanePreferences; private WorkspacePreferences workspacePreferences; private ImporterPreferences importerPreferences; private GrobidPreferences grobidPreferences; private ProtectedTermsPreferences protectedTermsPreferences; private MrDlibPreferences mrDlibPreferences; private EntryEditorPreferences entryEditorPreferences; private FilePreferences filePreferences; private GuiPreferences guiPreferences; private RemotePreferences remotePreferences; private ProxyPreferences proxyPreferences; private SSLPreferences sslPreferences; private SearchPreferences searchPreferences; private AutoLinkPreferences autoLinkPreferences; private ExportPreferences exportPreferences; private NameFormatterPreferences nameFormatterPreferences; private BibEntryPreferences bibEntryPreferences; private InternalPreferences internalPreferences; private SpecialFieldsPreferences specialFieldsPreferences; private GroupsPreferences groupsPreferences; private XmpPreferences xmpPreferences; private AutoCompletePreferences autoCompletePreferences; private CleanupPreferences cleanupPreferences; private PushToApplicationPreferences pushToApplicationPreferences; private ExternalApplicationsPreferences externalApplicationsPreferences; private CitationKeyPatternPreferences citationKeyPatternPreferences; private NameDisplayPreferences nameDisplayPreferences; private MainTablePreferences mainTablePreferences; private ColumnPreferences mainTableColumnPreferences; private ColumnPreferences searchDialogColumnPreferences; private JournalAbbreviationPreferences journalAbbreviationPreferences; private FieldPreferences fieldPreferences; // The constructor is made private to enforce this as a singleton class: private JabRefPreferences() { try { if (new File("jabref.xml").exists()) { importPreferences(Path.of("jabref.xml")); } } catch (JabRefException e) { LOGGER.warn("Could not import preferences from jabref.xml: " + e.getMessage(), e); } // load user preferences prefs = PREFS_NODE; // Since some of the preference settings themselves use localized strings, we cannot set the language after // the initialization of the preferences in main // Otherwise that language framework will be instantiated and more importantly, statically initialized preferences // like the SearchDisplayMode will never be translated. Localization.setLanguage(getLanguage()); defaults.put(SEARCH_DISPLAY_MODE, SearchDisplayMode.FILTER.toString()); defaults.put(SEARCH_CASE_SENSITIVE, Boolean.FALSE); defaults.put(SEARCH_REG_EXP, Boolean.FALSE); defaults.put(SEARCH_FULLTEXT, Boolean.FALSE); defaults.put(SEARCH_KEEP_SEARCH_STRING, Boolean.FALSE); defaults.put(SEARCH_KEEP_GLOBAL_WINDOW_ON_TOP, Boolean.TRUE); defaults.put(SEARCH_WINDOW_HEIGHT, 176.0); defaults.put(SEARCH_WINDOW_WIDTH, 600.0); defaults.put(GENERATE_KEY_ON_IMPORT, Boolean.TRUE); defaults.put(GROBID_ENABLED, Boolean.FALSE); defaults.put(GROBID_OPT_OUT, Boolean.FALSE); defaults.put(GROBID_URL, "http://grobid.jabref.org:8070"); defaults.put(PUSH_TEXMAKER_PATH, OS.getNativeDesktop().detectProgramPath("texmaker", "Texmaker")); defaults.put(PUSH_WINEDT_PATH, OS.getNativeDesktop().detectProgramPath("WinEdt", "WinEdt Team\\WinEdt")); defaults.put(PUSH_TEXSTUDIO_PATH, OS.getNativeDesktop().detectProgramPath("texstudio", "TeXstudio")); defaults.put(PUSH_LYXPIPE, USER_HOME + File.separator + ".lyx/lyxpipe"); defaults.put(PUSH_VIM, "vim"); defaults.put(PUSH_VIM_SERVER, "vim"); defaults.put(PUSH_EMACS_ADDITIONAL_PARAMETERS, "-n -e"); defaults.put(BIBLATEX_DEFAULT_MODE, Boolean.FALSE); // Set DOI to be the default ID entry generator defaults.put(ID_ENTRY_GENERATOR, DoiFetcher.NAME); defaults.put(USE_CUSTOM_DOI_URI, Boolean.FALSE); defaults.put(BASE_DOI_URI, "https://doi.org"); if (OS.OS_X) { defaults.put(FONT_FAMILY, "SansSerif"); defaults.put(PUSH_EMACS_PATH, "emacsclient"); } else if (OS.WINDOWS) { defaults.put(PUSH_EMACS_PATH, "emacsclient.exe"); } else { // Linux defaults.put(FONT_FAMILY, "SansSerif"); defaults.put(PUSH_EMACS_PATH, "emacsclient"); } defaults.put(PUSH_TO_APPLICATION, "TeXstudio"); defaults.put(RECENT_DATABASES, ""); defaults.put(EXTERNAL_FILE_TYPES, ""); defaults.put(KEY_PATTERN_REGEX, ""); defaults.put(KEY_PATTERN_REPLACEMENT, ""); // Proxy defaults.put(PROXY_USE, Boolean.FALSE); defaults.put(PROXY_HOSTNAME, ""); defaults.put(PROXY_PORT, "80"); defaults.put(PROXY_USE_AUTHENTICATION, Boolean.FALSE); defaults.put(PROXY_USERNAME, ""); defaults.put(PROXY_PASSWORD, ""); defaults.put(PROXY_PERSIST_PASSWORD, Boolean.FALSE); // SSL defaults.put(TRUSTSTORE_PATH, OS.getNativeDesktop() .getSslDirectory() .resolve("truststore.jks").toString()); defaults.put(POS_X, 0); defaults.put(POS_Y, 0); defaults.put(SIZE_X, 1024); defaults.put(SIZE_Y, 768); defaults.put(WINDOW_MAXIMISED, Boolean.TRUE); defaults.put(AUTO_RESIZE_MODE, Boolean.FALSE); // By default disable "Fit table horizontally on the screen" defaults.put(ENTRY_EDITOR_HEIGHT, 0.65); defaults.put(NAMES_AS_IS, Boolean.FALSE); // "Show names unchanged" defaults.put(NAMES_FIRST_LAST, Boolean.FALSE); // "Show 'Firstname Lastname'" defaults.put(NAMES_NATBIB, Boolean.TRUE); // "Natbib style" defaults.put(ABBR_AUTHOR_NAMES, Boolean.TRUE); // "Abbreviate names" defaults.put(NAMES_LAST_ONLY, Boolean.TRUE); // "Show last names only" // system locale as default defaults.put(LANGUAGE, Locale.getDefault().getLanguage()); defaults.put(REFORMAT_FILE_ON_SAVE_AND_EXPORT, Boolean.FALSE); // export order defaults.put(EXPORT_IN_ORIGINAL_ORDER, Boolean.TRUE); defaults.put(EXPORT_IN_SPECIFIED_ORDER, Boolean.FALSE); // export order: if EXPORT_IN_SPECIFIED_ORDER, then use following criteria defaults.put(EXPORT_PRIMARY_SORT_FIELD, InternalField.KEY_FIELD.getName()); defaults.put(EXPORT_PRIMARY_SORT_DESCENDING, Boolean.FALSE); defaults.put(EXPORT_SECONDARY_SORT_FIELD, StandardField.AUTHOR.getName()); defaults.put(EXPORT_SECONDARY_SORT_DESCENDING, Boolean.FALSE); defaults.put(EXPORT_TERTIARY_SORT_FIELD, StandardField.TITLE.getName()); defaults.put(EXPORT_TERTIARY_SORT_DESCENDING, Boolean.TRUE); defaults.put(NEWLINE, System.lineSeparator()); defaults.put(SIDE_PANE_COMPONENT_NAMES, ""); defaults.put(SIDE_PANE_COMPONENT_PREFERRED_POSITIONS, ""); defaults.put(COLUMN_NAMES, "groups;files;linked_id;field:entrytype;field:author/editor;field:title;field:year;field:journal/booktitle;special:ranking;special:readstatus;special:priority"); defaults.put(COLUMN_WIDTHS, "28;28;28;75;300;470;60;130;50;50;50"); defaults.put(XMP_PRIVACY_FILTERS, "pdf;timestamp;keywords;owner;note;review"); defaults.put(USE_XMP_PRIVACY_FILTER, Boolean.FALSE); defaults.put(WORKING_DIRECTORY, USER_HOME); defaults.put(EXPORT_WORKING_DIRECTORY, USER_HOME); defaults.put(CREATE_BACKUP, Boolean.TRUE); // Remembers working directory of last import defaults.put(IMPORT_WORKING_DIRECTORY, USER_HOME); defaults.put(PREFS_EXPORT_PATH, USER_HOME); defaults.put(AUTO_OPEN_FORM, Boolean.TRUE); defaults.put(OPEN_LAST_EDITED, Boolean.TRUE); defaults.put(LAST_EDITED, ""); defaults.put(LAST_FOCUSED, ""); defaults.put(DEFAULT_SHOW_SOURCE, Boolean.FALSE); defaults.put(MERGE_ENTRIES_DIFF_MODE, DiffMode.WORD.name()); defaults.put(MERGE_ENTRIES_SHOULD_SHOW_DIFF, Boolean.TRUE); defaults.put(MERGE_ENTRIES_SHOULD_SHOW_UNIFIED_DIFF, Boolean.TRUE); defaults.put(MERGE_ENTRIES_HIGHLIGHT_WORDS, Boolean.TRUE); defaults.put(MERGE_SHOW_ONLY_CHANGED_FIELDS, Boolean.FALSE); defaults.put(SHOW_RECOMMENDATIONS, Boolean.TRUE); defaults.put(ACCEPT_RECOMMENDATIONS, Boolean.FALSE); defaults.put(SHOW_LATEX_CITATIONS, Boolean.TRUE); defaults.put(SEND_LANGUAGE_DATA, Boolean.FALSE); defaults.put(SEND_OS_DATA, Boolean.FALSE); defaults.put(SEND_TIMEZONE_DATA, Boolean.FALSE); defaults.put(VALIDATE_IN_ENTRY_EDITOR, Boolean.TRUE); defaults.put(AUTO_COMPLETE, Boolean.FALSE); defaults.put(AUTOCOMPLETER_FIRSTNAME_MODE, AutoCompleteFirstNameMode.BOTH.name()); defaults.put(AUTOCOMPLETER_FIRST_LAST, Boolean.FALSE); // "Autocomplete names in 'Firstname Lastname' format only" defaults.put(AUTOCOMPLETER_LAST_FIRST, Boolean.FALSE); // "Autocomplete names in 'Lastname, Firstname' format only" defaults.put(AUTOCOMPLETER_COMPLETE_FIELDS, "author;editor;title;journal;publisher;keywords;crossref;related;entryset"); defaults.put(AUTO_ASSIGN_GROUP, Boolean.TRUE); defaults.put(DISPLAY_GROUP_COUNT, Boolean.TRUE); defaults.put(GROUP_INTERSECT_UNION_VIEW_MODE, GroupViewMode.INTERSECTION.name()); defaults.put(DEFAULT_HIERARCHICAL_CONTEXT, GroupHierarchyType.INDEPENDENT.name()); defaults.put(KEYWORD_SEPARATOR, ", "); defaults.put(DEFAULT_ENCODING, StandardCharsets.UTF_8.name()); defaults.put(DEFAULT_OWNER, System.getProperty("user.name")); defaults.put(MEMORY_STICK_MODE, Boolean.FALSE); defaults.put(SHOW_ADVANCED_HINTS, Boolean.TRUE); defaults.put(EXTRA_FILE_COLUMNS, Boolean.FALSE); defaults.put(PROTECTED_TERMS_ENABLED_INTERNAL, convertListToString(ProtectedTermsLoader.getInternalLists())); defaults.put(PROTECTED_TERMS_DISABLED_INTERNAL, ""); defaults.put(PROTECTED_TERMS_ENABLED_EXTERNAL, ""); defaults.put(PROTECTED_TERMS_DISABLED_EXTERNAL, ""); // OpenOffice/LibreOffice if (OS.WINDOWS) { defaults.put(OO_EXECUTABLE_PATH, OpenOfficePreferences.DEFAULT_WIN_EXEC_PATH); } else if (OS.OS_X) { defaults.put(OO_EXECUTABLE_PATH, OpenOfficePreferences.DEFAULT_OSX_EXEC_PATH); } else { // Linux defaults.put(OO_EXECUTABLE_PATH, OpenOfficePreferences.DEFAULT_LINUX_EXEC_PATH); } defaults.put(OO_SYNC_WHEN_CITING, Boolean.TRUE); defaults.put(OO_SHOW_PANEL, Boolean.FALSE); defaults.put(OO_USE_ALL_OPEN_BASES, Boolean.TRUE); defaults.put(OO_BIBLIOGRAPHY_STYLE_FILE, StyleLoader.DEFAULT_AUTHORYEAR_STYLE_PATH); defaults.put(OO_EXTERNAL_STYLE_FILES, ""); defaults.put(SPECIALFIELDSENABLED, Boolean.TRUE); defaults.put(FETCHER_CUSTOM_KEY_NAMES, "Springer;IEEEXplore;SAO/NASA ADS;ScienceDirect;Biodiversity Heritage"); defaults.put(FETCHER_CUSTOM_KEY_USES, "FALSE;FALSE;FALSE;FALSE;FALSE"); defaults.put(USE_OWNER, Boolean.FALSE); defaults.put(OVERWRITE_OWNER, Boolean.FALSE); defaults.put(AVOID_OVERWRITING_KEY, Boolean.FALSE); defaults.put(WARN_BEFORE_OVERWRITING_KEY, Boolean.TRUE); defaults.put(CONFIRM_DELETE, Boolean.TRUE); defaults.put(DEFAULT_CITATION_KEY_PATTERN, "[auth][year]"); defaults.put(UNWANTED_CITATION_KEY_CHARACTERS, "-`ʹ:!;?^+"); defaults.put(RESOLVE_STRINGS_FOR_FIELDS, "author;booktitle;editor;editora;editorb;editorc;institution;issuetitle;journal;journalsubtitle;journaltitle;mainsubtitle;month;publisher;shortauthor;shorteditor;subtitle;titleaddon"); defaults.put(DO_NOT_RESOLVE_STRINGS, Boolean.FALSE); defaults.put(NON_WRAPPABLE_FIELDS, "pdf;ps;url;doi;file;isbn;issn"); defaults.put(WARN_ABOUT_DUPLICATES_IN_INSPECTION, Boolean.TRUE); defaults.put(ADD_CREATION_DATE, Boolean.FALSE); defaults.put(ADD_MODIFICATION_DATE, Boolean.FALSE); defaults.put(UPDATE_TIMESTAMP, Boolean.FALSE); defaults.put(TIME_STAMP_FIELD, StandardField.TIMESTAMP.getName()); // default time stamp follows ISO-8601. Reason: https://xkcd.com/1179/ defaults.put(TIME_STAMP_FORMAT, "yyyy-MM-dd"); defaults.put(GENERATE_KEYS_BEFORE_SAVING, Boolean.FALSE); defaults.put(USE_REMOTE_SERVER, Boolean.TRUE); defaults.put(REMOTE_SERVER_PORT, 6050); defaults.put(EXTERNAL_JOURNAL_LISTS, ""); defaults.put(USE_AMS_FJOURNAL, true); defaults.put(CITE_COMMAND, "\\cite"); // obsoleted by the app-specific ones (not any more?) defaults.put(LAST_USED_EXPORT, ""); defaults.put(SIDE_PANE_WIDTH, 0.15); defaults.put(MAIN_FONT_SIZE, 9); defaults.put(OVERRIDE_DEFAULT_FONT_SIZE, false); defaults.put(AUTOLINK_EXACT_KEY_ONLY, Boolean.FALSE); defaults.put(AUTOLINK_FILES_ENABLED, Boolean.TRUE); defaults.put(LOCAL_AUTO_SAVE, Boolean.FALSE); defaults.put(ALLOW_INTEGER_EDITION_BIBTEX, Boolean.FALSE); // Curly brackets ({}) are the default delimiters, not quotes (") as these cause trouble when they appear within the field value: // Currently, JabRef does not escape them defaults.put(KEY_GEN_FIRST_LETTER_A, Boolean.TRUE); defaults.put(KEY_GEN_ALWAYS_ADD_LETTER, Boolean.FALSE); defaults.put(EMAIL_SUBJECT, Localization.lang("References")); defaults.put(KINDLE_EMAIL, ""); defaults.put(OPEN_FOLDERS_OF_ATTACHED_FILES, Boolean.FALSE); defaults.put(WEB_SEARCH_VISIBLE, Boolean.TRUE); defaults.put(GROUP_SIDEPANE_VISIBLE, Boolean.TRUE); defaults.put(SELECTED_FETCHER_INDEX, 0); defaults.put(STORE_RELATIVE_TO_BIB, Boolean.TRUE); defaults.put(COLLECT_TELEMETRY, Boolean.FALSE); defaults.put(ALREADY_ASKED_TO_COLLECT_TELEMETRY, Boolean.FALSE); defaults.put(ASK_AUTO_NAMING_PDFS_AGAIN, Boolean.TRUE); defaults.put(CLEANUP_JOBS, convertListToString(getDefaultCleanupJobs().stream().map(Enum::name).toList())); defaults.put(CLEANUP_FIELD_FORMATTERS_ENABLED, Boolean.FALSE); defaults.put(CLEANUP_FIELD_FORMATTERS, FieldFormatterCleanups.getMetaDataString(FieldFormatterCleanups.DEFAULT_SAVE_ACTIONS, OS.NEWLINE)); // use citation key appended with filename as default pattern defaults.put(IMPORT_FILENAMEPATTERN, FilePreferences.DEFAULT_FILENAME_PATTERNS[1]); // Default empty String to be backwards compatible defaults.put(IMPORT_FILEDIRPATTERN, ""); // Download files by default defaults.put(DOWNLOAD_LINKED_FILES, true); // Create Fulltext-Index by default defaults.put(FULLTEXT_INDEX_LINKED_FILES, true); String defaultExpression = "**/.*[citationkey].*\\\\.[extension]"; defaults.put(AUTOLINK_REG_EXP_SEARCH_EXPRESSION_KEY, defaultExpression); defaults.put(AUTOLINK_USE_REG_EXP_SEARCH_KEY, Boolean.FALSE); defaults.put(USE_DEFAULT_CONSOLE_APPLICATION, Boolean.TRUE); defaults.put(USE_DEFAULT_FILE_BROWSER_APPLICATION, Boolean.TRUE); if (OS.WINDOWS) { defaults.put(CONSOLE_COMMAND, "C:\\Program Files\\ConEmu\\ConEmu64.exe /single /dir \"%DIR\""); defaults.put(FILE_BROWSER_COMMAND, "explorer.exe /select, \"%DIR\""); } else { defaults.put(CONSOLE_COMMAND, ""); defaults.put(FILE_BROWSER_COMMAND, ""); } // version check defaults defaults.put(VERSION_IGNORED_UPDATE, ""); // preview defaults.put(CYCLE_PREVIEW, "Preview;" + CitationStyle.DEFAULT); defaults.put(CYCLE_PREVIEW_POS, 0); defaults.put(PREVIEW_AS_TAB, Boolean.FALSE); defaults.put(PREVIEW_STYLE, "<font face=\"sans-serif\">" + "<b>\\bibtextype</b><a name=\"\\citationkey\">\\begin{citationkey} (\\citationkey)</a>\\end{citationkey}__NEWLINE__" + "\\begin{author}<BR><BR>\\format[Authors(LastFirst, FullName,Sep= / ,LastSep= / ),HTMLChars]{\\author}\\end{author}__NEWLINE__" + "\\begin{editor & !author}<BR><BR>\\format[Authors(LastFirst,FullName,Sep= / ,LastSep= / ),HTMLChars]{\\editor} (\\format[IfPlural(Eds.,Ed.)]{\\editor})\\end{editor & !author}__NEWLINE__" + "\\begin{title}<BR><b>\\format[HTMLChars]{\\title}</b> \\end{title}__NEWLINE__" + "<BR>\\begin{date}\\date\\end{date}\\begin{edition}, \\edition. edition\\end{edition}__NEWLINE__" + "\\begin{editor & author}<BR><BR>\\format[Authors(LastFirst,FullName,Sep= / ,LastSep= / ),HTMLChars]{\\editor} (\\format[IfPlural(Eds.,Ed.)]{\\editor})\\end{editor & author}__NEWLINE__" + "\\begin{booktitle}<BR><i>\\format[HTMLChars]{\\booktitle}</i>\\end{booktitle}__NEWLINE__" + "\\begin{chapter} \\format[HTMLChars]{\\chapter}<BR>\\end{chapter}" + "\\begin{editor & !author}<BR>\\end{editor & !author}\\begin{!editor}<BR>\\end{!editor}\\begin{journal}<BR><i>\\format[HTMLChars]{\\journal}</i> \\end{journal} \\begin{volume}, Vol. \\volume\\end{volume}\\begin{series}<BR>\\format[HTMLChars]{\\series}\\end{series}\\begin{number}, No. \\format[HTMLChars]{\\number}\\end{number}__NEWLINE__" + "\\begin{school} \\format[HTMLChars]{\\school}, \\end{school}__NEWLINE__" + "\\begin{institution} <em>\\format[HTMLChars]{\\institution}, </em>\\end{institution}__NEWLINE__" + "\\begin{publisher}<BR>\\format[HTMLChars]{\\publisher}\\end{publisher}\\begin{location}: \\format[HTMLChars]{\\location} \\end{location}__NEWLINE__" + "\\begin{pages}<BR> p. \\format[FormatPagesForHTML]{\\pages}\\end{pages}__NEWLINE__" + "\\begin{abstract}<BR><BR><b>Abstract: </b>\\format[HTMLChars]{\\abstract} \\end{abstract}__NEWLINE__" + "\\begin{owncitation}<BR><BR><b>Own citation: </b>\\format[HTMLChars]{\\owncitation} \\end{owncitation}__NEWLINE__" + "\\begin{comment}<BR><BR><b>Comment: </b>\\format[HTMLChars]{\\comment}\\end{comment}__NEWLINE__" + "</font>__NEWLINE__"); // set default theme defaults.put(FX_THEME, Theme.BASE_CSS); setLanguageDependentDefaultValues(); } public void setLanguageDependentDefaultValues() { // Entry editor tab 0: defaults.put(CUSTOM_TAB_NAME + "_def0", Localization.lang("General")); String fieldNames = FieldFactory.getDefaultGeneralFields().stream().map(Field::getName).collect(Collectors.joining(STRINGLIST_DELIMITER.toString())); defaults.put(CUSTOM_TAB_FIELDS + "_def0", fieldNames); // Entry editor tab 1: defaults.put(CUSTOM_TAB_FIELDS + "_def1", StandardField.ABSTRACT.getName()); defaults.put(CUSTOM_TAB_NAME + "_def1", Localization.lang("Abstract")); // Entry editor tab 2: Comments Field - used for research comments, etc. defaults.put(CUSTOM_TAB_FIELDS + "_def2", StandardField.COMMENT.getName()); defaults.put(CUSTOM_TAB_NAME + "_def2", Localization.lang("Comments")); defaults.put(EMAIL_SUBJECT, Localization.lang("References")); } /** * @return Instance of JaRefPreferences * @deprecated Use {@link PreferencesService} instead */ @Deprecated public static JabRefPreferences getInstance() { if (JabRefPreferences.singleton == null) { JabRefPreferences.singleton = new JabRefPreferences(); } return JabRefPreferences.singleton; } //************************************************************************************************************* // Common serializer logic //************************************************************************************************************* private static String convertListToString(List<String> value) { return value.stream().map(val -> StringUtil.quote(val, STRINGLIST_DELIMITER.toString(), '\\')).collect(Collectors.joining(STRINGLIST_DELIMITER.toString())); } private static List<String> convertStringToList(String toConvert) { if (StringUtil.isBlank(toConvert)) { return Collections.emptyList(); } StringReader reader = new StringReader(toConvert); List<String> result = new ArrayList<>(); Optional<String> rs; try { while ((rs = getNextUnit(reader)).isPresent()) { result.add(rs.get()); } } catch (IOException e) { LOGGER.warn("Unable to convert String to List", e); } return result; } private static Optional<String> getNextUnit(Reader data) throws IOException { // character last read // -1 if end of stream // initialization necessary, because of Java compiler int c = -1; // last character was escape symbol boolean escape = false; // true if a STRINGLIST_DELIMITER is found boolean done = false; StringBuilder res = new StringBuilder(); while (!done && ((c = data.read()) != -1)) { if (c == '\\') { if (escape) { escape = false; res.append('\\'); } else { escape = true; } } else { if (c == STRINGLIST_DELIMITER) { if (escape) { res.append(STRINGLIST_DELIMITER); } else { done = true; } } else { res.append((char) c); } escape = false; } } if (res.length() > 0) { return Optional.of(res.toString()); } else if (c == -1) { // end of stream return Optional.empty(); } else { return Optional.of(""); } } //************************************************************************************************************* // Backingstore access logic //************************************************************************************************************* /** * Check whether a key is set (differently from null). * * @param key The key to check. * @return true if the key is set, false otherwise. */ public boolean hasKey(String key) { return prefs.get(key, null) != null; } public String get(String key) { return prefs.get(key, (String) defaults.get(key)); } public Optional<String> getAsOptional(String key) { return Optional.ofNullable(prefs.get(key, (String) defaults.get(key))); } public String get(String key, String def) { return prefs.get(key, def); } public boolean getBoolean(String key) { return prefs.getBoolean(key, getBooleanDefault(key)); } public boolean getBoolean(String key, boolean def) { return prefs.getBoolean(key, def); } private boolean getBooleanDefault(String key) { return (Boolean) defaults.get(key); } public int getInt(String key) { return prefs.getInt(key, getIntDefault(key)); } public double getDouble(String key) { return prefs.getDouble(key, getDoubleDefault(key)); } public int getIntDefault(String key) { return (Integer) defaults.get(key); } private double getDoubleDefault(String key) { return ((Number) defaults.get(key)).doubleValue(); } public void put(String key, String value) { prefs.put(key, value); } public void putBoolean(String key, boolean value) { prefs.putBoolean(key, value); } public void putInt(String key, int value) { prefs.putInt(key, value); } public void putInt(String key, Number value) { prefs.putInt(key, value.intValue()); } public void putDouble(String key, double value) { prefs.putDouble(key, value); } private void remove(String key) { prefs.remove(key); } /** * Puts a list of strings into the Preferences, by linking its elements with a STRINGLIST_DELIMITER into a single string. Escape characters make the process transparent even if strings contains a STRINGLIST_DELIMITER. */ public void putStringList(String key, List<String> value) { if (value == null) { remove(key); return; } put(key, convertListToString(value)); } /** * Returns a List of Strings containing the chosen columns. */ public List<String> getStringList(String key) { return convertStringToList(get(key)); } /** * Returns a Path */ private Path getPath(String key, Path defaultValue) { String rawPath = get(key); return StringUtil.isNotBlank(rawPath) ? Path.of(rawPath) : defaultValue; } /** * Clear all preferences. * * @throws BackingStoreException if JabRef is unable to write to the registry/the preferences storage */ @Override public void clear() throws BackingStoreException { clearAllBibEntryTypes(); clearCitationKeyPatterns(); clearTruststoreFromCustomCertificates(); clearCustomFetcherKeys(); prefs.clear(); new SharedDatabasePreferences().clear(); } private void clearTruststoreFromCustomCertificates() { TrustStoreManager trustStoreManager = new TrustStoreManager(Path.of(defaults.get(TRUSTSTORE_PATH).toString())); trustStoreManager.clearCustomCertificates(); } /** * Removes the given key from the preferences. * * @throws IllegalArgumentException if the key does not exist */ @Override public void deleteKey(String key) throws IllegalArgumentException { String keyTrimmed = key.trim(); if (hasKey(keyTrimmed)) { remove(keyTrimmed); } else { throw new IllegalArgumentException("Unknown preference key"); } } /** * Calling this method will write all preferences into the preference store. */ @Override public void flush() { if (getBoolean(MEMORY_STICK_MODE)) { try { exportPreferences(Path.of("jabref.xml")); } catch (JabRefException e) { LOGGER.warn("Could not export preferences for memory stick mode: " + e.getMessage(), e); } } try { prefs.flush(); } catch (BackingStoreException ex) { LOGGER.warn("Cannot communicate with backing store", ex); } } @Override public Map<String, Object> getPreferences() { Map<String, Object> result = new HashMap<>(); try { addPrefsRecursively(this.prefs, result); } catch (BackingStoreException e) { LOGGER.info("could not retrieve preference keys", e); } return result; } @Override public Map<String, Object> getDefaults() { return defaults; } private void addPrefsRecursively(Preferences prefs, Map<String, Object> result) throws BackingStoreException { for (String key : prefs.keys()) { result.put(key, getObject(prefs, key)); } for (String child : prefs.childrenNames()) { addPrefsRecursively(prefs.node(child), result); } } private Object getObject(Preferences prefs, String key) { try { return prefs.get(key, (String) defaults.get(key)); } catch (ClassCastException e) { try { return prefs.getBoolean(key, getBooleanDefault(key)); } catch (ClassCastException e2) { try { return prefs.getInt(key, getIntDefault(key)); } catch (ClassCastException e3) { return prefs.getDouble(key, getDoubleDefault(key)); } } } } /** * Returns a list of Strings stored by key+N with N being an incrementing number */ private List<String> getSeries(String key) { int i = 0; List<String> series = new ArrayList<>(); String item; while (!StringUtil.isBlank(item = get(key + i))) { series.add(item); i++; } return series; } /** * Removes all entries keyed by prefix+number, where number is equal to or higher than the given number. * * @param number or higher. */ private void purgeSeries(String prefix, int number) { int n = number; while (get(prefix + n) != null) { remove(prefix + n); n++; } } /** * Exports Preferences to an XML file. * * @param path Path to export to */ @Override public void exportPreferences(Path path) throws JabRefException { LOGGER.debug("Exporting preferences {}", path.toAbsolutePath()); try (OutputStream os = Files.newOutputStream(path)) { prefs.exportSubtree(os); } catch (BackingStoreException | IOException ex) { throw new JabRefException( "Could not export preferences", Localization.lang("Could not export preferences"), ex); } } /** * Imports Preferences from an XML file. * * @param file Path of file to import from * @throws JabRefException thrown if importing the preferences failed due to an InvalidPreferencesFormatException or an IOException */ @Override public void importPreferences(Path file) throws JabRefException { try (InputStream is = Files.newInputStream(file)) { Preferences.importPreferences(is); } catch (InvalidPreferencesFormatException | IOException ex) { throw new JabRefException( "Could not import preferences", Localization.lang("Could not import preferences"), ex); } } //************************************************************************************************************* // ToDo: Cleanup //************************************************************************************************************* @Override public LayoutFormatterPreferences getLayoutFormatterPreferences() { return new LayoutFormatterPreferences( getNameFormatterPreferences(), getFilePreferences().mainFileDirectoryProperty()); } @Override public KeyBindingRepository getKeyBindingRepository() { return new KeyBindingRepository(getStringList(BIND_NAMES), getStringList(BINDINGS)); } @Override public void storeKeyBindingRepository(KeyBindingRepository keyBindingRepository) { putStringList(BIND_NAMES, keyBindingRepository.getBindNames()); putStringList(BINDINGS, keyBindingRepository.getBindings()); } @Override public JournalAbbreviationPreferences getJournalAbbreviationPreferences() { if (Objects.nonNull(journalAbbreviationPreferences)) { return journalAbbreviationPreferences; } journalAbbreviationPreferences = new JournalAbbreviationPreferences( getStringList(EXTERNAL_JOURNAL_LISTS), getBoolean(USE_AMS_FJOURNAL)); journalAbbreviationPreferences.getExternalJournalLists().addListener((InvalidationListener) change -> putStringList(EXTERNAL_JOURNAL_LISTS, journalAbbreviationPreferences.getExternalJournalLists())); EasyBind.listen(journalAbbreviationPreferences.useFJournalFieldProperty(), (obs, oldValue, newValue) -> putBoolean(USE_AMS_FJOURNAL, newValue)); return journalAbbreviationPreferences; } //************************************************************************************************************* // CustomEntryTypes //************************************************************************************************************* @Override public BibEntryTypesManager getCustomEntryTypesRepository() { BibEntryTypesManager bibEntryTypesManager = new BibEntryTypesManager(); EnumSet.allOf(BibDatabaseMode.class).forEach(mode -> bibEntryTypesManager.addCustomOrModifiedTypes(getBibEntryTypes(mode), mode)); return bibEntryTypesManager; } private List<BibEntryType> getBibEntryTypes(BibDatabaseMode bibDatabaseMode) { List<BibEntryType> storedEntryTypes = new ArrayList<>(); Preferences prefsNode = getPrefsNodeForCustomizedEntryTypes(bibDatabaseMode); try { Arrays.stream(prefsNode.keys()) .map(key -> prefsNode.get(key, null)) .filter(Objects::nonNull) .forEach(typeString -> MetaDataParser.parseCustomEntryType(typeString).ifPresent(storedEntryTypes::add)); } catch (BackingStoreException e) { LOGGER.info("Parsing customized entry types failed.", e); } return storedEntryTypes; } private void clearAllBibEntryTypes() { for (BibDatabaseMode mode : BibDatabaseMode.values()) { clearBibEntryTypes(mode); } } private void clearBibEntryTypes(BibDatabaseMode mode) { try { Preferences prefsNode = getPrefsNodeForCustomizedEntryTypes(mode); prefsNode.clear(); prefsNode.flush(); } catch (BackingStoreException e) { LOGGER.error("Resetting customized entry types failed.", e); } } @Override public void storeCustomEntryTypesRepository(BibEntryTypesManager entryTypesManager) { clearAllBibEntryTypes(); storeBibEntryTypes(entryTypesManager.getAllTypes(BibDatabaseMode.BIBTEX), BibDatabaseMode.BIBTEX); storeBibEntryTypes(entryTypesManager.getAllTypes(BibDatabaseMode.BIBLATEX), BibDatabaseMode.BIBLATEX); } private void storeBibEntryTypes(Collection<BibEntryType> bibEntryTypes, BibDatabaseMode bibDatabaseMode) { Preferences prefsNode = getPrefsNodeForCustomizedEntryTypes(bibDatabaseMode); try { // clear old custom types clearBibEntryTypes(bibDatabaseMode); // store current custom types bibEntryTypes.forEach(type -> prefsNode.put(type.getType().getName(), MetaDataSerializer.serializeCustomEntryTypes(type))); prefsNode.flush(); } catch (BackingStoreException e) { LOGGER.info("Updating stored custom entry types failed.", e); } } private static Preferences getPrefsNodeForCustomizedEntryTypes(BibDatabaseMode mode) { return mode == BibDatabaseMode.BIBTEX ? PREFS_NODE.node(CUSTOMIZED_BIBTEX_TYPES) : PREFS_NODE.node(CUSTOMIZED_BIBLATEX_TYPES); } //************************************************************************************************************* // Misc //************************************************************************************************************* @Override public OpenOfficePreferences getOpenOfficePreferences() { if (Objects.nonNull(openOfficePreferences)) { return openOfficePreferences; } openOfficePreferences = new OpenOfficePreferences( get(OO_EXECUTABLE_PATH), getBoolean(OO_USE_ALL_OPEN_BASES), getBoolean(OO_SYNC_WHEN_CITING), getStringList(OO_EXTERNAL_STYLE_FILES), get(OO_BIBLIOGRAPHY_STYLE_FILE)); EasyBind.listen(openOfficePreferences.executablePathProperty(), (obs, oldValue, newValue) -> put(OO_EXECUTABLE_PATH, newValue)); EasyBind.listen(openOfficePreferences.useAllDatabasesProperty(), (obs, oldValue, newValue) -> putBoolean(OO_USE_ALL_OPEN_BASES, newValue)); EasyBind.listen(openOfficePreferences.syncWhenCitingProperty(), (obs, oldValue, newValue) -> putBoolean(OO_SYNC_WHEN_CITING, newValue)); openOfficePreferences.getExternalStyles().addListener((InvalidationListener) change -> putStringList(OO_EXTERNAL_STYLE_FILES, openOfficePreferences.getExternalStyles())); EasyBind.listen(openOfficePreferences.currentStyleProperty(), (obs, oldValue, newValue) -> put(OO_BIBLIOGRAPHY_STYLE_FILE, newValue)); return openOfficePreferences; } @Override public LibraryPreferences getLibraryPreferences() { if (Objects.nonNull(libraryPreferences)) { return libraryPreferences; } libraryPreferences = new LibraryPreferences( getBoolean(BIBLATEX_DEFAULT_MODE) ? BibDatabaseMode.BIBLATEX : BibDatabaseMode.BIBTEX, getBoolean(REFORMAT_FILE_ON_SAVE_AND_EXPORT), getBoolean(LOCAL_AUTO_SAVE)); EasyBind.listen(libraryPreferences.defaultBibDatabaseModeProperty(), (obs, oldValue, newValue) -> putBoolean(BIBLATEX_DEFAULT_MODE, (newValue == BibDatabaseMode.BIBLATEX))); EasyBind.listen(libraryPreferences.alwaysReformatOnSaveProperty(), (obs, oldValue, newValue) -> putBoolean(REFORMAT_FILE_ON_SAVE_AND_EXPORT, newValue)); EasyBind.listen(libraryPreferences.autoSaveProperty(), (obs, oldValue, newValue) -> putBoolean(LOCAL_AUTO_SAVE, newValue)); return libraryPreferences; } @Override public TelemetryPreferences getTelemetryPreferences() { if (Objects.nonNull(telemetryPreferences)) { return telemetryPreferences; } telemetryPreferences = new TelemetryPreferences( getBoolean(COLLECT_TELEMETRY), !getBoolean(ALREADY_ASKED_TO_COLLECT_TELEMETRY), // mind the ! getTelemetryUserId() ); EasyBind.listen(telemetryPreferences.collectTelemetryProperty(), (obs, oldValue, newValue) -> putBoolean(COLLECT_TELEMETRY, newValue)); EasyBind.listen(telemetryPreferences.askToCollectTelemetryProperty(), (obs, oldValue, newValue) -> putBoolean(ALREADY_ASKED_TO_COLLECT_TELEMETRY, !newValue)); return telemetryPreferences; } private String getTelemetryUserId() { Optional<String> userId = getAsOptional(USER_ID); if (userId.isPresent()) { return userId.get(); } else { String newUserId = UUID.randomUUID().toString(); put(USER_ID, newUserId); return newUserId; } } @Override public DOIPreferences getDOIPreferences() { if (Objects.nonNull(doiPreferences)) { return doiPreferences; } doiPreferences = new DOIPreferences( getBoolean(USE_CUSTOM_DOI_URI), get(BASE_DOI_URI)); EasyBind.listen(doiPreferences.useCustomProperty(), (obs, oldValue, newValue) -> putBoolean(USE_CUSTOM_DOI_URI, newValue)); EasyBind.listen(doiPreferences.defaultBaseURIProperty(), (obs, oldValue, newValue) -> put(BASE_DOI_URI, newValue)); return doiPreferences; } @Override public OwnerPreferences getOwnerPreferences() { if (Objects.nonNull(ownerPreferences)) { return ownerPreferences; } ownerPreferences = new OwnerPreferences( getBoolean(USE_OWNER), get(DEFAULT_OWNER), getBoolean(OVERWRITE_OWNER)); EasyBind.listen(ownerPreferences.useOwnerProperty(), (obs, oldValue, newValue) -> putBoolean(USE_OWNER, newValue)); EasyBind.listen(ownerPreferences.defaultOwnerProperty(), (obs, oldValue, newValue) -> { put(DEFAULT_OWNER, newValue); // trigger re-determination of userAndHost and the dependent preferences userAndHost = null; filePreferences = null; internalPreferences = null; }); EasyBind.listen(ownerPreferences.overwriteOwnerProperty(), (obs, oldValue, newValue) -> putBoolean(OVERWRITE_OWNER, newValue)); return ownerPreferences; } @Override public TimestampPreferences getTimestampPreferences() { if (Objects.nonNull(timestampPreferences)) { return timestampPreferences; } timestampPreferences = new TimestampPreferences( getBoolean(ADD_CREATION_DATE), getBoolean(ADD_MODIFICATION_DATE), getBoolean(UPDATE_TIMESTAMP), FieldFactory.parseField(get(TIME_STAMP_FIELD)), get(TIME_STAMP_FORMAT)); EasyBind.listen(timestampPreferences.addCreationDateProperty(), (obs, oldValue, newValue) -> putBoolean(ADD_CREATION_DATE, newValue)); EasyBind.listen(timestampPreferences.addModificationDateProperty(), (obs, oldValue, newValue) -> putBoolean(ADD_MODIFICATION_DATE, newValue)); return timestampPreferences; } @Override public GroupsPreferences getGroupsPreferences() { if (Objects.nonNull(groupsPreferences)) { return groupsPreferences; } groupsPreferences = new GroupsPreferences( GroupViewMode.valueOf(get(GROUP_INTERSECT_UNION_VIEW_MODE)), getBoolean(AUTO_ASSIGN_GROUP), getBoolean(DISPLAY_GROUP_COUNT), GroupHierarchyType.valueOf(get(DEFAULT_HIERARCHICAL_CONTEXT)) ); EasyBind.listen(groupsPreferences.groupViewModeProperty(), (obs, oldValue, newValue) -> put(GROUP_INTERSECT_UNION_VIEW_MODE, newValue.name())); EasyBind.listen(groupsPreferences.autoAssignGroupProperty(), (obs, oldValue, newValue) -> putBoolean(AUTO_ASSIGN_GROUP, newValue)); EasyBind.listen(groupsPreferences.displayGroupCountProperty(), (obs, oldValue, newValue) -> putBoolean(DISPLAY_GROUP_COUNT, newValue)); EasyBind.listen(groupsPreferences.defaultHierarchicalContextProperty(), (obs, oldValue, newValue) -> put(DEFAULT_HIERARCHICAL_CONTEXT, newValue.name())); return groupsPreferences; } //************************************************************************************************************* // EntryEditorPreferences //************************************************************************************************************* @Override public EntryEditorPreferences getEntryEditorPreferences() { if (Objects.nonNull(entryEditorPreferences)) { return entryEditorPreferences; } entryEditorPreferences = new EntryEditorPreferences( getEntryEditorTabs(), getDefaultEntryEditorTabs(), getBoolean(AUTO_OPEN_FORM), getBoolean(SHOW_RECOMMENDATIONS), getBoolean(ACCEPT_RECOMMENDATIONS), getBoolean(SHOW_LATEX_CITATIONS), getBoolean(DEFAULT_SHOW_SOURCE), getBoolean(VALIDATE_IN_ENTRY_EDITOR), getBoolean(ALLOW_INTEGER_EDITION_BIBTEX), getDouble(ENTRY_EDITOR_HEIGHT), getBoolean(AUTOLINK_FILES_ENABLED)); EasyBind.listen(entryEditorPreferences.entryEditorTabs(), (obs, oldValue, newValue) -> storeEntryEditorTabs(newValue)); // defaultEntryEditorTabs are read-only EasyBind.listen(entryEditorPreferences.shouldOpenOnNewEntryProperty(), (obs, oldValue, newValue) -> putBoolean(AUTO_OPEN_FORM, newValue)); EasyBind.listen(entryEditorPreferences.shouldShowRecommendationsTabProperty(), (obs, oldValue, newValue) -> putBoolean(SHOW_RECOMMENDATIONS, newValue)); EasyBind.listen(entryEditorPreferences.isMrdlibAcceptedProperty(), (obs, oldValue, newValue) -> putBoolean(ACCEPT_RECOMMENDATIONS, newValue)); EasyBind.listen(entryEditorPreferences.shouldShowLatexCitationsTabProperty(), (obs, oldValue, newValue) -> putBoolean(SHOW_LATEX_CITATIONS, newValue)); EasyBind.listen(entryEditorPreferences.showSourceTabByDefaultProperty(), (obs, oldValue, newValue) -> putBoolean(DEFAULT_SHOW_SOURCE, newValue)); EasyBind.listen(entryEditorPreferences.enableValidationProperty(), (obs, oldValue, newValue) -> putBoolean(VALIDATE_IN_ENTRY_EDITOR, newValue)); EasyBind.listen(entryEditorPreferences.allowIntegerEditionBibtexProperty(), (obs, oldValue, newValue) -> putBoolean(ALLOW_INTEGER_EDITION_BIBTEX, newValue)); EasyBind.listen(entryEditorPreferences.dividerPositionProperty(), (obs, oldValue, newValue) -> putDouble(ENTRY_EDITOR_HEIGHT, newValue.doubleValue())); EasyBind.listen(entryEditorPreferences.autoLinkEnabledProperty(), (obs, oldValue, newValue) -> putBoolean(AUTOLINK_FILES_ENABLED, newValue)); return entryEditorPreferences; } /** * Get a Map of defined tab names to default tab fields. * * @return A map of the currently defined tabs in the entry editor from scratch to cache */ private Map<String, Set<Field>> getEntryEditorTabs() { Map<String, Set<Field>> tabs = new LinkedHashMap<>(); List<String> tabNames = getSeries(CUSTOM_TAB_NAME); List<String> tabFields = getSeries(CUSTOM_TAB_FIELDS); if (tabNames.isEmpty() || (tabNames.size() != tabFields.size())) { // Nothing set, so we use the default values tabNames = getSeries(CUSTOM_TAB_NAME + "_def"); tabFields = getSeries(CUSTOM_TAB_FIELDS + "_def"); } for (int i = 0; i < tabNames.size(); i++) { tabs.put(tabNames.get(i), FieldFactory.parseFieldList(tabFields.get(i))); } return tabs; } /** * Stores the defined tabs and corresponding fields in the preferences. * * @param customTabs a map of tab names and the corresponding set of fields to be displayed in */ private void storeEntryEditorTabs(Map<String, Set<Field>> customTabs) { String[] names = customTabs.keySet().toArray(String[]::new); String[] fields = customTabs.values().stream() .map(set -> set.stream() .map(Field::getName) .collect(Collectors.joining(STRINGLIST_DELIMITER.toString()))) .toArray(String[]::new); for (int i = 0; i < customTabs.size(); i++) { put(CUSTOM_TAB_NAME + i, names[i]); put(CUSTOM_TAB_FIELDS + i, fields[i]); } purgeSeries(CUSTOM_TAB_NAME, customTabs.size()); purgeSeries(CUSTOM_TAB_FIELDS, customTabs.size()); getEntryEditorTabs(); } private Map<String, Set<Field>> getDefaultEntryEditorTabs() { Map<String, Set<Field>> customTabsMap = new LinkedHashMap<>(); int defNumber = 0; while (true) { // Saved as 'CUSTOMTABNAME_def{number}' and seperated by ';' String name = (String) defaults.get(CUSTOM_TAB_NAME + "_def" + defNumber); String fields = (String) defaults.get(CUSTOM_TAB_FIELDS + "_def" + defNumber); if (StringUtil.isNullOrEmpty(name) || StringUtil.isNullOrEmpty(fields)) { break; } customTabsMap.put(name, FieldFactory.parseFieldList((String) defaults.get(CUSTOM_TAB_FIELDS + "_def" + defNumber))); defNumber++; } return customTabsMap; } //************************************************************************************************************* // Network preferences //************************************************************************************************************* @Override public RemotePreferences getRemotePreferences() { if (Objects.nonNull(remotePreferences)) { return remotePreferences; } remotePreferences = new RemotePreferences( getInt(REMOTE_SERVER_PORT), getBoolean(USE_REMOTE_SERVER)); EasyBind.listen(remotePreferences.portProperty(), (obs, oldValue, newValue) -> putInt(REMOTE_SERVER_PORT, newValue)); EasyBind.listen(remotePreferences.useRemoteServerProperty(), (obs, oldValue, newValue) -> putBoolean(USE_REMOTE_SERVER, newValue)); return remotePreferences; } @Override public ProxyPreferences getProxyPreferences() { if (Objects.nonNull(proxyPreferences)) { return proxyPreferences; } proxyPreferences = new ProxyPreferences( getBoolean(PROXY_USE), get(PROXY_HOSTNAME), get(PROXY_PORT), getBoolean(PROXY_USE_AUTHENTICATION), get(PROXY_USERNAME), getProxyPassword(), getBoolean(PROXY_PERSIST_PASSWORD)); EasyBind.listen(proxyPreferences.useProxyProperty(), (obs, oldValue, newValue) -> putBoolean(PROXY_USE, newValue)); EasyBind.listen(proxyPreferences.hostnameProperty(), (obs, oldValue, newValue) -> put(PROXY_HOSTNAME, newValue)); EasyBind.listen(proxyPreferences.portProperty(), (obs, oldValue, newValue) -> put(PROXY_PORT, newValue)); EasyBind.listen(proxyPreferences.useAuthenticationProperty(), (obs, oldValue, newValue) -> putBoolean(PROXY_USE_AUTHENTICATION, newValue)); EasyBind.listen(proxyPreferences.usernameProperty(), (obs, oldValue, newValue) -> put(PROXY_USERNAME, newValue)); EasyBind.listen(proxyPreferences.passwordProperty(), (obs, oldValue, newValue) -> setProxyPassword(newValue)); EasyBind.listen(proxyPreferences.persistPasswordProperty(), (obs, oldValue, newValue) -> { putBoolean(PROXY_PERSIST_PASSWORD, newValue); if (!newValue) { try (final Keyring keyring = Keyring.create()) { keyring.deletePassword("org.jabref", "proxy"); } catch (Exception ex) { LOGGER.warn("Unable to remove proxy credentials"); } } }); return proxyPreferences; } private String getProxyPassword() { if (getBoolean(PROXY_PERSIST_PASSWORD)) { try (final Keyring keyring = Keyring.create()) { return new Password( keyring.getPassword("org.jabref", "proxy"), getInternalPreferences().getUserAndHost()) .decrypt(); } catch (PasswordAccessException ex) { LOGGER.warn("JabRef uses proxy password from key store but no password is stored"); } catch (Exception ex) { LOGGER.warn("JabRef could not open the key store"); } } return (String) defaults.get(PROXY_PASSWORD); } private void setProxyPassword(String password) { if (getProxyPreferences().shouldPersistPassword()) { try (final Keyring keyring = Keyring.create()) { if (StringUtil.isBlank(password)) { keyring.deletePassword("org.jabref", "proxy"); } else { keyring.setPassword("org.jabref", "proxy", new Password( password.trim(), getInternalPreferences().getUserAndHost()) .encrypt()); } } catch (Exception ex) { LOGGER.warn("Unable to open key store", ex); } } } @Override public SSLPreferences getSSLPreferences() { if (Objects.nonNull(sslPreferences)) { return sslPreferences; } sslPreferences = new SSLPreferences( get(TRUSTSTORE_PATH) ); return sslPreferences; } //************************************************************************************************************* // CitationKeyPatternPreferences //************************************************************************************************************* private GlobalCitationKeyPattern getGlobalCitationKeyPattern() { GlobalCitationKeyPattern citationKeyPattern = GlobalCitationKeyPattern.fromPattern(get(DEFAULT_CITATION_KEY_PATTERN)); Preferences preferences = PREFS_NODE.node(CITATION_KEY_PATTERNS_NODE); try { String[] keys = preferences.keys(); for (String key : keys) { citationKeyPattern.addCitationKeyPattern( EntryTypeFactory.parse(key), preferences.get(key, null)); } } catch ( BackingStoreException ex) { LOGGER.info("BackingStoreException in JabRefPreferences.getKeyPattern", ex); } return citationKeyPattern; } // public for use in PreferenceMigrations public void storeGlobalCitationKeyPattern(GlobalCitationKeyPattern pattern) { if ((pattern.getDefaultValue() == null) || pattern.getDefaultValue().isEmpty()) { put(DEFAULT_CITATION_KEY_PATTERN, ""); } else { put(DEFAULT_CITATION_KEY_PATTERN, pattern.getDefaultValue().get(0)); } // Store overridden definitions to Preferences. Preferences preferences = PREFS_NODE.node(CITATION_KEY_PATTERNS_NODE); try { preferences.clear(); // We remove all old entries. } catch ( BackingStoreException ex) { LOGGER.info("BackingStoreException in JabRefPreferences::putKeyPattern", ex); } for (EntryType entryType : pattern.getAllKeys()) { if (!pattern.isDefaultValue(entryType)) { // first entry in the map is the full pattern preferences.put(entryType.getName(), pattern.getValue(entryType).get(0)); } } } private void clearCitationKeyPatterns() throws BackingStoreException { Preferences preferences = PREFS_NODE.node(CITATION_KEY_PATTERNS_NODE); preferences.clear(); getCitationKeyPatternPreferences().setKeyPattern(getGlobalCitationKeyPattern()); } @Override public CitationKeyPatternPreferences getCitationKeyPatternPreferences() { if (Objects.nonNull(citationKeyPatternPreferences)) { return citationKeyPatternPreferences; } citationKeyPatternPreferences = new CitationKeyPatternPreferences( getBoolean(AVOID_OVERWRITING_KEY), getBoolean(WARN_BEFORE_OVERWRITING_KEY), getBoolean(GENERATE_KEYS_BEFORE_SAVING), getKeySuffix(), get(KEY_PATTERN_REGEX), get(KEY_PATTERN_REPLACEMENT), get(UNWANTED_CITATION_KEY_CHARACTERS), getGlobalCitationKeyPattern(), (String) defaults.get(DEFAULT_CITATION_KEY_PATTERN), getBibEntryPreferences().keywordSeparatorProperty()); EasyBind.listen(citationKeyPatternPreferences.shouldAvoidOverwriteCiteKeyProperty(), (obs, oldValue, newValue) -> putBoolean(AVOID_OVERWRITING_KEY, newValue)); EasyBind.listen(citationKeyPatternPreferences.shouldWarnBeforeOverwriteCiteKeyProperty(), (obs, oldValue, newValue) -> putBoolean(WARN_BEFORE_OVERWRITING_KEY, newValue)); EasyBind.listen(citationKeyPatternPreferences.shouldGenerateCiteKeysBeforeSavingProperty(), (obs, oldValue, newValue) -> putBoolean(GENERATE_KEYS_BEFORE_SAVING, newValue)); EasyBind.listen(citationKeyPatternPreferences.keySuffixProperty(), (obs, oldValue, newValue) -> { putBoolean(KEY_GEN_ALWAYS_ADD_LETTER, newValue == CitationKeyPatternPreferences.KeySuffix.ALWAYS); putBoolean(KEY_GEN_FIRST_LETTER_A, newValue == CitationKeyPatternPreferences.KeySuffix.SECOND_WITH_A); }); EasyBind.listen(citationKeyPatternPreferences.keyPatternRegexProperty(), (obs, oldValue, newValue) -> put(KEY_PATTERN_REGEX, newValue)); EasyBind.listen(citationKeyPatternPreferences.keyPatternReplacementProperty(), (obs, oldValue, newValue) -> put(KEY_PATTERN_REPLACEMENT, newValue)); EasyBind.listen(citationKeyPatternPreferences.unwantedCharactersProperty(), (obs, oldValue, newValue) -> put(UNWANTED_CITATION_KEY_CHARACTERS, newValue)); EasyBind.listen(citationKeyPatternPreferences.keyPatternProperty(), (obs, oldValue, newValue) -> storeGlobalCitationKeyPattern(newValue)); return citationKeyPatternPreferences; } private CitationKeyPatternPreferences.KeySuffix getKeySuffix() { CitationKeyPatternPreferences.KeySuffix keySuffix = CitationKeyPatternPreferences.KeySuffix.SECOND_WITH_B; if (getBoolean(KEY_GEN_ALWAYS_ADD_LETTER)) { keySuffix = CitationKeyPatternPreferences.KeySuffix.ALWAYS; } else if (getBoolean(KEY_GEN_FIRST_LETTER_A)) { keySuffix = CitationKeyPatternPreferences.KeySuffix.SECOND_WITH_A; } return keySuffix; } //************************************************************************************************************* // ExternalApplicationsPreferences //************************************************************************************************************* @Override public PushToApplicationPreferences getPushToApplicationPreferences() { if (Objects.nonNull(pushToApplicationPreferences)) { return pushToApplicationPreferences; } Map<String, String> applicationCommands = new HashMap<>(); applicationCommands.put(PushToApplications.EMACS, get(PUSH_EMACS_PATH)); applicationCommands.put(PushToApplications.LYX, get(PUSH_LYXPIPE)); applicationCommands.put(PushToApplications.TEXMAKER, get(PUSH_TEXMAKER_PATH)); applicationCommands.put(PushToApplications.TEXSTUDIO, get(PUSH_TEXSTUDIO_PATH)); applicationCommands.put(PushToApplications.VIM, get(PUSH_VIM)); applicationCommands.put(PushToApplications.WIN_EDT, get(PUSH_WINEDT_PATH)); pushToApplicationPreferences = new PushToApplicationPreferences( get(PUSH_TO_APPLICATION), applicationCommands, get(PUSH_EMACS_ADDITIONAL_PARAMETERS), get(PUSH_VIM_SERVER) ); EasyBind.listen(pushToApplicationPreferences.activeApplicationNameProperty(), (obs, oldValue, newValue) -> put(PUSH_TO_APPLICATION, newValue)); pushToApplicationPreferences.getCommandPaths().addListener((obs, oldValue, newValue) -> storePushToApplicationPath(newValue)); EasyBind.listen(pushToApplicationPreferences.emacsArgumentsProperty(), (obs, oldValue, newValue) -> put(PUSH_EMACS_ADDITIONAL_PARAMETERS, newValue)); EasyBind.listen(pushToApplicationPreferences.vimServerProperty(), (obs, oldValue, newValue) -> put(PUSH_VIM_SERVER, newValue)); return pushToApplicationPreferences; } private void storePushToApplicationPath(Map<String, String> commandPair) { commandPair.forEach((key, value) -> { switch (key) { case PushToApplications.EMACS -> put(PUSH_EMACS_PATH, value); case PushToApplications.LYX -> put(PUSH_LYXPIPE, value); case PushToApplications.TEXMAKER -> put(PUSH_TEXMAKER_PATH, value); case PushToApplications.TEXSTUDIO -> put(PUSH_TEXSTUDIO_PATH, value); case PushToApplications.VIM -> put(PUSH_VIM, value); case PushToApplications.WIN_EDT -> put(PUSH_WINEDT_PATH, value); } }); } @Override public ExternalApplicationsPreferences getExternalApplicationsPreferences() { if (Objects.nonNull(externalApplicationsPreferences)) { return externalApplicationsPreferences; } externalApplicationsPreferences = new ExternalApplicationsPreferences( get(EMAIL_SUBJECT), getBoolean(OPEN_FOLDERS_OF_ATTACHED_FILES), get(CITE_COMMAND), !getBoolean(USE_DEFAULT_CONSOLE_APPLICATION), // mind the ! get(CONSOLE_COMMAND), !getBoolean(USE_DEFAULT_FILE_BROWSER_APPLICATION), // mind the ! get(FILE_BROWSER_COMMAND), get(KINDLE_EMAIL)); EasyBind.listen(externalApplicationsPreferences.eMailSubjectProperty(), (obs, oldValue, newValue) -> put(EMAIL_SUBJECT, newValue)); EasyBind.listen(externalApplicationsPreferences.autoOpenEmailAttachmentsFolderProperty(), (obs, oldValue, newValue) -> putBoolean(OPEN_FOLDERS_OF_ATTACHED_FILES, newValue)); EasyBind.listen(externalApplicationsPreferences.citeCommandProperty(), (obs, oldValue, newValue) -> put(CITE_COMMAND, newValue)); EasyBind.listen(externalApplicationsPreferences.useCustomTerminalProperty(), (obs, oldValue, newValue) -> putBoolean(USE_DEFAULT_CONSOLE_APPLICATION, !newValue)); // mind the ! EasyBind.listen(externalApplicationsPreferences.customTerminalCommandProperty(), (obs, oldValue, newValue) -> put(CONSOLE_COMMAND, newValue)); EasyBind.listen(externalApplicationsPreferences.useCustomFileBrowserProperty(), (obs, oldValue, newValue) -> putBoolean(USE_DEFAULT_FILE_BROWSER_APPLICATION, !newValue)); // mind the ! EasyBind.listen(externalApplicationsPreferences.customFileBrowserCommandProperty(), (obs, oldValue, newValue) -> put(FILE_BROWSER_COMMAND, newValue)); EasyBind.listen(externalApplicationsPreferences.kindleEmailProperty(), (obs, oldValue, newValue) -> put(KINDLE_EMAIL, newValue)); return externalApplicationsPreferences; } //************************************************************************************************************* // Main table and search dialog preferences //************************************************************************************************************* @Override public MainTablePreferences getMainTablePreferences() { if (Objects.nonNull(mainTablePreferences)) { return mainTablePreferences; } mainTablePreferences = new MainTablePreferences( getMainTableColumnPreferences(), getBoolean(AUTO_RESIZE_MODE), getBoolean(EXTRA_FILE_COLUMNS)); EasyBind.listen(mainTablePreferences.resizeColumnsToFitProperty(), (obs, oldValue, newValue) -> putBoolean(AUTO_RESIZE_MODE, newValue)); EasyBind.listen(mainTablePreferences.extraFileColumnsEnabledProperty(), (obs, oldValue, newValue) -> putBoolean(EXTRA_FILE_COLUMNS, newValue)); return mainTablePreferences; } @Override public ColumnPreferences getMainTableColumnPreferences() { if (Objects.nonNull(mainTableColumnPreferences)) { return mainTableColumnPreferences; } List<MainTableColumnModel> columns = getColumns(COLUMN_NAMES, COLUMN_WIDTHS, COLUMN_SORT_TYPES, ColumnPreferences.DEFAULT_COLUMN_WIDTH); List<MainTableColumnModel> columnSortOrder = getColumnSortOrder(COLUMN_SORT_ORDER, columns); mainTableColumnPreferences = new ColumnPreferences(columns, columnSortOrder); mainTableColumnPreferences.getColumns().addListener((InvalidationListener) change -> { putStringList(COLUMN_NAMES, getColumnNamesAsStringList(mainTableColumnPreferences)); putStringList(COLUMN_WIDTHS, getColumnWidthsAsStringList(mainTableColumnPreferences)); putStringList(COLUMN_SORT_TYPES, getColumnSortTypesAsStringList(mainTableColumnPreferences)); }); mainTableColumnPreferences.getColumnSortOrder().addListener((InvalidationListener) change -> putStringList(COLUMN_SORT_ORDER, getColumnSortOrderAsStringList(mainTableColumnPreferences))); return mainTableColumnPreferences; } @Override public ColumnPreferences getSearchDialogColumnPreferences() { if (Objects.nonNull(searchDialogColumnPreferences)) { return searchDialogColumnPreferences; } List<MainTableColumnModel> columns = getColumns(COLUMN_NAMES, SEARCH_DIALOG_COLUMN_WIDTHS, SEARCH_DIALOG_COLUMN_SORT_TYPES, ColumnPreferences.DEFAULT_COLUMN_WIDTH); List<MainTableColumnModel> columnSortOrder = getColumnSortOrder(SEARCH_DIALOG_COLUMN_SORT_ORDER, columns); searchDialogColumnPreferences = new ColumnPreferences(columns, columnSortOrder); searchDialogColumnPreferences.getColumns().addListener((InvalidationListener) change -> { // MainTable and SearchResultTable use the same set of columnNames // putStringList(SEARCH_DIALOG_COLUMN_NAMES, getColumnNamesAsStringList(columnPreferences)); putStringList(SEARCH_DIALOG_COLUMN_WIDTHS, getColumnWidthsAsStringList(searchDialogColumnPreferences)); putStringList(SEARCH_DIALOG_COLUMN_SORT_TYPES, getColumnSortTypesAsStringList(searchDialogColumnPreferences)); }); searchDialogColumnPreferences.getColumnSortOrder().addListener((InvalidationListener) change -> putStringList(SEARCH_DIALOG_COLUMN_SORT_ORDER, getColumnSortOrderAsStringList(searchDialogColumnPreferences))); return searchDialogColumnPreferences; } // --- Generic column handling --- @SuppressWarnings("SameParameterValue") private List<MainTableColumnModel> getColumns(String columnNamesList, String columnWidthList, String sortTypeList, double defaultWidth) { List<String> columnNames = getStringList(columnNamesList); List<Double> columnWidths = getStringList(columnWidthList) .stream() .map(string -> { try { return Double.parseDouble(string); } catch ( NumberFormatException e) { LOGGER.error("Exception while parsing column widths. Choosing default.", e); return defaultWidth; } }).toList(); List<SortType> columnSortTypes = getStringList(sortTypeList) .stream() .map(SortType::valueOf).toList(); List<MainTableColumnModel> columns = new ArrayList<>(); for (int i = 0; i < columnNames.size(); i++) { MainTableColumnModel columnModel = MainTableColumnModel.parse(columnNames.get(i)); if (i < columnWidths.size()) { columnModel.widthProperty().setValue(columnWidths.get(i)); } if (i < columnSortTypes.size()) { columnModel.sortTypeProperty().setValue(columnSortTypes.get(i)); } columns.add(columnModel); } return columns; } private List<MainTableColumnModel> getColumnSortOrder(String sortOrderList, List<MainTableColumnModel> tableColumns) { List<MainTableColumnModel> columnsOrdered = new ArrayList<>(); getStringList(sortOrderList).forEach(columnName -> tableColumns.stream().filter(column -> column.getName().equals(columnName)) .findFirst() .ifPresent(columnsOrdered::add)); return columnsOrdered; } private static List<String> getColumnNamesAsStringList(ColumnPreferences columnPreferences) { return columnPreferences.getColumns().stream() .map(MainTableColumnModel::getName) .toList(); } private static List<String> getColumnWidthsAsStringList(ColumnPreferences columnPreferences) { return columnPreferences.getColumns().stream() .map(column -> column.widthProperty().getValue().toString()) .toList(); } private static List<String> getColumnSortTypesAsStringList(ColumnPreferences columnPreferences) { return columnPreferences.getColumns().stream() .map(column -> column.sortTypeProperty().getValue().toString()) .toList(); } private static List<String> getColumnSortOrderAsStringList(ColumnPreferences columnPreferences) { return columnPreferences.getColumnSortOrder().stream() .map(MainTableColumnModel::getName) .collect(Collectors.toList()); } //************************************************************************************************************* // NameDisplayPreferences //************************************************************************************************************* @Override public NameDisplayPreferences getNameDisplayPreferences() { if (Objects.nonNull(nameDisplayPreferences)) { return nameDisplayPreferences; } nameDisplayPreferences = new NameDisplayPreferences( getNameDisplayStyle(), getNameAbbreviationStyle()); EasyBind.listen(nameDisplayPreferences.displayStyleProperty(), (obs, oldValue, newValue) -> { putBoolean(NAMES_NATBIB, newValue == DisplayStyle.NATBIB); putBoolean(NAMES_AS_IS, newValue == DisplayStyle.AS_IS); putBoolean(NAMES_FIRST_LAST, newValue == DisplayStyle.FIRSTNAME_LASTNAME); }); EasyBind.listen(nameDisplayPreferences.abbreviationStyleProperty(), (obs, oldValue, newValue) -> { putBoolean(ABBR_AUTHOR_NAMES, newValue == AbbreviationStyle.FULL); putBoolean(NAMES_LAST_ONLY, newValue == AbbreviationStyle.LASTNAME_ONLY); }); return nameDisplayPreferences; } private AbbreviationStyle getNameAbbreviationStyle() { AbbreviationStyle abbreviationStyle = AbbreviationStyle.NONE; // default if (getBoolean(ABBR_AUTHOR_NAMES)) { abbreviationStyle = AbbreviationStyle.FULL; } else if (getBoolean(NAMES_LAST_ONLY)) { abbreviationStyle = AbbreviationStyle.LASTNAME_ONLY; } return abbreviationStyle; } private DisplayStyle getNameDisplayStyle() { DisplayStyle displayStyle = DisplayStyle.LASTNAME_FIRSTNAME; // default if (getBoolean(NAMES_NATBIB)) { displayStyle = DisplayStyle.NATBIB; } else if (getBoolean(NAMES_AS_IS)) { displayStyle = DisplayStyle.AS_IS; } else if (getBoolean(NAMES_FIRST_LAST)) { displayStyle = DisplayStyle.FIRSTNAME_LASTNAME; } return displayStyle; } //************************************************************************************************************* // BibEntryPreferences //************************************************************************************************************* @Override public BibEntryPreferences getBibEntryPreferences() { if (Objects.nonNull(bibEntryPreferences)) { return bibEntryPreferences; } bibEntryPreferences = new BibEntryPreferences( get(KEYWORD_SEPARATOR).charAt(0) ); EasyBind.listen(bibEntryPreferences.keywordSeparatorProperty(), ((observable, oldValue, newValue) -> put(KEYWORD_SEPARATOR, String.valueOf(newValue)))); return bibEntryPreferences; } //************************************************************************************************************* // InternalPreferences //************************************************************************************************************* @Override public InternalPreferences getInternalPreferences() { if (Objects.nonNull(internalPreferences)) { return internalPreferences; } internalPreferences = new InternalPreferences( Version.parse(get(VERSION_IGNORED_UPDATE)), getPath(PREFS_EXPORT_PATH, OS.getNativeDesktop().getDefaultFileChooserDirectory()), getUserAndHost(), getBoolean(MEMORY_STICK_MODE)); EasyBind.listen(internalPreferences.ignoredVersionProperty(), (obs, oldValue, newValue) -> put(VERSION_IGNORED_UPDATE, newValue.toString())); EasyBind.listen(internalPreferences.lastPreferencesExportPathProperty(), (obs, oldValue, newValue) -> put(PREFS_EXPORT_PATH, newValue.toString())); // user is a static value, should only be changed for debugging EasyBind.listen(internalPreferences.memoryStickModeProperty(), (obs, oldValue, newValue) -> { putBoolean(MEMORY_STICK_MODE, newValue); if (!newValue) { try { Files.deleteIfExists(Path.of("jabref.xml")); } catch (IOException e) { LOGGER.warn("Error accessing filesystem"); } } }); return internalPreferences; } private String getUserAndHost() { if (StringUtil.isNotBlank(userAndHost)) { return userAndHost; } userAndHost = get(DEFAULT_OWNER) + '-' + OS.getNativeDesktop().getHostName(); return userAndHost; } //************************************************************************************************************* // WorkspacePreferences //************************************************************************************************************* @Override public WorkspacePreferences getWorkspacePreferences() { if (workspacePreferences != null) { return workspacePreferences; } workspacePreferences = new WorkspacePreferences( getLanguage(), getBoolean(OVERRIDE_DEFAULT_FONT_SIZE), getInt(MAIN_FONT_SIZE), (Integer) defaults.get(MAIN_FONT_SIZE), new Theme(get(FX_THEME)), getBoolean(OPEN_LAST_EDITED), getBoolean(SHOW_ADVANCED_HINTS), getBoolean(WARN_ABOUT_DUPLICATES_IN_INSPECTION), getBoolean(CONFIRM_DELETE)); EasyBind.listen(workspacePreferences.languageProperty(), (obs, oldValue, newValue) -> { put(LANGUAGE, newValue.getId()); if (oldValue != newValue) { setLanguageDependentDefaultValues(); Localization.setLanguage(newValue); } }); EasyBind.listen(workspacePreferences.shouldOverrideDefaultFontSizeProperty(), (obs, oldValue, newValue) -> putBoolean(OVERRIDE_DEFAULT_FONT_SIZE, newValue)); EasyBind.listen(workspacePreferences.mainFontSizeProperty(), (obs, oldValue, newValue) -> putInt(MAIN_FONT_SIZE, newValue)); EasyBind.listen(workspacePreferences.themeProperty(), (obs, oldValue, newValue) -> put(FX_THEME, newValue.getName())); EasyBind.listen(workspacePreferences.openLastEditedProperty(), (obs, oldValue, newValue) -> putBoolean(OPEN_LAST_EDITED, newValue)); EasyBind.listen(workspacePreferences.showAdvancedHintsProperty(), (obs, oldValue, newValue) -> putBoolean(SHOW_ADVANCED_HINTS, newValue)); EasyBind.listen(workspacePreferences.warnAboutDuplicatesInInspectionProperty(), (obs, oldValue, newValue) -> putBoolean(WARN_ABOUT_DUPLICATES_IN_INSPECTION, newValue)); EasyBind.listen(workspacePreferences.confirmDeleteProperty(), (obs, oldValue, newValue) -> putBoolean(CONFIRM_DELETE, newValue)); return workspacePreferences; } private Language getLanguage() { return Stream.of(Language.values()) .filter(language -> language.getId().equalsIgnoreCase(get(LANGUAGE))) .findFirst() .orElse(Language.ENGLISH); } @Override public FieldPreferences getFieldPreferences() { if (Objects.nonNull(fieldPreferences)) { return fieldPreferences; } fieldPreferences = new FieldPreferences( !getBoolean(DO_NOT_RESOLVE_STRINGS), // mind the ! getStringList(RESOLVE_STRINGS_FOR_FIELDS).stream() .map(FieldFactory::parseField) .collect(Collectors.toList()), getStringList(NON_WRAPPABLE_FIELDS).stream() .map(FieldFactory::parseField) .collect(Collectors.toList())); EasyBind.listen(fieldPreferences.resolveStringsProperty(), (obs, oldValue, newValue) -> putBoolean(DO_NOT_RESOLVE_STRINGS, !newValue)); fieldPreferences.getResolvableFields().addListener((InvalidationListener) change -> put(RESOLVE_STRINGS_FOR_FIELDS, FieldFactory.serializeFieldsList(fieldPreferences.getResolvableFields()))); fieldPreferences.getNonWrappableFields().addListener((InvalidationListener) change -> put(NON_WRAPPABLE_FIELDS, FieldFactory.serializeFieldsList(fieldPreferences.getNonWrappableFields()))); return fieldPreferences; } //************************************************************************************************************* // Linked files preferences //************************************************************************************************************* @Override public FilePreferences getFilePreferences() { if (Objects.nonNull(filePreferences)) { return filePreferences; } filePreferences = new FilePreferences( getInternalPreferences().getUserAndHost(), getPath(MAIN_FILE_DIRECTORY, OS.getNativeDesktop().getDefaultFileChooserDirectory()).toString(), getBoolean(STORE_RELATIVE_TO_BIB), get(IMPORT_FILENAMEPATTERN), get(IMPORT_FILEDIRPATTERN), getBoolean(DOWNLOAD_LINKED_FILES), getBoolean(FULLTEXT_INDEX_LINKED_FILES), Path.of(get(WORKING_DIRECTORY)), ExternalFileTypes.fromString(get(EXTERNAL_FILE_TYPES)), getBoolean(CREATE_BACKUP), // We choose the data directory, because a ".bak" file should survive cache cleanups getPath(BACKUP_DIRECTORY, OS.getNativeDesktop().getBackupDirectory())); EasyBind.listen(filePreferences.mainFileDirectoryProperty(), (obs, oldValue, newValue) -> put(MAIN_FILE_DIRECTORY, newValue)); EasyBind.listen(filePreferences.storeFilesRelativeToBibFileProperty(), (obs, oldValue, newValue) -> putBoolean(STORE_RELATIVE_TO_BIB, newValue)); EasyBind.listen(filePreferences.fileNamePatternProperty(), (obs, oldValue, newValue) -> put(IMPORT_FILENAMEPATTERN, newValue)); EasyBind.listen(filePreferences.fileDirectoryPatternProperty(), (obs, oldValue, newValue) -> put(IMPORT_FILEDIRPATTERN, newValue)); EasyBind.listen(filePreferences.downloadLinkedFilesProperty(), (obs, oldValue, newValue) -> putBoolean(DOWNLOAD_LINKED_FILES, newValue)); EasyBind.listen(filePreferences.fulltextIndexLinkedFilesProperty(), (obs, oldValue, newValue) -> putBoolean(FULLTEXT_INDEX_LINKED_FILES, newValue)); EasyBind.listen(filePreferences.workingDirectoryProperty(), (obs, oldValue, newValue) -> put(WORKING_DIRECTORY, newValue.toString())); filePreferences.getExternalFileTypes().addListener((SetChangeListener<ExternalFileType>) c -> put(EXTERNAL_FILE_TYPES, ExternalFileTypes.toStringList(filePreferences.getExternalFileTypes()))); EasyBind.listen(filePreferences.createBackupProperty(), (obs, oldValue, newValue) -> putBoolean(CREATE_BACKUP, newValue)); EasyBind.listen(filePreferences.backupDirectoryProperty(), (obs, oldValue, newValue) -> put(BACKUP_DIRECTORY, newValue.toString())); return filePreferences; } @Override public AutoLinkPreferences getAutoLinkPreferences() { if (Objects.nonNull(autoLinkPreferences)) { return autoLinkPreferences; } autoLinkPreferences = new AutoLinkPreferences( getAutoLinkKeyDependency(), get(AUTOLINK_REG_EXP_SEARCH_EXPRESSION_KEY), getBoolean(ASK_AUTO_NAMING_PDFS_AGAIN), bibEntryPreferences.keywordSeparatorProperty()); EasyBind.listen(autoLinkPreferences.citationKeyDependencyProperty(), (obs, oldValue, newValue) -> { // Starts bibtex only omitted, as it is not being saved putBoolean(AUTOLINK_EXACT_KEY_ONLY, newValue == AutoLinkPreferences.CitationKeyDependency.EXACT); putBoolean(AUTOLINK_USE_REG_EXP_SEARCH_KEY, newValue == AutoLinkPreferences.CitationKeyDependency.REGEX); }); EasyBind.listen(autoLinkPreferences.askAutoNamingPdfsProperty(), (obs, oldValue, newValue) -> putBoolean(ASK_AUTO_NAMING_PDFS_AGAIN, newValue)); EasyBind.listen(autoLinkPreferences.regularExpressionProperty(), (obs, oldValue, newValue) -> put(AUTOLINK_REG_EXP_SEARCH_EXPRESSION_KEY, newValue)); return autoLinkPreferences; } private AutoLinkPreferences.CitationKeyDependency getAutoLinkKeyDependency() { AutoLinkPreferences.CitationKeyDependency citationKeyDependency = AutoLinkPreferences.CitationKeyDependency.START; // default if (getBoolean(AUTOLINK_EXACT_KEY_ONLY)) { citationKeyDependency = AutoLinkPreferences.CitationKeyDependency.EXACT; } else if (getBoolean(AUTOLINK_USE_REG_EXP_SEARCH_KEY)) { citationKeyDependency = AutoLinkPreferences.CitationKeyDependency.REGEX; } return citationKeyDependency; } //************************************************************************************************************* // Import/Export preferences //************************************************************************************************************* @Override public ExportPreferences getExportPreferences() { if (Objects.nonNull(exportPreferences)) { return exportPreferences; } exportPreferences = new ExportPreferences( get(LAST_USED_EXPORT), Path.of(get(EXPORT_WORKING_DIRECTORY)), getExportSaveOrder(), getCustomExportFormats()); EasyBind.listen(exportPreferences.lastExportExtensionProperty(), (obs, oldValue, newValue) -> put(LAST_USED_EXPORT, newValue)); EasyBind.listen(exportPreferences.exportWorkingDirectoryProperty(), (obs, oldValue, newValue) -> put(EXPORT_WORKING_DIRECTORY, newValue.toString())); EasyBind.listen(exportPreferences.exportSaveOrderProperty(), (obs, oldValue, newValue) -> storeExportSaveOrder(newValue)); exportPreferences.getCustomExporters().addListener((InvalidationListener) c -> storeCustomExportFormats(exportPreferences.getCustomExporters())); return exportPreferences; } private SaveOrder getExportSaveOrder() { List<SaveOrder.SortCriterion> sortCriteria = List.of( new SaveOrder.SortCriterion(FieldFactory.parseField(get(EXPORT_PRIMARY_SORT_FIELD)), getBoolean(EXPORT_PRIMARY_SORT_DESCENDING)), new SaveOrder.SortCriterion(FieldFactory.parseField(get(EXPORT_SECONDARY_SORT_FIELD)), getBoolean(EXPORT_SECONDARY_SORT_DESCENDING)), new SaveOrder.SortCriterion(FieldFactory.parseField(get(EXPORT_TERTIARY_SORT_FIELD)), getBoolean(EXPORT_TERTIARY_SORT_DESCENDING)) ); return new SaveOrder( SaveOrder.OrderType.fromBooleans(getBoolean(EXPORT_IN_SPECIFIED_ORDER), getBoolean(EXPORT_IN_ORIGINAL_ORDER)), sortCriteria ); } private void storeExportSaveOrder(SaveOrder saveOrder) { putBoolean(EXPORT_IN_ORIGINAL_ORDER, saveOrder.getOrderType() == SaveOrder.OrderType.ORIGINAL); putBoolean(EXPORT_IN_SPECIFIED_ORDER, saveOrder.getOrderType() == SaveOrder.OrderType.SPECIFIED); put(EXPORT_PRIMARY_SORT_FIELD, saveOrder.getSortCriteria().get(0).field.getName()); put(EXPORT_SECONDARY_SORT_FIELD, saveOrder.getSortCriteria().get(1).field.getName()); put(EXPORT_TERTIARY_SORT_FIELD, saveOrder.getSortCriteria().get(2).field.getName()); putBoolean(EXPORT_PRIMARY_SORT_DESCENDING, saveOrder.getSortCriteria().get(0).descending); putBoolean(EXPORT_SECONDARY_SORT_DESCENDING, saveOrder.getSortCriteria().get(1).descending); putBoolean(EXPORT_TERTIARY_SORT_DESCENDING, saveOrder.getSortCriteria().get(2).descending); } private SaveOrder getTableSaveOrder() { List<MainTableColumnModel> sortOrder = mainTableColumnPreferences.getColumnSortOrder(); List<SaveOrder.SortCriterion> criteria = new ArrayList<>(); for (var column : sortOrder) { boolean descending = column.getSortType() == SortType.DESCENDING; criteria.add(new SaveOrder.SortCriterion( FieldFactory.parseField(column.getQualifier()), descending)); } return new SaveOrder(SaveOrder.OrderType.TABLE, criteria); } @Override public SaveConfiguration getExportConfiguration() { SaveOrder saveOrder = switch (getExportSaveOrder().getOrderType()) { case TABLE -> this.getTableSaveOrder(); case SPECIFIED -> this.getExportSaveOrder(); case ORIGINAL -> SaveOrder.getDefaultSaveOrder(); }; return new SaveConfiguration() .withSaveOrder(saveOrder) .withMetadataSaveOrder(false) .withReformatOnSave(getLibraryPreferences().shouldAlwaysReformatOnSave()); } private List<TemplateExporter> getCustomExportFormats() { LayoutFormatterPreferences layoutPreferences = getLayoutFormatterPreferences(); SaveConfiguration saveConfiguration = getExportConfiguration(); List<TemplateExporter> formats = new ArrayList<>(); for (String toImport : getSeries(CUSTOM_EXPORT_FORMAT)) { List<String> formatData = convertStringToList(toImport); TemplateExporter format = new TemplateExporter( formatData.get(EXPORTER_NAME_INDEX), formatData.get(EXPORTER_FILENAME_INDEX), formatData.get(EXPORTER_EXTENSION_INDEX), layoutPreferences, saveConfiguration); format.setCustomExport(true); formats.add(format); } return formats; } private void storeCustomExportFormats(List<TemplateExporter> exporters) { if (exporters.isEmpty()) { purgeSeries(CUSTOM_EXPORT_FORMAT, 0); } else { for (int i = 0; i < exporters.size(); i++) { List<String> exporterData = new ArrayList<>(); exporterData.add(EXPORTER_NAME_INDEX, exporters.get(i).getName()); exporterData.add(EXPORTER_FILENAME_INDEX, exporters.get(i).getLayoutFileName()); // Only stores the first extension associated with FileType exporterData.add(EXPORTER_EXTENSION_INDEX, exporters.get(i).getFileType().getExtensions().get(0)); putStringList(CUSTOM_EXPORT_FORMAT + i, exporterData); } purgeSeries(CUSTOM_EXPORT_FORMAT, exporters.size()); } } //************************************************************************************************************* // Preview preferences //************************************************************************************************************* @Override public PreviewPreferences getPreviewPreferences() { if (Objects.nonNull(previewPreferences)) { return previewPreferences; } String style = get(PREVIEW_STYLE); List<PreviewLayout> layouts = getPreviewLayouts(style); this.previewPreferences = new PreviewPreferences( layouts, getPreviewCyclePosition(layouts), new TextBasedPreviewLayout(style, getLayoutFormatterPreferences(), Globals.journalAbbreviationRepository), (String) defaults.get(PREVIEW_STYLE), getBoolean(PREVIEW_AS_TAB)); previewPreferences.getLayoutCycle().addListener((InvalidationListener) c -> storePreviewLayouts(previewPreferences.getLayoutCycle())); EasyBind.listen(previewPreferences.layoutCyclePositionProperty(), (obs, oldValue, newValue) -> putInt(CYCLE_PREVIEW_POS, newValue)); EasyBind.listen(previewPreferences.customPreviewLayoutProperty(), (obs, oldValue, newValue) -> put(PREVIEW_STYLE, newValue.getText())); EasyBind.listen(previewPreferences.showPreviewAsExtraTabProperty(), (obs, oldValue, newValue) -> putBoolean(PREVIEW_AS_TAB, newValue)); return this.previewPreferences; } private List<PreviewLayout> getPreviewLayouts(String style) { List<String> cycle = getStringList(CYCLE_PREVIEW); // For backwards compatibility always add at least the default preview to the cycle if (cycle.isEmpty()) { cycle.add("Preview"); } return cycle.stream() .map(layout -> { if (CitationStyle.isCitationStyleFile(layout)) { return CitationStyle.createCitationStyleFromFile(layout) .map(file -> (PreviewLayout) new CitationStylePreviewLayout(file, Globals.entryTypesManager)) .orElse(null); } else { return new TextBasedPreviewLayout(style, getLayoutFormatterPreferences(), Globals.journalAbbreviationRepository); } }) .filter(Objects::nonNull) .collect(Collectors.toList()); } private void storePreviewLayouts(ObservableList<PreviewLayout> previewCycle) { putStringList(CYCLE_PREVIEW, previewCycle.stream() .map(layout -> { if (layout instanceof CitationStylePreviewLayout citationStyleLayout) { return citationStyleLayout.getFilePath(); } else { return layout.getDisplayName(); } }).collect(Collectors.toList()) ); } private int getPreviewCyclePosition(List<PreviewLayout> layouts) { int storedCyclePos = getInt(CYCLE_PREVIEW_POS); if (storedCyclePos < layouts.size()) { return storedCyclePos; } else { return 0; // fallback if stored position is no longer valid } } //************************************************************************************************************* // SidePanePreferences //************************************************************************************************************* @Override public SidePanePreferences getSidePanePreferences() { if (Objects.nonNull(sidePanePreferences)) { return sidePanePreferences; } sidePanePreferences = new SidePanePreferences( getVisibleSidePanes(), getSidePanePreferredPositions(), getInt(SELECTED_FETCHER_INDEX)); sidePanePreferences.visiblePanes().addListener((InvalidationListener) listener -> storeVisibleSidePanes(sidePanePreferences.visiblePanes())); sidePanePreferences.getPreferredPositions().addListener((InvalidationListener) listener -> storeSidePanePreferredPositions(sidePanePreferences.getPreferredPositions())); EasyBind.listen(sidePanePreferences.webSearchFetcherSelectedProperty(), (obs, oldValue, newValue) -> putInt(SELECTED_FETCHER_INDEX, newValue)); return sidePanePreferences; } private Set<SidePaneType> getVisibleSidePanes() { HashSet<SidePaneType> visiblePanes = new HashSet<>(); if (getBoolean(WEB_SEARCH_VISIBLE)) { visiblePanes.add(SidePaneType.WEB_SEARCH); } if (getBoolean(GROUP_SIDEPANE_VISIBLE)) { visiblePanes.add(SidePaneType.GROUPS); } if (getBoolean(OO_SHOW_PANEL)) { visiblePanes.add(SidePaneType.OPEN_OFFICE); } return visiblePanes; } private void storeVisibleSidePanes(Set<SidePaneType> visiblePanes) { putBoolean(WEB_SEARCH_VISIBLE, visiblePanes.contains(SidePaneType.WEB_SEARCH)); putBoolean(GROUP_SIDEPANE_VISIBLE, visiblePanes.contains(SidePaneType.GROUPS)); putBoolean(OO_SHOW_PANEL, visiblePanes.contains(SidePaneType.OPEN_OFFICE)); } private Map<SidePaneType, Integer> getSidePanePreferredPositions() { Map<SidePaneType, Integer> preferredPositions = new HashMap<>(); List<String> componentNames = getStringList(SIDE_PANE_COMPONENT_NAMES); List<String> componentPositions = getStringList(SIDE_PANE_COMPONENT_PREFERRED_POSITIONS); for (int i = 0; i < componentNames.size(); ++i) { String name = componentNames.get(i); try { SidePaneType type = Enum.valueOf(SidePaneType.class, name); preferredPositions.put(type, Integer.parseInt(componentPositions.get(i))); } catch (NumberFormatException e) { LOGGER.debug("Invalid number format for side pane component '" + name + "'", e); } catch (IllegalArgumentException e) { LOGGER.debug("Following component is not a side pane: '" + name + "'", e); } } return preferredPositions; } private void storeSidePanePreferredPositions(Map<SidePaneType, Integer> preferredPositions) { // Split the map into a pair of parallel String lists suitable for storage List<String> names = preferredPositions.keySet().stream() .map(Enum::toString) .collect(Collectors.toList()); List<String> positions = preferredPositions.values().stream() .map(integer -> Integer.toString(integer)) .collect(Collectors.toList()); putStringList(SIDE_PANE_COMPONENT_NAMES, names); putStringList(SIDE_PANE_COMPONENT_PREFERRED_POSITIONS, positions); } //************************************************************************************************************* // Cleanup preferences //************************************************************************************************************* @Override public CleanupPreferences getCleanupPreferences() { if (Objects.nonNull(cleanupPreferences)) { return cleanupPreferences; } cleanupPreferences = new CleanupPreferences( EnumSet.copyOf(getStringList(CLEANUP_JOBS).stream() .map(CleanupPreferences.CleanupStep::valueOf) .collect(Collectors.toSet())), new FieldFormatterCleanups(getBoolean(CLEANUP_FIELD_FORMATTERS_ENABLED), FieldFormatterCleanups.parse(StringUtil.unifyLineBreaks(get(CLEANUP_FIELD_FORMATTERS), "")))); cleanupPreferences.getObservableActiveJobs().addListener((SetChangeListener<CleanupPreferences.CleanupStep>) c -> putStringList(CLEANUP_JOBS, cleanupPreferences.getActiveJobs().stream().map(Enum::name).collect(Collectors.toList()))); EasyBind.listen(cleanupPreferences.fieldFormatterCleanupsProperty(), (fieldFormatters, oldValue, newValue) -> { putBoolean(CLEANUP_FIELD_FORMATTERS_ENABLED, newValue.isEnabled()); put(CLEANUP_FIELD_FORMATTERS, FieldFormatterCleanups.getMetaDataString(newValue.getConfiguredActions(), OS.NEWLINE)); }); return cleanupPreferences; } @Override public CleanupPreferences getDefaultCleanupPreset() { return new CleanupPreferences( getDefaultCleanupJobs(), new FieldFormatterCleanups( (Boolean) defaults.get(CLEANUP_FIELD_FORMATTERS_ENABLED), FieldFormatterCleanups.parse((String) defaults.get(CLEANUP_FIELD_FORMATTERS)))); } private static EnumSet<CleanupPreferences.CleanupStep> getDefaultCleanupJobs() { EnumSet<CleanupPreferences.CleanupStep> activeJobs = EnumSet.allOf(CleanupPreferences.CleanupStep.class); activeJobs.removeAll(EnumSet.of( CleanupPreferences.CleanupStep.CLEAN_UP_UPGRADE_EXTERNAL_LINKS, CleanupPreferences.CleanupStep.MOVE_PDF, CleanupPreferences.CleanupStep.RENAME_PDF_ONLY_RELATIVE_PATHS, CleanupPreferences.CleanupStep.CONVERT_TO_BIBLATEX, CleanupPreferences.CleanupStep.CONVERT_TO_BIBTEX)); return activeJobs; } //************************************************************************************************************* // GUI preferences //************************************************************************************************************* @Override public GuiPreferences getGuiPreferences() { if (Objects.nonNull(guiPreferences)) { return guiPreferences; } guiPreferences = new GuiPreferences( getDouble(POS_X), getDouble(POS_Y), getDouble(SIZE_X), getDouble(SIZE_Y), getBoolean(WINDOW_MAXIMISED), getStringList(LAST_EDITED), Path.of(get(LAST_FOCUSED)), getFileHistory(), get(ID_ENTRY_GENERATOR), DiffMode.parse(get(MERGE_ENTRIES_DIFF_MODE)), getBoolean(MERGE_ENTRIES_SHOULD_SHOW_DIFF), getBoolean(MERGE_ENTRIES_SHOULD_SHOW_UNIFIED_DIFF), getBoolean(MERGE_ENTRIES_HIGHLIGHT_WORDS), getDouble(SIDE_PANE_WIDTH), getBoolean(MERGE_SHOW_ONLY_CHANGED_FIELDS)); EasyBind.listen(guiPreferences.positionXProperty(), (obs, oldValue, newValue) -> putDouble(POS_X, newValue.doubleValue())); EasyBind.listen(guiPreferences.positionYProperty(), (obs, oldValue, newValue) -> putDouble(POS_Y, newValue.doubleValue())); EasyBind.listen(guiPreferences.sizeXProperty(), (obs, oldValue, newValue) -> putDouble(SIZE_X, newValue.doubleValue())); EasyBind.listen(guiPreferences.sizeYProperty(), (obs, oldValue, newValue) -> putDouble(SIZE_Y, newValue.doubleValue())); EasyBind.listen(guiPreferences.windowMaximisedProperty(), (obs, oldValue, newValue) -> putBoolean(WINDOW_MAXIMISED, newValue)); guiPreferences.getLastFilesOpened().addListener((ListChangeListener<String>) change -> { if (change.getList().isEmpty()) { prefs.remove(LAST_EDITED); } else { putStringList(LAST_EDITED, guiPreferences.getLastFilesOpened()); } }); EasyBind.listen(guiPreferences.lastFocusedFileProperty(), (obs, oldValue, newValue) -> { if (newValue != null) { put(LAST_FOCUSED, newValue.toAbsolutePath().toString()); } else { remove(LAST_FOCUSED); } }); guiPreferences.getFileHistory().addListener((InvalidationListener) change -> storeFileHistory(guiPreferences.getFileHistory())); EasyBind.listen(guiPreferences.lastSelectedIdBasedFetcherProperty(), (obs, oldValue, newValue) -> put(ID_ENTRY_GENERATOR, newValue)); EasyBind.listen(guiPreferences.mergeDiffModeProperty(), (obs, oldValue, newValue) -> put(MERGE_ENTRIES_DIFF_MODE, newValue.name())); EasyBind.listen(guiPreferences.mergeShouldShowDiffProperty(), (obs, oldValue, newValue) -> putBoolean(MERGE_ENTRIES_SHOULD_SHOW_DIFF, newValue)); EasyBind.listen(guiPreferences.mergeShouldShowUnifiedDiffProperty(), (obs, oldValue, newValue) -> putBoolean(MERGE_ENTRIES_SHOULD_SHOW_UNIFIED_DIFF, newValue)); EasyBind.listen(guiPreferences.mergeHighlightWordsProperty(), (obs, oldValue, newValue) -> putBoolean(MERGE_ENTRIES_HIGHLIGHT_WORDS, newValue)); EasyBind.listen(guiPreferences.sidePaneWidthProperty(), (obs, oldValue, newValue) -> putDouble(SIDE_PANE_WIDTH, newValue.doubleValue())); EasyBind.listen(guiPreferences.mergeShowChangedFieldOnlyProperty(), (obs, oldValue, newValue) -> putBoolean(MERGE_SHOW_ONLY_CHANGED_FIELDS, newValue)); return guiPreferences; } private FileHistory getFileHistory() { return FileHistory.of(getStringList(RECENT_DATABASES).stream() .map(Path::of) .toList()); } private void storeFileHistory(FileHistory history) { putStringList(RECENT_DATABASES, history.stream() .map(Path::toAbsolutePath) .map(Path::toString) .toList()); } //************************************************************************************************************* // Misc preferences //************************************************************************************************************* @Override public SearchPreferences getSearchPreferences() { if (Objects.nonNull(searchPreferences)) { return searchPreferences; } SearchDisplayMode searchDisplayMode; try { searchDisplayMode = SearchDisplayMode.valueOf(get(SEARCH_DISPLAY_MODE)); } catch (IllegalArgumentException ex) { // Should only occur when the searchmode is set directly via preferences.put and the enum was not used searchDisplayMode = SearchDisplayMode.valueOf((String) defaults.get(SEARCH_DISPLAY_MODE)); } searchPreferences = new SearchPreferences( searchDisplayMode, getBoolean(SEARCH_CASE_SENSITIVE), getBoolean(SEARCH_REG_EXP), getBoolean(SEARCH_FULLTEXT), getBoolean(SEARCH_KEEP_SEARCH_STRING), getBoolean(SEARCH_KEEP_GLOBAL_WINDOW_ON_TOP), getDouble(SEARCH_WINDOW_HEIGHT), getDouble(SEARCH_WINDOW_WIDTH)); EasyBind.listen(searchPreferences.searchDisplayModeProperty(), (obs, oldValue, newValue) -> put(SEARCH_DISPLAY_MODE, Objects.requireNonNull(searchPreferences.getSearchDisplayMode()).toString())); searchPreferences.getObservableSearchFlags().addListener((SetChangeListener<SearchRules.SearchFlags>) c -> { putBoolean(SEARCH_CASE_SENSITIVE, searchPreferences.getObservableSearchFlags().contains(SearchRules.SearchFlags.CASE_SENSITIVE)); putBoolean(SEARCH_REG_EXP, searchPreferences.getObservableSearchFlags().contains(SearchRules.SearchFlags.REGULAR_EXPRESSION)); putBoolean(SEARCH_FULLTEXT, searchPreferences.getObservableSearchFlags().contains(SearchRules.SearchFlags.FULLTEXT)); putBoolean(SEARCH_KEEP_SEARCH_STRING, searchPreferences.getObservableSearchFlags().contains(SearchRules.SearchFlags.KEEP_SEARCH_STRING)); }); EasyBind.listen(searchPreferences.keepWindowOnTopProperty(), (obs, oldValue, newValue) -> putBoolean(SEARCH_KEEP_GLOBAL_WINDOW_ON_TOP, searchPreferences.shouldKeepWindowOnTop())); EasyBind.listen(searchPreferences.getSearchWindowHeightProperty(), (obs, oldValue, newValue) -> putDouble(SEARCH_WINDOW_HEIGHT, searchPreferences.getSearchWindowHeight())); EasyBind.listen(searchPreferences.getSearchWindowWidthProperty(), (obs, oldValue, newValue) -> putDouble(SEARCH_WINDOW_WIDTH, searchPreferences.getSearchWindowWidth())); return searchPreferences; } @Override public XmpPreferences getXmpPreferences() { if (Objects.nonNull(xmpPreferences)) { return xmpPreferences; } xmpPreferences = new XmpPreferences( getBoolean(USE_XMP_PRIVACY_FILTER), getStringList(XMP_PRIVACY_FILTERS).stream().map(FieldFactory::parseField).collect(Collectors.toSet()), getBibEntryPreferences().keywordSeparatorProperty()); EasyBind.listen(xmpPreferences.useXmpPrivacyFilterProperty(), (obs, oldValue, newValue) -> putBoolean(USE_XMP_PRIVACY_FILTER, newValue)); xmpPreferences.getXmpPrivacyFilter().addListener((SetChangeListener<Field>) c -> putStringList(XMP_PRIVACY_FILTERS, xmpPreferences.getXmpPrivacyFilter().stream() .map(Field::getName) .collect(Collectors.toList()))); return xmpPreferences; } @Override public NameFormatterPreferences getNameFormatterPreferences() { if (Objects.nonNull(nameFormatterPreferences)) { return nameFormatterPreferences; } nameFormatterPreferences = new NameFormatterPreferences( getStringList(NAME_FORMATER_KEY), getStringList(NAME_FORMATTER_VALUE)); nameFormatterPreferences.getNameFormatterKey().addListener((InvalidationListener) change -> putStringList(NAME_FORMATER_KEY, nameFormatterPreferences.getNameFormatterKey())); nameFormatterPreferences.getNameFormatterValue().addListener((InvalidationListener) change -> putStringList(NAME_FORMATTER_VALUE, nameFormatterPreferences.getNameFormatterValue())); return nameFormatterPreferences; } @Override public AutoCompletePreferences getAutoCompletePreferences() { if (Objects.nonNull(autoCompletePreferences)) { return autoCompletePreferences; } AutoCompletePreferences.NameFormat nameFormat = AutoCompletePreferences.NameFormat.BOTH; if (getBoolean(AUTOCOMPLETER_LAST_FIRST)) { nameFormat = AutoCompletePreferences.NameFormat.LAST_FIRST; } else if (getBoolean(AUTOCOMPLETER_FIRST_LAST)) { nameFormat = AutoCompletePreferences.NameFormat.FIRST_LAST; } autoCompletePreferences = new AutoCompletePreferences( getBoolean(AUTO_COMPLETE), AutoCompleteFirstNameMode.parse(get(AUTOCOMPLETER_FIRSTNAME_MODE)), nameFormat, getStringList(AUTOCOMPLETER_COMPLETE_FIELDS).stream().map(FieldFactory::parseField).collect(Collectors.toSet()) ); EasyBind.listen(autoCompletePreferences.autoCompleteProperty(), (obs, oldValue, newValue) -> putBoolean(AUTO_COMPLETE, newValue)); EasyBind.listen(autoCompletePreferences.firstNameModeProperty(), (obs, oldValue, newValue) -> put(AUTOCOMPLETER_FIRSTNAME_MODE, newValue.name())); autoCompletePreferences.getCompleteFields().addListener((SetChangeListener<Field>) c -> putStringList(AUTOCOMPLETER_COMPLETE_FIELDS, autoCompletePreferences.getCompleteFields().stream() .map(Field::getName) .collect(Collectors.toList()))); EasyBind.listen(autoCompletePreferences.nameFormatProperty(), (obs, oldValue, newValue) -> { if (autoCompletePreferences.getNameFormat() == AutoCompletePreferences.NameFormat.BOTH) { putBoolean(AUTOCOMPLETER_LAST_FIRST, false); putBoolean(AUTOCOMPLETER_FIRST_LAST, false); } else if (autoCompletePreferences.getNameFormat() == AutoCompletePreferences.NameFormat.LAST_FIRST) { putBoolean(AUTOCOMPLETER_LAST_FIRST, true); putBoolean(AUTOCOMPLETER_FIRST_LAST, false); } else { putBoolean(AUTOCOMPLETER_LAST_FIRST, false); putBoolean(AUTOCOMPLETER_FIRST_LAST, true); } }); return autoCompletePreferences; } @Override public SpecialFieldsPreferences getSpecialFieldsPreferences() { if (Objects.nonNull(specialFieldsPreferences)) { return specialFieldsPreferences; } specialFieldsPreferences = new SpecialFieldsPreferences(getBoolean(SPECIALFIELDSENABLED)); EasyBind.listen(specialFieldsPreferences.specialFieldsEnabledProperty(), (obs, oldValue, newValue) -> putBoolean(SPECIALFIELDSENABLED, newValue)); return specialFieldsPreferences; } @Override public MrDlibPreferences getMrDlibPreferences() { if (Objects.nonNull(mrDlibPreferences)) { return mrDlibPreferences; } mrDlibPreferences = new MrDlibPreferences( getBoolean(ACCEPT_RECOMMENDATIONS), getBoolean(SEND_LANGUAGE_DATA), getBoolean(SEND_OS_DATA), getBoolean(SEND_TIMEZONE_DATA)); EasyBind.listen(mrDlibPreferences.acceptRecommendationsProperty(), (obs, oldValue, newValue) -> putBoolean(ACCEPT_RECOMMENDATIONS, newValue)); EasyBind.listen(mrDlibPreferences.sendLanguageProperty(), (obs, oldValue, newValue) -> putBoolean(SEND_LANGUAGE_DATA, newValue)); EasyBind.listen(mrDlibPreferences.sendOsProperty(), (obs, oldValue, newValue) -> putBoolean(SEND_OS_DATA, newValue)); EasyBind.listen(mrDlibPreferences.sendTimezoneProperty(), (obs, oldValue, newValue) -> putBoolean(SEND_TIMEZONE_DATA, newValue)); return mrDlibPreferences; } @Override public ProtectedTermsPreferences getProtectedTermsPreferences() { if (Objects.nonNull(protectedTermsPreferences)) { return protectedTermsPreferences; } protectedTermsPreferences = new ProtectedTermsPreferences( getStringList(PROTECTED_TERMS_ENABLED_INTERNAL), getStringList(PROTECTED_TERMS_ENABLED_EXTERNAL), getStringList(PROTECTED_TERMS_DISABLED_INTERNAL), getStringList(PROTECTED_TERMS_DISABLED_EXTERNAL) ); protectedTermsPreferences.getEnabledExternalTermLists().addListener((InvalidationListener) change -> putStringList(PROTECTED_TERMS_ENABLED_EXTERNAL, protectedTermsPreferences.getEnabledExternalTermLists())); protectedTermsPreferences.getDisabledExternalTermLists().addListener((InvalidationListener) change -> putStringList(PROTECTED_TERMS_DISABLED_EXTERNAL, protectedTermsPreferences.getDisabledExternalTermLists())); protectedTermsPreferences.getEnabledInternalTermLists().addListener((InvalidationListener) change -> putStringList(PROTECTED_TERMS_ENABLED_INTERNAL, protectedTermsPreferences.getEnabledInternalTermLists())); protectedTermsPreferences.getDisabledInternalTermLists().addListener((InvalidationListener) change -> putStringList(PROTECTED_TERMS_DISABLED_INTERNAL, protectedTermsPreferences.getDisabledInternalTermLists())); return protectedTermsPreferences; } //************************************************************************************************************* // Importer preferences //************************************************************************************************************* @Override public ImporterPreferences getImporterPreferences() { if (Objects.nonNull(importerPreferences)) { return importerPreferences; } importerPreferences = new ImporterPreferences( getBoolean(GENERATE_KEY_ON_IMPORT), Path.of(get(IMPORT_WORKING_DIRECTORY)), getBoolean(WARN_ABOUT_DUPLICATES_IN_INSPECTION), getCustomImportFormats(), getFetcherKeys() ); EasyBind.listen(importerPreferences.generateNewKeyOnImportProperty(), (obs, oldValue, newValue) -> putBoolean(GENERATE_KEY_ON_IMPORT, newValue)); EasyBind.listen(importerPreferences.importWorkingDirectoryProperty(), (obs, oldValue, newValue) -> put(IMPORT_WORKING_DIRECTORY, newValue.toString())); EasyBind.listen(importerPreferences.warnAboutDuplicatesOnImportProperty(), (obs, oldValue, newValue) -> putBoolean(WARN_ABOUT_DUPLICATES_IN_INSPECTION, newValue)); importerPreferences.getApiKeys().addListener((InvalidationListener) c -> storeFetcherKeys(importerPreferences.getApiKeys())); importerPreferences.getCustomImporters().addListener((InvalidationListener) c -> storeCustomImportFormats(importerPreferences.getCustomImporters())); return importerPreferences; } private Set<CustomImporter> getCustomImportFormats() { Set<CustomImporter> importers = new TreeSet<>(); for (String toImport : getSeries(CUSTOM_IMPORT_FORMAT)) { List<String> importerString = convertStringToList(toImport); try { if (importerString.size() == 2) { // New format: basePath, className importers.add(new CustomImporter(importerString.get(0), importerString.get(1))); } else { // Old format: name, cliId, className, basePath importers.add(new CustomImporter(importerString.get(3), importerString.get(2))); } } catch (Exception e) { LOGGER.warn("Could not load {} from preferences. Will ignore.", importerString.get(0), e); } } return importers; } private void storeCustomImportFormats(Set<CustomImporter> importers) { purgeSeries(CUSTOM_IMPORT_FORMAT, 0); CustomImporter[] importersArray = importers.toArray(new CustomImporter[0]); for (int i = 0; i < importersArray.length; i++) { putStringList(CUSTOM_IMPORT_FORMAT + i, importersArray[i].getAsStringList()); } } private Set<FetcherApiKey> getFetcherKeys() { Set<FetcherApiKey> fetcherApiKeys = new HashSet<>(); List<String> names = getStringList(FETCHER_CUSTOM_KEY_NAMES); List<String> uses = getStringList(FETCHER_CUSTOM_KEY_USES); List<String> keys = getFetcherKeysFromKeyring(names); for (int i = 0; i < names.size(); i++) { fetcherApiKeys.add(new FetcherApiKey( names.get(i), // i < uses.size() ? Boolean.parseBoolean(uses.get(i)) : false (i < uses.size()) && Boolean.parseBoolean(uses.get(i)), i < keys.size() ? keys.get(i) : "")); } return fetcherApiKeys; } private List<String> getFetcherKeysFromKeyring(List<String> names) { List<String> keys = new ArrayList<>(); try (final Keyring keyring = Keyring.create()) { for (String fetcher : names) { try { keys.add(new Password( keyring.getPassword("org.jabref.customapikeys", fetcher), getInternalPreferences().getUserAndHost()) .decrypt()); } catch (PasswordAccessException ex) { LOGGER.warn("No api key stored for {} fetcher", fetcher); keys.add(""); } } } catch (Exception ex) { LOGGER.warn("JabRef could not open the key store"); } return keys; } private void storeFetcherKeys(Set<FetcherApiKey> fetcherApiKeys) { List<String> names = new ArrayList<>(); List<String> uses = new ArrayList<>(); List<String> keys = new ArrayList<>(); for (FetcherApiKey apiKey : fetcherApiKeys) { names.add(apiKey.getName()); uses.add(String.valueOf(apiKey.shouldUse())); keys.add(apiKey.getKey()); } putStringList(FETCHER_CUSTOM_KEY_NAMES, names); putStringList(FETCHER_CUSTOM_KEY_USES, uses); storeFetcherKeysToKeyring(names, keys); } private void storeFetcherKeysToKeyring(List<String> names, List<String> keys) { try (final Keyring keyring = Keyring.create()) { for (int i = 0; i < names.size(); i++) { if (StringUtil.isNullOrEmpty(keys.get(i))) { try { keyring.deletePassword("org.jabref.customapikeys", names.get(i)); } catch (PasswordAccessException ex) { // Already removed } } else { keyring.setPassword("org.jabref.customapikeys", names.get(i), new Password( keys.get(i), getInternalPreferences().getUserAndHost()) .encrypt()); } } } catch (Exception ex) { LOGGER.error("Unable to open key store"); } } private void clearCustomFetcherKeys() { List<String> names = getStringList(FETCHER_CUSTOM_KEY_NAMES); try (final Keyring keyring = Keyring.create()) { for (String name : names) { keyring.deletePassword("org.jabref.customapikeys", name); } } catch (Exception ex) { LOGGER.error("Unable to open key store"); } } @Override public GrobidPreferences getGrobidPreferences() { if (Objects.nonNull(grobidPreferences)) { return grobidPreferences; } grobidPreferences = new GrobidPreferences( getBoolean(GROBID_ENABLED), getBoolean(GROBID_OPT_OUT), get(GROBID_URL)); EasyBind.listen(grobidPreferences.grobidEnabledProperty(), (obs, oldValue, newValue) -> putBoolean(GROBID_ENABLED, newValue)); EasyBind.listen(grobidPreferences.grobidOptOutProperty(), (obs, oldValue, newValue) -> putBoolean(GROBID_OPT_OUT, newValue)); EasyBind.listen(grobidPreferences.grobidURLProperty(), (obs, oldValue, newValue) -> put(GROBID_URL, newValue)); return grobidPreferences; } @Override public ImportFormatPreferences getImportFormatPreferences() { return new ImportFormatPreferences( getBibEntryPreferences(), getCitationKeyPatternPreferences(), getFieldPreferences(), getXmpPreferences(), getDOIPreferences(), getGrobidPreferences()); } }
144,107
48.284542
675
java
null
jabref-main/src/main/java/org/jabref/preferences/LibraryPreferences.java
package org.jabref.preferences; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleObjectProperty; import org.jabref.model.database.BibDatabaseMode; public class LibraryPreferences { private final ObjectProperty<BibDatabaseMode> defaultBibDatabaseMode; private final BooleanProperty alwaysReformatOnSave; private final BooleanProperty autoSave; public LibraryPreferences(BibDatabaseMode defaultBibDatabaseMode, boolean alwaysReformatOnSave, boolean autoSave) { this.defaultBibDatabaseMode = new SimpleObjectProperty<>(defaultBibDatabaseMode); this.alwaysReformatOnSave = new SimpleBooleanProperty(alwaysReformatOnSave); this.autoSave = new SimpleBooleanProperty(autoSave); } public BibDatabaseMode getDefaultBibDatabaseMode() { return defaultBibDatabaseMode.get(); } public ObjectProperty<BibDatabaseMode> defaultBibDatabaseModeProperty() { return defaultBibDatabaseMode; } public void setDefaultBibDatabaseMode(BibDatabaseMode defaultBibDatabaseMode) { this.defaultBibDatabaseMode.set(defaultBibDatabaseMode); } public boolean shouldAlwaysReformatOnSave() { return alwaysReformatOnSave.get(); } public BooleanProperty alwaysReformatOnSaveProperty() { return alwaysReformatOnSave; } public void setAlwaysReformatOnSave(boolean alwaysReformatOnSave) { this.alwaysReformatOnSave.set(alwaysReformatOnSave); } public boolean shouldAutoSave() { return autoSave.get(); } public BooleanProperty autoSaveProperty() { return autoSave; } public void setAutoSave(boolean shouldAutoSave) { this.autoSave.set(shouldAutoSave); } }
1,906
30.783333
89
java
null
jabref-main/src/main/java/org/jabref/preferences/MrDlibPreferences.java
package org.jabref.preferences; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; public class MrDlibPreferences { private final BooleanProperty acceptRecommendations; private final BooleanProperty sendLanguage; private final BooleanProperty sendOs; private final BooleanProperty sendTimezone; public MrDlibPreferences(boolean acceptRecommendations, boolean shouldSendLanguage, boolean shouldSendOs, boolean shouldSendTimezone) { this.acceptRecommendations = new SimpleBooleanProperty(acceptRecommendations); this.sendLanguage = new SimpleBooleanProperty(shouldSendLanguage); this.sendOs = new SimpleBooleanProperty(shouldSendOs); this.sendTimezone = new SimpleBooleanProperty(shouldSendTimezone); } public boolean shouldAcceptRecommendations() { return acceptRecommendations.get(); } public BooleanProperty acceptRecommendationsProperty() { return acceptRecommendations; } public void setAcceptRecommendations(boolean acceptRecommendations) { this.acceptRecommendations.set(acceptRecommendations); } public boolean shouldSendLanguage() { return sendLanguage.get(); } public BooleanProperty sendLanguageProperty() { return sendLanguage; } public void setSendLanguage(boolean sendLanguage) { this.sendLanguage.set(sendLanguage); } public boolean shouldSendOs() { return sendOs.get(); } public BooleanProperty sendOsProperty() { return sendOs; } public void setSendOs(boolean sendOs) { this.sendOs.set(sendOs); } public boolean shouldSendTimezone() { return sendTimezone.get(); } public BooleanProperty sendTimezoneProperty() { return sendTimezone; } public void setSendTimezone(boolean sendTimezone) { this.sendTimezone.set(sendTimezone); } }
1,954
27.75
139
java
null
jabref-main/src/main/java/org/jabref/preferences/PreferencesFilter.java
package org.jabref.preferences; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; public class PreferencesFilter { private final PreferencesService preferences; public PreferencesFilter(PreferencesService preferences) { this.preferences = preferences; } public List<PreferenceOption> getPreferenceOptions() { Map<String, Object> defaults = new HashMap<>(preferences.getDefaults()); Map<String, Object> prefs = preferences.getPreferences(); return prefs.entrySet().stream() .map(entry -> new PreferenceOption(entry.getKey(), entry.getValue(), defaults.get(entry.getKey()))) .collect(Collectors.toList()); } public List<PreferenceOption> getDeviatingPreferences() { return getPreferenceOptions().stream() .filter(PreferenceOption::isChanged) .sorted() .collect(Collectors.toList()); } public enum PreferenceType { BOOLEAN, INTEGER, STRING } public static class PreferenceOption implements Comparable<PreferenceOption> { private final String key; private final Object value; private final Optional<Object> defaultValue; private final PreferenceType type; public PreferenceOption(String key, Object value, Object defaultValue) { this.key = Objects.requireNonNull(key); this.value = Objects.requireNonNull(value); this.defaultValue = Optional.ofNullable(defaultValue); this.type = Objects.requireNonNull(getType(value)); if ((defaultValue != null) && !Objects.equals(this.type, getType(defaultValue))) { throw new IllegalStateException("types must match between default value and value"); } } private PreferenceType getType(Object value) { if (value instanceof Boolean) { return PreferenceType.BOOLEAN; } else if (value instanceof Integer) { return PreferenceType.INTEGER; } else { return PreferenceType.STRING; } } public boolean isUnchanged() { return Objects.equals(value, defaultValue.orElse(null)); } public boolean isChanged() { return !isUnchanged(); } @Override public String toString() { return String.format("%s: %s=%s (%s)", type, key, value, defaultValue.orElse("NULL")); } public String getKey() { return key; } public Object getValue() { return value; } public Optional<Object> getDefaultValue() { return defaultValue; } public PreferenceType getType() { return type; } @Override public int compareTo(PreferenceOption o) { return Objects.compare(this.key, o.key, String::compareTo); } } }
3,160
30.29703
119
java
null
jabref-main/src/main/java/org/jabref/preferences/PreferencesService.java
package org.jabref.preferences; import java.nio.file.Path; import java.util.Map; import java.util.prefs.BackingStoreException; import org.jabref.gui.autocompleter.AutoCompletePreferences; import org.jabref.gui.entryeditor.EntryEditorPreferences; import org.jabref.gui.groups.GroupsPreferences; import org.jabref.gui.keyboard.KeyBindingRepository; import org.jabref.gui.maintable.ColumnPreferences; import org.jabref.gui.maintable.MainTablePreferences; import org.jabref.gui.maintable.NameDisplayPreferences; import org.jabref.gui.specialfields.SpecialFieldsPreferences; import org.jabref.logic.JabRefException; import org.jabref.logic.bibtex.FieldPreferences; import org.jabref.logic.citationkeypattern.CitationKeyPatternPreferences; import org.jabref.logic.exporter.SaveConfiguration; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.ImporterPreferences; import org.jabref.logic.importer.fetcher.GrobidPreferences; import org.jabref.logic.journals.JournalAbbreviationPreferences; import org.jabref.logic.layout.LayoutFormatterPreferences; import org.jabref.logic.layout.format.NameFormatterPreferences; import org.jabref.logic.net.ProxyPreferences; import org.jabref.logic.net.ssl.SSLPreferences; import org.jabref.logic.openoffice.OpenOfficePreferences; import org.jabref.logic.preferences.DOIPreferences; import org.jabref.logic.preferences.OwnerPreferences; import org.jabref.logic.preferences.TimestampPreferences; import org.jabref.logic.protectedterms.ProtectedTermsPreferences; import org.jabref.logic.remote.RemotePreferences; import org.jabref.logic.util.io.AutoLinkPreferences; import org.jabref.logic.xmp.XmpPreferences; import org.jabref.model.entry.BibEntryTypesManager; public interface PreferencesService { void clear() throws BackingStoreException; void deleteKey(String key) throws IllegalArgumentException; void flush(); void exportPreferences(Path file) throws JabRefException; void importPreferences(Path file) throws JabRefException; InternalPreferences getInternalPreferences(); BibEntryPreferences getBibEntryPreferences(); JournalAbbreviationPreferences getJournalAbbreviationPreferences(); void storeKeyBindingRepository(KeyBindingRepository keyBindingRepository); KeyBindingRepository getKeyBindingRepository(); FilePreferences getFilePreferences(); FieldPreferences getFieldPreferences(); OpenOfficePreferences getOpenOfficePreferences(); Map<String, Object> getPreferences(); Map<String, Object> getDefaults(); LayoutFormatterPreferences getLayoutFormatterPreferences(); ImportFormatPreferences getImportFormatPreferences(); SaveConfiguration getExportConfiguration(); BibEntryTypesManager getCustomEntryTypesRepository(); void storeCustomEntryTypesRepository(BibEntryTypesManager entryTypesManager); CleanupPreferences getCleanupPreferences(); CleanupPreferences getDefaultCleanupPreset(); LibraryPreferences getLibraryPreferences(); TelemetryPreferences getTelemetryPreferences(); DOIPreferences getDOIPreferences(); OwnerPreferences getOwnerPreferences(); TimestampPreferences getTimestampPreferences(); GroupsPreferences getGroupsPreferences(); EntryEditorPreferences getEntryEditorPreferences(); RemotePreferences getRemotePreferences(); ProxyPreferences getProxyPreferences(); SSLPreferences getSSLPreferences(); CitationKeyPatternPreferences getCitationKeyPatternPreferences(); PushToApplicationPreferences getPushToApplicationPreferences(); ExternalApplicationsPreferences getExternalApplicationsPreferences(); ColumnPreferences getMainTableColumnPreferences(); MainTablePreferences getMainTablePreferences(); NameDisplayPreferences getNameDisplayPreferences(); ColumnPreferences getSearchDialogColumnPreferences(); WorkspacePreferences getWorkspacePreferences(); AutoLinkPreferences getAutoLinkPreferences(); ExportPreferences getExportPreferences(); ImporterPreferences getImporterPreferences(); GrobidPreferences getGrobidPreferences(); PreviewPreferences getPreviewPreferences(); SidePanePreferences getSidePanePreferences(); GuiPreferences getGuiPreferences(); XmpPreferences getXmpPreferences(); NameFormatterPreferences getNameFormatterPreferences(); AutoCompletePreferences getAutoCompletePreferences(); SpecialFieldsPreferences getSpecialFieldsPreferences(); SearchPreferences getSearchPreferences(); MrDlibPreferences getMrDlibPreferences(); ProtectedTermsPreferences getProtectedTermsPreferences(); }
4,664
30.734694
81
java
null
jabref-main/src/main/java/org/jabref/preferences/PreviewPreferences.java
package org.jabref.preferences; import java.util.List; import javafx.beans.property.BooleanProperty; import javafx.beans.property.IntegerProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import org.jabref.logic.layout.TextBasedPreviewLayout; import org.jabref.logic.preview.PreviewLayout; public class PreviewPreferences { private final ObservableList<PreviewLayout> layoutCycle; private final IntegerProperty layoutCyclePosition; private final ObjectProperty<TextBasedPreviewLayout> customPreviewLayout; private final StringProperty defaultCustomPreviewLayout; private final BooleanProperty showPreviewAsExtraTab; public PreviewPreferences(List<PreviewLayout> layoutCycle, int layoutCyclePosition, TextBasedPreviewLayout customPreviewLayout, String defaultCustomPreviewLayout, boolean showPreviewAsExtraTab) { this.layoutCycle = FXCollections.observableArrayList(layoutCycle); this.layoutCyclePosition = new SimpleIntegerProperty(layoutCyclePosition); this.customPreviewLayout = new SimpleObjectProperty<>(customPreviewLayout); this.defaultCustomPreviewLayout = new SimpleStringProperty(defaultCustomPreviewLayout); this.showPreviewAsExtraTab = new SimpleBooleanProperty(showPreviewAsExtraTab); } public ObservableList<PreviewLayout> getLayoutCycle() { return layoutCycle; } public int getLayoutCyclePosition() { return layoutCyclePosition.getValue(); } public IntegerProperty layoutCyclePositionProperty() { return layoutCyclePosition; } public void setLayoutCyclePosition(int position) { if (layoutCycle.isEmpty()) { this.layoutCyclePosition.setValue(0); } else { int previewCyclePosition = position; while (previewCyclePosition < 0) { previewCyclePosition += layoutCycle.size(); } this.layoutCyclePosition.setValue(previewCyclePosition % layoutCycle.size()); } } public PreviewLayout getSelectedPreviewLayout() { if (layoutCycle.size() <= 0 || layoutCyclePosition.getValue() < 0 || layoutCyclePosition.getValue() >= layoutCycle.size()) { return getCustomPreviewLayout(); } else { return layoutCycle.get(layoutCyclePosition.getValue()); } } public TextBasedPreviewLayout getCustomPreviewLayout() { return customPreviewLayout.getValue(); } public ObjectProperty<TextBasedPreviewLayout> customPreviewLayoutProperty() { return customPreviewLayout; } public void setCustomPreviewLayout(TextBasedPreviewLayout layout) { this.customPreviewLayout.set(layout); } public String getDefaultCustomPreviewLayout() { return defaultCustomPreviewLayout.getValue(); } public boolean shouldShowPreviewAsExtraTab() { return showPreviewAsExtraTab.getValue(); } public BooleanProperty showPreviewAsExtraTabProperty() { return showPreviewAsExtraTab; } public void setShowPreviewAsExtraTab(boolean showPreviewAsExtraTab) { this.showPreviewAsExtraTab.set(showPreviewAsExtraTab); } }
3,663
35.277228
95
java
null
jabref-main/src/main/java/org/jabref/preferences/PushToApplicationPreferences.java
package org.jabref.preferences; import java.util.Map; import javafx.beans.property.MapProperty; import javafx.beans.property.SimpleMapProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.collections.FXCollections; public class PushToApplicationPreferences { private final StringProperty activeApplicationName; private final MapProperty<String, String> commandPaths; private final StringProperty emacsArguments; private final StringProperty vimServer; public PushToApplicationPreferences(String activeApplicationName, Map<String, String> commandPaths, String emacsArguments, String vimServer) { this.activeApplicationName = new SimpleStringProperty(activeApplicationName); this.commandPaths = new SimpleMapProperty<>(FXCollections.observableMap(commandPaths)); this.emacsArguments = new SimpleStringProperty(emacsArguments); this.vimServer = new SimpleStringProperty(vimServer); } public String getActiveApplicationName() { return activeApplicationName.getValue(); } public StringProperty activeApplicationNameProperty() { return activeApplicationName; } public void setActiveApplicationName(String activeApplicationName) { this.activeApplicationName.set(activeApplicationName); } public MapProperty<String, String> getCommandPaths() { return commandPaths; } public void setCommandPaths(Map<String, String> commandPaths) { this.commandPaths.clear(); this.commandPaths.putAll(commandPaths); } public String getEmacsArguments() { return emacsArguments.get(); } public StringProperty emacsArgumentsProperty() { return emacsArguments; } public void setEmacsArguments(String emacsArguments) { this.emacsArguments.set(emacsArguments); } public String getVimServer() { return vimServer.get(); } public StringProperty vimServerProperty() { return vimServer; } public void setVimServer(String vimServer) { this.vimServer.set(vimServer); } }
2,273
30.583333
95
java
null
jabref-main/src/main/java/org/jabref/preferences/SearchPreferences.java
package org.jabref.preferences; import java.util.EnumSet; import javafx.beans.property.BooleanProperty; import javafx.beans.property.DoubleProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableSet; import org.jabref.gui.search.SearchDisplayMode; import org.jabref.model.search.rules.SearchRules.SearchFlags; public class SearchPreferences { private final ObjectProperty<SearchDisplayMode> searchDisplayMode; private final ObservableSet<SearchFlags> searchFlags; private final BooleanProperty keepWindowOnTop; private final DoubleProperty searchWindowHeight = new SimpleDoubleProperty(); private final DoubleProperty searchWindowWidth = new SimpleDoubleProperty(); public SearchPreferences(SearchDisplayMode searchDisplayMode, boolean isCaseSensitive, boolean isRegularExpression, boolean isFulltext, boolean isKeepSearchString, boolean keepWindowOnTop, double searchWindowHeight, double searchWindowWidth) { this.searchDisplayMode = new SimpleObjectProperty<>(searchDisplayMode); this.keepWindowOnTop = new SimpleBooleanProperty(keepWindowOnTop); searchFlags = FXCollections.observableSet(EnumSet.noneOf(SearchFlags.class)); if (isCaseSensitive) { searchFlags.add(SearchFlags.CASE_SENSITIVE); } if (isRegularExpression) { searchFlags.add(SearchFlags.REGULAR_EXPRESSION); } if (isFulltext) { searchFlags.add(SearchFlags.FULLTEXT); } if (isKeepSearchString) { searchFlags.add(SearchFlags.KEEP_SEARCH_STRING); } this.setSearchWindowHeight(searchWindowHeight); this.setSearchWindowWidth(searchWindowWidth); } public SearchPreferences(SearchDisplayMode searchDisplayMode, EnumSet<SearchFlags> searchFlags, boolean keepWindowOnTop) { this.searchDisplayMode = new SimpleObjectProperty<>(searchDisplayMode); this.keepWindowOnTop = new SimpleBooleanProperty(keepWindowOnTop); this.searchFlags = FXCollections.observableSet(searchFlags); } public EnumSet<SearchFlags> getSearchFlags() { // copy of returns an exception when the EnumSet is empty if (searchFlags.isEmpty()) { return EnumSet.noneOf(SearchFlags.class); } return EnumSet.copyOf(searchFlags); } protected ObservableSet<SearchFlags> getObservableSearchFlags() { return searchFlags; } public SearchDisplayMode getSearchDisplayMode() { return searchDisplayMode.get(); } public ObjectProperty<SearchDisplayMode> searchDisplayModeProperty() { return searchDisplayMode; } public void setSearchDisplayMode(SearchDisplayMode searchDisplayMode) { this.searchDisplayMode.set(searchDisplayMode); } public boolean isCaseSensitive() { return searchFlags.contains(SearchFlags.CASE_SENSITIVE); } public void setSearchFlag(SearchFlags flag, boolean value) { if (searchFlags.contains(flag) && !value) { searchFlags.remove(flag); } else if (!searchFlags.contains(flag) && value) { searchFlags.add(flag); } } public boolean isRegularExpression() { return searchFlags.contains(SearchFlags.REGULAR_EXPRESSION); } public boolean isFulltext() { return searchFlags.contains(SearchFlags.FULLTEXT); } public boolean shouldKeepSearchString() { return searchFlags.contains(SearchFlags.KEEP_SEARCH_STRING); } public boolean shouldKeepWindowOnTop() { return keepWindowOnTop.get(); } public BooleanProperty keepWindowOnTopProperty() { return keepWindowOnTop; } public void setKeepWindowOnTop(boolean keepWindowOnTop) { this.keepWindowOnTop.set(keepWindowOnTop); } public double getSearchWindowHeight() { return this.searchWindowHeight.get(); } public double getSearchWindowWidth() { return this.searchWindowWidth.get(); } public DoubleProperty getSearchWindowHeightProperty() { return this.searchWindowHeight; } public DoubleProperty getSearchWindowWidthProperty() { return this.searchWindowWidth; } public void setSearchWindowHeight(double height) { this.searchWindowHeight.set(height); } public void setSearchWindowWidth(double width) { this.searchWindowWidth.set(width); } }
4,652
32.47482
247
java
null
jabref-main/src/main/java/org/jabref/preferences/SidePanePreferences.java
package org.jabref.preferences; import java.util.Map; import java.util.Set; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableMap; import javafx.collections.ObservableSet; import org.jabref.gui.sidepane.SidePaneType; public class SidePanePreferences { private final ObservableSet<SidePaneType> visiblePanes; private final ObservableMap<SidePaneType, Integer> preferredPositions; private final IntegerProperty webSearchFetcherSelected; public SidePanePreferences(Set<SidePaneType> visiblePanes, Map<SidePaneType, Integer> preferredPositions, int webSearchFetcherSelected) { this.visiblePanes = FXCollections.observableSet(visiblePanes); this.preferredPositions = FXCollections.observableMap(preferredPositions); this.webSearchFetcherSelected = new SimpleIntegerProperty(webSearchFetcherSelected); } public ObservableSet<SidePaneType> visiblePanes() { return visiblePanes; } public ObservableMap<SidePaneType, Integer> getPreferredPositions() { return preferredPositions; } public void setPreferredPositions(Map<SidePaneType, Integer> positions) { preferredPositions.clear(); preferredPositions.putAll(positions); } public int getWebSearchFetcherSelected() { return webSearchFetcherSelected.get(); } public IntegerProperty webSearchFetcherSelectedProperty() { return webSearchFetcherSelected; } public void setWebSearchFetcherSelected(int webSearchFetcherSelected) { this.webSearchFetcherSelected.set(webSearchFetcherSelected); } }
1,776
33.173077
92
java
null
jabref-main/src/main/java/org/jabref/preferences/TelemetryPreferences.java
package org.jabref.preferences; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; public class TelemetryPreferences { private final BooleanProperty collectTelemetry; private final BooleanProperty askToCollectTelemetry; private final StringProperty userId; public TelemetryPreferences(boolean shouldCollectTelemetry, boolean shouldAskToCollectTelemetry, String userId) { this.collectTelemetry = new SimpleBooleanProperty(shouldCollectTelemetry); this.askToCollectTelemetry = new SimpleBooleanProperty(shouldAskToCollectTelemetry); this.userId = new SimpleStringProperty(userId); } public boolean shouldCollectTelemetry() { return collectTelemetry.get(); } public BooleanProperty collectTelemetryProperty() { return collectTelemetry; } public void setCollectTelemetry(boolean collectTelemetry) { this.collectTelemetry.set(collectTelemetry); } public boolean shouldAskToCollectTelemetry() { return askToCollectTelemetry.get(); } public BooleanProperty askToCollectTelemetryProperty() { return askToCollectTelemetry; } public void setAskToCollectTelemetry(boolean askToCollectTelemetry) { this.askToCollectTelemetry.set(askToCollectTelemetry); } public String getUserId() { return userId.get(); } }
1,569
31.040816
92
java